diff --git a/.env.example b/.env.example index 22f00fe..d7d2491 100644 --- a/.env.example +++ b/.env.example @@ -25,13 +25,16 @@ HERMEVEN_ALLOWED_ORIGINS= # --- Speech-to-text ----------------------------------------------------------- # "builtin" (default): Whisper runs inside the bridge on the CPU. No account, and recordings -# never leave the bridge host. Model files (about 80 MB) are downloaded on first start. +# never leave the bridge host. The model is pinned (commit id + SHA-256 per file) and is +# never downloaded by the running bridge: fetch it once with +# npm run bridge:cli -- fetch-model # "openai-compatible": any server with POST {base}/audio/transcriptions. # "none": typed questions only. STT_PROVIDER=builtin -# STT_MODEL=onnx-community/whisper-base # or whisper-tiny (faster), whisper-base.en (English only) -# STT_DTYPE=q8 -# STT_CACHE_DIR=./data/models +# STT_MODEL=whisper-base # bundled pinned models: whisper-base, whisper-tiny (faster, less accurate) +# STT_MODEL_DIR=./data/models # where the verified files live; can be read-only at run time +# STT_MODEL_MANIFEST= # path to your own manifest for any other model (must pin a +# # 40-character commit id and a SHA-256 for every file) # # For STT_PROVIDER=openai-compatible: # STT_BASE_URL=https://stt.example/v1 diff --git a/README.md b/README.md index 395931c..cdab788 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ small bridge between the two. | Path | State | |---|---| | Client, bridge and contract | Implemented. | -| Automated tests with fakes (130) | Passing. | +| Automated tests with fakes (182) | Passing. | | Client in Even's official simulator | Passing (6 scenarios). Simulator only. | | Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. | -| Built-in speech-to-text (Whisper, in the bridge) | Passing (4 scenarios) on a real speech recording. Not yet on audio from the glasses. | +| Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. | | Running on a droplet | **Not run.** See `docs/deploy-droplet.md`. | | Real model, real tools, approval flow | **Not run.** | | Physical G2, ring, locked-phone use, battery | **Not run.** See `docs/device-test-plan.md`. | @@ -44,6 +44,7 @@ G2 <-Bluetooth-> Even phone app (WebView: apps/even-client) ```sh npm ci cp .env.example .env # set HERMES_API_KEY; add HERMEVEN_ALLOWED_ORIGINS=http://localhost:5173 +npm run bridge:cli -- fetch-model # one-time: download and verify the pinned speech model npm run bridge # terminal 1 npm run client:dev # terminal 2, then open http://localhost:5173 npm run bridge:cli -- pair # terminal 3: prints a one-time pairing code diff --git a/apps/even-client/scripts/write-manifest.mjs b/apps/even-client/scripts/write-manifest.mjs index 0033c83..0c99e69 100644 --- a/apps/even-client/scripts/write-manifest.mjs +++ b/apps/even-client/scripts/write-manifest.mjs @@ -24,11 +24,20 @@ if (origin !== raw) { console.error(`[manifest] HERMEVEN_BRIDGE_ORIGIN must be a bare origin (scheme://host[:port]), got a path or trailing slash.`); process.exit(1); } -if (!origin.startsWith('https://')) { - console.warn('[manifest] The bridge origin is not https. Acceptable only for a local development build.'); +// Same rule as the app enforces at run time (src/net/bridgeClient.ts): HTTPS, or HTTP to +// loopback for the simulator. A packaged app must never be allowed to send the device +// credential and recordings over plain HTTP to a LAN or public host. +const { protocol, hostname } = new URL(origin); +const loopback = hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname); +if (protocol !== 'https:' && !(protocol === 'http:' && loopback)) { + console.error('[manifest] HERMEVEN_BRIDGE_ORIGIN must be https:// (plain http is accepted only for loopback).'); + process.exit(1); +} +if (protocol === 'http:') { + console.warn('[manifest] Loopback HTTP origin: this build is for the simulator only and cannot work on a phone.'); } const template = readFileSync(resolve(here, '../app.template.json'), 'utf8'); -const out = resolve(here, '../dist-manifest/app.json'); +const out = process.env.HERMEVEN_MANIFEST_OUT ?? resolve(here, '../dist-manifest/app.json'); mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, template.replace('__HERMEVEN_BRIDGE_ORIGIN__', origin)); console.log(`[manifest] wrote ${out}`); diff --git a/apps/even-client/src/core/controller.ts b/apps/even-client/src/core/controller.ts index bc1ad3d..7e7a0a6 100644 --- a/apps/even-client/src/core/controller.ts +++ b/apps/even-client/src/core/controller.ts @@ -16,8 +16,14 @@ interface Stored { tokenExpiresAt: string; pairingExpiresAt: string; conversationId: string | null; - /** A turn that was in flight; re-attached by polling after a restart, never resubmitted. */ + /** + * The request id of a turn that may exist on the bridge. Written BEFORE the first submit and + * cleared only on a definitive answer: a terminal result, a definite rejection, or the bridge + * confirming it has no such turn. After a restart it is re-attached by polling. + */ activeRequestId: string | null; + /** The user abandoned that turn but the bridge has not yet acknowledged the cancel. */ + activeCancelled: boolean; } export interface DiagEntry { @@ -81,6 +87,8 @@ export class Controller { private pending: PendingInput | null = null; private lastTurn: TurnResult | null = null; private hudReady = false; + private creating: { epoch: number; promise: Promise } | null = null; + private createChain: Promise = Promise.resolve(); private stopped = false; private ticker: ReturnType | null = null; private readonly log: DiagEntry[] = []; @@ -134,13 +142,16 @@ export class Controller { } } } + // A turn the user had abandoned is not shown again; its cancel is simply delivered now. + const abandoned = this.stored?.activeCancelled ? this.stored.activeRequestId : null; this.dispatch({ type: 'init', paired: this.stored !== null, conversationId: this.stored?.conversationId ?? null, captureMaxSeconds, - resumeRequestId: this.stored?.activeRequestId ?? null, + resumeRequestId: abandoned ? null : (this.stored?.activeRequestId ?? null), }); + if (abandoned) void this.cancelTurn(abandoned); } /** Stop for good: every pending retry and poll loop winds down and nothing more is drawn or emitted. */ @@ -180,6 +191,7 @@ export class Controller { pairingExpiresAt: credential.pairing_expires_at, conversationId: null, activeRequestId: null, + activeCancelled: false, }; await this.save(); this.note('pairing', `paired as ${credential.device_id}`); @@ -210,7 +222,13 @@ export class Controller { async renew(): Promise { if (!this.client || !this.stored) return; - const credential = await this.client.renew(); + let credential; + try { + credential = await this.client.renew(); + } catch (err) { + if (err instanceof BridgeApiError) await this.afterAuthFailure(err); + throw err; + } this.client.token = credential.token; this.stored = { ...this.stored, token: credential.token, tokenExpiresAt: credential.token_expires_at }; await this.save(); @@ -224,6 +242,7 @@ export class Controller { this.status = await this.client.device(); } catch (err) { this.note('bridge', `status check failed: ${describe(err)}`); + if (err instanceof BridgeApiError) await this.afterAuthFailure(err); } this.emit(); } @@ -275,7 +294,7 @@ export class Controller { case 'cancel_turn': return await this.cancelTurn(effect.requestId); case 'create_conversation': - return await this.createConversation(effect.generation); + return await this.createConversation(effect.epoch); case 'exit_dialog': return await this.device.requestExit(); } @@ -296,9 +315,15 @@ export class Controller { this.capture = capture; this.micOpen = true; const ok = await this.device.startMic(); - if (this.capture !== capture) { - // Cancelled while the microphone was opening. - if (!this.capture) await this.closeMic(); + if (this.capture !== capture || this.stale(generation)) { + // Cancelled while the microphone was opening. Stop unconditionally unless a newer + // capture now owns the microphone: a stop that turns out to be redundant is harmless. + if (!this.capture || this.capture === capture) { + this.capture = null; + this.micOpen = false; + this.stopTicker(); + await this.device.stopMic(); + } return; } if (!ok) { @@ -364,24 +389,64 @@ export class Controller { return this.stopped || generation !== this.state.generation; } - private async ensureConversation(): Promise { - if (this.state.conversationId) return this.state.conversationId; - const created = await this.client!.createConversation(); - if (this.stored) { - this.stored = { ...this.stored, conversationId: created.conversation_id }; - await this.save(); - } - this.dispatch({ type: 'conversation_created', generation: this.state.generation, conversationId: created.conversation_id }); - return created.conversation_id; + /** + * The current conversation id, creating one if there is none. At most one create is in + * flight per conversation epoch, and creates are sent strictly one after another, so the + * bridge and the app can never disagree about which conversation is the live one: the last + * create the app sent is the last one the bridge processed. + */ + private ensureConversation(): Promise { + if (this.state.conversationId) return Promise.resolve(this.state.conversationId); + const epoch = this.state.conversationEpoch; + if (this.creating && this.creating.epoch === epoch) return this.creating.promise; + + const client = this.client; + const promise = this.createChain.then(async () => { + if (!client || this.stopped || epoch !== this.state.conversationEpoch) throw new StaleConversationError(); + const created = await client.createConversation(); + // Checked BEFORE anything is stored: a result for a conversation the user has since + // replaced (or for a pairing that has ended) is dropped, not persisted. + if (this.stopped || epoch !== this.state.conversationEpoch || this.client !== client) throw new StaleConversationError(); + if (this.stored) { + this.stored = { ...this.stored, conversationId: created.conversation_id }; + await this.save(); + } + this.note('conversation', `conversation ${created.conversation_id}`); + this.dispatch({ type: 'conversation_created', epoch, conversationId: created.conversation_id }); + return created.conversation_id; + }); + this.createChain = promise.then( + () => undefined, + () => undefined, + ); + const entry = { epoch, promise }; + this.creating = entry; + void this.createChain.then(() => { + if (this.creating === entry) this.creating = null; + }); + return promise; } private async submit(generation: number, requestId: string): Promise { const pending = this.pending; if (!this.client || !pending || pending.requestId !== requestId) return; + // Remember the request id before anything is sent. From here until the bridge gives a + // definite answer, this request may or may not exist there; if the page dies in between, + // the next start re-attaches to it by id instead of forgetting a turn that is running. + await this.setActiveRequest(requestId); for (let attempt = 1; ; attempt++) { if (this.stale(generation)) return; try { - const conversationId = await this.ensureConversation(); + let conversationId: string; + try { + conversationId = await this.ensureConversation(); + } catch (err) { + if (!(err instanceof StaleConversationError)) throw err; + // The conversation was replaced while it was being created; use the new one. + if (this.stale(generation)) return; + attempt -= 1; + continue; + } if (this.stale(generation)) return; const base = { requestId, conversationId, locale: this.options.locale }; // The same request id on every attempt: the bridge deduplicates, so a retry after a @@ -396,15 +461,16 @@ export class Controller { void this.cancelTurn(requestId); return; } - await this.setActiveRequest(requestId); this.note('turn', `accepted ${requestId}${result.replayed ? ' (duplicate ignored by bridge)' : ''}`); this.onResult(generation, result); if (!result.terminal) await this.poll(generation, requestId); return; } catch (err) { if (err instanceof BridgeApiError) { + // A contract error is a definite "this turn was not created". this.note('turn', `rejected: ${err.body.code}`); this.pending = null; + await this.setActiveRequest(null); if (!this.stale(generation)) this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) }); await this.afterAuthFailure(err); return; @@ -412,6 +478,8 @@ export class Controller { if (!(err instanceof BridgeNetworkError)) throw err; this.note('bridge', `submit attempt ${attempt} failed: ${err.message}`); if (attempt >= this.submitAttempts) { + // Ambiguous: a request may have been admitted even though no reply came back. The + // request id stays stored; a retry or a restart reconciles under the same id. if (!this.stale(generation)) this.dispatch({ type: 'network_lost', generation, stage: 'submit' }); return; } @@ -439,8 +507,13 @@ export class Controller { if (this.stale(generation)) return; if (err instanceof BridgeApiError) { this.note('turn', `status rejected: ${err.body.code}`); + // not_found is the bridge confirming the turn does not exist: it was never admitted. await this.setActiveRequest(null); - this.dispatch({ type: 'turn_rejected', generation, error: this.hudError(err) }); + const error: HudError = + err.body.code === 'not_found' + ? { code: 'not_delivered', hud: 'Your last request did not reach the bridge. Please ask again.', retryable: true } + : this.hudError(err); + this.dispatch({ type: 'turn_rejected', generation, error }); await this.afterAuthFailure(err); return; } @@ -458,7 +531,7 @@ export class Controller { let pages: string[] | null = null; if (result.terminal) { this.lastTurn = result; - void this.setActiveRequest(null); + void this.clearActiveRequest(result.request_id); this.note( 'turn', `done ${result.request_id}: ${result.outcome}${result.error ? ` (${result.error.code})` : ''}` + @@ -479,42 +552,48 @@ export class Controller { } private async cancelTurn(requestId: string): Promise { - await this.setActiveRequest(null); - if (!this.client) return; + // Keep the id, marked as abandoned, until the bridge acknowledges the cancel. If the cancel + // cannot be delivered now it is retried on the next start, so an abandoned turn is not + // left running unnoticed and is never shown to the user again. + if (this.stored && this.stored.activeRequestId === requestId && !this.stored.activeCancelled) { + this.stored = { ...this.stored, activeCancelled: true }; + await this.save(); + } + const client = this.client; + if (!client) return; for (let attempt = 1; attempt <= 3; attempt++) { try { - const result = await this.client.cancelTurn(requestId); + const result = await client.cancelTurn(requestId); this.note('turn', `cancel requested for ${requestId}; bridge state ${result.state}`); + await this.clearActiveRequest(requestId); return; } catch (err) { if (err instanceof BridgeApiError) { // not_found: the request never reached the bridge, so there is nothing to cancel. this.note('turn', `cancel answered ${err.body.code}`); + await this.clearActiveRequest(requestId); + await this.afterAuthFailure(err); return; } + if (this.stopped) return; await sleep(this.submitRetryMs); } } - this.note('turn', `cancel for ${requestId} could not be delivered; the agent may still be running`); + this.note('turn', `cancel for ${requestId} could not be delivered yet; it will be retried`); } - private async createConversation(generation: number): Promise { - if (!this.client) return; + private async createConversation(epoch: number): Promise { + if (!this.client || epoch !== this.state.conversationEpoch) return; try { - const created = await this.client.createConversation(); - if (this.stored) { - this.stored = { ...this.stored, conversationId: created.conversation_id }; - await this.save(); - } - this.note('conversation', `new conversation ${created.conversation_id}`); - this.dispatch({ type: 'conversation_created', generation, conversationId: created.conversation_id }); + await this.ensureConversation(); } catch (err) { + if (err instanceof StaleConversationError) return; const error: HudError = err instanceof BridgeApiError ? this.hudError(err) : { code: 'network', hud: 'Could not reach the bridge.', retryable: true }; this.note('conversation', `create failed: ${describe(err)}`); - this.dispatch({ type: 'conversation_failed', generation, error }); + this.dispatch({ type: 'conversation_failed', epoch, error }); if (err instanceof BridgeApiError) await this.afterAuthFailure(err); } } @@ -588,8 +667,11 @@ export class Controller { } private async afterAuthFailure(err: BridgeApiError): Promise { - if (err.body.code !== 'unauthorized') return; - // Revoked or unknown credential: holding on to it helps nobody. + if (err.body.code !== 'unauthorized' && err.body.code !== 'credential_expired') return; + if (!this.stored) return; + // Revoked, unknown or expired: the stored credential can no longer do anything (an expired + // token cannot even renew itself), so it is forgotten and the pairing screen comes back. + this.note('auth', `credential no longer accepted: ${err.body.code}`); await this.forget(); this.dispatch({ type: 'unpaired' }); } @@ -607,11 +689,16 @@ export class Controller { } private async setActiveRequest(requestId: string | null): Promise { - if (!this.stored || this.stored.activeRequestId === requestId) return; - this.stored = { ...this.stored, activeRequestId: requestId }; + if (!this.stored || (this.stored.activeRequestId === requestId && !this.stored.activeCancelled)) return; + this.stored = { ...this.stored, activeRequestId: requestId, activeCancelled: false }; await this.save(); } + /** Clear the stored request id only if it is still this one (a newer turn may own the slot). */ + private async clearActiveRequest(requestId: string): Promise { + if (this.stored?.activeRequestId === requestId) await this.setActiveRequest(null); + } + private async load(): Promise { try { const raw = await this.device.storageGet(STORAGE_KEY); @@ -626,6 +713,7 @@ export class Controller { pairingExpiresAt: String(parsed.pairingExpiresAt ?? ''), conversationId: typeof parsed.conversationId === 'string' ? parsed.conversationId : null, activeRequestId: typeof parsed.activeRequestId === 'string' ? parsed.activeRequestId : null, + activeCancelled: parsed.activeCancelled === true, }; } catch { return null; @@ -670,6 +758,11 @@ export function pollDelay(elapsedMs: number): number { return 1000; } +/** The conversation this create was for has been replaced; its result must not be used. */ +class StaleConversationError extends Error { + override name = 'StaleConversationError'; +} + function describe(err: unknown): string { if (err instanceof BridgeApiError) return `${err.body.code} (HTTP ${err.status})`; if (err instanceof Error) return `${err.name}: ${err.message}`; diff --git a/apps/even-client/src/core/hud.ts b/apps/even-client/src/core/hud.ts index b719d1b..dcf5d25 100644 --- a/apps/even-client/src/core/hud.ts +++ b/apps/even-client/src/core/hud.ts @@ -93,7 +93,9 @@ export function renderHud(state: AppState, nowMs: number): HudFrame { return { body: 'Glasses disconnected.', status: 'Reconnect to continue' }; } return state.canResend - ? { body: 'No connection to the bridge.\n\nYour request has not been sent.', status: 'Tap: retry · Double-tap: discard' } + ? // Deliberately not "has not been sent": a request can be admitted even when no reply + // comes back, so the honest statement is that it is unconfirmed. + { body: 'No connection to the bridge.\n\nYour request is not confirmed yet.', status: 'Tap: retry · Double-tap: discard' } : { body: 'Connection lost.\n\nStill waiting for the answer…', status: 'Reconnecting · Double-tap: cancel' }; case 'error': diff --git a/apps/even-client/src/core/reducer.ts b/apps/even-client/src/core/reducer.ts index ee3f605..18d1207 100644 --- a/apps/even-client/src/core/reducer.ts +++ b/apps/even-client/src/core/reducer.ts @@ -38,6 +38,10 @@ export interface AppState { */ generation: number; conversationId: string | null; + /** Bumped whenever the conversation is reset; a create result from an older epoch is dropped. */ + conversationEpoch: number; + /** A new conversation has been requested and not yet confirmed. */ + creatingConversation: boolean; requestId: string | null; captureStartedAt: number | null; captureMaxSeconds: number; @@ -57,6 +61,8 @@ export const initialState: AppState = { phase: 'unpaired', generation: 0, conversationId: null, + conversationEpoch: 0, + creatingConversation: false, requestId: null, captureStartedAt: null, captureMaxSeconds: 30, @@ -83,8 +89,8 @@ export type AppEvent = | { type: 'capture_started'; generation: number; at: number } | { type: 'capture_failed'; generation: number; reason: 'mic_refused' | 'mic_stalled' | 'empty' } | { type: 'capture_limit'; generation: number } - | { type: 'conversation_created'; generation: number; conversationId: string } - | { type: 'conversation_failed'; generation: number; error: HudError } + | { type: 'conversation_created'; epoch: number; conversationId: string } + | { type: 'conversation_failed'; epoch: number; error: HudError } /** `pages` is the already-paginated plain-text answer when the result carries one. */ | { type: 'turn_update'; generation: number; result: TurnResult; pages: string[] | null } | { type: 'turn_rejected'; generation: number; error: HudError } @@ -101,7 +107,7 @@ export type Effect = | { type: 'resubmit'; generation: number; requestId: string } | { type: 'poll'; generation: number; requestId: string } | { type: 'cancel_turn'; requestId: string } - | { type: 'create_conversation'; generation: number } + | { type: 'create_conversation'; epoch: number } | { type: 'exit_dialog' }; export interface Step { @@ -153,6 +159,7 @@ export function reduce(state: AppState, event: AppEvent): Step { generation: state.generation + 1, captureMaxSeconds: event.captureMaxSeconds, conversationId: event.conversationId, + conversationEpoch: state.conversationEpoch + 1, }; if (!event.paired) return same({ ...base, phase: 'unpaired' }); if (event.resumeRequestId) { @@ -169,7 +176,12 @@ export function reduce(state: AppState, event: AppEvent): Step { case 'unpaired': { const effects: Effect[] = state.phase === 'listening' ? [{ type: 'discard_capture' }] : []; return { - state: { ...initialState, generation: state.generation + 1, captureMaxSeconds: state.captureMaxSeconds }, + state: { + ...initialState, + generation: state.generation + 1, + conversationEpoch: state.conversationEpoch + 1, + captureMaxSeconds: state.captureMaxSeconds, + }, effects, }; } @@ -238,21 +250,36 @@ export function reduce(state: AppState, event: AppEvent): Step { case 'new_conversation': { // Only from a resting state: a reset must never be mistaken for cancelling the backend. if (!IDLE.has(state.phase)) return same(state); - const generation = state.generation + 1; + // One is already on its way: a second press must not start a second create. + if (state.creatingConversation) return same(state); + const conversationEpoch = state.conversationEpoch + 1; return { - state: { ...clearTurn(state), phase: 'ready', generation, conversationId: null, notice: 'New conversation' }, - effects: [{ type: 'create_conversation', generation }], + state: { + ...clearTurn(state), + phase: 'ready', + generation: state.generation + 1, + conversationId: null, + conversationEpoch, + creatingConversation: true, + notice: 'New conversation', + }, + effects: [{ type: 'create_conversation', epoch: conversationEpoch }], }; } case 'conversation_created': { - if (event.generation !== state.generation) return same(state); - return same({ ...state, conversationId: event.conversationId }); + // Keyed to the conversation epoch, not the turn generation: the user may already have + // started a question (which bumps the generation) while the conversation was being made. + if (event.epoch !== state.conversationEpoch) return same(state); + return same({ ...state, conversationId: event.conversationId, creatingConversation: false }); } case 'conversation_failed': { - if (event.generation !== state.generation) return same(state); - return same({ ...clearTurn(state), phase: 'error', error: event.error }); + if (event.epoch !== state.conversationEpoch) return same(state); + // If a question is in flight, its own submit reports the failure; only a resting screen + // is replaced by the error. + if (!IDLE.has(state.phase)) return same({ ...state, creatingConversation: false }); + return same({ ...clearTurn(state), creatingConversation: false, phase: 'error', error: event.error }); } case 'capture_started': { diff --git a/apps/even-client/src/device/evenAdapter.ts b/apps/even-client/src/device/evenAdapter.ts index be4e812..f8ebb38 100644 --- a/apps/even-client/src/device/evenAdapter.ts +++ b/apps/even-client/src/device/evenAdapter.ts @@ -14,23 +14,14 @@ import type { DevicePort } from './port.ts'; const BODY = { id: 1, name: 'body' } as const; const STATUS = { id: 2, name: 'status' } as const; -/** A flaky BLE hop can hang a bridge call for a long time; never let one block the UI forever. */ -const CALL_TIMEOUT_MS = 8000; +/** A flaky BLE hop can hang a host call for a long time; never let one block the UI forever. */ +export const CALL_TIMEOUT_MS = 8000; -function withTimeout(promise: Promise, fallback: T): Promise { - return new Promise((resolve) => { - const timer = setTimeout(() => resolve(fallback), CALL_TIMEOUT_MS); - promise.then( - (value) => { - clearTimeout(timer); - resolve(value); - }, - () => { - clearTimeout(timer); - resolve(fallback); - }, - ); - }); +interface Bounded { + /** The caller's answer: the real result, or the fallback if the host took too long. */ + value: T; + /** True when `value` is the fallback because the host had not answered in time. */ + timedOut: boolean; } /** @@ -43,15 +34,37 @@ export class EvenDevice implements DevicePort { private pending: HudFrame | null = null; private flushing = false; private ready = false; - /** All host calls go through one queue: concurrent bridge calls are documented as unsafe. */ + /** + * All host calls go through one queue: concurrent bridge calls are documented as unsafe. + * The queue advances only when the host call has ACTUALLY settled. A caller that gives up + * waiting gets a fallback answer, but the next host call still waits its turn, so two calls + * are never in flight together and a late completion is always followed, in order, by + * whatever was queued behind it. + */ private queue: Promise = Promise.resolve(); - constructor(private readonly bridge: EvenAppBridge) {} + constructor( + private readonly bridge: EvenAppBridge, + private readonly callTimeoutMs: number = CALL_TIMEOUT_MS, + ) {} - private enqueue(call: () => Promise, fallback: T): Promise { - const next = this.queue.then(() => withTimeout(call(), fallback)); - this.queue = next.catch(() => undefined); - return next; + private enqueueBounded(call: () => Promise, fallback: T): Promise> { + // What the host really does, serialised behind every earlier call. + const settled: Promise = this.queue.then(call).catch(() => fallback); + this.queue = settled; + // What the caller sees: the same result, or the fallback after the timeout. The timer + // starts when the call is requested, so time spent queued behind a stuck call counts. + return new Promise((resolve) => { + const timer = setTimeout(() => resolve({ value: fallback, timedOut: true }), this.callTimeoutMs); + void settled.then((value) => { + clearTimeout(timer); + resolve({ value, timedOut: false }); + }); + }); + } + + private async enqueue(call: () => Promise, fallback: T): Promise { + return (await this.enqueueBounded(call, fallback)).value; } async init(frame: HudFrame): Promise { @@ -136,10 +149,21 @@ export class EvenDevice implements DevicePort { } } - startMic(): Promise { - return this.enqueue(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false); + async startMic(): Promise { + const started = await this.enqueueBounded(() => this.bridge.audioControl(true, AudioInputSource.Glasses), false); + if (started.timedOut) { + // The caller is being told "the microphone did not open" and will not stop it. But the + // host may still open it later. Queue a stop now: it runs strictly after the pending + // start settles, so whatever the start ends up doing, the microphone finishes closed. + void this.enqueueBounded(() => this.bridge.audioControl(false), false); + } + return started.value; } + /** + * Always sends the stop, even if a start is still pending or was never confirmed: closing a + * closed microphone is harmless, leaving one open is not. Queued behind any pending start. + */ async stopMic(): Promise { await this.enqueue(() => this.bridge.audioControl(false), false); } diff --git a/apps/even-client/src/net/bridgeClient.ts b/apps/even-client/src/net/bridgeClient.ts index a2a2f69..98c0cf3 100644 --- a/apps/even-client/src/net/bridgeClient.ts +++ b/apps/even-client/src/net/bridgeClient.ts @@ -35,10 +35,30 @@ export interface BridgeClientOptions { fetchImpl?: typeof fetch; } +/** + * Hosts on which plain HTTP is tolerated: this machine only, for the simulator and the + * browser preview. Exact matches, so `127.0.0.1.example.com` or `localhost.example.com` + * do not qualify, and neither does any LAN or public address. + */ +export function isLoopbackHost(hostname: string): boolean { + return hostname === 'localhost' || hostname === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname); +} + +/** + * The device credential and the user's recordings travel to this URL, so it must be HTTPS. + * The one exception is HTTP to loopback, which never leaves the machine. + */ export function normalizeBridgeUrl(raw: string): string { - const url = new URL(raw.trim()); - if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('Bridge URL must start with https://'); - return url.origin + url.pathname.replace(/\/+$/, ''); + let url: URL; + try { + url = new URL(raw.trim()); + } catch { + throw new Error('Enter the bridge address as a full URL, for example https://bridge.example'); + } + if (url.username || url.password) throw new Error('The bridge address must not contain a user name or password.'); + if (url.protocol === 'https:') return url.origin + url.pathname.replace(/\/+$/, ''); + if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return url.origin + url.pathname.replace(/\/+$/, ''); + throw new Error('The bridge address must start with https://'); } export class BridgeClient { diff --git a/apps/even-client/test/reducer.test.ts b/apps/even-client/test/reducer.test.ts index 4073611..57091a3 100644 --- a/apps/even-client/test/reducer.test.ts +++ b/apps/even-client/test/reducer.test.ts @@ -329,11 +329,37 @@ describe('pairing, restore and conversations', () => { const s = ready(); const step = reduce(s, { type: 'new_conversation' }); expect(step.state.conversationId).toBeNull(); - expect(step.effects).toEqual([{ type: 'create_conversation', generation: step.state.generation }]); - const stale = reduce(step.state, { type: 'conversation_created', generation: s.generation, conversationId: 'old' }); + expect(step.state.creatingConversation).toBe(true); + expect(step.effects).toEqual([{ type: 'create_conversation', epoch: step.state.conversationEpoch }]); + const stale = reduce(step.state, { type: 'conversation_created', epoch: s.conversationEpoch, conversationId: 'old' }); expect(stale.state.conversationId).toBeNull(); - const fresh = reduce(step.state, { type: 'conversation_created', generation: step.state.generation, conversationId: 'new' }); + const fresh = reduce(step.state, { type: 'conversation_created', epoch: step.state.conversationEpoch, conversationId: 'new' }); expect(fresh.state.conversationId).toBe('new'); + expect(fresh.state.creatingConversation).toBe(false); + }); + + it('a second "new conversation" while one is being created starts nothing (CODY-009)', () => { + const first = reduce(ready(), { type: 'new_conversation' }); + const second = reduce(first.state, { type: 'new_conversation' }); + expect(second.state).toBe(first.state); + expect(second.effects).toEqual([]); + }); + + it('the conversation result is accepted even after a question has started, because it is keyed to the conversation, not the turn (CODY-009)', () => { + const created = reduce(ready(), { type: 'new_conversation' }); + const asking = reduce(created.state, { type: 'submit_text', freshId: ID1, text: 'hi' }); + expect(asking.state.generation).toBeGreaterThan(created.state.generation); + const done = reduce(asking.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'new' }); + expect(done.state.conversationId).toBe('new'); + expect(done.state.phase).toBe('thinking'); + }); + + it('a conversation result from before a re-pair or a later reset is dropped', () => { + const created = reduce(ready(), { type: 'new_conversation' }); + const repaired = reduce(created.state, { type: 'init', paired: true, conversationId: null, captureMaxSeconds: 30, resumeRequestId: null }); + expect(reduce(repaired.state, { type: 'conversation_created', epoch: created.state.conversationEpoch, conversationId: 'x' }).state).toBe(repaired.state); + const failedLate = reduce(repaired.state, { type: 'conversation_failed', epoch: created.state.conversationEpoch, error: { code: 'x', hud: 'x', retryable: false } }); + expect(failedLate.state).toBe(repaired.state); }); it('unpairing while listening closes the microphone', () => { diff --git a/deploy/bridge.env.example b/deploy/bridge.env.example index 3120fdd..0f838c8 100644 --- a/deploy/bridge.env.example +++ b/deploy/bridge.env.example @@ -11,7 +11,9 @@ HERMEVEN_DB_PATH=/var/lib/hermeven/hermeven.sqlite # Read the real value from the phone page: Diagnostics -> "Page origin". HERMEVEN_ALLOWED_ORIGINS= -# Built-in speech-to-text (the default). Model files are downloaded once into this directory. +# 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 +# npm run bridge:cli -- fetch-model STT_PROVIDER=builtin -STT_MODEL=onnx-community/whisper-base -STT_CACHE_DIR=/var/lib/hermeven/models +STT_MODEL=whisper-base +STT_MODEL_DIR=/opt/hermeven/models diff --git a/deploy/hermeven-bridge.service b/deploy/hermeven-bridge.service index 276f510..45ddf7c 100644 --- a/deploy/hermeven-bridge.service +++ b/deploy/hermeven-bridge.service @@ -20,11 +20,16 @@ RestartSec=3 TimeoutStopSec=20 # Hardening +# Everything the service creates is owner-only (database, WAL, SHM). +UMask=0077 +StateDirectory=hermeven +StateDirectoryMode=0700 NoNewPrivileges=true PrivateTmp=true ProtectSystem=strict ProtectHome=true ReadWritePaths=/var/lib/hermeven +# The verified speech model is read-only to the service: it lives under /opt (see ProtectSystem). ProtectKernelTunables=true ProtectControlGroups=true RestrictSUIDSGID=true diff --git a/docs/bridge-api.md b/docs/bridge-api.md index f39a986..5cd1559 100644 --- a/docs/bridge-api.md +++ b/docs/bridge-api.md @@ -95,7 +95,7 @@ Defined in `packages/contracts/src/errors.ts`. Codes are stable; a code is never |---|---|---| | `invalid_request`, `unsupported_schema_version`, `unsupported_media`, `payload_too_large` | The request was malformed. | no | | `unauthorized`, `credential_expired`, `forbidden` | Credential missing, revoked or expired. | no | -| `pairing_invalid`, `pairing_locked` | Wrong code; too many wrong codes. | no | +| `pairing_invalid` | The pairing code was wrong, expired or already used. The answer is identical in all three cases. (`pairing_locked` is reserved and no longer returned.) | no | | `not_found` | Unknown, or belongs to another device. | no | | `request_id_conflict` | Request id reused for different content. | no | | `conversation_busy` | A turn is still running in this conversation. | yes | diff --git a/docs/compatibility.md b/docs/compatibility.md index d350f0d..26d5464 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -40,7 +40,7 @@ exactly in `apps/even-client/package.json`. | Fastify / @fastify/cors | 5.12.8 / 11.4.3 | | better-sqlite3 | 13.2.0 | | @huggingface/transformers (ONNX Runtime 1.30.0) | 4.3.2 | -| Speech model | `onnx-community/whisper-base`, `q8` | +| Speech model | `onnx-community/whisper-base` at commit `27a07b4b52b3a4c5886134bb4320e93e1a4bbc7c`, `q8`; alternative `onnx-community/whisper-tiny` at `ff4177021cc41f7db950912b73ea4fdf7d01d8e7`. Per-file SHA-256 in `services/bridge/models/`. | | @sinclair/typebox | 0.34.52 | | pino | 10.4.0 | diff --git a/docs/deploy-droplet.md b/docs/deploy-droplet.md index 9895cf6..d7d06aa 100644 --- a/docs/deploy-droplet.md +++ b/docs/deploy-droplet.md @@ -29,7 +29,7 @@ weights: | Memory after transcribing | about 0.8 GB | | 11 s of speech, process pinned to one core | about 1.7 s | | Same, `whisper-tiny` | about 1.2 s, about 0.6 GB | -| Model download on first start | about 80 MB (`base`), cached afterwards | +| Model download at deploy time (`fetch-model`) | 79 MB (`whisper-base`), 4 s on the desktop's connection | | Longest pause of the bridge's event loop while transcribing | 3 ms (the model runs in a worker thread) | Pinning to one core made no difference to speed, so extra cores will not help; a single droplet @@ -41,8 +41,8 @@ Suggested starting point, to be confirmed by measuring on the droplet: **2 GB RA for the bridge alone. 1 GB is likely too tight alongside the OS. If Hermes shares the droplet, add whatever Hermes needs; that was not measured. -If transcription is too slow on the droplet, set `STT_MODEL=onnx-community/whisper-tiny` -(faster, less accurate) or, for English only, `onnx-community/whisper-base.en`. +If transcription is too slow on the droplet, set `STT_MODEL=whisper-tiny` (faster, less +accurate) and run `fetch-model` again. ## Steps @@ -59,11 +59,22 @@ If transcription is too slow on the droplet, set `STT_MODEL=onnx-community/whisp needed: the bridge runs through `tsx`.) 5. **Configuration.** Copy `deploy/bridge.env.example` to `/etc/hermeven/bridge.env`, fill it in, `chmod 600`, `chown hermeven`. +5a. **Speech model.** As root (not the service user), fetch and verify the pinned model into a + directory the service can read but not write: + ```sh + HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env npm --prefix /opt/hermeven run bridge:cli -- fetch-model + HERMEVEN_ENV_FILE=/etc/hermeven/bridge.env npm --prefix /opt/hermeven run bridge:cli -- verify-model + ``` + Every file is checked against the SHA-256 committed in `services/bridge/models/`. The running + service never downloads anything: it re-verifies these files each time it loads the model and + refuses to load if one is missing or different. This is the only step that needs outbound + access to huggingface.co. 6. **Hermes.** Enable its API server with a key, bound to `127.0.0.1`. Use a read-only or test profile first. 7. **Service.** Copy `deploy/hermeven-bridge.service` to `/etc/systemd/system/`, then `systemctl daemon-reload && systemctl enable --now hermeven-bridge`. Watch - `journalctl -u hermeven-bridge -f` for `stt.ready` (the first start downloads the model). + `journalctl -u hermeven-bridge -f` for `stt.ready`. `stt.load_failed` with `reason: missing` + or `mismatch` means step 5a was skipped or the files changed. 8. **TLS.** Put `deploy/Caddyfile.example` at `/etc/caddy/Caddyfile` with your hostname, reload Caddy, then check `curl https://bridge.example.com/healthz`. 9. **App build.** On your own machine: @@ -80,6 +91,7 @@ If transcription is too slow on the droplet, set `STT_MODEL=onnx-community/whisp - Time from `stt.loading` to `stt.ready`, and memory of the service after a few questions. - `transcribe_ms` for a few real questions (the phone page shows it per question). - That `curl http://:8787/healthz` from outside **fails** (bridge not exposed). +- `stat -c '%a' /var/lib/hermeven /var/lib/hermeven/hermeven.sqlite*` shows `700` and `600`. - That the unit's hardening options do not stop the model loading. `ProtectSystem=strict` and `MemoryMax` in particular are untested with ONNX Runtime. diff --git a/docs/feasibility.md b/docs/feasibility.md index 3030b1f..124e29a 100644 --- a/docs/feasibility.md +++ b/docs/feasibility.md @@ -101,7 +101,8 @@ a suspended stream. The microphone is never reopened without a new tap. Decision (updated after Dan asked for speech-to-text to be built in and to run on a droplet): the bridge runs OpenAI's Whisper model itself, on the CPU, through ONNX Runtime -(`@huggingface/transformers` 4.3.2, model `onnx-community/whisper-base`, 8-bit weights). No +(`@huggingface/transformers` 4.3.2, model `onnx-community/whisper-base` pinned to a commit and +verified by SHA-256, 8-bit weights; fetched ahead of time, never downloaded by the running bridge). No provider account, and recordings never leave the bridge host. An adapter for any external OpenAI-compatible transcription endpoint remains as an alternative. diff --git a/docs/handoff/2026-11-18-cody-round-3.md b/docs/handoff/2026-11-18-cody-round-3.md new file mode 100644 index 0000000..b71ea48 --- /dev/null +++ b/docs/handoff/2026-11-18-cody-round-3.md @@ -0,0 +1,74 @@ +# Handoff for Cody, Round 3 + +From: Claude (implementation). Date: 2026-11-18. + +**Not reviewed.** Cody's Round 2 verdict (NEEDS CHANGES) applies to `3d5691d` only. Nothing below +is a claim that any finding is closed; that is Cody's call on the new SHA. + +| Item | Value | +|---|---| +| Repository | `git@git.xylo.gg:Xylo-Digital/hermeven.git` | +| Branch | `cody/slice-1-review` | +| Reviewed in Round 2 | `3d5691dfa3e3015f7d0e4f760de60c588ffea0dc` | +| `main` | `0c9dcd864f16782097471e5bbf57cbd701c26616` (unchanged; nothing merged) | +| New head for Round 3 | the tip of `cody/slice-1-review` after this push; the exact SHA is in the push report, since a file cannot contain its own commit id | + +## What was done for each finding + +| Finding | Change | Where | +|---|---|---| +| CODY-001 | Bridge URL must be HTTPS; HTTP only for `localhost`, `127.x.x.x`, `[::1]` (exact match). Same rule in the manifest generator, which exits 1. URLs with embedded credentials are refused. | `net/bridgeClient.ts`, `scripts/write-manifest.mjs` | +| CODY-002 | The host-call queue advances only when the SDK call has actually settled; the caller's timeout is a separate, bounded answer. A start that times out queues a stop behind it. The controller stops unconditionally when a capture was abandoned while opening. | `device/evenAdapter.ts`, `core/controller.ts` | +| CODY-003 | The request id is stored before the first submit and cleared only on a terminal result, a definite rejection, or the bridge confirming it has no such turn. An undelivered cancel is remembered and retried at next start. The HUD says "not confirmed yet" instead of "has not been sent". | `core/controller.ts`, `core/hud.ts` | +| CODY-004 | `Devices.revoke` flags every non-terminal turn of the device in the same transaction that revokes it. `TurnEngine.revokeDevice` (HTTP path) applies the flags at once; a one-second sweep applies flags written by the CLI process. Workers abort transcription and ask Hermes to stop. | `devices.ts`, `turns.ts`, `server.ts`, `app.ts` | +| CODY-005 | Manifests pin a 40-character commit id and a SHA-256 and size per file (`services/bridge/models/`). `fetch-model` downloads and verifies; the worker verifies on every load, disables remote models, and loads only from the store. No unpinned configuration exists. | `stt/modelStore.mjs`, `stt/whisperWorker.mjs`, `config.ts`, `cli.ts`, `deploy/*` | +| CODY-006 | Database file is created 0600 before SQLite opens it, in a 0700 directory; WAL and SHM inherit. Unit sets `UMask=0077` and a 0700 state directory. | `db.ts`, `deploy/hermeven-bridge.service`, `docs/deploy-droplet.md` | +| CODY-007 | `credential_expired` is handled like `unauthorized` on every runtime path (submit, poll, cancel, status refresh, renew, conversation create). | `core/controller.ts` | +| CODY-008 | `approval_started_at` is written once, when the approval is first seen (it was previously rewritten on every poll). The agent deadline is stored in a new column and updated in the same write that ends an approval wait. Both are restored after a restart. Schema migration v2. | `turns.ts`, `db.ts` | +| CODY-009 | One in-flight create per conversation epoch, shared by the menu action and the lazy first-turn path; creates are sent strictly in sequence; a result for a replaced conversation is dropped before persistence. A second "new conversation" while one is pending does nothing. | `core/controller.ts`, `core/reducer.ts` | +| CODY-010 | Wrong guesses no longer count against the outstanding code. Brute force is bounded by 49 bits of entropy, a 5-minute lifetime and the per-address limit. Wrong, expired and used codes return the same response. `pairing_locked` is reserved and no longer returned. | `devices.ts`, `server.ts` | + +The tests for each are listed in `docs/test-evidence.md` under "Round 3". + +## Check results + +| Check | Result | +|---|---| +| `npm run typecheck` | exit 0 | +| `npm test` | 182 passed, 0 failed | +| `npm run client:build` | built | +| `npm run test:real-stt` | 11 passed, 0 failed | +| `npm run test:real-hermes` | 9 passed, 0 failed | +| `npm run test:simulator` | 6 passed, 0 failed | +| `git diff --check` | clean | + +No check was omitted. + +## Decisions made while fixing, for Cody to judge + +- **CODY-010 uses entropy and a per-address limit, with no global cap.** A global cap would let a + flood block the owner's own pairing, which is the same denial of service by another route. The + arithmetic is in `docs/security.md`. +- **CODY-009 keys the result check to a conversation epoch, not the turn generation.** A question + asked while the conversation is being created bumps the turn generation; a strict generation + check would throw away the conversation that question is waiting for. +- **CODY-005 removes the automatic first-start download entirely**, including for development. +- **CODY-004 through the CLI is honoured within the sweep interval (1 s)**, not instantly, because + the CLI is a separate process with no channel to the running bridge other than the database. +- **CODY-003: after a restart, a voice question that never reached the bridge cannot be resent**, + because the recording lived only in memory. The user is told to ask again, and only after the + bridge has confirmed it has no record of the request. + +## Things the author is unsure about + +- `whisperWorker.mjs` and `modelStore.mjs` are plain JavaScript, typed only through a hand-written + declaration file. +- Between verifying the model files and loading them there is a short window; a read-only model + directory closes it, and that is a deployment setting, not something the code enforces. +- The CODY-006 test observes permissions at each `chmod` call, not continuously. +- A device revoked through the CLI while its turn is still being submitted to Hermes relies on the + poll loop noticing the flag after admission. + +## Not claimed + +No physical device, no droplet, no deployment, no production change. Nothing merged to `main`. diff --git a/docs/security.md b/docs/security.md index fd1561e..cd9a597 100644 --- a/docs/security.md +++ b/docs/security.md @@ -24,8 +24,9 @@ devices. Not reviewed by anyone but its author yet; see `docs/handoff/`. | Threat | Control | Tested | |---|---|---| | Hermes key or STT key leaks through the client | Neither is in the client code, bundle or any API response. The production bundle was searched for them. | yes | -| Stolen device credential | Scoped to one device and one profile; cannot name a Hermes session; expires in 7 days; pairing ends at 90 days; revocable from the phone or the bridge host; stored on the bridge as SHA-256 only. | yes | -| Guessing a pairing code | 10 characters from a 31-symbol alphabet (about 49 bits); valid 5 minutes; single use; a new code voids the old one; 5 wrong guesses burn every outstanding code; 5 attempts per minute per client address. | yes | +| Stolen device credential | Scoped to one device and one profile; cannot name a Hermes session; expires in 7 days; pairing ends at 90 days; revocable from the phone or the bridge host; stored on the bridge as SHA-256 only. Revoking also cancels every turn the device has in flight and asks Hermes to stop it, from the HTTP route and from the CLI alike. | yes | +| Credential or recordings sent in clear text | The app refuses any bridge address that is not HTTPS, except HTTP to loopback; the manifest generator refuses to package one. | yes | +| Guessing a pairing code | 10 characters from a 31-symbol alphabet (8.2 x 10^14 values, about 49 bits); valid 5 minutes; single use; a new code voids the old one; 5 attempts per minute per client address. At that rate one address gets 25 guesses per code: a 3 in 10^14 chance. Even a million guesses in the 5 minutes would be about 1 in 10^9. Wrong guesses do not consume the code, so nobody can void the owner's code by guessing; every failure returns the same answer. | yes | | Client picks someone else's agent session or profile | Requests with unknown fields are rejected. The Hermes session id is generated by the bridge and never leaves it. A device is valid only for the profile it was paired under. | yes | | One device reads or cancels another's turn | Every lookup is scoped to the authenticated device; a foreign id answers 404, not 403. | yes | | Duplicate or replayed submit runs a tool twice | Client request id is the bridge's idempotency key; the bridge forwards a derived key to Hermes. | yes, including against real Hermes | @@ -34,6 +35,8 @@ devices. Not reviewed by anyone but its author yet; see `docs/handoff/`. | Request flooding | Per-device turn limit, per-address pairing limit, general per-device limit. | yes | | Cross-origin browser abuse | CORS allows only exact configured origins and sends no credentials mode. CORS is not treated as authentication: every route still needs the bearer credential. | yes | | Secrets or content in logs | Logs carry ids, states, codes and timings. Request logging is off, a redaction list backs it up, and Hermes's own diagnostic text is never relayed or logged. | yes | +| Substituted speech-model files | The model is pinned to a commit id with a SHA-256 for every file. Files are fetched ahead of time and verified; the bridge re-verifies on every load, never downloads at run time, and reads from a directory that can be read-only. There is no unpinned mode. | yes, including with no network at all | +| State files readable by other users | The database is created owner-only before SQLite opens it (so its WAL and SHM files inherit that), in a 0700 directory; the systemd unit sets `UMask=0077`. | yes, under umask 0022 | | Recordings retained | Audio exists only in memory for the length of one transcription call and is never written to disk by the bridge. | by construction; not independently audited | | Agent approves its own privileged action | The bridge never calls Hermes's approval endpoint. | yes | | Markup injection from an agent answer into the phone page | The page is built with `textContent` only. | by construction | @@ -48,14 +51,19 @@ Stated so they are not mistaken for protections. encrypted, and the public SDK offers nothing better. The mitigation is that the credential is narrow, expiring and revocable, not that it is safe at rest. Anyone with the unlocked phone, or with developer access to the app's storage, can use it until it is revoked. +1a. **Pairing brute force is bounded by entropy and a per-address limit, not by a lockout.** A + distributed attacker is limited only by how fast the bridge answers. That is still far short + of a useful chance (see the table), but it is a deliberate trade against letting anyone + cancel the owner's code. 2. **Renewal needs only the current token.** A thief who renews before the owner notices keeps access until revoked or until the 90-day pairing lifetime ends. 3. **Audio leaves the phone for the bridge host.** With the default built-in speech model it goes no further. With `STT_PROVIDER=openai-compatible` it is sent to that provider, whose retention is outside our control. -3a. **The built-in model's files are downloaded from the Hugging Face hub on first start** and - are not pinned to a revision or checked against a known hash. A compromised hub account or - path could serve different weights. Pinning a revision is a follow-up. +3a. **The pinned hashes are only as trustworthy as the moment they were recorded.** They were + taken from the hub on 2026-11-18. They prove the files have not changed since; they do not + prove the files were benign then. The verified-then-loaded sequence also has a small window + between check and use, which a read-only model directory closes. 3b. **The speech model runs in a worker thread of the bridge process**, not a separate sandboxed process. It no longer stalls the bridge (measured 3 ms), but a crash inside the native runtime could still take the bridge down; systemd restarts it and in-flight turns are diff --git a/docs/setup.md b/docs/setup.md index 841cad7..2b47413 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -1,14 +1,18 @@ # Setup Requirements: Node.js 22.13 or later and a Hermes install with the API server enabled. Speech -recognition is built into the bridge (Whisper on the CPU, about 0.8 GB of memory); the first -start downloads about 80 MB of model files into `data/models`. +recognition is built into the bridge (Whisper on the CPU, about 0.8 GB of memory). The model is +pinned and verified, and the bridge never downloads it by itself: fetch it once (79 MB). ```sh npm ci cp .env.example .env # then edit: HERMES_API_KEY at minimum +npm run bridge:cli -- fetch-model # downloads and verifies the pinned speech model ``` +The bridge address entered in the app must be `https://`. Plain `http://` is accepted only for +this machine (`localhost`, `127.x.x.x`), which is what the simulator and browser preview use. + ## 1. Hermes Enable the API server for the profile you want to use (see Hermes's "API Server" docs): diff --git a/docs/test-evidence.md b/docs/test-evidence.md index d00f549..429f914 100644 --- a/docs/test-evidence.md +++ b/docs/test-evidence.md @@ -253,3 +253,62 @@ unauthenticated `/v1/device` answered 401, `bridge:cli -- pair` printed a code, - Selecting a contextual-menu item. The checklist for the hardware items is `docs/device-test-plan.md`. + +## Round 3: after Cody's review (2026-11-18) + +Cody reviewed `3d5691d` and returned NEEDS CHANGES with ten findings. This section records what +was run after the fixes. Everything above this heading describes the code before them; where a +number differs, this section is the current one. + +``` +$ npm run typecheck exit 0 +$ npm test Test Files 10 passed (10) Tests 182 passed (182) (4 consecutive runs) +$ npm run client:build built; the development pairing hook is absent from the bundle +$ npm run test:real-stt Tests 11 passed (11) +$ npm run test:real-hermes Tests 9 passed (9) +$ npm run test:simulator Tests 6 passed (6) (3 consecutive runs) +$ git diff --check clean +``` + +No check was omitted. The offline speech test needs unprivileged network namespaces +(`unshare -rn`); they were available here and the test ran. Where they are not, that test prints +"OFFLINE CHECK NOT RUN" rather than passing silently. + +### Regression tests added, by finding + +| Finding | Test (file) | What it proves | +|---|---|---| +| CODY-001 | `tests/integration/clientSecurity.test.ts` | 15 public, private-LAN and look-alike HTTP addresses rejected; HTTPS accepted; HTTP accepted only for `localhost`, `127.x.x.x`, `[::1]`; the HTTP client refuses a remote HTTP base URL; manifest generation exits 1 and writes nothing for remote HTTP | +| CODY-002 | same file, fake timers and a host whose calls settle on command | Start times out, host opens the microphone late: a stop follows and the microphone ends closed; at most one host call in flight throughout; stop requested during a pending start waits its turn; calls queued behind a stuck call are sent one at a time | +| CODY-003 | `tests/integration/client-bridge.test.ts` | Every reply dropped after the bridge admitted the turn, then a client restart: one Hermes execution for that request, re-attached under the same request id, the HUD never said "not sent"; a request that truly never arrived is reported only after the bridge confirms it has no record; an undeliverable cancel is retried on the next start | +| CODY-004 | `tests/integration/bridge.test.ts` | Revoking over HTTP during a hanging run: one stop request reaches Hermes, the turn settles as cancelled, every later request is 401; the same through the CLI path (database only); revocation during transcription aborts it within 250 ms, in-process and via the sweep; another device's turn is untouched | +| CODY-005 | `services/bridge/test/modelStore.test.ts`, `tests/real-stt/realStt.test.ts` | Branch, tag and short revisions refused; unknown model without a manifest refused; a hub serving different bytes fails the fetch and leaves nothing behind; a changed or missing file refuses to load, with no network request; real pinned artifacts fetched from the real hub and verified; one flipped byte in the real model refuses to load; transcription from a read-only store; transcription inside a network namespace with no interfaces | +| CODY-006 | `services/bridge/test/units.test.ts` | In a child process under umask 0022: directory 0700, database, WAL and SHM 0600, and none of the three was group- or world-accessible at any point observed during creation | +| CODY-007 | `tests/integration/client-bridge.test.ts` | Credential expires during a live session: asking, waiting for an answer, status refresh, renew and new conversation each clear the stored pairing and return to the pairing screen; pairing again works | +| CODY-008 | `tests/integration/bridge.test.ts` | Restart before the original agent deadline: approval timeout still fires 700 ms after the approval was first seen, not after the restart; restart after the original agent deadline: still classified `approval_timeout`; approved after a restart: the paused deadline is stored and survives a second restart; a run that never finishes afterwards ends as `agent_timeout` | +| CODY-009 | `tests/integration/client-bridge.test.ts`, `apps/even-client/test/reducer.test.ts` | "New conversation" twice plus an immediate question with the reply delayed: one create, one stored id equal to the bridge's active conversation, the question succeeds; cancel-and-ask-again during a pending lazy create: one create; a reset during a pending create with the first reply arriving late: its result is dropped before persistence, the second create is not sent until the first settles, app and bridge agree | +| CODY-010 | `tests/integration/bridge.test.ts` | 40 wrong guesses, then the real code still pairs; every failure (wrong, expired, used) is byte-identical; a client is cut off after its 5 attempts per minute | + +### Did the new tests have teeth? + +Each fix was removed or broken in turn, 20 ways, and the default suite re-run. 16 were caught +at once. Two more exposed missing coverage (the CLI-path sweep during transcription; a database +file created loose and tightened a moment later); tests were added and both are now caught. +The remaining two are redundant safeguards whose removal changes nothing observable: the +directory `chmod` after `mkdir` with mode 0700 (a umask can only remove permissions), and the +final permission pass after a file that was already created owner-only. + +### Real deployment sequence, run by hand on the development desktop + +`verify-model` on an empty store exited 1 ("missing"). The bridge started without the model, +answered `/healthz`, and logged `stt.load_failed` with `reason: missing` and the command to run. +`fetch-model` downloaded 7 files (79 MB) from huggingface.co at the pinned commit in 4 s and +verified them. `verify-model` then exited 0, and the bridge logged `stt.ready` in 1.1 s. The +state directory was 700 and the database, WAL and SHM files 600. + +This was not a droplet. `deploy/` and `docs/deploy-droplet.md` remain unrun. + +### Still not tested + +Unchanged from the list above: no physical G2, no audio from the glasses, no real model or tools +behind Hermes, no approval prompt from a real Hermes, no droplet, no HTTPS termination. diff --git a/packages/contracts/src/errors.ts b/packages/contracts/src/errors.ts index f4fed6e..c09514e 100644 --- a/packages/contracts/src/errors.ts +++ b/packages/contracts/src/errors.ts @@ -19,6 +19,7 @@ export const ERROR_CODES = { unsupported_media: { http: 415, retryable: false }, rate_limited: { http: 429, retryable: true }, pairing_invalid: { http: 401, retryable: false }, + /** Reserved. No longer returned: every pairing failure is `pairing_invalid` (see docs/security.md). */ pairing_locked: { http: 429, retryable: false }, internal: { http: 500, retryable: false }, // turn outcomes (carried in TurnResult.error, HTTP status of the GET is still 200) diff --git a/services/bridge/models/whisper-base.json b/services/bridge/models/whisper-base.json new file mode 100644 index 0000000..fac8536 --- /dev/null +++ b/services/bridge/models/whisper-base.json @@ -0,0 +1,43 @@ +{ + "name": "whisper-base", + "model": "onnx-community/whisper-base", + "revision": "27a07b4b52b3a4c5886134bb4320e93e1a4bbc7c", + "dtype": "q8", + "files": [ + { + "path": "config.json", + "sha256": "f4d0608f7d918166da7edb3e188de5ef1bfe70d9802e785d271fd88111e9cf4b", + "bytes": 2243 + }, + { + "path": "generation_config.json", + "sha256": "61070cf8de25b1e9256e8e102ded49d8d24a8369ed36ef84fdf21549e68125a0", + "bytes": 3832 + }, + { + "path": "preprocessor_config.json", + "sha256": "a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d", + "bytes": 339 + }, + { + "path": "tokenizer.json", + "sha256": "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566", + "bytes": 2480466 + }, + { + "path": "tokenizer_config.json", + "sha256": "2e036e4dbacfdeb7242c7d4ec4149f4a16e86026048f94d1637e3a8ee9c6a573", + "bytes": 282682 + }, + { + "path": "onnx/encoder_model_quantized.onnx", + "sha256": "5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46", + "bytes": 23201314 + }, + { + "path": "onnx/decoder_model_merged_quantized.onnx", + "sha256": "fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b", + "bytes": 53693315 + } + ] +} diff --git a/services/bridge/models/whisper-tiny.json b/services/bridge/models/whisper-tiny.json new file mode 100644 index 0000000..cc200c5 --- /dev/null +++ b/services/bridge/models/whisper-tiny.json @@ -0,0 +1,43 @@ +{ + "name": "whisper-tiny", + "model": "onnx-community/whisper-tiny", + "revision": "ff4177021cc41f7db950912b73ea4fdf7d01d8e7", + "dtype": "q8", + "files": [ + { + "path": "config.json", + "sha256": "46aeea0a406afbeb563fc8e59ca10609203df4299af6a83f73752fef369efd2d", + "bytes": 2243 + }, + { + "path": "generation_config.json", + "sha256": "f5c67e5a4f7102f8cb4d058bc95da276bbc19eeec997267c3bb0f25ef68facd1", + "bytes": 3772 + }, + { + "path": "preprocessor_config.json", + "sha256": "a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d", + "bytes": 339 + }, + { + "path": "tokenizer.json", + "sha256": "27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566", + "bytes": 2480466 + }, + { + "path": "tokenizer_config.json", + "sha256": "2a4c4281cf9f51ac6ccc406fdc711a087afe6530f671fa7b80953edc498275ce", + "bytes": 282683 + }, + { + "path": "onnx/encoder_model_quantized.onnx", + "sha256": "2af4a414ca47aa30f61246017e5fe82b0a8d229281d1255ba666a2a7f6b84d19", + "bytes": 10124990 + }, + { + "path": "onnx/decoder_model_merged_quantized.onnx", + "sha256": "25e807a962b6349356d0ea5d0dfe530b7e5bf0e2a484aeca0359d03143faddd3", + "bytes": 30719241 + } + ] +} diff --git a/services/bridge/src/app.ts b/services/bridge/src/app.ts index ada1249..74f91b1 100644 --- a/services/bridge/src/app.ts +++ b/services/bridge/src/app.ts @@ -38,14 +38,14 @@ export function sttFromConfig(config: BridgeConfig): SttAdapter { return new OpenAiCompatibleStt({ baseUrl: config.stt.baseUrl, apiKey: config.stt.apiKey, model: config.stt.model }); } if (config.stt.provider === 'builtin') { - return new BuiltinWhisperStt({ model: config.stt.model, dtype: config.stt.dtype, cacheDir: config.stt.cacheDir }); + return new BuiltinWhisperStt({ manifest: config.stt.manifest!, modelDir: config.stt.modelDir }); } return new NoSttAdapter(); } export async function createBridge( config: BridgeConfig, - overrides: { hermes?: HermesAdapter; stt?: SttAdapter; timing?: EngineTiming; logger?: object | boolean } = {}, + overrides: { hermes?: HermesAdapter; stt?: SttAdapter; timing?: EngineTiming; logger?: object | boolean; cancelSweepMs?: number } = {}, ): Promise { const db = openDb(config.dbPath); const hermes = @@ -65,13 +65,16 @@ export async function createBridge( ? (given as Logger) : pino(given as object) : pino({ level: 'silent' }); - const engine = new TurnEngine({ db, config, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing }); + const engine = new TurnEngine({ db, config, devices, hermes, stt, log: logger as unknown as EngineLog, timing: overrides.timing }); const app = await buildServer({ config, devices, hermes, stt, engine, logger }); engine.recover(); engine.purgeExpired(); const purge = setInterval(() => engine.purgeExpired(), 60_000); purge.unref(); + // Picks up revocations made by the operator CLI, which writes to the database directly. + const cancelSweep = setInterval(() => engine.applyCancelFlags(), overrides.cancelSweepMs ?? 1000); + cancelSweep.unref(); return { app, @@ -81,6 +84,7 @@ export async function createBridge( engine, async close() { clearInterval(purge); + clearInterval(cancelSweep); await app.close(); await engine.shutdown(); await stt.close?.(); diff --git a/services/bridge/src/cli.ts b/services/bridge/src/cli.ts index 1934d88..3123243 100644 --- a/services/bridge/src/cli.ts +++ b/services/bridge/src/cli.ts @@ -2,6 +2,7 @@ import { ConfigError, loadConfig } from './config.ts'; import { openDb } from './db.ts'; import { Devices } from './devices.ts'; import { loadEnvFile } from './env.ts'; +import { fetchModel, verifyModel } from './stt/modelStore.mjs'; /** * Operator CLI. It talks to the SQLite file directly, so there is no admin @@ -15,17 +16,45 @@ function usage(): never { ' pair Print a single-use pairing code for one new device', ' devices List paired devices', ' revoke Revoke a device credential immediately', + ' fetch-model Download the pinned speech model and verify every file', + ' verify-model Check the speech model on disk against its pinned hashes', ].join('\n'), ); process.exit(2); } -function main(): void { +async function main(): Promise { loadEnvFile(); const config = loadConfig(); + const [command, arg] = process.argv.slice(2); + + // Model commands run at deploy time, possibly as a different user from the service, and + // must not create or touch the database. + if (command === 'fetch-model' || command === 'verify-model') { + const manifest = config.stt.manifest; + if (!manifest) { + console.log('STT_PROVIDER is not "builtin": there is no speech model to manage.'); + return; + } + console.log(`${manifest.model} at ${manifest.revision} (${manifest.dtype}) in ${config.stt.modelDir}`); + if (command === 'fetch-model') { + const result = await fetchModel(config.stt.modelDir, manifest, { + onFile: (path, bytes) => console.log(` fetched ${path} (${bytes} bytes)`), + }); + console.log(`Verified ${result.verified} file(s); downloaded ${result.downloaded}.`); + return; + } + const check = await verifyModel(config.stt.modelDir, manifest); + if (!check.ok) { + console.error(`Verification FAILED: ${check.reason} ${check.path}`); + process.exit(1); + } + console.log(`Verified ${manifest.files.length} file(s).`); + return; + } + const db = openDb(config.dbPath); const devices = new Devices(db, config); - const [command, arg] = process.argv.slice(2); switch (command) { case 'pair': { @@ -62,9 +91,7 @@ function main(): void { db.close(); } -try { - main(); -} catch (err) { - console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err); +main().catch((err: unknown) => { + console.error(err instanceof ConfigError ? `Configuration error: ${err.message}` : err instanceof Error ? err.message : err); process.exit(1); -} +}); diff --git a/services/bridge/src/config.ts b/services/bridge/src/config.ts index b6edbfe..a1f6b52 100644 --- a/services/bridge/src/config.ts +++ b/services/bridge/src/config.ts @@ -1,4 +1,7 @@ +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; @@ -25,11 +28,11 @@ export interface BridgeConfig { provider: 'none' | 'builtin' | 'openai-compatible'; baseUrl: string; apiKey: string; - /** Hub model id for `builtin`; provider model name for `openai-compatible`. */ + /** Bundled manifest name for `builtin`; provider model name for `openai-compatible`. */ model: string; - /** `builtin` only: weight precision and where model files are cached. */ - dtype: string; - cacheDir: string; + /** `builtin` only: the pinned artifacts to load, and the directory they are read from. */ + manifest: ModelManifest | null; + modelDir: string; }; limits: { captureMaxSeconds: number; @@ -46,7 +49,6 @@ export interface BridgeConfig { tokenTtlSeconds: number; pairingTtlSeconds: number; pairingCodeTtlSeconds: number; - pairingCodeMaxFailures: number; }; /** How long input/answer text stays in the bridge's result cache. Hermes is the authority. */ resultRetentionSeconds: number; @@ -98,6 +100,34 @@ function httpUrl(key: string, raw: string): string { return raw.replace(/\/+$/, ''); } +/** Manifests shipped with the bridge: `services/bridge/models/.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'); @@ -132,14 +162,10 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig { 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' ? 'onnx-community/whisper-base' : ''); - if (sttProvider === 'builtin' && !/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(sttModel)) { - throw new ConfigError('STT_MODEL must be a Hugging Face model id such as onnx-community/whisper-base'); - } - const sttDtype = env.STT_DTYPE || 'q8'; - if (!['q8', 'q4', 'fp32', 'fp16', 'int8', 'uint8'].includes(sttDtype)) { - throw new ConfigError('STT_DTYPE must be one of q8, q4, fp32, fp16, int8, uint8'); - } + 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'); @@ -169,8 +195,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig { baseUrl: sttBaseUrl, apiKey: env.STT_API_KEY || '', model: sttModel, - dtype: sttDtype, - cacheDir: env.STT_CACHE_DIR || './data/models', + manifest: sttManifest, + modelDir: env.STT_MODEL_DIR || './data/models', }, limits: { captureMaxSeconds, @@ -188,7 +214,6 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig { 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), - pairingCodeMaxFailures: int(env, 'HERMEVEN_PAIRING_CODE_MAX_FAILURES', 5, 1, 20), }, resultRetentionSeconds: int(env, 'HERMEVEN_RESULT_RETENTION_SECONDS', 900, 10, 86_400), logLevel: env.HERMEVEN_LOG_LEVEL || 'info', diff --git a/services/bridge/src/db.ts b/services/bridge/src/db.ts index 408dcc1..871bf34 100644 --- a/services/bridge/src/db.ts +++ b/services/bridge/src/db.ts @@ -1,5 +1,5 @@ import Database from 'better-sqlite3'; -import { mkdirSync } from 'node:fs'; +import { chmodSync, closeSync, existsSync, mkdirSync, openSync } from 'node:fs'; import { dirname } from 'node:path'; export type Db = Database.Database; @@ -66,15 +66,47 @@ const MIGRATIONS: string[] = [ CREATE INDEX turns_conversation ON turns(conversation_id, state); CREATE INDEX turns_state ON turns(state); `, + // v2: the agent deadline is stored, so a restart resumes the same deadline (including time + // already paused for an approval) instead of recomputing it. + ` + ALTER TABLE turns ADD COLUMN agent_deadline_at INTEGER; + `, ]; +/** The database holds credential hashes and, briefly, question and answer text. */ +const DIR_MODE = 0o700; +const FILE_MODE = 0o600; + +function sidecars(path: string): string[] { + return [path, `${path}-wal`, `${path}-shm`]; +} + +/** Force owner-only permissions on the database and its WAL/SHM files, whatever the umask. */ +export function secureDbFiles(path: string): void { + if (path === ':memory:') return; + for (const file of sidecars(path)) if (existsSync(file)) chmodSync(file, FILE_MODE); +} + export function openDb(path: string): Db { - if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true }); + if (path !== ':memory:') { + const dir = dirname(path); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + // mkdir's mode is masked by the umask; state the result explicitly. + chmodSync(dir, DIR_MODE); + } + // Create the file ourselves, owner-only, BEFORE SQLite opens it. SQLite gives the WAL and + // SHM files the same permissions as the database file, so they are never world-readable, + // not even for a moment. + if (!existsSync(path)) closeSync(openSync(path, 'a', FILE_MODE)); + chmodSync(path, FILE_MODE); + } const db = new Database(path); db.pragma('journal_mode = WAL'); db.pragma('foreign_keys = ON'); db.pragma('busy_timeout = 5000'); migrate(db); + secureDbFiles(path); return db; } diff --git a/services/bridge/src/devices.ts b/services/bridge/src/devices.ts index 31dd96d..70ae618 100644 --- a/services/bridge/src/devices.ts +++ b/services/bridge/src/devices.ts @@ -15,11 +15,15 @@ export interface DeviceRow { } export type AuthFailure = 'unauthorized' | 'credential_expired'; -export type PairingFailure = 'pairing_invalid' | 'pairing_locked'; +export type PairingFailure = 'pairing_invalid'; // No 0/O, 1/I/L: read aloud or typed on a phone without ambiguity. 31 symbols. const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'; -const CODE_LENGTH = 10; // ~49.5 bits; with 5 total failures before lockout, guessing is not viable. +// ~49.5 bits. Brute force is bounded by this entropy, the code's few-minute lifetime and the +// per-client attempt limit in the HTTP layer; see docs/security.md for the arithmetic. Wrong +// guesses are deliberately NOT counted against the outstanding code: if they were, anyone +// who can reach the endpoint could void the owner's real code with a handful of junk guesses. +const CODE_LENGTH = 10; export function sha256(value: string): string { return createHash('sha256').update(value).digest('hex'); @@ -55,8 +59,8 @@ export class Devices { } /** - * Exchange a pairing code for a device credential. A wrong guess counts against every - * outstanding code, so the code is burned after a few failures regardless of who guessed. + * Exchange a pairing code for a device credential. A wrong, expired or already-used code + * all fail the same way and change nothing: only the correct code consumes the code. */ claimPairingCode( rawCode: string, @@ -66,22 +70,10 @@ export class Devices { const hash = sha256(normalizeCode(rawCode)); return this.db.transaction(() => { const live = this.db - .prepare('SELECT id, code_hash, failed_attempts FROM pairing_codes WHERE used_at IS NULL AND expires_at > ?') - .all(now) as Array<{ id: number; code_hash: string; failed_attempts: number }>; + .prepare('SELECT id, code_hash FROM pairing_codes WHERE used_at IS NULL AND expires_at > ?') + .all(now) as Array<{ id: number; code_hash: string }>; const match = live.find((row) => safeEqualHex(row.code_hash, hash)); - if (!match) { - let locked = false; - for (const row of live) { - const failures = row.failed_attempts + 1; - if (failures >= this.config.credentials.pairingCodeMaxFailures) { - this.db.prepare('UPDATE pairing_codes SET failed_attempts = ?, used_at = ? WHERE id = ?').run(failures, now, row.id); - locked = true; - } else { - this.db.prepare('UPDATE pairing_codes SET failed_attempts = ? WHERE id = ?').run(failures, row.id); - } - } - return { ok: false as const, reason: locked ? ('pairing_locked' as const) : ('pairing_invalid' as const) }; - } + if (!match) return { ok: false as const, reason: 'pairing_invalid' as const }; this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE id = ?').run(now, match.id); const token = newToken(); const device: DeviceRow = { @@ -130,11 +122,21 @@ export class Devices { return { device: this.get(deviceId)!, token }; } + /** + * Revoke a device. One transaction ends its access, closes its conversation and flags every + * turn it still has in flight for cancellation, so nothing the device started keeps running + * on its behalf. The flag is in the database, so it also reaches a bridge process that did + * not perform the revocation (the operator CLI is a separate process): the turn engine acts + * on it by aborting transcription and asking Hermes to stop. + */ revoke(deviceId: string): boolean { const now = this.now(); return this.db.transaction(() => { const res = this.db.prepare('UPDATE devices SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL').run(now, deviceId); this.db.prepare('UPDATE conversations SET closed_at = ? WHERE device_id = ? AND closed_at IS NULL').run(now, deviceId); + this.db + .prepare("UPDATE turns SET cancel_requested = 1, updated_at = ? WHERE device_id = ? AND state != 'done' AND cancel_requested = 0") + .run(now, deviceId); return res.changes > 0; })(); } diff --git a/services/bridge/src/main.ts b/services/bridge/src/main.ts index 3f9dc55..55d247e 100644 --- a/services/bridge/src/main.ts +++ b/services/bridge/src/main.ts @@ -11,14 +11,25 @@ async function main(): Promise { }); await bridge.app.listen({ host: config.host, port: config.port }); - // Load the built-in speech model in the background so the first spoken question is not - // slowed by it. On a first start this downloads the model files. - if (bridge.stt instanceof BuiltinWhisperStt) { + // Verify and load the built-in speech model in the background so the first spoken question + // is not slowed by it. Nothing is downloaded here: the files must already be in the model + // store (`bridge:cli fetch-model`) and must match their pinned hashes. + const stt = bridge.stt; + if (stt instanceof BuiltinWhisperStt) { const started = Date.now(); - bridge.app.log.info({ model: config.stt.model, dtype: config.stt.dtype }, 'stt.loading'); - bridge.stt.warm().then( - () => bridge.app.log.info({ load_ms: Date.now() - started }, 'stt.ready'), - () => bridge.app.log.error({ model: config.stt.model }, 'stt.load_failed'), + const pin = { model: config.stt.manifest!.model, revision: config.stt.manifest!.revision }; + bridge.app.log.info(pin, 'stt.loading'); + stt.warm().then( + () => bridge.app.log.info({ ...pin, load_ms: Date.now() - started }, 'stt.ready'), + () => + bridge.app.log.error( + { + ...pin, + reason: stt.lastLoadFailure, + hint: stt.lastLoadFailure === 'missing' ? 'run: npm run bridge:cli -- fetch-model' : undefined, + }, + 'stt.load_failed', + ), ); } diff --git a/services/bridge/src/server.ts b/services/bridge/src/server.ts index c740c03..f45ff97 100644 --- a/services/bridge/src/server.ts +++ b/services/bridge/src/server.ts @@ -171,12 +171,8 @@ export async function buildServer(deps: ServerDeps): Promise { const result = devices.claimPairingCode(body.code, body.device_name.trim() || 'device'); if (!result.ok) { req.log.warn({ reason: result.reason }, 'pairing.rejected'); - throw new ApiError( - result.reason, - result.reason === 'pairing_locked' - ? 'Too many wrong codes. Generate a new pairing code on the bridge.' - : 'Pairing code is not valid.', - ); + // One answer for wrong, expired and used codes: the response reveals nothing about which. + throw new ApiError('pairing_invalid', 'Pairing code is not valid.'); } req.log.info({ device_id: result.device.id }, 'pairing.claimed'); return reply.code(201).send(credential(result.device, result.token)); @@ -212,7 +208,7 @@ export async function buildServer(deps: ServerDeps): Promise { app.delete('/v1/device', async (req) => { const device = authenticate(req); - devices.revoke(device.id); + engine.revokeDevice(device.id); req.log.info({ device_id: device.id }, 'device.revoked'); return { schema_version: SCHEMA_VERSION, revoked: true }; }); diff --git a/services/bridge/src/stt/builtinWhisper.ts b/services/bridge/src/stt/builtinWhisper.ts index 2961e04..843dcb2 100644 --- a/services/bridge/src/stt/builtinWhisper.ts +++ b/services/bridge/src/stt/builtinWhisper.ts @@ -1,6 +1,7 @@ import { Worker } from 'node:worker_threads'; import { AUDIO_FORMAT } from '@hermeven/contracts'; import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts'; +import type { ModelManifest } from './modelStore.mjs'; /** * Built-in speech-to-text: OpenAI's Whisper model run on the bridge host's CPU @@ -10,15 +11,15 @@ import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts' * The model lives in a worker thread (whisperWorker.mjs), so loading it and * transcribing never block the bridge's HTTP server or its Hermes polling. * - * The model files are downloaded from the Hugging Face hub the first time the - * bridge starts and are then read from `cacheDir`. + * The bridge never downloads anything at run time. Model files are fetched ahead of + * time (`bridge:cli fetch-model`) at a pinned commit, and every file is checked against + * its pinned SHA-256 each time the model is loaded. */ export interface BuiltinWhisperOptions { - /** Hub id, for example `onnx-community/whisper-base` (multilingual) or `...-base.en`. */ - model: string; - /** Weight precision. `q8` is the small, CPU-friendly default. */ - dtype: string; - cacheDir: string; + /** What exactly to load: hub id, immutable revision, precision, and each file's hash. */ + manifest: ModelManifest; + /** Model store directory. Read-only at run time. */ + modelDir: string; /** Test seam: replaces the worker thread with an in-process recogniser. */ load?: () => Promise; } @@ -58,6 +59,8 @@ export class BuiltinWhisperStt implements SttAdapter { private recognizer: Promise | null = null; private worker: Worker | null = null; private closed = false; + /** Why the last load failed: `missing`, `mismatch` (files differ from the pin) or `load`. */ + lastLoadFailure: 'missing' | 'mismatch' | 'load' | null = null; /** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */ private queue: Promise = Promise.resolve(); @@ -102,9 +105,10 @@ export class BuiltinWhisperStt implements SttAdapter { }; worker.on('error', () => fail('worker error')); worker.on('exit', () => fail('worker exited')); - worker.on('message', (message: { type: string; id?: number; text?: string }) => { + worker.on('message', (message: { type: string; id?: number; text?: string; reason?: 'missing' | 'mismatch' | 'load' }) => { if (message.type === 'loaded') { loaded = true; + this.lastLoadFailure = null; resolve( (audio, options) => new Promise((res, rej) => { @@ -115,6 +119,7 @@ export class BuiltinWhisperStt implements SttAdapter { }), ); } else if (message.type === 'load_failed') { + this.lastLoadFailure = message.reason ?? 'load'; void worker.terminate(); } else if (message.id !== undefined) { const pending = waiting.get(message.id); @@ -123,7 +128,7 @@ export class BuiltinWhisperStt implements SttAdapter { else pending?.reject(new Error('recognition failed')); } }); - worker.postMessage({ type: 'load', model: this.opts.model, dtype: this.opts.dtype, cacheDir: this.opts.cacheDir }); + worker.postMessage({ type: 'load', dir: this.opts.modelDir, manifest: this.opts.manifest }); }); } @@ -150,7 +155,7 @@ export class BuiltinWhisperStt implements SttAdapter { } // English-only models take no language argument; multilingual ones are told the // language from the device locale rather than left to guess it from a short clip. - const options: Record = this.opts.model.endsWith('.en') + const options: Record = this.opts.manifest.model.endsWith('.en') ? {} : { language: request.locale.split('-')[0]!.toLowerCase(), task: 'transcribe' }; try { diff --git a/services/bridge/src/stt/modelStore.d.mts b/services/bridge/src/stt/modelStore.d.mts new file mode 100644 index 0000000..0bed217 --- /dev/null +++ b/services/bridge/src/stt/modelStore.d.mts @@ -0,0 +1,24 @@ +export interface ModelFile { + path: string; + sha256: string; + bytes: number; +} +export interface ModelManifest { + name: string; + /** Hugging Face hub id, `/`. */ + model: string; + /** Full 40-character commit id. Branches and tags are refused. */ + revision: string; + dtype: string; + files: ModelFile[]; +} +export type VerifyResult = { ok: true } | { ok: false; reason: 'missing' | 'mismatch'; path: string }; + +export function validateManifest(value: unknown): ModelManifest; +export function modelPath(dir: string, manifest: ModelManifest): string; +export function verifyModel(dir: string, manifest: ModelManifest): Promise; +export function fetchModel( + dir: string, + manifest: ModelManifest, + options?: { baseUrl?: string; fetchImpl?: typeof fetch; onFile?: (path: string, bytes: number) => void }, +): Promise<{ downloaded: number; verified: number }>; diff --git a/services/bridge/src/stt/modelStore.mjs b/services/bridge/src/stt/modelStore.mjs new file mode 100644 index 0000000..ebcaaf4 --- /dev/null +++ b/services/bridge/src/stt/modelStore.mjs @@ -0,0 +1,123 @@ +// Pinned speech-model artifacts: manifest validation, download and verification. +// +// Plain JavaScript because the worker thread imports it directly; types are in +// modelStore.d.mts. This is the only code that decides whether model files are trusted. +import { createHash } from 'node:crypto'; +import { createReadStream, createWriteStream } from 'node:fs'; +import { mkdir, rename, rm, stat } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { Readable } from 'node:stream'; +import { pipeline as pump } from 'node:stream/promises'; + +const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/; +const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/; +const DTYPES = new Set(['q8', 'q4', 'fp32', 'fp16', 'int8', 'uint8']); + +/** Throws with a plain reason unless the manifest pins everything it names. */ +export function validateManifest(value) { + const fail = (why) => { + throw new Error(`Invalid model manifest: ${why}`); + }; + if (!value || typeof value !== 'object') fail('not an object'); + const { name, model, revision, dtype, files } = value; + if (typeof name !== 'string' || !SEGMENT.test(name)) fail('name'); + if (typeof model !== 'string' || !MODEL_ID.test(model)) fail('model must be /'); + // A branch or tag can move. Only a full commit id is immutable. + if (typeof revision !== 'string' || !/^[0-9a-f]{40}$/.test(revision)) fail('revision must be a full 40-character commit id'); + if (typeof dtype !== 'string' || !DTYPES.has(dtype)) fail('dtype'); + if (!Array.isArray(files) || files.length === 0) fail('files'); + const seen = new Set(); + for (const file of files) { + if (!file || typeof file !== 'object') fail('file entry'); + if (typeof file.path !== 'string' || !file.path.split('/').every((s) => SEGMENT.test(s))) fail(`unsafe path`); + if (seen.has(file.path)) fail('duplicate path'); + seen.add(file.path); + if (typeof file.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(file.sha256)) fail(`sha256 for ${file.path}`); + if (!Number.isInteger(file.bytes) || file.bytes <= 0) fail(`bytes for ${file.path}`); + } + return { name, model, revision, dtype, files: files.map((f) => ({ path: f.path, sha256: f.sha256, bytes: f.bytes })) }; +} + +/** Directory that holds one model's files inside the model store. */ +export function modelPath(dir, manifest) { + return join(dir, manifest.model); +} + +async function sha256File(path) { + const hash = createHash('sha256'); + await pump(createReadStream(path), hash); + return hash.digest('hex'); +} + +/** + * Check every file the manifest names: present, exact size, exact SHA-256. + * Resolves `{ ok: true }` or `{ ok: false, reason: 'missing' | 'mismatch', path }`. + */ +export async function verifyModel(dir, manifest) { + const root = modelPath(dir, manifest); + for (const file of manifest.files) { + const path = join(root, file.path); + let info; + try { + info = await stat(path); + } catch { + return { ok: false, reason: 'missing', path: file.path }; + } + if (!info.isFile()) return { ok: false, reason: 'missing', path: file.path }; + if (info.size !== file.bytes) return { ok: false, reason: 'mismatch', path: file.path }; + if ((await sha256File(path)) !== file.sha256) return { ok: false, reason: 'mismatch', path: file.path }; + } + return { ok: true }; +} + +/** + * Download the pinned revision's files into the store, verifying each before it is put in + * place. A file that does not match its pinned hash is deleted and the fetch fails. + * Files already present and correct are left alone, so the command is safe to repeat. + */ +export async function fetchModel(dir, manifest, options = {}) { + const baseUrl = (options.baseUrl ?? 'https://huggingface.co').replace(/\/+$/, ''); + const fetchImpl = options.fetchImpl ?? fetch; + const root = modelPath(dir, manifest); + let downloaded = 0; + for (const file of manifest.files) { + const dest = join(root, file.path); + const single = { ...manifest, files: [file] }; + if ((await verifyModel(dir, single)).ok) continue; + await mkdir(dirname(dest), { recursive: true }); + const partial = `${dest}.partial`; + await rm(partial, { force: true }); + // The commit id in the URL pins what the hub serves; the hash check does not rely on that. + const url = `${baseUrl}/${manifest.model}/resolve/${manifest.revision}/${file.path}`; + const res = await fetchImpl(url, { redirect: 'follow' }); + if (!res.ok || !res.body) throw new Error(`Download failed for ${file.path}: HTTP ${res.status}`); + const hash = createHash('sha256'); + let bytes = 0; + try { + await pump( + Readable.fromWeb(res.body), + async function* (source) { + for await (const chunk of source) { + bytes += chunk.length; + if (bytes > file.bytes) throw new Error(`Download for ${file.path} is larger than pinned`); + hash.update(chunk); + yield chunk; + } + }, + createWriteStream(partial, { mode: 0o644 }), + ); + if (bytes !== file.bytes || hash.digest('hex') !== file.sha256) { + throw new Error(`Downloaded ${file.path} does not match its pinned SHA-256`); + } + } catch (err) { + await rm(partial, { force: true }); + throw err; + } + await rename(partial, dest); + downloaded += 1; + options.onFile?.(file.path, file.bytes); + } + const check = await verifyModel(dir, manifest); + if (!check.ok) throw new Error(`Model store failed verification after fetch: ${check.reason} ${check.path}`); + return { downloaded, verified: manifest.files.length }; +} diff --git a/services/bridge/src/stt/whisperWorker.mjs b/services/bridge/src/stt/whisperWorker.mjs index 5403403..f84abc1 100644 --- a/services/bridge/src/stt/whisperWorker.mjs +++ b/services/bridge/src/stt/whisperWorker.mjs @@ -2,27 +2,41 @@ // directly by `new Worker(...)`, so it must run without any TypeScript loader. // // Protocol (all messages are plain objects): -// in : { type: 'load', model, dtype, cacheDir } -// out: { type: 'loaded' } | { type: 'load_failed' } +// in : { type: 'load', dir, manifest } +// out: { type: 'loaded' } | { type: 'load_failed', reason: 'missing' | 'mismatch' | 'load' } // in : { type: 'run', id, samples: Float32Array, options } // out: { type: 'result', id, text } | { type: 'failed', id } -// Error details are deliberately not sent back: they could contain file paths, and nothing +// Only fixed reason codes are sent back: error text could contain file paths, and nothing // derived from audio content should travel as an error string. import { parentPort } from 'node:worker_threads'; +import { verifyModel } from './modelStore.mjs'; let recognizer = null; parentPort.on('message', async (message) => { if (message.type === 'load') { try { - const { pipeline } = await import('@huggingface/transformers'); - recognizer = await pipeline('automatic-speech-recognition', message.model, { - dtype: message.dtype, - cache_dir: message.cacheDir, + // 1. The files on disk must be exactly the pinned ones. + const check = await verifyModel(message.dir, message.manifest); + if (!check.ok) { + parentPort.postMessage({ type: 'load_failed', reason: check.reason }); + return; + } + // 2. Load from that directory only. The network is never consulted at run time: remote + // models are disabled, so a missing file is an error rather than a download. + const { env, pipeline } = await import('@huggingface/transformers'); + env.allowRemoteModels = false; + env.allowLocalModels = true; + env.localModelPath = message.dir; + env.useFSCache = false; + env.useBrowserCache = false; + recognizer = await pipeline('automatic-speech-recognition', message.manifest.model, { + dtype: message.manifest.dtype, + local_files_only: true, }); parentPort.postMessage({ type: 'loaded' }); } catch { - parentPort.postMessage({ type: 'load_failed' }); + parentPort.postMessage({ type: 'load_failed', reason: 'load' }); } return; } diff --git a/services/bridge/src/turns.ts b/services/bridge/src/turns.ts index f3e2677..73b8ec1 100644 --- a/services/bridge/src/turns.ts +++ b/services/bridge/src/turns.ts @@ -9,6 +9,7 @@ import { } from '@hermeven/contracts'; import type { BridgeConfig } from './config.ts'; import type { Db } from './db.ts'; +import type { Devices } from './devices.ts'; import { buildRunBody, HermesSubmitError, @@ -39,6 +40,8 @@ export interface TurnRow { updated_at: number; agent_started_at: number | null; approval_started_at: number | null; + /** Absolute time the agent must finish by; pushed back by time spent awaiting approval. */ + agent_deadline_at: number | null; completed_at: number | null; transcribe_ms: number | null; agent_ms: number | null; @@ -118,6 +121,7 @@ export class TurnEngine { private readonly deps: { db: Db; config: BridgeConfig; + devices: Devices; hermes: HermesAdapter; stt: SttAdapter; log: EngineLog; @@ -220,6 +224,7 @@ export class TurnEngine { updated_at: now, agent_started_at: null, approval_started_at: null, + agent_deadline_at: null, completed_at: null, transcribe_ms: null, agent_ms: null, @@ -261,6 +266,38 @@ export class TurnEngine { return this.row(requestId); } + /** + * Revoke a device and stop everything it has in flight. Access ends and the turns are + * flagged in one transaction (Devices.revoke); this then acts on the flags at once. + */ + revokeDevice(deviceId: string): boolean { + const revoked = this.deps.devices.revoke(deviceId); + this.deps.log.info({ device_id: deviceId, revoked }, 'device.revoke_applied'); + this.applyCancelFlags(); + return revoked; + } + + /** + * Act on cancel flags set directly in the database: abort transcription and wake the worker + * so it asks Hermes to stop. Runs right after an in-process revocation, and on a short + * timer so a revocation made by the operator CLI (another process) is honoured promptly. + */ + applyCancelFlags(): number { + if (this.active.size === 0) return 0; + const flagged = this.deps.db + .prepare("SELECT request_id FROM turns WHERE state != 'done' AND cancel_requested = 1") + .all() as Array<{ request_id: string }>; + let nudged = 0; + for (const { request_id } of flagged) { + const active = this.active.get(request_id); + if (!active) continue; + active.sttAbort?.abort(); + active.wake?.(); + nudged += 1; + } + return nudged; + } + /** Resume or settle every turn a previous process left in flight. Call once at startup. */ recover(): void { const rows = this.deps.db.prepare("SELECT * FROM turns WHERE state != 'done'").all() as TurnRow[]; @@ -427,13 +464,15 @@ export class TurnEngine { .get(row.conversation_id) as ConversationRow; // Persist the exact body BEFORE the first network attempt, so a crash can replay it // under the same idempotency key instead of guessing. + const agentStartedAt = this.now(); this.setState(requestId, 'thinking', { pending_body: buildRunBody({ input: row.input_text ?? '', sessionId: conversation.hermes_session_id, instructions: this.deps.config.hermes.instructions, }), - agent_started_at: this.now(), + agent_started_at: agentStartedAt, + agent_deadline_at: agentStartedAt + this.timing.agentDeadlineMs, }); } @@ -482,7 +521,7 @@ export class TurnEngine { /** Returns the run id, or null when the turn was settled here. */ private async submitToHermes(requestId: string, active: ActiveTurn, maybeAlreadySent: boolean): Promise { const row = this.row(requestId)!; - const deadline = (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs; + const deadline = row.agent_deadline_at ?? (row.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs; let ambiguous = maybeAlreadySent; let notSent = 0; @@ -529,8 +568,11 @@ export class TurnEngine { private async poll(requestId: string, active: ActiveTurn): Promise { const start = this.row(requestId)!; const runId = start.hermes_run_id!; - let deadlineAt = (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs; - let approvalSince: number | null = null; + // Both clocks come from the database, so a bridge restart resumes them where they were: + // the approval wait is measured from when the approval was first seen, and the agent + // deadline keeps whatever pause earlier approvals earned it. + let deadlineAt = start.agent_deadline_at ?? (start.agent_started_at ?? this.now()) + this.timing.agentDeadlineMs; + let approvalSince: number | null = start.approval_started_at; let stopReason: 'user' | 'agent_timeout' | 'approval_timeout' | null = null; let stopAccepted = false; let graceUntil = 0; @@ -587,14 +629,20 @@ export class TurnEngine { this.finish(requestId, 'unknown', { code: 'outcome_unknown' }); return; case 'waiting_for_approval': - if (approvalSince === null) approvalSince = now; - if (!stopReason) this.setState(requestId, 'approval_required', { approval_started_at: now }); + if (approvalSince === null) { + // Recorded once, when the approval is first seen, and never moved afterwards. + approvalSince = now; + this.update(requestId, { approval_started_at: now }); + } + if (!stopReason) this.setState(requestId, 'approval_required'); break; default: if (approvalSince !== null) { // Approval was resolved on another surface; time spent waiting does not count. + // Persisted in one write, so a restart cannot apply the pause twice or not at all. deadlineAt += now - approvalSince; approvalSince = null; + this.update(requestId, { agent_deadline_at: deadlineAt, approval_started_at: null }); } if (!stopReason) this.setState(requestId, 'thinking'); } diff --git a/services/bridge/test/builtinWhisper.test.ts b/services/bridge/test/builtinWhisper.test.ts index df09329..67de19c 100644 --- a/services/bridge/test/builtinWhisper.test.ts +++ b/services/bridge/test/builtinWhisper.test.ts @@ -9,14 +9,14 @@ function tone(seconds: number, amplitude = 8000): Buffer { return buf; } const never = new AbortController().signal; +const manifestFor = (model: string) => ({ name: 'test', model, revision: 'a'.repeat(40), dtype: 'q8', files: [] }); function make(recognizer: Recognizer, model = 'onnx-community/whisper-base') { let loads = 0; const calls: Array<{ samples: number; options: Record }> = []; const stt = new BuiltinWhisperStt({ - model, - dtype: 'q8', - cacheDir: '/nonexistent', + manifest: manifestFor(model), + modelDir: '/nonexistent', load: async () => { loads += 1; return async (audio, options) => { @@ -99,9 +99,8 @@ describe('built-in Whisper adapter', () => { it('a model that fails to load is "unavailable" and is retried next time', async () => { let attempts = 0; const stt = new BuiltinWhisperStt({ - model: 'onnx-community/whisper-base', - dtype: 'q8', - cacheDir: '/nonexistent', + manifest: manifestFor('onnx-community/whisper-base'), + modelDir: '/nonexistent', load: async () => { attempts += 1; if (attempts === 1) throw new Error('no network'); diff --git a/services/bridge/test/modelStore.test.ts b/services/bridge/test/modelStore.test.ts new file mode 100644 index 0000000..8d550c3 --- /dev/null +++ b/services/bridge/test/modelStore.test.ts @@ -0,0 +1,196 @@ +import { createHash } from 'node:crypto'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { bundledManifestPath, ConfigError, loadConfig } from '../src/config.ts'; +import { BuiltinWhisperStt } from '../src/stt/builtinWhisper.ts'; +import { fetchModel, validateManifest, verifyModel, type ModelManifest } from '../src/stt/modelStore.mjs'; + +/** + * Pinning and verification of speech-model artifacts. A local stand-in for the model hub is + * used, so these run without network. The real pinned artifacts are fetched and verified by + * `npm run test:real-stt`. + */ +const sha = (data: string | Buffer) => createHash('sha256').update(data).digest('hex'); +const CONTENT: Record = { + 'config.json': Buffer.from('{"a":1}'), + 'onnx/model.onnx': Buffer.from('not really weights, but bytes all the same'), +}; +const REVISION = '0123456789abcdef0123456789abcdef01234567'; +const manifest: ModelManifest = { + name: 'test-model', + model: 'test-org/test-model', + revision: REVISION, + dtype: 'q8', + files: Object.entries(CONTENT).map(([path, data]) => ({ path, sha256: sha(data), bytes: data.length })), +}; + +let dir: string; +let hub: Server; +let hubUrl: string; +let requests: string[]; +let served: Record; + +beforeEach(async () => { + dir = mkdtempSync(join(tmpdir(), 'hermeven-models-')); + requests = []; + served = { ...CONTENT }; + hub = createServer((req, res) => { + requests.push(req.url ?? ''); + const prefix = `/${manifest.model}/resolve/${REVISION}/`; + const file = req.url?.startsWith(prefix) ? served[req.url.slice(prefix.length)] : undefined; + if (!file) return void res.writeHead(404).end(); + res.writeHead(200, { 'Content-Length': file.length }).end(file); + }); + await new Promise((r) => hub.listen(0, '127.0.0.1', r)); + hubUrl = `http://127.0.0.1:${(hub.address() as AddressInfo).port}`; +}); +afterEach(async () => { + hub.closeAllConnections(); + await new Promise((r) => hub.close(() => r())); + chmodRecursive(dir, 0o700, 0o600); + rmSync(dir, { recursive: true, force: true }); +}); + +function chmodRecursive(path: string, dirMode: number, fileMode: number): void { + if (!existsSync(path)) return; + chmodSync(path, dirMode); + for (const entry of readdirSync(path, { withFileTypes: true })) { + const child = join(path, entry.name); + if (entry.isDirectory()) chmodRecursive(child, dirMode, fileMode); + else chmodSync(child, fileMode); + } +} + +describe('manifest validation: nothing unpinned is accepted', () => { + const base = { ...manifest }; + it('accepts a fully pinned manifest', () => { + expect(validateManifest(base)).toEqual(manifest); + }); + it('refuses a branch, tag or short id as the revision', () => { + for (const revision of ['main', 'v1.0', REVISION.slice(0, 12), REVISION.toUpperCase(), '', undefined]) { + expect(() => validateManifest({ ...base, revision })).toThrow(/revision/); + } + }); + it('refuses a file without a full SHA-256 or size', () => { + expect(() => validateManifest({ ...base, files: [{ path: 'a', bytes: 1 }] })).toThrow(/sha256/); + expect(() => validateManifest({ ...base, files: [{ path: 'a', sha256: 'abc', bytes: 1 }] })).toThrow(/sha256/); + expect(() => validateManifest({ ...base, files: [{ path: 'a', sha256: sha('x') }] })).toThrow(/bytes/); + expect(() => validateManifest({ ...base, files: [] })).toThrow(/files/); + }); + it('refuses paths that could leave the model store', () => { + for (const path of ['../evil', '/etc/passwd', 'a/../../b', 'a//b', '.hidden/x', 'a\\b']) { + expect(() => validateManifest({ ...base, files: [{ path, sha256: sha('x'), bytes: 1 }] })).toThrow(/unsafe path/); + } + expect(() => validateManifest({ ...base, model: '../x/y' })).toThrow(/model/); + }); + it('the bundled manifests are valid and pin a commit', () => { + for (const name of ['whisper-base', 'whisper-tiny']) { + const bundled = validateManifest(JSON.parse(readFileSync(bundledManifestPath(name), 'utf8'))); + expect(bundled.revision).toMatch(/^[0-9a-f]{40}$/); + expect(bundled.files.length).toBeGreaterThanOrEqual(7); + } + }); +}); + +describe('configuration: an unpinned built-in model cannot be configured', () => { + const env = { HERMES_API_KEY: 'k', HERMEVEN_DB_PATH: ':memory:' }; + it('defaults to the bundled pinned whisper-base', () => { + const config = loadConfig(env); + expect(config.stt.provider).toBe('builtin'); + expect(config.stt.manifest).toMatchObject({ model: 'onnx-community/whisper-base', dtype: 'q8' }); + expect(config.stt.manifest!.revision).toMatch(/^[0-9a-f]{40}$/); + }); + it('refuses a hub id or any model without a bundled manifest', () => { + for (const model of ['onnx-community/whisper-base', 'whisper-large', 'main', '../../etc/passwd']) { + expect(() => loadConfig({ ...env, STT_MODEL: model })).toThrow(ConfigError); + } + }); + it('accepts a custom manifest only if it is fully pinned', () => { + const good = join(dir, 'good.json'); + writeFileSync(good, JSON.stringify(manifest)); + expect(loadConfig({ ...env, STT_MODEL_MANIFEST: good }).stt.manifest).toEqual(manifest); + const moving = join(dir, 'moving.json'); + writeFileSync(moving, JSON.stringify({ ...manifest, revision: 'main' })); + expect(() => loadConfig({ ...env, STT_MODEL_MANIFEST: moving })).toThrow(/revision/); + expect(() => loadConfig({ ...env, STT_MODEL_MANIFEST: join(dir, 'absent.json') })).toThrow(ConfigError); + }); +}); + +describe('fetch and verify', () => { + it('downloads the pinned revision, verifies it, and is a no-op the second time', async () => { + expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'missing', path: 'config.json' }); + expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 2, verified: 2 }); + expect(requests).toEqual([ + `/test-org/test-model/resolve/${REVISION}/config.json`, + `/test-org/test-model/resolve/${REVISION}/onnx/model.onnx`, + ]); + expect(await verifyModel(dir, manifest)).toEqual({ ok: true }); + requests.length = 0; + expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 0, verified: 2 }); + expect(requests).toEqual([]); + }); + + it('a hub that serves different bytes fails the fetch and leaves nothing in place', async () => { + served['onnx/model.onnx'] = Buffer.from('not really weights, but bytes all the SAME'); // same length + await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/does not match its pinned SHA-256/); + const onnxDir = join(dir, manifest.model, 'onnx'); + expect(existsSync(join(onnxDir, 'model.onnx'))).toBe(false); + expect(readdirSync(onnxDir)).toEqual([]); + expect((await verifyModel(dir, manifest)).ok).toBe(false); + + served['onnx/model.onnx'] = Buffer.concat([CONTENT['onnx/model.onnx']!, Buffer.from('extra')]); + await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/larger than pinned/); + delete served['config.json']; + rmSync(join(dir, manifest.model), { recursive: true }); + await expect(fetchModel(dir, manifest, { baseUrl: hubUrl })).rejects.toThrow(/HTTP 404/); + }); + + it('detects a file changed on disk, by content and by size', async () => { + await fetchModel(dir, manifest, { baseUrl: hubUrl }); + const target = join(dir, manifest.model, 'config.json'); + writeFileSync(target, '{"a":2}'); // same size, different content + expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'config.json' }); + writeFileSync(target, '{"a":1} '); + expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'config.json' }); + // Fetching again repairs it from the pinned revision. + expect(await fetchModel(dir, manifest, { baseUrl: hubUrl })).toEqual({ downloaded: 1, verified: 2 }); + }); + + it('verification works on a read-only store', async () => { + await fetchModel(dir, manifest, { baseUrl: hubUrl }); + chmodRecursive(dir, 0o500, 0o400); + expect(await verifyModel(dir, manifest)).toEqual({ ok: true }); + }); +}); + +describe('the adapter refuses to load unverified artifacts, and never downloads', () => { + const pcm = () => { + const buf = Buffer.alloc(32000); + for (let i = 0; i < 16000; i++) buf.writeInt16LE(Math.round(Math.sin(i / 5) * 8000), i * 2); + return buf; + }; + const signal = new AbortController().signal; + + it('missing files: unavailable, reason "missing", and no network request', async () => { + const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); + await expect(stt.transcribe({ pcm: pcm(), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); + expect(stt.lastLoadFailure).toBe('missing'); + expect(requests).toEqual([]); + await stt.close(); + }); + + it('tampered files: unavailable, reason "mismatch"', async () => { + await fetchModel(dir, manifest, { baseUrl: hubUrl }); + writeFileSync(join(dir, manifest.model, 'onnx/model.onnx'), Buffer.from('not really weights, but bytes all the SAME')); + requests.length = 0; + const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); + await expect(stt.transcribe({ pcm: pcm(), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); + expect(stt.lastLoadFailure).toBe('mismatch'); + expect(requests).toEqual([]); + await stt.close(); + }); +}); diff --git a/services/bridge/test/units.test.ts b/services/bridge/test/units.test.ts index b45cf44..c77920c 100644 --- a/services/bridge/test/units.test.ts +++ b/services/bridge/test/units.test.ts @@ -1,3 +1,8 @@ +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, rmSync, statSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'vitest'; import { ConfigError, loadConfig } from '../src/config.ts'; import { openDb } from '../src/db.ts'; @@ -46,6 +51,64 @@ describe('configuration', () => { }); }); +describe('state files are owner-only whatever the umask (CODY-006)', () => { + const mode = (path: string) => statSync(path).mode & 0o777; + + it('under umask 0022 the directory is 0700 and the database, WAL and SHM are 0600', () => { + const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); + const dbPath = join(root, 'state', 'hermeven.sqlite'); + // A separate process, so the permissive umask is real and does not leak into this one. + const script = ` + process.umask(0o022); + const { openDb } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))}); + const fs = await import('node:fs'); + const { syncBuiltinESMExports } = await import('node:module'); + // Record the loosest mode each state file ever has, from the instant SQLite or the + // bridge touches permissions, so a file that is briefly world-readable is caught too. + const loosest = {}; + const seen = (p) => { try { const mode = fs.statSync(p).mode & 0o777; loosest[p] = Math.max(loosest[p] ?? 0, mode & 0o077); } catch {} }; + const realChmod = fs.chmodSync; + fs.default.chmodSync = (p, mode) => { seen(${JSON.stringify(dbPath)}); seen(${JSON.stringify(dbPath + '-wal')}); seen(${JSON.stringify(dbPath + '-shm')}); return realChmod(p, mode); }; + syncBuiltinESMExports(); + const db = openDb(${JSON.stringify(dbPath)}); + db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run(); + const { statSync } = fs; + const m = (p) => (statSync(p).mode & 0o777).toString(8); + const everLoose = Object.values(loosest).some((bits) => bits !== 0); + // Read while the database is open, so the WAL and SHM files exist. + console.log(JSON.stringify({ everLoose, umask: process.umask().toString(8), dir: m(${JSON.stringify(join(root, 'state'))}), db: m(${JSON.stringify(dbPath)}), wal: m(${JSON.stringify(dbPath + '-wal')}), shm: m(${JSON.stringify(dbPath + '-shm')}) })); + db.close(); + `; + try { + const out = execFileSync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script], { + encoding: 'utf8', + cwd: fileURLToPath(new URL('..', import.meta.url)), + }); + expect(JSON.parse(out.trim().split('\n').at(-1)!)).toEqual({ everLoose: false, umask: '22', dir: '700', db: '600', wal: '600', shm: '600' }); + expect(mode(dbPath)).toBe(0o600); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('an existing database with loose permissions is tightened when opened', async () => { + const { chmodSync } = await import('node:fs'); + const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); + const dbPath = join(root, 'hermeven.sqlite'); + try { + openDb(dbPath).close(); + chmodSync(dbPath, 0o644); + const db = openDb(dbPath); + db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run(); + expect(mode(dbPath)).toBe(0o600); + expect(mode(`${dbPath}-wal`)).toBe(0o600); + db.close(); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); + describe('device credentials', () => { const setup = (env: Record = {}) => { let now = 1_000_000; diff --git a/tests/integration/bridge.test.ts b/tests/integration/bridge.test.ts index 5015636..2575039 100644 --- a/tests/integration/bridge.test.ts +++ b/tests/integration/bridge.test.ts @@ -129,15 +129,45 @@ describe('pairing', () => { expect(second.body.error.code).toBe('pairing_invalid'); }); - it('wrong guesses burn the outstanding code', async () => { - h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '50', HERMEVEN_PAIRING_CODE_MAX_FAILURES: '3' } }); + it('unrelated wrong guesses cannot invalidate the owner\'s real code (CODY-010)', async () => { + h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '60' } }); const { code } = h.bridge.devices.createPairingCode(); const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } }); - expect((await guess('AAAAA-AAAAA')).body.error.code).toBe('pairing_invalid'); - expect((await guess('AAAAA-AAAAB')).body.error.code).toBe('pairing_invalid'); - expect((await guess('AAAAA-AAAAC')).body.error.code).toBe('pairing_locked'); - // The real code no longer works. - expect((await guess(code)).status).toBe(401); + const responses = []; + for (let i = 0; i < 40; i++) responses.push(await guess(`AAAAA-AAA${String(i).padStart(2, '0')}`.replace(/[01]/g, 'B'))); + // Every failure looks the same: same status, same code, same message, nothing about lockout. + expect(new Set(responses.map((r) => `${r.status} ${JSON.stringify(r.body)}`)).size).toBe(1); + expect(responses[0]!.status).toBe(401); + expect(responses[0]!.body.error).toEqual({ code: 'pairing_invalid', message: 'Pairing code is not valid.', retryable: false }); + // The real code still works after forty wrong guesses. + expect((await guess(code)).status).toBe(201); + // And then it is spent, with the same indistinguishable failure. + const spent = await guess(code); + expect(`${spent.status} ${JSON.stringify(spent.body)}`).toBe(`${responses[0]!.status} ${JSON.stringify(responses[0]!.body)}`); + }); + + it('an expired code fails exactly like a wrong one', async () => { + h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '60' } }); + const { code } = h.bridge.devices.createPairingCode(); + h.bridge.db.prepare('UPDATE pairing_codes SET expires_at = 1').run(); + const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } }); + const expired = await guess(code); + const wrong = await guess('ZZZZZ-ZZZZZ'); + expect(expired.status).toBe(401); + expect(expired.body).toEqual(wrong.body); + }); + + it('brute force stays bounded: a client gets its per-minute attempts and no more, and still cannot burn the code', async () => { + h = await createHarness({ env: { HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE: '5' } }); + const { code } = h.bridge.devices.createPairingCode(); + const guess = (c: string) => h.api('POST', '/v1/pairing/claim', { json: { schema_version: 1, code: c, device_name: 'x' } }); + const statuses = []; + for (let i = 0; i < 30; i++) statuses.push((await guess('ZZZZZ-ZZZZZ')).status); + expect(statuses.filter((s) => s === 401)).toHaveLength(5); + expect(statuses.filter((s) => s === 429)).toHaveLength(25); + // The limiter is per client address. The owner pairing from another address is unaffected, + // which is exercised here at the layer below HTTP because the test has one address. + expect(h.bridge.devices.claimPairingCode(code, 'owner').ok).toBe(true); }); it('claim attempts are rate limited per client', async () => { @@ -590,6 +620,211 @@ describe('duplicates, retries, cancellation and recovery', () => { }); }); +describe('device revocation stops what the device started (CODY-004)', () => { + beforeEach(async () => { + h = await createHarness({ timing: { agentDeadlineMs: 30_000, cancelGraceMs: 2000 } }); + }); + + it('revoking over HTTP during a hanging run asks Hermes to stop and settles the turn', async () => { + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.hermes.next({ kind: 'hang' }); + const res = await h.textTurn(cred.token, conv, 'long job'); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'thinking'); + expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false); + + expect((await h.api('DELETE', '/v1/device', { token: cred.token })).status).toBe(200); + + // The device can no longer ask, so the outcome is read from the bridge's own records. + const row = () => h.bridge.db.prepare('SELECT state, outcome, cancel_requested FROM turns WHERE request_id = ?').get(id) as any; + const deadline = Date.now() + 3000; + while (row().state !== 'done' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10)); + expect(row()).toEqual({ state: 'done', outcome: 'cancelled', cancel_requested: 1 }); + expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1); + expect(h.hermes.lastRun()!.status).toBe('cancelled'); + + // Still unauthorized afterwards, for reads, new turns and cancels alike. + expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).status).toBe(401); + expect((await h.textTurn(cred.token, conv, 'again')).status).toBe(401); + expect((await h.api('POST', `/v1/turns/${id}/cancel`, { token: cred.token, json: {} })).status).toBe(401); + expect((await h.api('POST', '/v1/conversations', { token: cred.token, json: { schema_version: 1 } })).status).toBe(401); + expect(h.hermes.executions).toBe(1); + }); + + it('revoking from the operator CLI path (database only, no engine call) also stops the run', async () => { + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.hermes.next({ kind: 'hang' }); + const res = await h.textTurn(cred.token, conv, 'long job'); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'thinking'); + + // Exactly what `bridge:cli revoke` does: a second Devices instance on the same database + // file, as another process would have. The running engine is never called. + const { Devices } = await import('../../services/bridge/src/devices.ts'); + const { openDb } = await import('../../services/bridge/src/db.ts'); + const otherProcessDb = openDb(h.config.dbPath); + const [device] = h.bridge.devices.list(); + expect(new Devices(otherProcessDb, h.config).revoke(device!.id)).toBe(true); + otherProcessDb.close(); + + const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any; + const deadline = Date.now() + 3000; + while (row().state !== 'done' && Date.now() < deadline) await new Promise((r) => setTimeout(r, 10)); + expect(row()).toEqual({ state: 'done', outcome: 'cancelled' }); + expect(h.hermes.requests.filter((r) => r.path.endsWith('/stop'))).toHaveLength(1); + expect((await h.api('GET', '/v1/device', { token: cred.token })).status).toBe(401); + }); + + it('revoking during transcription aborts it and nothing reaches the agent', async () => { + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.stt.next({ delayMs: 350, text: 'never used' }); + const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'transcribing'); + const started = Date.now(); + await h.api('DELETE', '/v1/device', { token: cred.token }); + const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any; + while (row().state !== 'done' && Date.now() - started < 3000) await new Promise((r) => setTimeout(r, 5)); + expect(row()).toEqual({ state: 'done', outcome: 'cancelled' }); + // Settled by the abort, not by waiting for the recogniser to finish. + expect(Date.now() - started).toBeLessThan(250); + await new Promise((r) => setTimeout(r, 400)); + expect(h.hermes.executions).toBe(0); + }); + + it('a CLI-path revocation during transcription is picked up by the sweep and aborts the recogniser', async () => { + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.stt.next({ delayMs: 380, text: 'never used' }); + const res = await h.audioTurn(cred.token, conv, syntheticPcm(0.5)); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'transcribing'); + const { Devices } = await import('../../services/bridge/src/devices.ts'); + const { openDb } = await import('../../services/bridge/src/db.ts'); + const otherProcessDb = openDb(h.config.dbPath); + const started = Date.now(); + new Devices(otherProcessDb, h.config).revoke(h.bridge.devices.list()[0]!.id); + otherProcessDb.close(); + const row = () => h.bridge.db.prepare('SELECT state, outcome FROM turns WHERE request_id = ?').get(id) as any; + while (row().state !== 'done' && Date.now() - started < 3000) await new Promise((r) => setTimeout(r, 5)); + expect(row()).toEqual({ state: 'done', outcome: 'cancelled' }); + // Nobody in this process was told; only the periodic sweep can have aborted it this early. + expect(Date.now() - started).toBeLessThan(250); + await new Promise((r) => setTimeout(r, 400)); + expect(h.hermes.executions).toBe(0); + }); + + it('revoking one device leaves another device\'s running turn alone', async () => { + const a = await h.pair('a'); + const b = await h.pair('b'); + const convB = await h.conversation(b.token); + h.hermes.next({ kind: 'complete', afterMs: 300, output: 'b is fine' }); + const res = await h.textTurn(b.token, convB, 'b question'); + await h.waitState(b.token, res.body.request_id, 'thinking'); + await h.api('DELETE', '/v1/device', { token: a.token }); + const done = await h.waitTerminal(b.token, res.body.request_id); + expect(done.outcome).toBe('succeeded'); + expect(done.cancel_requested).toBe(false); + expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false); + }); +}); + +describe('approval wait and agent deadline survive a bridge restart (CODY-008)', () => { + it('restart BEFORE the original agent deadline: the approval timeout still fires at its original time', async () => { + h = await createHarness({ timing: { agentDeadlineMs: 5000, approvalWaitMs: 700, cancelGraceMs: 1000 } }); + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.hermes.next({ kind: 'approval' }); + const res = await h.textTurn(cred.token, conv, 'needs approval'); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'approval_required'); + const before = h.bridge.db.prepare('SELECT approval_started_at, agent_deadline_at FROM turns').get() as any; + expect(before.approval_started_at).toBeGreaterThan(0); + + await new Promise((r) => setTimeout(r, 400)); + // Polling must not have moved the recorded start of the wait. + expect((h.bridge.db.prepare('SELECT approval_started_at FROM turns').get() as any).approval_started_at).toBe(before.approval_started_at); + await h.restartBridge(); + const restartedAt = Date.now(); + const done = await h.waitTerminal(cred.token, id); + // 700 ms from first sight of the approval, not 700 ms from the restart. + expect(Date.now() - before.approval_started_at).toBeGreaterThanOrEqual(690); + expect(Date.now() - restartedAt).toBeLessThan(550); + expect(done.outcome).toBe('cancelled'); + expect(done.error?.code).toBe('approval_timeout'); + }); + + it('restart AFTER the original agent deadline, still awaiting approval: classified as approval timeout, not agent timeout', async () => { + h = await createHarness({ timing: { agentDeadlineMs: 300, approvalWaitMs: 1200, cancelGraceMs: 1000 } }); + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.hermes.next({ kind: 'approval' }); + const res = await h.textTurn(cred.token, conv, 'needs approval'); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'approval_required'); + const startedAt = (h.bridge.db.prepare('SELECT approval_started_at FROM turns').get() as any).approval_started_at; + await new Promise((r) => setTimeout(r, 500)); // the 300 ms agent deadline is now in the past + await h.restartBridge(); + // Not stopped on restart just because the unpaused agent deadline has passed. + await new Promise((r) => setTimeout(r, 200)); + expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).body.state).toBe('approval_required'); + const done = await h.waitTerminal(cred.token, id); + expect(done.error?.code).toBe('approval_timeout'); + expect(Date.now() - startedAt).toBeGreaterThanOrEqual(1190); + expect(Date.now() - startedAt).toBeLessThan(1900); + }); + + it('restart while waiting, then approved elsewhere: the run keeps the time it had left and completes', async () => { + h = await createHarness({ timing: { agentDeadlineMs: 600, approvalWaitMs: 5000, cancelGraceMs: 1000 } }); + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.hermes.next({ kind: 'approval' }); + const res = await h.textTurn(cred.token, conv, 'needs approval'); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'approval_required'); + await new Promise((r) => setTimeout(r, 400)); + await h.restartBridge(); + await new Promise((r) => setTimeout(r, 500)); // 900 ms since start: past the unpaused 600 ms deadline + const run = h.hermes.lastRun()!; + run.status = 'running'; // approved on another surface; the agent carries on for a while + await h.waitState(cred.token, id, 'thinking'); + const row = h.bridge.db.prepare('SELECT approval_started_at, agent_deadline_at, agent_started_at FROM turns').get() as any; + expect(row.approval_started_at).toBeNull(); + // The deadline was pushed back by the time spent waiting (about 900 ms), and stored. + expect(row.agent_deadline_at - row.agent_started_at).toBeGreaterThan(600 + 800); + + // A second restart must not lose or double the pause. + await h.restartBridge(); + await new Promise((r) => setTimeout(r, 150)); + expect((await h.api('GET', `/v1/turns/${id}`, { token: cred.token })).body.state).toBe('thinking'); + h.hermes.approve(run.runId, 'approved and finished'); + const done = await h.waitTerminal(cred.token, id); + expect(done.outcome).toBe('succeeded'); + expect(done.answer_text).toBe('approved and finished'); + expect(h.hermes.executions).toBe(1); + }); + + it('after approval and restart, the paused agent deadline still ends a run that never finishes, as an agent timeout', async () => { + h = await createHarness({ timing: { agentDeadlineMs: 500, approvalWaitMs: 5000, cancelGraceMs: 1000 } }); + const cred = await h.pair(); + const conv = await h.conversation(cred.token); + h.hermes.next({ kind: 'approval' }); + const res = await h.textTurn(cred.token, conv, 'needs approval'); + const id = res.body.request_id; + await h.waitState(cred.token, id, 'approval_required'); + await new Promise((r) => setTimeout(r, 300)); + h.hermes.lastRun()!.status = 'running'; + await h.waitState(cred.token, id, 'thinking'); + await h.restartBridge(); + const done = await h.waitTerminal(cred.token, id); + expect(done.outcome).toBe('cancelled'); + expect(done.error?.code).toBe('agent_timeout'); + }); +}); + describe('logging and retention', () => { it('logs carry ids, states and timings but never questions, answers, audio, tokens or keys', async () => { h = await createHarness(); diff --git a/tests/integration/client-bridge.test.ts b/tests/integration/client-bridge.test.ts index b114f18..cb1a600 100644 --- a/tests/integration/client-bridge.test.ts +++ b/tests/integration/client-bridge.test.ts @@ -16,7 +16,14 @@ let h: Harness; let device: FakeDevice; let controller: Controller; let snapshot: Snapshot; -let network: { down: boolean }; +let network: { + down: boolean; + /** Runs the real request, then loses the reply: the bridge acts, the client hears nothing. */ + dropReplies: boolean; + /** Optional per-request hook: return a promise to delay or reorder a reply. */ + hook: ((url: string, init: RequestInit | undefined, send: () => Promise) => Promise | null) | null; + sent: Array<{ method: string; path: string }>; +}; async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise { const deadline = Date.now() + timeoutMs; @@ -41,7 +48,20 @@ function makeController(dev: FakeDevice): Controller { baseUrl, token, timeoutMs: 500, - fetchImpl: (input, init) => (network.down ? Promise.reject(new TypeError('offline')) : fetch(input, init)), + fetchImpl: async (input, init) => { + if (network.down) throw new TypeError('offline'); + const url = String(input); + network.sent.push({ method: init?.method ?? 'GET', path: new URL(url).pathname }); + const send = () => fetch(input, init); + const hooked = network.hook?.(url, init, send); + if (hooked) return hooked; + const res = await send(); + if (network.dropReplies) { + await res.arrayBuffer(); + throw new TypeError('reply lost'); + } + return res; + }, }), onChange: (s) => { snapshot = s; @@ -60,7 +80,7 @@ async function pairedController(): Promise { } beforeEach(async () => { - network = { down: false }; + network = { down: false, dropReplies: false, hook: null, sent: [] }; h = await createHarness({ env: { HERMEVEN_CAPTURE_MAX_SECONDS: '2' } }); }); afterEach(async () => { @@ -197,7 +217,7 @@ describe('cancel and stale results', () => { }); describe('connection loss', () => { - it('bridge unreachable at submit: nothing is sent; tap resends the same request exactly once', async () => { + it('bridge unreachable at submit: tap resends the same request exactly once', async () => { await pairedController(); network.down = true; device.tap(); @@ -205,7 +225,8 @@ describe('connection loss', () => { device.speak(0.5); device.tap(); await until('disconnected', () => phase() === 'disconnected'); - expect(device.frame.body).toContain('has not been sent'); + expect(device.frame.body).toContain('not confirmed yet'); + expect(device.frame.body).not.toContain('not been sent'); expect(device.micOpen).toBe(false); const requestId = snapshot.state.requestId; @@ -340,3 +361,250 @@ describe('restart, revocation and disconnect', () => { for (const secret of ['walrus', 'narwhal', token]) expect(log).not.toContain(secret); }); }); + +describe('CODY-003: a submit whose reply is lost is ambiguous, never "not sent"', () => { + it('replies dropped after the bridge admitted the turn, then a client restart: one execution, same request id, re-attached', async () => { + await pairedController(); + // An ordinary first question, so a conversation exists before the connection turns bad. + controller.askText('hello'); + await until('first answer', () => phase() === 'answer'); + h.hermes.next({ kind: 'complete', afterMs: 400, output: 'the one and only answer' }); + h.stt.next({ text: 'transfer ten pounds' }); + + device.tap(); + await until('listening', () => phase() === 'listening' && device.micOpen); + device.speak(0.5); + // From now on every request reaches the bridge and is acted on, but no reply comes back. + network.dropReplies = true; + device.tap(); + await until('disconnected', () => phase() === 'disconnected'); + const requestId = snapshot.state.requestId!; + + // The bridge really did admit it, and Hermes really is running it. + await until('admitted by the bridge', () => h.hermes.executions === 2); + // The HUD does not claim the request was not sent. + for (const frame of device.frames) expect(frame.body).not.toMatch(/not been sent|was not sent|has not been sent/i); + expect(device.frame.body).toContain('not confirmed yet'); + // The id was stored before the first attempt, so a restart can find the turn. + expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId); + + // The page dies and comes back. The recording is gone; only storage survives. + await controller.stop(); + const reborn = new FakeDevice(); + for (const [k, v] of device.storage) reborn.storage.set(k, v); + device = reborn; + network.dropReplies = false; + controller = makeController(device); + await controller.start(); + + await until('answer after restart', () => phase() === 'answer'); + expect(device.frame.body).toBe('the one and only answer'); + expect(snapshot.lastTurn!.request_id).toBe(requestId); + // Two questions were asked in this test; the lost-reply one ran exactly once. + expect(h.hermes.executions).toBe(2); + expect(h.hermes.lastRun()!.input).toBe('transfer ten pounds'); + expect(h.stt.calls).toBe(1); + expect(device.micOpens).toBe(0); + expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBeNull(); + }); + + it('same loss without a restart: tapping retry re-attaches under the same id and still executes once', async () => { + await pairedController(); + controller.askText('hello'); + await until('first answer', () => phase() === 'answer'); + h.hermes.next({ kind: 'complete', afterMs: 200, output: 'answered once' }); + network.dropReplies = true; + controller.askText('do the thing'); + await until('disconnected', () => phase() === 'disconnected'); + const requestId = snapshot.state.requestId!; + network.dropReplies = false; + device.tap(); + await until('answer', () => phase() === 'answer'); + expect(snapshot.lastTurn!.request_id).toBe(requestId); + expect(device.frame.body).toBe('answered once'); + expect(h.hermes.executions).toBe(2); + expect(h.hermes.requests.filter((r) => r.method === 'POST' && r.path === '/v1/runs')).toHaveLength(2); + }); + + it('a request that truly never arrived is reported as such only after the bridge confirms it has no record', async () => { + await pairedController(); + network.down = true; + controller.askText('lost in the tunnel'); + await until('disconnected', () => phase() === 'disconnected'); + const requestId = snapshot.state.requestId!; + expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId); + + await controller.stop(); + const reborn = new FakeDevice(); + for (const [k, v] of device.storage) reborn.storage.set(k, v); + device = reborn; + network.down = false; + controller = makeController(device); + await controller.start(); + await until('confirmed absent', () => phase() === 'error'); + expect(snapshot.state.error).toMatchObject({ code: 'not_delivered', retryable: true }); + expect(device.frame.body).toContain('did not reach the bridge'); + expect(h.hermes.executions).toBe(0); + expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBeNull(); + }); + + it('a cancel that cannot be delivered is remembered and delivered on the next start, without showing the abandoned turn', async () => { + await pairedController(); + h.hermes.next({ kind: 'hang' }); + controller.askText('abandon me'); + await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1); + const requestId = snapshot.state.requestId!; + network.down = true; + device.doubleTap(); + expect(phase()).toBe('cancelled'); + await until('cancel recorded as pending', () => JSON.parse(device.storage.get('hermeven.v1')!).activeCancelled === true); + await new Promise((r) => setTimeout(r, 200)); + expect(JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId).toBe(requestId); + expect(h.hermes.requests.some((r) => r.path.endsWith('/stop'))).toBe(false); + + await controller.stop(); + const reborn = new FakeDevice(); + for (const [k, v] of device.storage) reborn.storage.set(k, v); + device = reborn; + network.down = false; + controller = makeController(device); + await controller.start(); + expect(phase()).toBe('ready'); + await until('stop reached Hermes', () => h.hermes.requests.some((r) => r.path.endsWith('/stop'))); + await until('slot cleared', () => JSON.parse(device.storage.get('hermeven.v1')!).activeRequestId === null); + expect(device.frames.every((f) => !f.body.includes('Thinking'))).toBe(true); + }); +}); + +describe('CODY-007: an expired credential is treated like a revoked one', () => { + const expireNow = () => h.bridge.db.prepare('UPDATE devices SET token_expires_at = ?').run(Date.now() - 1000); + + it('expiry during a live session: asking clears the local pairing and brings pairing back', async () => { + await pairedController(); + expect(snapshot.paired).toBe(true); + expireNow(); + controller.askText('still there?'); + await until('unpaired', () => phase() === 'unpaired'); + expect(snapshot.paired).toBe(false); + expect(device.storage.get('hermeven.v1')).toBe(''); + expect(device.frame.body).toContain('Open Hermeven on your phone to pair'); + expect(h.hermes.executions).toBe(0); + // Pairing works again straight away. + const { code } = h.bridge.devices.createPairingCode(); + await controller.pair(h.url, code, 'again'); + expect(phase()).toBe('ready'); + controller.askText('hello again'); + await until('answer', () => phase() === 'answer'); + }); + + it('expiry while waiting for an answer', async () => { + await pairedController(); + h.hermes.next({ kind: 'hang' }); + controller.askText('long one'); + await until('thinking', () => phase() === 'thinking' && h.hermes.executions === 1); + expireNow(); + await until('unpaired', () => phase() === 'unpaired'); + expect(device.storage.get('hermeven.v1')).toBe(''); + }); + + it('expiry noticed by the status refresh, by renew, and by new conversation', async () => { + for (const action of ['refresh', 'renew', 'conversation'] as const) { + await controller?.stop(); + await pairedController(); + expireNow(); + if (action === 'refresh') await controller.refreshStatus(); + else if (action === 'renew') await expect(controller.renew()).rejects.toMatchObject({ body: { code: 'credential_expired' } }); + else controller.newConversation(); + await until(`unpaired after ${action}`, () => phase() === 'unpaired'); + expect(snapshot.paired, action).toBe(false); + expect(device.storage.get('hermeven.v1'), action).toBe(''); + } + }); +}); + +describe('CODY-009: exactly one conversation is created, whatever the timing', () => { + const creates = () => network.sent.filter((r) => r.method === 'POST' && r.path === '/v1/conversations').length; + const serverActive = async () => { + const token = JSON.parse(device.storage.get('hermeven.v1')!).token; + return (await h.api('GET', '/v1/device', { token })).body.active_conversation_id as string; + }; + /** Hold every reply to a conversation create until released. */ + function holdCreates() { + const held: Array<() => void> = []; + network.hook = (url, init, send) => { + if (init?.method !== 'POST' || !url.endsWith('/v1/conversations')) return null; + return send().then((res) => new Promise((resolve) => held.push(() => resolve(res)))); + }; + return { + count: () => held.length, + release: (index: number) => held[index]!(), + }; + } + + it('"new conversation" pressed twice and a question asked at once, with the create reply delayed: one create, one stored id, the question succeeds', async () => { + await pairedController(); + const gate = holdCreates(); + device.menu(MENU_ITEM.NEW_CONVERSATION); + device.menu(MENU_ITEM.NEW_CONVERSATION); + controller.askText('first question in the new conversation'); + await until('create reached the bridge', () => gate.count() === 1); + await new Promise((r) => setTimeout(r, 150)); + expect(creates()).toBe(1); + expect(h.hermes.executions).toBe(0); // the turn is waiting for its conversation, not racing it + gate.release(0); + await until('answer', () => phase() === 'answer'); + expect(creates()).toBe(1); + const stored = JSON.parse(device.storage.get('hermeven.v1')!).conversationId; + expect(stored).toBe(snapshot.state.conversationId); + expect(stored).toBe(await serverActive()); + expect(snapshot.lastTurn!.conversation_id).toBe(stored); + expect(snapshot.lastTurn!.outcome).toBe('succeeded'); + expect(h.hermes.sessions.size).toBe(1); + }); + + it('first question right after pairing, cancelled and asked again while the lazy create is still pending: still one create', async () => { + await pairedController(); + const gate = holdCreates(); + controller.askText('one'); + await until('create reached the bridge', () => gate.count() === 1); + device.doubleTap(); // abandon the first question; the create it started is still in flight + controller.askText('two'); + await new Promise((r) => setTimeout(r, 150)); + expect(creates()).toBe(1); + gate.release(0); + await until('answer', () => phase() === 'answer'); + expect(creates()).toBe(1); + expect(h.hermes.lastRun()!.input).toBe('two'); + expect(h.hermes.executions).toBe(1); + expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBe(await serverActive()); + }); + + it('a reset during a pending create: replies arrive out of order, yet app and bridge agree on the live conversation and the next question succeeds', async () => { + await pairedController(); + const gate = holdCreates(); + controller.askText('one'); // lazy create A + await until('create A at the bridge', () => gate.count() === 1); + device.doubleTap(); + device.menu(MENU_ITEM.NEW_CONVERSATION); // reset: create B is wanted while A is unanswered + await new Promise((r) => setTimeout(r, 150)); + // B is not sent until A has settled, so the bridge can never process them in the wrong order. + expect(creates()).toBe(1); + expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBeNull(); + + gate.release(0); // A's reply arrives late, for a conversation the user has already replaced + await until('create B at the bridge', () => gate.count() === 2); + // A's result was dropped before persistence. + expect(JSON.parse(device.storage.get('hermeven.v1')!).conversationId).toBeNull(); + expect(snapshot.state.conversationId).toBeNull(); + controller.askText('first question after the reset'); // immediate first turn, B still pending + gate.release(1); + await until('answer', () => phase() === 'answer'); + + expect(creates()).toBe(2); // one per conversation the user asked for, never more + const stored = JSON.parse(device.storage.get('hermeven.v1')!).conversationId; + expect(stored).toBe(await serverActive()); + expect(snapshot.lastTurn!.conversation_id).toBe(stored); + expect(snapshot.lastTurn!.outcome).toBe('succeeded'); + expect(h.hermes.executions).toBe(1); + }); +}); diff --git a/tests/integration/clientSecurity.test.ts b/tests/integration/clientSecurity.test.ts new file mode 100644 index 0000000..1dd4024 --- /dev/null +++ b/tests/integration/clientSecurity.test.ts @@ -0,0 +1,230 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { CALL_TIMEOUT_MS, EvenDevice } from '../../apps/even-client/src/device/evenAdapter.ts'; +import { BridgeClient, isLoopbackHost, normalizeBridgeUrl } from '../../apps/even-client/src/net/bridgeClient.ts'; + +describe('CODY-001: the bridge address must be HTTPS, or HTTP to loopback only', () => { + const REMOTE_HTTP = [ + 'http://bridge.example.com', + 'http://bridge.example.com:8787/x', + 'http://203.0.113.7:8787', // public + 'http://192.168.1.20:8787', // private LAN + 'http://10.0.0.5', + 'http://172.16.4.4:80', + 'http://100.114.1.2:8787', // carrier-grade / tailnet range + 'http://169.254.1.1', + 'http://[fe80::1]:8787', + 'http://[2001:db8::1]', + 'http://0.0.0.0:8787', + 'http://localhost.example.com', // loopback look-alikes + 'http://127.0.0.1.example.com', + 'http://127.evil.example', + 'http://my-laptop.local:8787', + ]; + + it('rejects every public and private-LAN HTTP address', () => { + for (const url of REMOTE_HTTP) expect(() => normalizeBridgeUrl(url), url).toThrow(/https/); + }); + + it('rejects other schemes, credentials in the URL, and non-URLs', () => { + for (const url of ['ftp://bridge.example', 'ws://bridge.example', 'javascript:alert(1)', 'file:///etc/passwd', 'bridge.example', '']) { + expect(() => normalizeBridgeUrl(url), url).toThrow(); + } + expect(() => normalizeBridgeUrl('https://user:pass@bridge.example')).toThrow(/user name or password/); + }); + + it('accepts HTTPS anywhere and HTTP only on loopback', () => { + expect(normalizeBridgeUrl(' https://bridge.example.com/ ')).toBe('https://bridge.example.com'); + expect(normalizeBridgeUrl('https://192.168.1.20:8443/p/x/')).toBe('https://192.168.1.20:8443/p/x'); + expect(normalizeBridgeUrl('http://127.0.0.1:8787')).toBe('http://127.0.0.1:8787'); + expect(normalizeBridgeUrl('http://localhost:8787/')).toBe('http://localhost:8787'); + expect(normalizeBridgeUrl('http://[::1]:8787')).toBe('http://[::1]:8787'); + expect(normalizeBridgeUrl('http://127.8.9.10')).toBe('http://127.8.9.10'); + expect(isLoopbackHost('LOCALHOST')).toBe(false); // URL parsing lower-cases; raw input is not trusted + }); + + it('the HTTP client itself refuses a remote HTTP base URL, so no code path can bypass the check', () => { + expect(() => new BridgeClient({ baseUrl: 'http://192.168.1.20:8787' })).toThrow(/https/); + expect(() => new BridgeClient({ baseUrl: 'https://bridge.example.com' })).not.toThrow(); + }); + + describe('manifest generation', () => { + const script = fileURLToPath(new URL('../../apps/even-client/scripts/write-manifest.mjs', import.meta.url)); + let dir: string; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'hermeven-manifest-')); + }); + afterEach(() => rmSync(dir, { recursive: true, force: true })); + const run = (origin: string) => + spawnSync(process.execPath, [script], { + env: { ...process.env, HERMEVEN_BRIDGE_ORIGIN: origin, HERMEVEN_MANIFEST_OUT: join(dir, 'app.json') }, + encoding: 'utf8', + }); + + it('exits nonzero and writes nothing for remote HTTP origins', () => { + for (const origin of ['http://bridge.example.com', 'http://192.168.1.20:8787', 'http://10.0.0.5', 'http://localhost.example.com']) { + const res = run(origin); + expect(res.status, origin).toBe(1); + expect(res.stderr).toContain('https://'); + expect(existsSync(join(dir, 'app.json')), origin).toBe(false); + } + }); + + it('writes the whitelist for HTTPS, and for loopback HTTP with a warning', () => { + const https = run('https://bridge.example.com'); + expect(https.status).toBe(0); + const manifest = JSON.parse(readFileSync(join(dir, 'app.json'), 'utf8')); + expect(manifest.permissions[0]).toMatchObject({ name: 'network', whitelist: ['https://bridge.example.com'] }); + const loopback = run('http://127.0.0.1:8787'); + expect(loopback.status).toBe(0); + expect(loopback.stderr).toContain('simulator only'); + }); + + it('still refuses origins with a path', () => { + expect(run('https://bridge.example.com/api').status).toBe(1); + }); + }); +}); + +describe('CODY-002: host calls stay serialised and a late microphone start ends closed', () => { + type Call = { name: string; args: unknown[]; resolve: (value: unknown) => void; settled: boolean }; + + /** A stand-in for the Even host whose calls settle only when the test says so. */ + function fakeHost() { + const calls: Call[] = []; + let inFlight = 0; + let maxInFlight = 0; + let micOpen = false; + const call = (name: string, args: unknown[], onSettle?: (value: unknown) => void) => + new Promise((resolve) => { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + const entry: Call = { + name, + args, + settled: false, + resolve: (value) => { + entry.settled = true; + inFlight -= 1; + onSettle?.(value); + resolve(value); + }, + }; + calls.push(entry); + }); + const bridge = { + createStartUpPageContainer: (...a: unknown[]) => call('create', a), + textContainerUpgrade: (...a: unknown[]) => call('text', a), + audioControl: (open: boolean, ...rest: unknown[]) => + call(open ? 'mic_on' : 'mic_off', [open, ...rest], (ok) => { + if (ok) micOpen = open; + }), + shutDownPageContainer: (...a: unknown[]) => call('exit', a), + getLocalStorage: (...a: unknown[]) => call('get', a), + setLocalStorage: (...a: unknown[]) => call('set', a), + }; + return { bridge, calls, micOpen: () => micOpen, maxInFlight: () => maxInFlight, pending: () => calls.filter((c) => !c.settled) }; + } + const tick = async () => { + for (let i = 0; i < 10; i++) await Promise.resolve(); + }; + + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('timeout, then the host opens the microphone late: the microphone ends closed and calls never overlap', async () => { + const host = fakeHost(); + const device = new EvenDevice(host.bridge as never); + + const starting = device.startMic(); + await tick(); + expect(host.pending().map((c) => c.name)).toEqual(['mic_on']); + + // The host does not answer within the caller's timeout. + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1); + expect(await starting).toBe(false); // the app is told the microphone did not open + + // Nothing else has been sent to the host while the start is still pending. + expect(host.calls.map((c) => c.name)).toEqual(['mic_on']); + expect(host.maxInFlight()).toBe(1); + + // Now the late completion arrives: the host really did open the microphone. + host.pending()[0]!.resolve(true); + await tick(); + expect(host.micOpen()).toBe(true); + // The compensating stop goes out next, strictly after the start settled. + expect(host.calls.map((c) => c.name)).toEqual(['mic_on', 'mic_off']); + host.pending()[0]!.resolve(true); + await tick(); + expect(host.micOpen()).toBe(false); + expect(host.maxInFlight()).toBe(1); + expect(host.pending()).toEqual([]); + }); + + it('a stop requested while the start is still pending waits its turn and still leaves the microphone closed', async () => { + const host = fakeHost(); + const device = new EvenDevice(host.bridge as never); + const starting = device.startMic(); + await tick(); + const stopping = device.stopMic(); // user cancelled while the microphone was opening + device.show({ body: 'x', status: 'y' }); + await tick(); + expect(host.calls.map((c) => c.name)).toEqual(['mic_on']); // stop is queued, not sent alongside + + host.pending()[0]!.resolve(true); + await tick(); + expect(await starting).toBe(true); + expect(host.calls.map((c) => c.name)).toEqual(['mic_on', 'mic_off']); + host.pending()[0]!.resolve(true); + await stopping; + expect(host.micOpen()).toBe(false); + expect(host.maxInFlight()).toBe(1); + }); + + it('a start that times out and then fails late leaves nothing open and the queue usable', async () => { + const host = fakeHost(); + const device = new EvenDevice(host.bridge as never); + const starting = device.startMic(); + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1); + expect(await starting).toBe(false); + host.pending()[0]!.resolve(false); // the host refused after all + await tick(); + host.pending()[0]!.resolve(true); // the compensating stop + await tick(); + expect(host.micOpen()).toBe(false); + + // A later start works normally. + const again = device.startMic(); + await tick(); + host.pending()[0]!.resolve(true); + expect(await again).toBe(true); + expect(host.micOpen()).toBe(true); + expect(host.maxInFlight()).toBe(1); + }); + + it('many calls behind a stuck one each time out for their caller but are sent one at a time, in order', async () => { + const host = fakeHost(); + const device = new EvenDevice(host.bridge as never); + const a = device.storageGet('a'); + const b = device.storageSet('b', '1'); + const c = device.requestExit(); + await tick(); + expect(host.calls.map((x) => x.name)).toEqual(['get']); + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT_MS + 1); + expect(await a).toBe(''); // bounded for the caller + await b; + await c; + expect(host.calls.map((x) => x.name)).toEqual(['get']); // still only the stuck call at the host + host.pending()[0]!.resolve('late'); + await tick(); + expect(host.calls.map((x) => x.name)).toEqual(['get', 'set']); + host.pending()[0]!.resolve(true); + await tick(); + expect(host.calls.map((x) => x.name)).toEqual(['get', 'set', 'exit']); + expect(host.maxInFlight()).toBe(1); + }); +}); diff --git a/tests/integration/harness.ts b/tests/integration/harness.ts index 14646c8..0799497 100644 --- a/tests/integration/harness.ts +++ b/tests/integration/harness.ts @@ -79,6 +79,8 @@ export async function createHarness( const boot = async () => { h.bridge = await createBridge(config, { timing, + // Fast sweep so a database-only revocation (the operator CLI path) is seen quickly. + cancelSweepMs: 25, logger: pino({ level: 'debug', redact: { paths: LOG_REDACT, censor: '[redacted]' } }, sink), }); await h.bridge.app.listen({ host: '127.0.0.1', port: 0 }); diff --git a/tests/real-stt/offlineProbe.mts b/tests/real-stt/offlineProbe.mts new file mode 100644 index 0000000..4a22947 --- /dev/null +++ b/tests/real-stt/offlineProbe.mts @@ -0,0 +1,24 @@ +// Run inside a network namespace with no interfaces (`unshare -rn`). Proves the built-in +// speech model verifies and transcribes with no network at all. Prints one JSON line. +import { readFileSync } from 'node:fs'; +import { loadConfig } from '../../services/bridge/src/config.ts'; +import { BuiltinWhisperStt } from '../../services/bridge/src/stt/builtinWhisper.ts'; + +const [modelDir, wavPath] = process.argv.slice(2); +let networkReachable = true; +try { + await fetch('https://huggingface.co/', { signal: AbortSignal.timeout(3000) }); +} catch { + networkReachable = false; +} +const config = loadConfig({ HERMES_API_KEY: 'unused', HERMEVEN_DB_PATH: ':memory:', STT_MODEL_DIR: modelDir }); +const stt = new BuiltinWhisperStt({ manifest: config.stt.manifest!, modelDir: config.stt.modelDir }); +let text = ''; +let error: string | null = null; +try { + text = await stt.transcribe({ pcm: readFileSync(wavPath!).subarray(44), locale: 'en-US', signal: new AbortController().signal }); +} catch (err) { + error = `${(err as Error).name}:${stt.lastLoadFailure}`; +} +await stt.close(); +console.log(JSON.stringify({ networkReachable, text, error, revision: config.stt.manifest!.revision })); diff --git a/tests/real-stt/realStt.test.ts b/tests/real-stt/realStt.test.ts index 21f914c..ba03b9c 100644 --- a/tests/real-stt/realStt.test.ts +++ b/tests/real-stt/realStt.test.ts @@ -1,8 +1,11 @@ -import { readFileSync } from 'node:fs'; -import { dirname, resolve } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { chmodSync, cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { BuiltinWhisperStt } from '../../services/bridge/src/stt/builtinWhisper.ts'; +import { fetchModel, modelPath, verifyModel, type ModelManifest } from '../../services/bridge/src/stt/modelStore.mjs'; import { createHarness, type Harness } from '../integration/harness.ts'; /** @@ -15,30 +18,59 @@ import { createHarness, type Harness } from '../integration/harness.ts'; */ const here = dirname(fileURLToPath(import.meta.url)); const speech = readFileSync(resolve(here, 'fixtures/jfk.wav')).subarray(44); // strip the WAV header: raw PCM +const store = resolve(here, '.cache'); let h: Harness; let token: string; let conversation: string; +let manifest: ModelManifest; +const scratch: string[] = []; + +function chmodTree(path: string, dirMode: number, fileMode: number): void { + chmodSync(path, dirMode); + for (const entry of readdirSync(path, { withFileTypes: true })) { + const child = join(path, entry.name); + if (entry.isDirectory()) chmodTree(child, dirMode, fileMode); + else chmodSync(child, fileMode); + } +} +/** A private copy of the verified model store, so a test can damage or lock it. */ +function copyStore(): string { + const dir = mkdtempSync(join(tmpdir(), 'hermeven-model-copy-')); + scratch.push(dir); + cpSync(store, dir, { recursive: true }); + return dir; +} beforeAll(async () => { h = await createHarness({ stt: false, env: { STT_PROVIDER: 'builtin', - STT_CACHE_DIR: resolve(here, '.cache'), + STT_MODEL_DIR: store, HERMEVEN_CAPTURE_MAX_SECONDS: '30', }, timing: { transcribeDeadlineMs: 120_000, agentDeadlineMs: 30_000 }, }); expect(h.bridge.stt).toBeInstanceOf(BuiltinWhisperStt); + manifest = h.config.stt.manifest!; + // The deployment step: fetch the pinned revision from the real hub and verify every file + // against the SHA-256 values committed in services/bridge/models/. Files already present and + // correct are not downloaded again. + const fetched = await fetchModel(store, manifest); + console.info(`[real-stt] pinned ${manifest.model}@${manifest.revision}: ${fetched.verified} files verified, ${fetched.downloaded} downloaded`); const started = Date.now(); await (h.bridge.stt as BuiltinWhisperStt).warm(); - console.info(`[real-stt] model ${h.config.stt.model} (${h.config.stt.dtype}) loaded in ${Date.now() - started} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`); + console.info(`[real-stt] model verified and loaded in ${Date.now() - started} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`); token = (await h.pair()).token; conversation = await h.conversation(token); }); afterAll(async () => { await h?.close(); + for (const dir of scratch) { + if (existsSync(dir)) chmodTree(dir, 0o700, 0o600); + rmSync(dir, { recursive: true, force: true }); + } }); describe('built-in Whisper speech-to-text', () => { @@ -105,21 +137,8 @@ describe('built-in Whisper speech-to-text', () => { expect(doneB.input_text).toContain('fellow Americans'); }); - it('a model that cannot be loaded makes speech "unavailable" without taking the bridge down', async () => { - const broken = new BuiltinWhisperStt({ model: 'hermeven-test/does-not-exist', dtype: 'q8', cacheDir: resolve(here, '.cache') }); - try { - const err = await broken - .transcribe({ pcm: Buffer.from(speech.subarray(0, 32000)), locale: 'en-US', signal: new AbortController().signal }) - .catch((e) => e); - expect(err).toMatchObject({ name: 'SttError', kind: 'unavailable' }); - } finally { - await broken.close(); - } - expect((await h.api('GET', '/healthz')).status).toBe(200); - }); - it('closing the adapter stops its worker thread, and a closed adapter refuses further work', async () => { - const stt = new BuiltinWhisperStt({ model: h.config.stt.model, dtype: h.config.stt.dtype, cacheDir: resolve(here, '.cache') }); + const stt = new BuiltinWhisperStt({ manifest, modelDir: store }); const signal = new AbortController().signal; expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans'); await stt.close(); @@ -134,4 +153,77 @@ describe('built-in Whisper speech-to-text', () => { expect(done.outcome).toBe('succeeded'); expect((done.input_text ?? '').toLowerCase()).toContain('fellow americans'); }); + + describe('deployment checks (CODY-005): pinned, verified, offline, read-only', () => { + const signal = new AbortController().signal; + + it('the real artifacts on disk match the committed pins', async () => { + expect(await verifyModel(store, manifest)).toEqual({ ok: true }); + expect(manifest.revision).toMatch(/^[0-9a-f]{40}$/); + }); + + it('one changed byte in the real model: load is refused as a mismatch, speech is unavailable, the bridge keeps running', async () => { + const dir = copyStore(); + const target = join(modelPath(dir, manifest), 'onnx/encoder_model_quantized.onnx'); + const bytes = readFileSync(target); + const middle = bytes.length >> 1; + bytes[middle] = bytes[middle]! ^ 0x01; + writeFileSync(target, bytes); + expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'onnx/encoder_model_quantized.onnx' }); + const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); + try { + await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); + expect(stt.lastLoadFailure).toBe('mismatch'); + } finally { + await stt.close(); + } + expect((await h.api('GET', '/healthz')).status).toBe(200); + }); + + it('a missing file is refused as missing, with no attempt to download it', async () => { + const dir = copyStore(); + rmSync(join(modelPath(dir, manifest), 'tokenizer.json')); + const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); + try { + await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); + expect(stt.lastLoadFailure).toBe('missing'); + } finally { + await stt.close(); + } + expect(existsSync(join(modelPath(dir, manifest), 'tokenizer.json'))).toBe(false); + }); + + it('transcribes from a read-only model store and writes nothing into it', async () => { + const dir = copyStore(); + chmodTree(dir, 0o500, 0o400); + const before = readdirSync(modelPath(dir, manifest), { recursive: true }).sort(); + const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); + try { + expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans'); + } finally { + await stt.close(); + } + expect(readdirSync(modelPath(dir, manifest), { recursive: true }).sort()).toEqual(before); + }); + + it('verifies and transcribes with no network at all (network namespace with no interfaces)', () => { + const probe = spawnSync( + 'unshare', + ['-rn', process.execPath, '--import', 'tsx', resolve(here, 'offlineProbe.mts'), store, resolve(here, 'fixtures/jfk.wav')], + { encoding: 'utf8', cwd: resolve(here, '../../services/bridge'), timeout: 120_000 }, + ); + if (probe.error || (probe.status !== 0 && /unshare|Operation not permitted/i.test(probe.stderr))) { + // Reported, not hidden: on this machine the offline proof could not be run. + console.info(`[real-stt] OFFLINE CHECK NOT RUN: unprivileged network namespaces are unavailable (${(probe.stderr || String(probe.error)).trim().slice(0, 120)})`); + return; + } + expect(probe.status, probe.stderr.slice(-500)).toBe(0); + const out = JSON.parse(probe.stdout.trim().split('\n').at(-1)!); + console.info(`[real-stt] offline run: networkReachable=${out.networkReachable} transcript=${JSON.stringify(out.text)}`); + expect(out.networkReachable).toBe(false); + expect(out.error).toBeNull(); + expect(out.revision).toBe(manifest.revision); + expect(out.text).toContain('ask not what your country can do for you'); + }); + }); });