Files
hermeven/services/bridge/src/server.ts
T
DanandClaude Fable 5.2 b57505406b Sound check on the phone page (probe for issue #1); timing logs for name checks and previews; 0.4.1
- apps/even-client: a collapsed "Sound check" on the phone page. Finds out whether the page
  may play sound in the Even app, without a touch, in the background, and which outputs it can
  see. Plays only on a button press; sends nothing to the bridge.
- services/bridge: wake.checked (every name check) and preview.done log the clip length and the
  duration, never the words.
- tests: hands free after a recording in Agents with menu, wake and preview all on; the log
  lines carry only the fields above.
- docs: 0.4.0 rollout and Dan's device report; security 3c, 3e, 3f; 0005 records that the
  Round 20 reading of "agent sub-app" was wrong (not changed here).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-29 11:24:16 -08:00

440 lines
20 KiB
TypeScript

import cors from '@fastify/cors';
import Fastify, { LogController, type FastifyBaseLogger, type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
import {
AUDIO_FORMAT,
AudioTurnQuery,
check,
AgentsResponse,
ConversationCreateRequest,
httpStatusFor,
isRetryable,
PairingClaimRequest,
SCHEMA_VERSION,
TextTurnRequest,
WakeQuery,
type ConversationResponse,
type DeviceCredential,
type DeviceStatusResponse,
type ErrorCode,
type ErrorResponse,
type Limits,
type TranscribeResponse,
type WakeResponse,
} from '@hermeven/contracts';
import { DEFAULT_AGENT_ID, type BridgeConfig } from './config.ts';
import type { DeviceRow, Devices } from './devices.ts';
import type { HermesAdapter } from './hermes/adapter.ts';
import { RateLimiter } from './ratelimit.ts';
import type { SttAdapter } from './stt/adapter.ts';
import type { TurnEngine } from './turns.ts';
import { matchWake } from './wake.ts';
export interface ServerDeps {
config: BridgeConfig;
devices: Devices;
engine: TurnEngine;
hermes: HermesAdapter;
stt: SttAdapter;
/** Request bodies, queries and auth headers are never passed to it. */
logger: FastifyBaseLogger;
}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
class ApiError extends Error {
constructor(
readonly code: ErrorCode,
message: string,
) {
super(message);
}
}
function errorBody(code: ErrorCode, message: string): ErrorResponse {
return { schema_version: SCHEMA_VERSION, error: { code, message, retryable: isRetryable(code) } };
}
function iso(ms: number): string {
return new Date(ms).toISOString();
}
export function effectiveLimits(config: BridgeConfig): Limits {
return {
capture_max_seconds: config.limits.captureMaxSeconds,
transcribe_deadline_seconds: config.limits.transcribeDeadlineSeconds,
agent_deadline_seconds: config.limits.agentDeadlineSeconds,
approval_wait_seconds: config.limits.approvalWaitSeconds,
audio_max_bytes: config.limits.audioMaxBytes,
text_max_chars: config.limits.textMaxChars,
};
}
/**
* Whether a browser page at `origin` may read this bridge's responses.
* Exact matches against the configured list; otherwise, if a loopback host was configured with
* `:*`, an `http://<that host>:<port>` origin with a numeric port. Nothing else, and never a
* missing or `null` origin.
*/
export function isAllowedOrigin(config: Pick<BridgeConfig, 'allowedOrigins' | 'allowedLoopbackAnyPort'>, origin: string | undefined): boolean {
if (!origin || origin === 'null') return false;
if (config.allowedOrigins.includes(origin)) return true;
if (config.allowedLoopbackAnyPort.length === 0) return false;
// Matched as text, start to end, so look-alikes such as http://127.0.0.1.example.com:80 or
// http://127.0.0.1:80@example.com cannot pass.
const match = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):(\d{1,5})$/.exec(origin);
if (!match) return false;
const port = Number(match[2]);
return port >= 1 && port <= 65535 && config.allowedLoopbackAnyPort.includes(match[1]!);
}
export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
const { config, devices, engine } = deps;
const app = Fastify({
loggerInstance: deps.logger,
trustProxy: config.trustProxy,
// JSON bodies are tiny; the audio parser below sets its own, larger limit.
bodyLimit: 32 * 1024,
// Per-request access logs are off: routes log ids and outcomes themselves, and a URL
// can carry request metadata we do not want duplicated into logs.
logController: new LogController({ disableRequestLogging: true }),
// Fastify's default id is a counter; ours never contains client-supplied text.
genReqId: () => crypto.randomUUID(),
});
// CORS: exact origins, plus (only if configured) any port on a loopback address.
// CORS only tells browsers who may read answers; every route except /healthz and the
// pairing claim still requires a device credential.
await app.register(cors, {
origin: (origin, callback) => callback(null, isAllowedOrigin(config, origin)),
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Authorization', 'Content-Type'],
credentials: false,
maxAge: 600,
});
app.addHook('onSend', async (_req, reply) => {
reply.header('X-Content-Type-Options', 'nosniff');
reply.header('Cache-Control', 'no-store');
reply.header('Referrer-Policy', 'no-referrer');
});
// Raw audio: buffered in memory with a hard cap, never parsed as JSON, never written to disk.
app.addContentTypeParser(
'application/octet-stream',
{ parseAs: 'buffer', bodyLimit: config.limits.audioMaxBytes },
(_req, body, done) => done(null, body),
);
app.setErrorHandler((err: Error & { statusCode?: number; code?: string }, req, reply) => {
if (err instanceof ApiError) {
return reply.code(httpStatusFor(err.code)).send(errorBody(err.code, err.message));
}
if (err.code === 'FST_ERR_CTP_BODY_TOO_LARGE' || err.statusCode === 413) {
return reply.code(413).send(errorBody('payload_too_large', 'Request body is too large.'));
}
if (err.code === 'FST_ERR_CTP_INVALID_MEDIA_TYPE' || err.statusCode === 415) {
return reply.code(415).send(errorBody('unsupported_media', 'Unsupported content type.'));
}
if (err.statusCode && err.statusCode >= 400 && err.statusCode < 500) {
return reply.code(400).send(errorBody('invalid_request', 'Malformed request.'));
}
req.log.error({ err_name: err.name, err_code: err.code ?? null }, 'request.failed');
return reply.code(500).send(errorBody('internal', 'Internal error.'));
});
app.setNotFoundHandler((_req, reply) => reply.code(404).send(errorBody('not_found', 'Not found.')));
const pairingLimiter = new RateLimiter(config.limits.pairingAttemptsPerMinute, 60_000);
const turnLimiter = new RateLimiter(config.limits.turnsPerMinute, 60_000);
const readLimiter = new RateLimiter(600, 60_000);
const wakeLimiter = new RateLimiter(config.limits.wakeChecksPerMinute, 60_000);
/** Devices with a wake check being transcribed: one at a time each. */
const wakeBusy = new Set<string>();
const previewLimiter = new RateLimiter(config.limits.previewsPerMinute, 60_000);
const previewBusy = new Set<string>();
/** The checks shared by the two routes that take a clip of audio and create nothing. */
function audioClip(req: FastifyRequest): { pcm: Buffer; locale: string } {
const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase();
if (contentType !== 'application/octet-stream') throw new ApiError('unsupported_media', 'Unsupported content type.');
const query = req.query as Record<string, unknown>;
requireVersion(query.schema_version);
if (!check(WakeQuery, query)) throw new ApiError('invalid_request', 'Malformed request.');
const pcm = req.body as Buffer;
if (!Buffer.isBuffer(pcm) || pcm.length === 0) throw new ApiError('invalid_request', 'Audio body is empty.');
if (pcm.length % 2 !== 0) throw new ApiError('invalid_request', 'Audio is not whole 16-bit samples.');
return { pcm, locale: query.locale };
}
function authenticate(req: FastifyRequest): DeviceRow {
const header = req.headers.authorization ?? '';
const token = header.startsWith('Bearer ') ? header.slice(7).trim() : '';
const result = devices.authenticate(token);
if (!result.ok) {
throw new ApiError(
result.reason,
result.reason === 'credential_expired' ? 'Credential expired. Renew or pair again.' : 'Not authorized.',
);
}
if (!readLimiter.take(result.device.id)) throw new ApiError('rate_limited', 'Too many requests.');
return result.device;
}
function requireVersion(value: unknown): void {
if (value !== SCHEMA_VERSION && value !== String(SCHEMA_VERSION)) {
throw new ApiError('unsupported_schema_version', `This bridge speaks contract version ${SCHEMA_VERSION}.`);
}
}
function requireUuid(value: string): string {
if (!UUID_RE.test(value)) throw new ApiError('not_found', 'Not found.');
return value;
}
function credential(device: DeviceRow, token: string): DeviceCredential {
return {
schema_version: SCHEMA_VERSION,
device_id: device.id,
token,
token_expires_at: iso(device.token_expires_at),
pairing_expires_at: iso(device.pairing_expires_at),
};
}
// ------------------------------------------------------------------ health
// Liveness only: no configuration, versions, counts or downstream state.
app.get('/healthz', async () => ({ status: 'ok', schema_version: SCHEMA_VERSION }));
// ----------------------------------------------------------------- pairing
app.post('/v1/pairing/claim', async (req, reply) => {
if (!pairingLimiter.take(req.ip)) throw new ApiError('rate_limited', 'Too many pairing attempts. Wait a minute.');
const body = req.body as Record<string, unknown> | undefined;
requireVersion(body?.schema_version);
if (!check(PairingClaimRequest, body)) throw new ApiError('invalid_request', 'Malformed pairing request.');
const result = devices.claimPairingCode(body.code, body.device_name.trim() || 'device');
if (!result.ok) {
req.log.warn({ reason: result.reason }, 'pairing.rejected');
// One answer for wrong, expired and used codes: the response reveals nothing about which.
throw new ApiError('pairing_invalid', 'Pairing code is not valid.');
}
req.log.info({ device_id: result.device.id }, 'pairing.claimed');
return reply.code(201).send(credential(result.device, result.token));
});
// ------------------------------------------------------------------ device
app.get('/v1/device', async (req): Promise<DeviceStatusResponse> => {
const device = authenticate(req);
return {
schema_version: SCHEMA_VERSION,
device_id: device.id,
device_name: device.name,
token_expires_at: iso(device.token_expires_at),
pairing_expires_at: iso(device.pairing_expires_at),
agent_reachable: await deps.hermes.reachable(),
stt_configured: deps.stt.configured,
active_conversation_id: engine.activeConversation(device.id)?.id ?? null,
limits: effectiveLimits(config),
audio_format: {
encoding: AUDIO_FORMAT.encoding,
sample_rate: AUDIO_FORMAT.sampleRate,
channels: AUDIO_FORMAT.channels,
},
};
});
/**
* The agents this device may talk to, default first. Names only: no address, profile or key
* ever leaves the bridge. A separate route (not a field on /v1/device) so that clients built
* before it existed, which reject unknown fields, keep working.
*/
app.get('/v1/agents', async (req): Promise<AgentsResponse> => {
authenticate(req);
return { schema_version: SCHEMA_VERSION, agents: config.agents.map(({ id, name }) => ({ id, name })) };
});
app.post('/v1/device/renew', async (req) => {
const device = authenticate(req);
const renewed = devices.renew(device.id);
req.log.info({ device_id: device.id }, 'device.renewed');
return credential(renewed.device, renewed.token);
});
app.delete('/v1/device', async (req) => {
const device = authenticate(req);
engine.revokeDevice(device.id);
req.log.info({ device_id: device.id }, 'device.revoked');
return { schema_version: SCHEMA_VERSION, revoked: true };
});
// ----------------------------------------------------------- conversations
app.post('/v1/conversations', async (req, reply): Promise<ConversationResponse> => {
const device = authenticate(req);
const body = req.body as Record<string, unknown> | undefined;
requireVersion(body?.schema_version);
if (!check(ConversationCreateRequest, body)) throw new ApiError('invalid_request', 'Malformed conversation request.');
const agentId = (body as { agent_id?: string }).agent_id ?? DEFAULT_AGENT_ID;
// Only an agent the owner listed. The id is never used to build an address here.
if (!engine.knowsAgent(agentId)) throw new ApiError('invalid_request', 'Unknown agent.');
const conversation = engine.createConversation(device.id, agentId);
reply.code(201);
return { schema_version: SCHEMA_VERSION, conversation_id: conversation.id, created_at: iso(conversation.created_at) };
});
// ------------------------------------------------------------------- turns
app.post('/v1/turns', async (req: FastifyRequest, reply: FastifyReply) => {
const device = authenticate(req);
const contentType = String(req.headers['content-type'] ?? '').split(';')[0]!.trim().toLowerCase();
let meta: { requestId: string; conversationId: string; locale: string };
let input: { kind: 'text'; text: string } | { kind: 'audio'; pcm: Buffer };
if (contentType === 'application/json') {
const body = req.body as Record<string, unknown> | undefined;
requireVersion(body?.schema_version);
if (!check(TextTurnRequest, body)) throw new ApiError('invalid_request', 'Malformed turn request.');
const text = body.input.text.trim();
if (!text) throw new ApiError('invalid_request', 'Text is empty.');
meta = { requestId: body.request_id, conversationId: body.conversation_id, locale: body.locale };
input = { kind: 'text', text };
} else if (contentType === 'application/octet-stream') {
const query = req.query as Record<string, unknown>;
requireVersion(query.schema_version);
if (!check(AudioTurnQuery, query)) {
// A declared format we have not validated against real SDK output is refused, not guessed.
const formatDeclared = 'encoding' in query || 'sample_rate' in query || 'channels' in query;
const formatOk =
query.encoding === AUDIO_FORMAT.encoding &&
query.sample_rate === String(AUDIO_FORMAT.sampleRate) &&
query.channels === String(AUDIO_FORMAT.channels);
if (formatDeclared && !formatOk) throw new ApiError('unsupported_media', 'Unsupported audio format.');
throw new ApiError('invalid_request', 'Malformed turn metadata.');
}
const pcm = req.body as Buffer;
if (!Buffer.isBuffer(pcm) || pcm.length === 0) throw new ApiError('invalid_request', 'Audio body is empty.');
if (pcm.length % 2 !== 0) throw new ApiError('invalid_request', 'Audio is not whole 16-bit samples.');
meta = { requestId: query.request_id, conversationId: query.conversation_id, locale: query.locale };
input = { kind: 'audio', pcm };
} else {
throw new ApiError('unsupported_media', 'Unsupported content type.');
}
// A duplicate of an existing request never consumes rate budget or creates work.
const existing = engine.get(device.id, meta.requestId);
if (!existing && !turnLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
const result = engine.submit(device.id, meta, input);
if (!result.ok) throw new ApiError(result.code, result.message);
reply.code(result.replayed ? 200 : 202);
return engine.toResult(result.turn, result.replayed);
});
// -------------------------------------------------------------------- wake
/**
* One stretch of speech heard while the app was open: does it begin with an agent's name?
* Transcribed in memory and dropped. No turn, no row, nothing sent to any agent; a match only
* tells the app who was addressed and what was said after the name, and the app then asks in
* the ordinary way. Speech that was not for an agent is not returned and never logged.
*/
app.post('/v1/wake', async (req): Promise<WakeResponse> => {
const device = authenticate(req);
const { pcm, locale } = audioClip(req);
// Nobody can be called by voice (no speech-to-text, or no agent with a usable name): the
// app is told so once and stops sending audio.
if (!deps.stt.configured || !config.agents.some((a) => a.wakeWords.length > 0)) throw new ApiError('not_found', 'Not found.');
if (wakeBusy.has(device.id) || !wakeLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
const none: WakeResponse = { schema_version: SCHEMA_VERSION, matched: false, agent_id: null, text: '', near_miss: null };
wakeBusy.add(device.id);
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), config.limits.transcribeDeadlineSeconds * 1000);
const startedAt = Date.now();
// How long the clip was and how long it took, for every check, matched or not. Never what
// was said: without this a slow or silent hands-free session cannot be told apart from a
// microphone that hears nothing.
const checked = (matched: boolean, nearMiss: boolean) =>
req.log.info(
{
device_id: device.id,
audio_ms: Math.round((pcm.length / AUDIO_FORMAT.bytesPerSecond) * 1000),
check_ms: Date.now() - startedAt,
matched,
near_miss: nearMiss,
},
'wake.checked',
);
try {
const transcript = await deps.stt.transcribe({ pcm, locale, signal: abort.signal });
const match = matchWake(transcript, config.agents);
checked(match.matched, !match.matched && match.nearMiss !== null);
if (!match.matched) return { ...none, near_miss: match.nearMiss };
req.log.info({ device_id: device.id, agent_id: match.agentId, name_only: match.text === '' }, 'wake.matched');
return { ...none, matched: true, agent_id: match.agentId, text: match.text.slice(0, config.limits.textMaxChars) };
} catch (err) {
// A failed transcription is "nothing was addressed to anyone": there is no request to fail.
req.log.warn({ device_id: device.id, err_name: err instanceof Error ? err.name : 'unknown' }, 'wake.transcription_failed');
return none;
} finally {
clearTimeout(timer);
wakeBusy.delete(device.id);
}
});
// ----------------------------------------------------------------- preview
/**
* The words in a recording that is still being made, for showing on the glasses while the
* user speaks. Transcribed in memory and dropped: no turn, no row, nothing sent to any agent,
* and the text is never logged. The question that is finally sent is transcribed by its own
* turn, so a preview can never become what the agent receives.
*/
app.post('/v1/transcribe', async (req, reply): Promise<TranscribeResponse> => {
const device = authenticate(req);
const { pcm, locale } = audioClip(req);
if (!deps.stt.configured) throw new ApiError('not_found', 'Not found.');
if (previewBusy.has(device.id) || !previewLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
previewBusy.add(device.id);
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), config.limits.transcribeDeadlineSeconds * 1000);
// The app has stopped waiting (the recording was sent or cancelled): stop too, so the real
// transcription is not kept waiting behind a preview nobody will see.
reply.raw.on('close', () => {
if (!reply.raw.writableEnded) abort.abort();
});
try {
const startedAt = Date.now();
const text = await deps.stt.transcribe({ pcm, locale, signal: abort.signal });
// Length and duration only, never the words: this is how the delay a preview can add to
// the real transcription gets measured.
req.log.info(
{ device_id: device.id, audio_ms: Math.round((pcm.length / AUDIO_FORMAT.bytesPerSecond) * 1000), preview_ms: Date.now() - startedAt, empty: text.trim() === '' },
'preview.done',
);
return { schema_version: SCHEMA_VERSION, text: text.trim().slice(0, config.limits.textMaxChars) };
} catch (err) {
// No preview this time. The recording itself is unaffected.
req.log.warn({ device_id: device.id, err_name: err instanceof Error ? err.name : 'unknown' }, 'preview.transcription_failed');
return { schema_version: SCHEMA_VERSION, text: '' };
} finally {
clearTimeout(timer);
previewBusy.delete(device.id);
}
});
app.get('/v1/turns/:requestId', async (req) => {
const device = authenticate(req);
const { requestId } = req.params as { requestId: string };
// Another device's turn is "not found", never "forbidden": ids are not an oracle.
const turn = engine.get(device.id, requireUuid(requestId));
if (!turn) throw new ApiError('not_found', 'Not found.');
return engine.toResult(turn);
});
app.post('/v1/turns/:requestId/cancel', async (req) => {
const device = authenticate(req);
const { requestId } = req.params as { requestId: string };
const turn = engine.cancel(device.id, requireUuid(requestId));
if (!turn) throw new ApiError('not_found', 'Not found.');
return engine.toResult(turn);
});
return app;
}