Files
hermeven/services/bridge/src/db.ts
T
DanandClaude Fable 5.2 e1c02d5266 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>
2026-11-18 19:49:14 -08:00

123 lines
4.1 KiB
TypeScript

import Database from 'better-sqlite3';
import { chmodSync, closeSync, existsSync, mkdirSync, openSync } from 'node:fs';
import { dirname } from 'node:path';
export type Db = Database.Database;
const MIGRATIONS: string[] = [
`
CREATE TABLE devices (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
profile TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
token_expires_at INTEGER NOT NULL,
pairing_expires_at INTEGER NOT NULL,
revoked_at INTEGER,
last_seen_at INTEGER
);
CREATE TABLE pairing_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code_hash TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
used_at INTEGER,
failed_attempts INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE conversations (
id TEXT PRIMARY KEY,
device_id TEXT NOT NULL REFERENCES devices(id),
-- Opaque reference into Hermes. Generated by the bridge, never accepted from a client.
hermes_session_id TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
closed_at INTEGER
);
CREATE INDEX conversations_device ON conversations(device_id, closed_at);
CREATE TABLE turns (
request_id TEXT PRIMARY KEY,
device_id TEXT NOT NULL REFERENCES devices(id),
conversation_id TEXT NOT NULL REFERENCES conversations(id),
input_kind TEXT NOT NULL,
-- SHA-256 of metadata + input bytes: detects a reused request_id with a different payload.
input_fingerprint TEXT NOT NULL,
locale TEXT NOT NULL,
state TEXT NOT NULL,
outcome TEXT,
error_code TEXT,
error_message TEXT,
cancel_requested INTEGER NOT NULL DEFAULT 0,
hermes_idempotency_key TEXT NOT NULL,
hermes_run_id TEXT,
-- Exact Hermes request body, held only between "about to submit" and "run id persisted"
-- so a crash in that window can replay the same idempotent request. Cleared afterwards.
pending_body TEXT,
-- Result cache, cleared after the retention window. Hermes stays the transcript authority.
input_text TEXT,
answer_text TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
agent_started_at INTEGER,
approval_started_at INTEGER,
completed_at INTEGER,
transcribe_ms INTEGER,
agent_ms INTEGER
);
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:') {
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;
}
function migrate(db: Db): void {
const current = db.pragma('user_version', { simple: true }) as number;
for (let v = current; v < MIGRATIONS.length; v++) {
const sql = MIGRATIONS[v]!;
db.transaction(() => {
db.exec(sql);
db.pragma(`user_version = ${v + 1}`);
})();
}
}