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'; 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('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); }); });