First vertical slice: Even client, bridge, contract v1, tests, docs
Client (apps/even-client): pure interaction reducer with generation-based stale-result rejection, HUD renderer, measured pagination, Even Hub SDK 0.0.16 adapter, bridge HTTP client, phone pairing/status/diagnostics page. Bridge (services/bridge): device pairing and revocable expiring credentials, turn engine with idempotent submit, cancel, deadlines and restart recovery, Hermes Runs API adapter, OpenAI-compatible STT adapter, operator CLI. Contract (packages/contracts): versioned schemas, types and error codes. Tests: 122 unit/integration (fakes), 6 simulator scenarios (Even Hub simulator 0.9.5), 9 scenarios against a real Hermes v0.23.1 gateway with a stub model. No real STT, real model or physical device has been exercised; see docs/test-evidence.md and docs/device-test-plan.md. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
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' | 'pairing_locked';
|
||||
|
||||
// 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.
|
||||
|
||||
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 guess counts against every
|
||||
* outstanding code, so the code is burned after a few failures regardless of who guessed.
|
||||
*/
|
||||
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, 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 }>;
|
||||
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) };
|
||||
}
|
||||
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(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);
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user