import { execFileSync, spawnSync } 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, secureStateDir, StateDirectoryError } from '../src/db.ts'; import { Devices } from '../src/devices.ts'; import { buildRunBody } from '../src/hermes/adapter.ts'; import { mapRunStatus } from '../src/hermes/runsAdapter.ts'; import { RateLimiter } from '../src/ratelimit.ts'; import { pcmToWav } from '../src/stt/adapter.ts'; const base = { HERMES_API_KEY: 'k', HERMEVEN_DB_PATH: ':memory:', STT_PROVIDER: 'none' }; describe('configuration', () => { it('binds loopback by default and refuses a public bind without an explicit acknowledgement', () => { expect(loadConfig(base).host).toBe('127.0.0.1'); expect(() => loadConfig({ ...base, HERMEVEN_HOST: '0.0.0.0' })).toThrow(ConfigError); expect(loadConfig({ ...base, HERMEVEN_HOST: '0.0.0.0', HERMEVEN_ALLOW_NON_LOOPBACK: 'true' }).host).toBe('0.0.0.0'); }); it('requires https for Hermes and STT outside loopback', () => { expect(() => loadConfig({ ...base, HERMES_BASE_URL: 'http://hermes.example:8642' })).toThrow(/https/); expect(loadConfig({ ...base, HERMES_BASE_URL: 'https://hermes.example/p/work/' }).hermes.baseUrl).toBe('https://hermes.example/p/work'); expect(() => loadConfig({ ...base, STT_PROVIDER: 'openai-compatible', STT_BASE_URL: 'http://stt.example/v1', STT_MODEL: 'm' }), ).toThrow(/https/); }); it('requires a Hermes key and exact CORS origins', () => { expect(() => loadConfig({ HERMEVEN_DB_PATH: ':memory:' })).toThrow(/HERMES_API_KEY/); expect(() => loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: '*' })).toThrow(ConfigError); expect(() => loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: 'https://a.example/path' })).toThrow(ConfigError); expect(loadConfig({ ...base, HERMEVEN_ALLOWED_ORIGINS: 'https://a.example, http://localhost:5173' }).allowedOrigins).toEqual([ 'https://a.example', 'http://localhost:5173', ]); }); it('derives the audio byte cap from the capture cap and never puts secrets in error text', () => { const config = loadConfig({ ...base, HERMEVEN_CAPTURE_MAX_SECONDS: '10' }); expect(config.limits.audioMaxBytes).toBe(11 * 32000); try { loadConfig({ ...base, HERMES_API_KEY: 'super-secret', HERMEVEN_PORT: 'abc' }); throw new Error('should have thrown'); } catch (err) { expect(String(err)).not.toContain('super-secret'); } }); }); 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('a PRE-EXISTING state directory at 0755 is tightened to 0700 under umask 0022, with database, WAL and SHM at 0600', () => { const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); const stateDir = join(root, 'state'); const dbPath = join(stateDir, 'hermeven.sqlite'); const script = ` process.umask(0o022); const fs = await import('node:fs'); fs.mkdirSync(${JSON.stringify(stateDir)}); fs.chmodSync(${JSON.stringify(stateDir)}, 0o755); const m = (p) => (fs.statSync(p).mode & 0o777).toString(8); const before = m(${JSON.stringify(stateDir)}); const { openDb } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))}); const db = openDb(${JSON.stringify(dbPath)}); db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run(); console.log(JSON.stringify({ umask: process.umask().toString(8), before, dir: m(${JSON.stringify(stateDir)}), 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({ umask: '22', before: '755', dir: '700', db: '600', wal: '600', shm: '600' }); expect(mode(stateDir)).toBe(0o700); } finally { rmSync(root, { recursive: true, force: true }); } }); it('other loose directory modes (0750, 0777, 0711) are all tightened to exactly 0700', async () => { const { chmodSync, mkdirSync } = await import('node:fs'); for (const loose of [0o750, 0o777, 0o711, 0o701]) { const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); const stateDir = join(root, 'state'); mkdirSync(stateDir); chmodSync(stateDir, loose); try { openDb(join(stateDir, 'hermeven.sqlite')).close(); expect(mode(stateDir), loose.toString(8)).toBe(0o700); expect(mode(join(stateDir, 'hermeven.sqlite'))).toBe(0o600); } finally { rmSync(root, { recursive: true, force: true }); } } }); it('a directory that cannot be secured stops the bridge with an operator-facing error, and nothing is created in it', async () => { const { existsSync, statSync: stat } = await import('node:fs'); // A world-writable directory owned by someone else (root's /tmp) cannot be chmod-ed by us. const shared = '/tmp'; if (!existsSync(shared) || stat(shared).uid === process.getuid?.()) { console.info('[units] NOT RUN: no directory owned by another user is available to test the refusal'); return; } const dbPath = join(shared, `hermeven-refusal-test-${process.pid}.sqlite`); let error: unknown; try { openDb(dbPath).close(); } catch (err) { error = err; } expect(error).toBeInstanceOf(StateDirectoryError); expect((error as Error).message).toContain('/tmp'); expect((error as Error).message).toMatch(/mode 0700/); expect((error as Error).message).toMatch(/install -d -m 0700|HERMEVEN_DB_PATH/); expect(existsSync(dbPath)).toBe(false); expect(stat(shared).mode & 0o777).not.toBe(0o700); // and we did not change it }); describe('ownership: a 0700 directory is only private if it is ours', () => { const snapshotOf = (path: string) => { const s = statSync(path); return { mode: s.mode & 0o7777, uid: s.uid, gid: s.gid, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs }; }; it('a foreign-owned directory that is ALREADY 0700 is refused, nothing is created, and it is not touched (the real /root)', async () => { const { existsSync, readdirSync } = await import('node:fs'); const foreign = '/root'; const isFixture = existsSync(foreign) && statSync(foreign).uid !== process.geteuid!() && (statSync(foreign).mode & 0o777) === 0o700; if (!isFixture) { console.info('[units] NOT RUN on the real /root: it is not a foreign-owned 0700 directory here (the namespace and injected-uid tests below still cover this)'); return; } const before = snapshotOf(foreign); const dbPath = join(foreign, `hermeven-foreign-owner-test-${process.pid}.sqlite`); expect(() => secureStateDir(foreign)).toThrow(StateDirectoryError); let error: unknown; try { openDb(dbPath).close(); } catch (err) { error = err; } expect(error).toBeInstanceOf(StateDirectoryError); expect((error as Error).message).toContain('/root'); expect((error as Error).message).toMatch(/owned by uid 0, not by the bridge/); expect((error as Error).message).toMatch(/left untouched/); expect((error as Error).message).toMatch(/install -d -m 0700/); expect(snapshotOf(foreign)).toEqual(before); // We cannot list /root, which is the point; the refusal happened before any create call. expect(() => readdirSync(foreign)).toThrow(); }); it('deterministic everywhere: a 0700 directory with a different owner uid is refused before SQLite creates or opens anything, and is not mutated', async () => { const { chmodSync, mkdirSync, readdirSync, writeFileSync, existsSync } = await import('node:fs'); const root = mkdtempSync(join(tmpdir(), 'hermeven-owner-')); const stateDir = join(root, 'state'); mkdirSync(stateDir); chmodSync(stateDir, 0o700); const dbPath = join(stateDir, 'hermeven.sqlite'); const someoneElse = process.geteuid!() + 1; // the bridge "runs as" a uid that does not own the directory try { const before = snapshotOf(stateDir); expect(() => secureStateDir(stateDir, someoneElse)).toThrow(StateDirectoryError); let error: unknown; try { openDb(dbPath, { effectiveUid: someoneElse }).close(); } catch (err) { error = err; } expect(error).toBeInstanceOf(StateDirectoryError); expect((error as Error).message).toMatch(new RegExp(`owned by uid ${process.geteuid!()}, not by the bridge`)); expect(readdirSync(stateDir)).toEqual([]); // no database, WAL, SHM or anything else expect(existsSync(dbPath)).toBe(false); expect(snapshotOf(stateDir)).toEqual(before); // An existing database in a foreign-owned directory is not opened either. writeFileSync(dbPath, ''); const withFile = snapshotOf(stateDir); expect(() => openDb(dbPath, { effectiveUid: someoneElse })).toThrow(StateDirectoryError); expect(readdirSync(stateDir)).toEqual(['hermeven.sqlite']); expect(statSync(dbPath).size).toBe(0); // SQLite never wrote a header into it expect(snapshotOf(stateDir)).toEqual(withFile); // Sanity: the same directory is accepted for its real owner. openDb(dbPath).close(); } finally { rmSync(root, { recursive: true, force: true }); } }); it('a foreign-owned directory with a LOOSE mode is refused without being chmod-ed', async () => { const { chmodSync, mkdirSync, readdirSync } = await import('node:fs'); const root = mkdtempSync(join(tmpdir(), 'hermeven-owner-')); const stateDir = join(root, 'state'); mkdirSync(stateDir); chmodSync(stateDir, 0o755); try { expect(() => openDb(join(stateDir, 'hermeven.sqlite'), { effectiveUid: process.geteuid!() + 1 })).toThrow(/left untouched/); expect(mode(stateDir)).toBe(0o755); // not "fixed" on someone else's behalf expect(readdirSync(stateDir)).toEqual([]); } finally { rmSync(root, { recursive: true, force: true }); } }); it('isolated user fixture: inside a user namespace, with the real process uid and no injection, a foreign-owned 0700 directory is refused', () => { // In `unshare -r` this process is uid 0 and the real root's /root appears as owned by the // overflow uid: a genuine foreign owner, checked by the unmodified production code path. const script = ` const fs = await import('node:fs'); const { openDb, StateDirectoryError } = await import(${JSON.stringify(fileURLToPath(new URL('../src/db.ts', import.meta.url)))}); const dir = '/root'; const st = fs.statSync(dir); const before = { mode: st.mode & 0o7777, uid: st.uid, mtimeMs: st.mtimeMs, ctimeMs: st.ctimeMs }; let outcome = 'ACCEPTED_FOREIGN_OWNER'; let message = ''; try { openDb(dir + '/hermeven-ns-test.sqlite').close(); } catch (err) { outcome = err instanceof StateDirectoryError ? 'StateDirectoryError' : 'other:' + err.name; message = err.message; } const st2 = fs.statSync(dir); const after = { mode: st2.mode & 0o7777, uid: st2.uid, mtimeMs: st2.mtimeMs, ctimeMs: st2.ctimeMs }; console.log(JSON.stringify({ euid: process.geteuid(), dirUid: st.uid, dirMode: (st.mode & 0o777).toString(8), outcome, message, unchanged: JSON.stringify(before) === JSON.stringify(after) })); `; const run = spawnSync('unshare', ['-r', process.execPath, '--import', 'tsx', '--input-type=module', '-e', script], { encoding: 'utf8', cwd: fileURLToPath(new URL('..', import.meta.url)), timeout: 60_000, }); if (run.error || run.status !== 0) { console.info(`[units] NOT RUN: user namespaces unavailable (${(run.stderr || String(run.error)).trim().slice(0, 120)})`); return; } const out = JSON.parse(run.stdout.trim().split('\n').at(-1)!); if (out.dirUid === out.euid || out.dirMode !== '700') { console.info(`[units] NOT RUN: /root is not a foreign-owned 0700 directory in the namespace (${JSON.stringify(out)})`); return; } expect(out.outcome).toBe('StateDirectoryError'); expect(out.message).toMatch(/not by the bridge/); expect(out.unchanged).toBe(true); }); }); it('a path whose parent is a file is refused clearly', async () => { const { writeFileSync } = await import('node:fs'); const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); try { writeFileSync(join(root, 'not-a-dir'), 'x'); expect(() => openDb(join(root, 'not-a-dir', 'db.sqlite'))).toThrow(); } finally { rmSync(root, { recursive: true, force: true }); } }); it('an existing database with loose permissions is tightened when opened', async () => { const { chmodSync } = await import('node:fs'); const root = mkdtempSync(join(tmpdir(), 'hermeven-perm-')); const dbPath = join(root, 'hermeven.sqlite'); try { openDb(dbPath).close(); chmodSync(dbPath, 0o644); const db = openDb(dbPath); db.prepare("INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES ('x', 1, 2)").run(); expect(mode(dbPath)).toBe(0o600); expect(mode(`${dbPath}-wal`)).toBe(0o600); db.close(); } finally { rmSync(root, { recursive: true, force: true }); } }); }); describe('device credentials', () => { const setup = (env: Record = {}) => { let now = 1_000_000; const config = loadConfig({ ...base, ...env }); const devices = new Devices(openDb(':memory:'), config, () => now); return { devices, config, advance: (ms: number) => (now += ms) }; }; it('stores only a hash of the token and of the pairing code', () => { const { devices } = setup(); const { code } = devices.createPairingCode(); const claimed = devices.claimPairingCode(code, 'g2'); if (!claimed.ok) throw new Error('claim failed'); const row = devices.get(claimed.device.id)!; expect(row.token_hash).not.toContain(claimed.token); expect(row.token_hash).toMatch(/^[0-9a-f]{64}$/); expect(JSON.stringify(row)).not.toContain(claimed.token); }); it('pairing codes expire, are case/format tolerant, and a new code voids the old one', () => { const { devices, advance } = setup({ HERMEVEN_PAIRING_CODE_TTL_SECONDS: '60' }); const first = devices.createPairingCode(); const second = devices.createPairingCode(); expect(devices.claimPairingCode(first.code, 'x').ok).toBe(false); expect(devices.claimPairingCode(second.code.toLowerCase().replace('-', ' '), 'x').ok).toBe(true); const third = devices.createPairingCode(); advance(61_000); expect(devices.claimPairingCode(third.code, 'x')).toEqual({ ok: false, reason: 'pairing_invalid' }); }); it('tokens expire, can be renewed while valid, and never outlive the pairing', () => { const { devices, advance } = setup({ HERMEVEN_TOKEN_TTL_SECONDS: '100', HERMEVEN_PAIRING_TTL_SECONDS: '250' }); const claimed = devices.claimPairingCode(devices.createPairingCode().code, 'g2'); if (!claimed.ok) throw new Error('claim failed'); advance(90_000); expect(devices.authenticate(claimed.token).ok).toBe(true); const renewed = devices.renew(claimed.device.id); expect(devices.authenticate(claimed.token)).toEqual({ ok: false, reason: 'unauthorized' }); advance(90_000); expect(devices.authenticate(renewed.token).ok).toBe(true); const again = devices.renew(claimed.device.id); // Renewal cannot push past the absolute pairing lifetime (t = 250 s). expect(again.device.token_expires_at).toBe(again.device.pairing_expires_at); advance(80_000); expect(devices.authenticate(again.token)).toEqual({ ok: false, reason: 'credential_expired' }); }); it('a device paired for one profile is not valid for another', () => { const db = openDb(':memory:'); const a = new Devices(db, loadConfig({ ...base, HERMES_PROFILE_LABEL: 'personal' })); const claimed = a.claimPairingCode(a.createPairingCode().code, 'g2'); if (!claimed.ok) throw new Error('claim failed'); const b = new Devices(db, loadConfig({ ...base, HERMES_PROFILE_LABEL: 'work' })); expect(b.authenticate(claimed.token)).toEqual({ ok: false, reason: 'unauthorized' }); }); it('pairing codes have enough entropy and an unambiguous alphabet', () => { const { devices } = setup(); const codes = new Set(Array.from({ length: 200 }, () => devices.createPairingCode().code)); expect(codes.size).toBe(200); for (const code of codes) expect(code).toMatch(/^[A-HJ-KM-NP-Z2-9]{5}-[A-HJ-KM-NP-Z2-9]{5}$/); }); }); describe('Hermes adapter helpers', () => { it('builds a byte-stable request body', () => { const a = buildRunBody({ input: 'hi "there"', sessionId: 'hermeven-1', instructions: 'be brief' }); expect(a).toBe('{"input":"hi \\"there\\"","session_id":"hermeven-1","instructions":"be brief"}'); expect(buildRunBody({ input: 'hi', sessionId: 's', instructions: '' })).toBe('{"input":"hi","session_id":"s"}'); }); it('maps run statuses, treating anything unrecognised as still running', () => { expect(mapRunStatus({ status: 'completed', output: 'x' })).toEqual({ state: 'completed', output: 'x', finished: true, error: null }); expect(mapRunStatus({ status: 'failed', output: 'part', completed: false, partial: true }).finished).toBe(false); expect(mapRunStatus({ status: 'waiting_for_approval' }).state).toBe('waiting_for_approval'); expect(mapRunStatus({ status: 'unknown' }).state).toBe('unknown'); expect(mapRunStatus({ status: 'some_future_status' }).state).toBe('running'); expect(mapRunStatus({ status: 'completed', output: { not: 'text' } }).output).toBe(''); }); }); describe('small utilities', () => { it('rate limiter enforces a fixed window per key', () => { let now = 0; const limiter = new RateLimiter(2, 1000, () => now); expect([limiter.take('a'), limiter.take('a'), limiter.take('a'), limiter.take('b')]).toEqual([true, true, false, true]); now = 1000; expect(limiter.take('a')).toBe(true); }); it('wraps PCM in a correct WAV header', () => { const wav = pcmToWav(Buffer.alloc(3200, 1)); expect(wav.length).toBe(3244); expect(wav.toString('ascii', 0, 4)).toBe('RIFF'); expect(wav.readUInt32LE(4)).toBe(3236); expect(wav.readUInt16LE(20)).toBe(1); expect(wav.readUInt16LE(22)).toBe(1); expect(wav.readUInt32LE(24)).toBe(16000); expect(wav.readUInt32LE(28)).toBe(32000); expect(wav.readUInt16LE(34)).toBe(16); expect(wav.readUInt32LE(40)).toBe(3200); }); });