import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto'; import type { BridgeConfig } from './config.ts'; import type { Db } from './db.ts'; export interface DeviceRow { id: string; name: string; profile: string; token_hash: string; created_at: number; token_expires_at: number; pairing_expires_at: number; revoked_at: number | null; last_seen_at: number | null; } export type AuthFailure = 'unauthorized' | 'credential_expired'; 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'; // ~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'); } function normalizeCode(code: string): string { return code.toUpperCase().replace(/[^A-Z0-9]/g, ''); } function newToken(): string { return `hvn_${randomBytes(32).toString('base64url')}`; } export class Devices { constructor( private readonly db: Db, private readonly config: BridgeConfig, private readonly now: () => number = Date.now, ) {} /** Operator action (CLI): mint a single-use, time-limited pairing code. Invalidates older unused codes. */ createPairingCode(): { code: string; expiresAt: number } { const code = Array.from({ length: CODE_LENGTH }, () => CODE_ALPHABET[randomInt(CODE_ALPHABET.length)]).join(''); const now = this.now(); const expiresAt = now + this.config.credentials.pairingCodeTtlSeconds * 1000; this.db.transaction(() => { this.db.prepare('UPDATE pairing_codes SET used_at = ? WHERE used_at IS NULL').run(now); this.db .prepare('INSERT INTO pairing_codes (code_hash, created_at, expires_at) VALUES (?, ?, ?)') .run(sha256(code), now, expiresAt); })(); return { code: `${code.slice(0, 5)}-${code.slice(5)}`, expiresAt }; } /** * 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, deviceName: string, ): { ok: true; device: DeviceRow; token: string } | { ok: false; reason: PairingFailure } { const now = this.now(); const hash = sha256(normalizeCode(rawCode)); return this.db.transaction(() => { const live = this.db .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) 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 = { id: randomUUID(), name: deviceName, profile: this.config.hermes.profileLabel, token_hash: sha256(token), created_at: now, token_expires_at: now + this.config.credentials.tokenTtlSeconds * 1000, pairing_expires_at: now + this.config.credentials.pairingTtlSeconds * 1000, revoked_at: null, last_seen_at: now, }; device.token_expires_at = Math.min(device.token_expires_at, device.pairing_expires_at); this.db .prepare( `INSERT INTO devices (id, name, profile, token_hash, created_at, token_expires_at, pairing_expires_at, last_seen_at) VALUES (@id, @name, @profile, @token_hash, @created_at, @token_expires_at, @pairing_expires_at, @last_seen_at)`, ) .run(device); return { ok: true as const, device, token }; })(); } authenticate(token: string): { ok: true; device: DeviceRow } | { ok: false; reason: AuthFailure } { if (!token || token.length > 200) return { ok: false, reason: 'unauthorized' }; const row = this.db.prepare('SELECT * FROM devices WHERE token_hash = ?').get(sha256(token)) as DeviceRow | undefined; if (!row || row.revoked_at !== null) return { ok: false, reason: 'unauthorized' }; const now = this.now(); if (row.token_expires_at <= now || row.pairing_expires_at <= now) return { ok: false, reason: 'credential_expired' }; // A device is only valid for the profile this bridge is configured to serve. if (row.profile !== this.config.hermes.profileLabel) return { ok: false, reason: 'unauthorized' }; this.db.prepare('UPDATE devices SET last_seen_at = ? WHERE id = ?').run(now, row.id); return { ok: true, device: row }; } /** Explicit renewal: rotates the token (the old one stops working immediately). */ renew(deviceId: string): { device: DeviceRow; token: string } { const now = this.now(); const token = newToken(); const current = this.get(deviceId)!; const tokenExpiresAt = Math.min(now + this.config.credentials.tokenTtlSeconds * 1000, current.pairing_expires_at); this.db .prepare('UPDATE devices SET token_hash = ?, token_expires_at = ? WHERE id = ?') .run(sha256(token), tokenExpiresAt, deviceId); 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; })(); } get(deviceId: string): DeviceRow | undefined { return this.db.prepare('SELECT * FROM devices WHERE id = ?').get(deviceId) as DeviceRow | undefined; } list(): DeviceRow[] { return this.db.prepare('SELECT * FROM devices ORDER BY created_at').all() as DeviceRow[]; } } function safeEqualHex(a: string, b: string): boolean { const ab = Buffer.from(a, 'hex'); const bb = Buffer.from(b, 'hex'); return ab.length === bb.length && timingSafeEqual(ab, bb); }