Address Cody review round 2: all ten findings (CODY-001 to CODY-010)

CODY-001 Bridge URL must be HTTPS (HTTP only to loopback), in the client and
         in manifest generation.
CODY-002 Even host calls stay serialised until the SDK call really settles;
         a microphone start that completes after its timeout is followed by
         a stop.
CODY-003 Request id is stored before the first submit and cleared only on a
         definitive answer; lost replies are treated as ambiguous and
         reconciled under the same id; HUD no longer claims "not sent".
CODY-004 Revoking a device cancels its in-flight turns, aborts
         transcription and asks Hermes to stop, from HTTP and CLI paths.
CODY-005 Speech model pinned to a commit with per-file SHA-256; fetched and
         verified ahead of time; verified on every load; never downloaded
         at run time; no unpinned configuration.
CODY-006 State directory 0700, database/WAL/SHM 0600 regardless of umask.
CODY-007 credential_expired handled like unauthorized on every path.
CODY-008 Approval wait start and paused agent deadline persisted and
         restored across restarts (schema v2).
CODY-009 Exactly one conversation create per epoch, sent in sequence, with
         stale results dropped before persistence.
CODY-010 Wrong pairing guesses no longer consume the outstanding code;
         failures are indistinguishable.

Checks: typecheck clean; npm test 182 passed; client build ok;
test:real-stt 11 passed (including with no network); test:real-hermes 9
passed; test:simulator 6 passed; git diff --check clean.

Not reviewed. No physical-device, droplet or production evidence.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-18 19:49:14 -08:00
co-authored by Claude Fable 5.2
parent 3d5691dfa3
commit e1c02d5266
43 changed files with 2104 additions and 227 deletions
+242 -7
View File
@@ -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();
+273 -5
View File
@@ -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<Response>) => Promise<Response> | null) | null;
sent: Array<{ method: string; path: string }>;
};
async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise<void> {
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<void> {
}
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<Response>((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);
});
});
+230
View File
@@ -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);
});
});
+2
View File
@@ -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 });