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
+43
View File
@@ -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
}
]
}
+43
View File
@@ -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
}
]
}
+7 -3
View File
@@ -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<Bridge> {
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?.();
+34 -7
View File
@@ -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 <device-id> 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<void> {
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);
}
});
+41 -16
View File
@@ -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/<name>.json`. */
export function bundledManifestPath(name: string): string {
return fileURLToPath(new URL(`../models/${name}.json`, import.meta.url));
}
function loadModelManifest(name: string, customPath: string | undefined): ModelManifest {
let path: string;
if (customPath) {
path = customPath;
} else {
if (!/^[a-z0-9][a-z0-9.-]*$/.test(name)) {
throw new ConfigError('STT_MODEL must be the name of a bundled pinned model (whisper-base, whisper-tiny)');
}
path = bundledManifestPath(name);
if (!existsSync(path)) {
throw new ConfigError(
`STT_MODEL "${name}" has no bundled pinned manifest. Use whisper-base or whisper-tiny, or point ` +
'STT_MODEL_MANIFEST at a manifest that pins a commit id and a SHA-256 for every file.',
);
}
}
try {
return validateManifest(JSON.parse(readFileSync(path, 'utf8')));
} catch (err) {
throw new ConfigError(`Speech model manifest could not be used: ${err instanceof Error ? err.message : 'unreadable'}`);
}
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
const host = env.HERMEVEN_HOST || '127.0.0.1';
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
@@ -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',
+34 -2
View File
@@ -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;
}
+21 -19
View File
@@ -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;
})();
}
+18 -7
View File
@@ -11,14 +11,25 @@ async function main(): Promise<void> {
});
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',
),
);
}
+3 -7
View File
@@ -171,12 +171,8 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
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<FastifyInstance> {
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 };
});
+15 -10
View File
@@ -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<Recognizer>;
}
@@ -58,6 +59,8 @@ export class BuiltinWhisperStt implements SttAdapter {
private recognizer: Promise<Recognizer> | 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<unknown> = 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<string, unknown> = this.opts.model.endsWith('.en')
const options: Record<string, unknown> = this.opts.manifest.model.endsWith('.en')
? {}
: { language: request.locale.split('-')[0]!.toLowerCase(), task: 'transcribe' };
try {
+24
View File
@@ -0,0 +1,24 @@
export interface ModelFile {
path: string;
sha256: string;
bytes: number;
}
export interface ModelManifest {
name: string;
/** Hugging Face hub id, `<owner>/<name>`. */
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<VerifyResult>;
export function fetchModel(
dir: string,
manifest: ModelManifest,
options?: { baseUrl?: string; fetchImpl?: typeof fetch; onFile?: (path: string, bytes: number) => void },
): Promise<{ downloaded: number; verified: number }>;
+123
View File
@@ -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 <owner>/<name>');
// 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 };
}
+22 -8
View File
@@ -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;
}
+54 -6
View File
@@ -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<string | null> {
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<void> {
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');
}
+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;