diff --git a/.env.example b/.env.example index d7d2491..6877262 100644 --- a/.env.example +++ b/.env.example @@ -21,6 +21,10 @@ HERMEVEN_DB_PATH=./data/hermeven.sqlite # Exact origins of the page that calls the bridge (comma separated, no wildcards). # Read the real value from Diagnostics -> "Page origin" in the phone page. +# One wildcard is accepted: the port of a loopback address, written http://127.0.0.1:* +# The Even phone app serves an installed app from http://127.0.0.1: and uses a new port +# on every launch, so an installed app needs exactly that entry. A page served from the +# bridge's own hostname (the QR sideload path) needs no entry at all. HERMEVEN_ALLOWED_ORIGINS= # --- Speech-to-text ----------------------------------------------------------- diff --git a/deploy/bridge.env.example b/deploy/bridge.env.example index 0f838c8..3f121d4 100644 --- a/deploy/bridge.env.example +++ b/deploy/bridge.env.example @@ -8,8 +8,10 @@ HERMEVEN_PORT=8787 # Caddy is in front, so the client address comes from its forwarded header. HERMEVEN_TRUST_PROXY=true HERMEVEN_DB_PATH=/var/lib/hermeven/hermeven.sqlite -# Read the real value from the phone page: Diagnostics -> "Page origin". -HERMEVEN_ALLOWED_ORIGINS= +# An app installed through Even Hub is served from http://127.0.0.1:, with a new port on +# every launch, so it needs the loopback any-port entry below. Remove it if you only ever load +# the page from this bridge's own hostname (QR sideload), which needs no entry. +HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:* # Built-in speech-to-text (the default). The model is pinned and verified; the running service # never downloads it and only reads this directory. Populate it at deploy time with diff --git a/services/bridge/src/config.ts b/services/bridge/src/config.ts index a1f6b52..efe7916 100644 --- a/services/bridge/src/config.ts +++ b/services/bridge/src/config.ts @@ -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:` 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: { diff --git a/services/bridge/src/server.ts b/services/bridge/src/server.ts index f45ff97..3149f21 100644 --- a/services/bridge/src/server.ts +++ b/services/bridge/src/server.ts @@ -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://:` origin with a numeric port. Nothing else, and never a + * missing or `null` origin. + */ +export function isAllowedOrigin(config: Pick, 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 { const { config, devices, engine } = deps; const app = Fastify({ @@ -78,10 +96,11 @@ export async function buildServer(deps: ServerDeps): Promise { 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, diff --git a/services/bridge/test/units.test.ts b/services/bridge/test/units.test.ts index bdde20a..6245b7d 100644 --- a/services/bridge/test/units.test.ts +++ b/services/bridge/test/units.test.ts @@ -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); diff --git a/tests/integration/bridge.test.ts b/tests/integration/bridge.test.ts index 2575039..f5dcdd0 100644 --- a/tests/integration/bridge.test.ts +++ b/tests/integration/bridge.test.ts @@ -118,6 +118,69 @@ describe('health, auth and binding', () => { }); }); +describe('loopback any-port origins (the Even app serves an installed app from 127.0.0.1 on a new port each launch)', () => { + const preflight = (origin: string) => + h.api('OPTIONS', '/v1/pairing/claim', { + headers: { Origin: origin, 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'content-type' }, + }); + const allowed = async (origin: string) => (await preflight(origin)).headers.get('access-control-allow-origin'); + + it('off by default: a loopback page on another port is not allowed', async () => { + h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'http://127.0.0.1:40315' } }); + expect(await allowed('http://127.0.0.1:40315')).toBe('http://127.0.0.1:40315'); + expect(await allowed('http://127.0.0.1:40316')).toBeNull(); + }); + + it('with http://127.0.0.1:* configured: any port on 127.0.0.1 is allowed and echoed exactly; nothing else is', async () => { + h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'https://app.example, http://127.0.0.1:*' } }); + for (const origin of ['http://127.0.0.1:40315', 'http://127.0.0.1:51234', 'http://127.0.0.1:1', 'http://127.0.0.1:65535', 'https://app.example']) { + expect(await allowed(origin), origin).toBe(origin); + } + for (const origin of [ + 'http://127.0.0.1', // no port: not what the Even app uses, and not what was configured + 'https://127.0.0.1:40315', // https was not configured + 'http://localhost:40315', // a different loopback name, not configured + 'http://[::1]:40315', + 'http://127.0.0.2:40315', + 'http://127.0.0.1.example.com:40315', + 'http://127.0.0.1:40315.example.com', + 'http://127.0.0.1:40315@example.com', + 'http://example.com:40315', + 'http://192.168.1.20:40315', + 'http://10.0.0.5:8080', + 'http://127.0.0.1:0', + 'http://127.0.0.1:65536', + 'http://127.0.0.1:abc', + 'http://127.0.0.1:40315/', + 'https://evil.example', + 'null', + ]) { + expect(await allowed(origin), origin).toBeNull(); + } + // The response varies by Origin, so a cache cannot serve one origin's answer to another. + expect((await preflight('http://127.0.0.1:40315')).headers.get('vary') ?? '').toMatch(/origin/i); + }); + + it('being an allowed origin grants nothing: every route still needs the device credential', async () => { + h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'http://127.0.0.1:*' } }); + const origin = { Origin: 'http://127.0.0.1:40315' }; + expect((await h.api('GET', '/v1/device', { headers: origin })).status).toBe(401); + expect((await h.textTurn('hvn_wrong', randomUUID(), 'hi')).status).toBe(401); + const cred = await h.pair(); + const ok = await h.api('GET', '/v1/device', { token: cred.token, headers: origin }); + expect(ok.status).toBe(200); + expect(ok.headers.get('access-control-allow-origin')).toBe('http://127.0.0.1:40315'); + expect(h.hermes.executions).toBe(0); + }); + + it('localhost and [::1] can be opted in separately', async () => { + h = await createHarness({ env: { HERMEVEN_ALLOWED_ORIGINS: 'http://localhost:*,http://[::1]:*' } }); + expect(await allowed('http://localhost:5173')).toBe('http://localhost:5173'); + expect(await allowed('http://[::1]:5173')).toBe('http://[::1]:5173'); + expect(await allowed('http://127.0.0.1:5173')).toBeNull(); + }); +}); + describe('pairing', () => { it('codes are single-use', async () => { h = await createHarness();