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,297 @@
|
||||
import cors from '@fastify/cors';
|
||||
import Fastify, { LogController, type FastifyBaseLogger, type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
|
||||
import {
|
||||
AUDIO_FORMAT,
|
||||
AudioTurnQuery,
|
||||
check,
|
||||
ConversationCreateRequest,
|
||||
httpStatusFor,
|
||||
isRetryable,
|
||||
PairingClaimRequest,
|
||||
SCHEMA_VERSION,
|
||||
TextTurnRequest,
|
||||
type ConversationResponse,
|
||||
type DeviceCredential,
|
||||
type DeviceStatusResponse,
|
||||
type ErrorCode,
|
||||
type ErrorResponse,
|
||||
type Limits,
|
||||
} from '@hermeven/contracts';
|
||||
import 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';
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
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(),
|
||||
});
|
||||
|
||||
// Exact-origin CORS. 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: config.allowedOrigins.length ? config.allowedOrigins : false,
|
||||
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);
|
||||
|
||||
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');
|
||||
throw new ApiError(
|
||||
result.reason,
|
||||
result.reason === 'pairing_locked'
|
||||
? 'Too many wrong codes. Generate a new pairing code on the bridge.'
|
||||
: '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,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
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);
|
||||
devices.revoke(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 conversation = engine.createConversation(device.id);
|
||||
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);
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user