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:
@@ -21,6 +21,10 @@ HERMEVEN_DB_PATH=./data/hermeven.sqlite
|
|||||||
|
|
||||||
# Exact origins of the page that calls the bridge (comma separated, no wildcards).
|
# 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.
|
# 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:<port> 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=
|
HERMEVEN_ALLOWED_ORIGINS=
|
||||||
|
|
||||||
# --- Speech-to-text -----------------------------------------------------------
|
# --- Speech-to-text -----------------------------------------------------------
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ HERMEVEN_PORT=8787
|
|||||||
# Caddy is in front, so the client address comes from its forwarded header.
|
# Caddy is in front, so the client address comes from its forwarded header.
|
||||||
HERMEVEN_TRUST_PROXY=true
|
HERMEVEN_TRUST_PROXY=true
|
||||||
HERMEVEN_DB_PATH=/var/lib/hermeven/hermeven.sqlite
|
HERMEVEN_DB_PATH=/var/lib/hermeven/hermeven.sqlite
|
||||||
# Read the real value from the phone page: Diagnostics -> "Page origin".
|
# An app installed through Even Hub is served from http://127.0.0.1:<port>, with a new port on
|
||||||
HERMEVEN_ALLOWED_ORIGINS=
|
# 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
|
# 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
|
# never downloads it and only reads this directory. Populate it at deploy time with
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ export interface BridgeConfig {
|
|||||||
dbPath: string;
|
dbPath: string;
|
||||||
/** Exact browser origins allowed by CORS. Empty = no cross-origin browser access. */
|
/** Exact browser origins allowed by CORS. Empty = no cross-origin browser access. */
|
||||||
allowedOrigins: string[];
|
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). */
|
/** Refuse to bind a non-loopback address without this (TLS must terminate in front). */
|
||||||
allowNonLoopback: boolean;
|
allowNonLoopback: boolean;
|
||||||
/** Trust X-Forwarded-For from a reverse proxy (only when one is actually in front). */
|
/** 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 || '';
|
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)');
|
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(',')
|
.split(',')
|
||||||
.map((s) => s.trim())
|
.map((s) => s.trim())
|
||||||
.filter(Boolean);
|
.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) {
|
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;
|
let parsed: URL;
|
||||||
try {
|
try {
|
||||||
parsed = new URL(origin);
|
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),
|
port: int(env, 'HERMEVEN_PORT', 8787, 0, 65535),
|
||||||
dbPath: env.HERMEVEN_DB_PATH || './data/hermeven.sqlite',
|
dbPath: env.HERMEVEN_DB_PATH || './data/hermeven.sqlite',
|
||||||
allowedOrigins,
|
allowedOrigins,
|
||||||
|
allowedLoopbackAnyPort,
|
||||||
allowNonLoopback,
|
allowNonLoopback,
|
||||||
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
|
trustProxy: bool(env, 'HERMEVEN_TRUST_PROXY'),
|
||||||
hermes: {
|
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> {
|
export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
||||||
const { config, devices, engine } = deps;
|
const { config, devices, engine } = deps;
|
||||||
const app = Fastify({
|
const app = Fastify({
|
||||||
@@ -78,10 +96,11 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
|
|||||||
genReqId: () => crypto.randomUUID(),
|
genReqId: () => crypto.randomUUID(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Exact-origin CORS. CORS only tells browsers who may read answers; every route
|
// CORS: exact origins, plus (only if configured) any port on a loopback address.
|
||||||
// except /healthz and the pairing claim still requires a device credential.
|
// 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, {
|
await app.register(cors, {
|
||||||
origin: config.allowedOrigins.length ? config.allowedOrigins : false,
|
origin: (origin, callback) => callback(null, isAllowedOrigin(config, origin)),
|
||||||
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
||||||
allowedHeaders: ['Authorization', 'Content-Type'],
|
allowedHeaders: ['Authorization', 'Content-Type'],
|
||||||
credentials: false,
|
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', () => {
|
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' });
|
const config = loadConfig({ ...base, HERMEVEN_CAPTURE_MAX_SECONDS: '10' });
|
||||||
expect(config.limits.audioMaxBytes).toBe(11 * 32000);
|
expect(config.limits.audioMaxBytes).toBe(11 * 32000);
|
||||||
|
|||||||
@@ -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', () => {
|
describe('pairing', () => {
|
||||||
it('codes are single-use', async () => {
|
it('codes are single-use', async () => {
|
||||||
h = await createHarness();
|
h = await createHarness();
|
||||||
|
|||||||
Reference in New Issue
Block a user