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
+5 -6
View File
@@ -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<string, unknown> }> = [];
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');
+196
View File
@@ -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<string, Buffer> = {
'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<string, Buffer>;
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<void>((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<void>((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();
});
});
+63
View File
@@ -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<string, string> = {}) => {
let now = 1_000_000;