Allow loopback origins on any port when configured (http://127.0.0.1:*)
An app installed through Even Hub is served by the Even phone app from http://127.0.0.1:<port>, and the port changed between two launches on a real phone (40315, then another). An exact-origin allow-list therefore cannot admit it. HERMEVEN_ALLOWED_ORIGINS now accepts one wildcard form, the port of a loopback address over http (127.0.0.1, localhost, [::1]), off unless configured. No other wildcard is accepted. CORS remains advisory: every route still requires the device credential. Tests: 224 unit/integration. Not reviewed, not deployed. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,12 @@ export interface BridgeConfig {
|
||||
dbPath: string;
|
||||
/** Exact browser origins allowed by CORS. Empty = no cross-origin browser access. */
|
||||
allowedOrigins: string[];
|
||||
/**
|
||||
* Loopback hosts whose pages are allowed from ANY port (`http://127.0.0.1:*`). Needed because
|
||||
* the Even phone app serves an installed app from `http://127.0.0.1:<port>` and picks a new
|
||||
* port on every launch (observed on a real phone, 2026-11-21). Empty unless configured.
|
||||
*/
|
||||
allowedLoopbackAnyPort: string[];
|
||||
/** Refuse to bind a non-loopback address without this (TLS must terminate in front). */
|
||||
allowNonLoopback: boolean;
|
||||
/** Trust X-Forwarded-For from a reverse proxy (only when one is actually in front). */
|
||||
@@ -141,12 +147,28 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
const hermesKey = env.HERMES_API_KEY || '';
|
||||
if (!hermesKey) throw new ConfigError('HERMES_API_KEY is required (the Hermes API server refuses to start without one)');
|
||||
|
||||
const allowedOrigins = (env.HERMEVEN_ALLOWED_ORIGINS || '')
|
||||
const originEntries = (env.HERMEVEN_ALLOWED_ORIGINS || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
// The one permitted wildcard: any port on a loopback address, over plain http, written
|
||||
// exactly as `http://127.0.0.1:*`, `http://localhost:*` or `http://[::1]:*`. A loopback
|
||||
// origin can only be a page served on the same device as the browser making the request.
|
||||
// No other wildcard exists: not for hosts, not for schemes, not for non-loopback ports.
|
||||
const allowedLoopbackAnyPort: string[] = [];
|
||||
const allowedOrigins: string[] = [];
|
||||
for (const entry of originEntries) {
|
||||
const anyPort = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):\*$/.exec(entry);
|
||||
if (anyPort) allowedLoopbackAnyPort.push(anyPort[1]!);
|
||||
else allowedOrigins.push(entry);
|
||||
}
|
||||
for (const origin of allowedOrigins) {
|
||||
if (origin === '*' ) throw new ConfigError('HERMEVEN_ALLOWED_ORIGINS must list exact origins, not *');
|
||||
if (origin.includes('*')) {
|
||||
throw new ConfigError(
|
||||
'HERMEVEN_ALLOWED_ORIGINS must list exact origins. The only wildcard accepted is the port of a ' +
|
||||
'loopback address, written http://127.0.0.1:* (or localhost, or [::1]).',
|
||||
);
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(origin);
|
||||
@@ -180,6 +202,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
|
||||
port: int(env, 'HERMEVEN_PORT', 8787, 0, 65535),
|
||||
dbPath: env.HERMEVEN_DB_PATH || './data/hermeven.sqlite',
|
||||
allowedOrigins,
|
||||
allowedLoopbackAnyPort,
|
||||
allowNonLoopback,
|
||||
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
|
||||
hermes: {
|
||||
|
||||
@@ -64,6 +64,24 @@ export function effectiveLimits(config: BridgeConfig): Limits {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a browser page at `origin` may read this bridge's responses.
|
||||
* Exact matches against the configured list; otherwise, if a loopback host was configured with
|
||||
* `:*`, an `http://<that host>:<port>` origin with a numeric port. Nothing else, and never a
|
||||
* missing or `null` origin.
|
||||
*/
|
||||
export function isAllowedOrigin(config: Pick<BridgeConfig, 'allowedOrigins' | 'allowedLoopbackAnyPort'>, origin: string | undefined): boolean {
|
||||
if (!origin || origin === 'null') return false;
|
||||
if (config.allowedOrigins.includes(origin)) return true;
|
||||
if (config.allowedLoopbackAnyPort.length === 0) return false;
|
||||
// Matched as text, start to end, so look-alikes such as http://127.0.0.1.example.com:80 or
|
||||
// http://127.0.0.1:80@example.com cannot pass.
|
||||
const match = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})$/.exec(origin);
|
||||
if (!match) return false;
|
||||
const port = Number(match[2]);
|
||||
return port >= 1 && port <= 65535 && config.allowedLoopbackAnyPort.includes(match[1]!);
|
||||
}
|
||||
|
||||
export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
const { config, devices, engine } = deps;
|
||||
const app = Fastify({
|
||||
@@ -78,10 +96,11 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||
genReqId: () => crypto.randomUUID(),
|
||||
});
|
||||
|
||||
// Exact-origin CORS. CORS only tells browsers who may read answers; every route
|
||||
// except /healthz and the pairing claim still requires a device credential.
|
||||
// CORS: exact origins, plus (only if configured) any port on a loopback address.
|
||||
// CORS only tells browsers who may read answers; every route except /healthz and the
|
||||
// pairing claim still requires a device credential.
|
||||
await app.register(cors, {
|
||||
origin: config.allowedOrigins.length ? config.allowedOrigins : false,
|
||||
origin: (origin, callback) => callback(null, isAllowedOrigin(config, origin)),
|
||||
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Authorization', 'Content-Type'],
|
||||
credentials: false,
|
||||
|
||||
@@ -39,6 +39,28 @@ describe('configuration', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('the only origin wildcard is the port of a loopback address over http', () => {
|
||||
const c = loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: 'https://a.example, http://127.0.0.1:*' });
|
||||
expect(c.allowedOrigins).toEqual(['https://a.example']);
|
||||
expect(c.allowedLoopbackAnyPort).toEqual(['127.0.0.1']);
|
||||
expect(loadConfig(base).allowedLoopbackAnyPort).toEqual([]);
|
||||
for (const bad of [
|
||||
'*',
|
||||
'http://*',
|
||||
'http://*:8080',
|
||||
'https://127.0.0.1:*', // https wildcard not offered
|
||||
'http://192.168.1.20:*', // LAN
|
||||
'http://10.0.0.5:*',
|
||||
'http://example.com:*',
|
||||
'https://*.example.com',
|
||||
'http://127.0.0.1:*/', // trailing slash: not the exact form
|
||||
'http://127.0.0.2:*',
|
||||
'http://127.0.0.1.example.com:*',
|
||||
]) {
|
||||
expect(() => loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: bad }), bad).toThrow(ConfigError);
|
||||
}
|
||||
});
|
||||
|
||||
it('derives the audio byte cap from the capture cap and never puts secrets in error text', () => {
|
||||
const config = loadConfig({ ...base, HERMEVEN_CAPTURE_MAX_SECONDS: '10' });
|
||||
expect(config.limits.audioMaxBytes).toBe(11 * 32000);
|
||||
|
||||
Reference in New Issue
Block a user