Files
hermeven/services/bridge/src/config.ts
T
DanandClaude Fable 5.2 bc00ae9fb1 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>
2026-11-21 13:31:40 -08:00

245 lines
10 KiB
TypeScript

import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { AUDIO_FORMAT, DEFAULT_LIMITS } from '@hermeven/contracts';
import { validateManifest, type ModelManifest } from './stt/modelStore.mjs';
export interface BridgeConfig {
host: string;
port: number;
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). */
trustProxy: boolean;
hermes: {
/** Base URL of the Hermes API server, e.g. http://127.0.0.1:8642 or .../p/<profile>. */
baseUrl: string;
apiKey: string;
/** Label of the configured profile; devices are bound to it. Not sent to Hermes. */
profileLabel: string;
/** Per-request ephemeral instructions layered on the agent prompt. Empty disables. */
instructions: string;
pollIntervalMs: number;
requestTimeoutMs: number;
};
stt: {
provider: 'none' | 'builtin' | 'openai-compatible';
baseUrl: string;
apiKey: string;
/** Bundled manifest name for `builtin`; provider model name for `openai-compatible`. */
model: string;
/** `builtin` only: the pinned artifacts to load, and the directory they are read from. */
manifest: ModelManifest | null;
modelDir: string;
};
limits: {
captureMaxSeconds: number;
transcribeDeadlineSeconds: number;
agentDeadlineSeconds: number;
approvalWaitSeconds: number;
cancelGraceSeconds: number;
textMaxChars: number;
audioMaxBytes: number;
turnsPerMinute: number;
pairingAttemptsPerMinute: number;
};
credentials: {
tokenTtlSeconds: number;
pairingTtlSeconds: number;
pairingCodeTtlSeconds: number;
};
/** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */
resultRetentionSeconds: number;
logLevel: string;
}
const DEFAULT_INSTRUCTIONS =
'The user reads this reply on a small monochrome heads-up display. ' +
'Answer in plain text without Markdown, tables, code fences or links. ' +
'Lead with the direct answer in one or two short sentences, then add detail only if it is needed.';
export class ConfigError extends Error {
override name = 'ConfigError';
}
function int(env: NodeJS.ProcessEnv, key: string, fallback: number, min = 1, max = Number.MAX_SAFE_INTEGER): number {
const raw = env[key];
if (raw === undefined || raw === '') return fallback;
const n = Number(raw);
if (!Number.isInteger(n) || n < min || n > max) {
throw new ConfigError(`${key} must be an integer between ${min} and ${max}`);
}
return n;
}
function bool(env: NodeJS.ProcessEnv, key: string, fallback = false): boolean {
const raw = env[key];
if (raw === undefined || raw === '') return fallback;
if (['1', 'true', 'yes'].includes(raw.toLowerCase())) return true;
if (['0', 'false', 'no'].includes(raw.toLowerCase())) return false;
throw new ConfigError(`${key} must be true or false`);
}
export function isLoopback(host: string): boolean {
return host === 'localhost' || host === '::1' || /^127\./.test(host);
}
function httpUrl(key: string, raw: string): string {
let url: URL;
try {
url = new URL(raw);
} catch {
throw new ConfigError(`${key} is not a valid URL`);
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new ConfigError(`${key} must be http(s)`);
if (url.protocol === 'http:' && !isLoopback(url.hostname)) {
throw new ConfigError(`${key} must use https outside loopback`);
}
return raw.replace(/\/+$/, '');
}
/** Manifests shipped with the bridge: `services/bridge/models/<name>.json`. */
export function bundledManifestPath(name: string): string {
return fileURLToPath(new URL(`../models/${name}.json`, import.meta.url));
}
function loadModelManifest(name: string, customPath: string | undefined): ModelManifest {
let path: string;
if (customPath) {
path = customPath;
} else {
if (!/^[a-z0-9][a-z0-9.-]*$/.test(name)) {
throw new ConfigError('STT_MODEL must be the name of a bundled pinned model (whisper-base, whisper-tiny)');
}
path = bundledManifestPath(name);
if (!existsSync(path)) {
throw new ConfigError(
`STT_MODEL "${name}" has no bundled pinned manifest. Use whisper-base or whisper-tiny, or point ` +
'STT_MODEL_MANIFEST at a manifest that pins a commit id and a SHA-256 for every file.',
);
}
}
try {
return validateManifest(JSON.parse(readFileSync(path, 'utf8')));
} catch (err) {
throw new ConfigError(`Speech model manifest could not be used: ${err instanceof Error ? err.message : 'unreadable'}`);
}
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
const host = env.HERMEVEN_HOST || '127.0.0.1';
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
if (!isLoopback(host) && !allowNonLoopback) {
throw new ConfigError(
'HERMEVEN_HOST is not loopback. Put a TLS-terminating proxy or private network in front and set ' +
'HERMEVEN_ALLOW_NON_LOOPBACK=true to confirm.',
);
}
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 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.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);
} catch {
throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry is not an origin: ${origin}`);
}
if (parsed.origin !== origin) throw new ConfigError(`HERMEVEN_ALLOWED_ORIGINS entry must be scheme://host[:port]: ${origin}`);
}
// Built-in Whisper is the default: voice works with no provider account and no audio
// leaving the bridge host.
const sttProvider = (env.STT_PROVIDER || 'builtin') as BridgeConfig['stt']['provider'];
if (sttProvider !== 'none' && sttProvider !== 'builtin' && sttProvider !== 'openai-compatible') {
throw new ConfigError('STT_PROVIDER must be "builtin", "openai-compatible" or "none"');
}
const sttModel = env.STT_MODEL || (sttProvider === 'builtin' ? 'whisper-base' : '');
// The built-in model is always pinned: a commit id plus a SHA-256 for every file. There is
// no unpinned mode. A model that is not bundled needs its own manifest file.
const sttManifest = sttProvider === 'builtin' ? loadModelManifest(sttModel, env.STT_MODEL_MANIFEST) : null;
let sttBaseUrl = '';
if (sttProvider === 'openai-compatible') {
if (!env.STT_BASE_URL) throw new ConfigError('STT_BASE_URL is required for STT_PROVIDER=openai-compatible');
if (!env.STT_MODEL) throw new ConfigError('STT_MODEL is required for STT_PROVIDER=openai-compatible');
sttBaseUrl = httpUrl('STT_BASE_URL', env.STT_BASE_URL);
}
const captureMaxSeconds = int(env, 'HERMEVEN_CAPTURE_MAX_SECONDS', DEFAULT_LIMITS.captureMaxSeconds, 1, 120);
return {
host,
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: {
baseUrl: httpUrl('HERMES_BASE_URL', env.HERMES_BASE_URL || 'http://127.0.0.1:8642'),
apiKey: hermesKey,
profileLabel: env.HERMES_PROFILE_LABEL || 'default',
instructions: env.HERMEVEN_INSTRUCTIONS === undefined ? DEFAULT_INSTRUCTIONS : env.HERMEVEN_INSTRUCTIONS,
pollIntervalMs: int(env, 'HERMES_POLL_INTERVAL_MS', 150, 20, 10_000),
requestTimeoutMs: int(env, 'HERMES_REQUEST_TIMEOUT_MS', 10_000, 50, 120_000),
},
stt: {
provider: sttProvider,
baseUrl: sttBaseUrl,
apiKey: env.STT_API_KEY || '',
model: sttModel,
manifest: sttManifest,
modelDir: env.STT_MODEL_DIR || './data/models',
},
limits: {
captureMaxSeconds,
transcribeDeadlineSeconds: int(env, 'HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS', DEFAULT_LIMITS.transcribeDeadlineSeconds, 1, 300),
agentDeadlineSeconds: int(env, 'HERMEVEN_AGENT_DEADLINE_SECONDS', DEFAULT_LIMITS.agentDeadlineSeconds, 1, 3600),
approvalWaitSeconds: int(env, 'HERMEVEN_APPROVAL_WAIT_SECONDS', DEFAULT_LIMITS.approvalWaitSeconds, 1, 3600),
cancelGraceSeconds: int(env, 'HERMEVEN_CANCEL_GRACE_SECONDS', 30, 1, 600),
textMaxChars: DEFAULT_LIMITS.textMaxChars,
// One extra second of headroom over the capture cap for frame alignment.
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600),
pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60),
},
credentials: {
tokenTtlSeconds: int(env, 'HERMEVEN_TOKEN_TTL_SECONDS', 7 * 86_400, 60),
pairingTtlSeconds: int(env, 'HERMEVEN_PAIRING_TTL_SECONDS', 90 * 86_400, 60),
pairingCodeTtlSeconds: int(env, 'HERMEVEN_PAIRING_CODE_TTL_SECONDS', 300, 30, 3600),
},
resultRetentionSeconds: int(env, 'HERMEVEN_RESULT_RETENTION_SECONDS', 900, 10, 86_400),
logLevel: env.HERMEVEN_LOG_LEVEL || 'info',
};
}