import * as ed from "@noble/ed25519"; /** * In-process relay store for the generic signed-event sync endpoint * (backend-expansion todo 2). This is a pure relay: it verifies every pushed * event's own signature before storing it, and never creates, mutates, or * counter-signs anything on anyone's behalf. It stores each entry exactly as * it arrived (its author's public key and signature untouched) and hands it * back verbatim on pull, so a pulled entry replays on another device as its * ORIGINAL author, never as the relay or the receiving device. * * Mirroring `api/_lib/blobStore.ts`'s stub style: this todo's acceptance * criteria only require cross-device propagation within one running server * (not cross-restart durability, unlike the blob store), so the backing store * is a plain module-level array that starts empty on each process. Tests that * need a clean slate between cases call `resetEventRelayStore()` - the * in-process analogue of the blob store's per-run `BLOB_STORE_DIR`. */ /** The over-the-wire shape of one signed Event Log entry. `authorPubkey` and * `signature` are lowercase hex (Uint8Array bytes don't survive JSON), the * payload is opaque JSON data the relay never interprets. */ export interface WireEventEntry { payload: unknown; /** 32-byte Ed25519 public key as 64 hex chars. */ authorPubkey: string; /** 64-byte Ed25519 signature as 128 hex chars. */ signature: string; lamportTs: number; } /** A pushed entry whose structure is malformed (missing/ill-typed field), * surfaced as a 400 by the handler rather than a generic 500. */ export class MalformedEventError extends Error { constructor(detail: string) { super(`event relay rejected a malformed event: ${detail}`); this.name = "MalformedEventError"; } } /** A pushed entry whose signature does not verify against its own payload, * lamportTs, and authorPubkey - a forged/tampered push, surfaced as a 422 by * the handler. The relay never stores such an entry. */ export class EventSignatureError extends Error { constructor() { super( "event relay rejected an event: signature does not verify against its payload, lamportTs, and authorPubkey.", ); this.name = "EventSignatureError"; } } const PUBKEY_HEX = /^[0-9a-f]{64}$/i; const SIGNATURE_HEX = /^[0-9a-f]{128}$/i; let store: WireEventEntry[] = []; const seen = new Set(); /** Clear the in-process store (test isolation; see module doc comment). */ export function resetEventRelayStore(): void { store = []; seen.clear(); } function identity(entry: WireEventEntry): string { return `${entry.authorPubkey.toLowerCase()}:${entry.signature.toLowerCase()}`; } function hexToBytes(hex: string): Uint8Array { const out = new Uint8Array(hex.length / 2); for (let i = 0; i < out.length; i++) { out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); } return out; } /** Canonical signed message - MUST stay byte-identical to `canonicalMessage` * in `src/lib/eventlog.ts` (the client signs over exactly this), or no honest * event would ever verify. Plain JSON payloads round-trip through * JSON.parse/JSON.stringify with identical bytes, so re-deriving it here from * the parsed wire payload reproduces what the author signed. */ function canonicalMessage(payload: unknown, lamportTs: number): Uint8Array { return new TextEncoder().encode(JSON.stringify({ payload, lamportTs })); } /** Validate the structure of one pushed entry, throwing `MalformedEventError` * on the first problem. Returns a normalized `WireEventEntry` on success. */ export function assertWellFormed(raw: unknown): WireEventEntry { if (typeof raw !== "object" || raw === null) { throw new MalformedEventError("entry is not an object"); } const o = raw as Record; if (!("payload" in o)) { throw new MalformedEventError("missing payload"); } if (typeof o.authorPubkey !== "string" || !PUBKEY_HEX.test(o.authorPubkey)) { throw new MalformedEventError("authorPubkey must be 64 hex chars (32 bytes)"); } if (typeof o.signature !== "string" || !SIGNATURE_HEX.test(o.signature)) { throw new MalformedEventError("signature must be 128 hex chars (64 bytes)"); } if ( typeof o.lamportTs !== "number" || !Number.isInteger(o.lamportTs) || o.lamportTs < 0 ) { throw new MalformedEventError("lamportTs must be a non-negative integer"); } return { payload: o.payload, authorPubkey: o.authorPubkey, signature: o.signature, lamportTs: o.lamportTs, }; } async function verifyWireEntry(entry: WireEventEntry): Promise { const message = canonicalMessage(entry.payload, entry.lamportTs); try { return await ed.verifyAsync( hexToBytes(entry.signature), message, hexToBytes(entry.authorPubkey), ); } catch { // A structurally-valid hex that still can't be parsed as a point/scalar // is a verification failure, not a server crash. return false; } } /** * Validate AND signature-verify every entry in `rawEntries` before storing * ANY of them: a batch containing one malformed or forged entry is rejected * whole (throws), so a tampered event never lands in the store or a later * pull. Valid entries already present (same authorPubkey+signature) are * skipped, keeping push idempotent. Returns the count newly stored. */ export async function pushEvents(rawEntries: readonly unknown[]): Promise { const validated: WireEventEntry[] = []; for (const raw of rawEntries) { const entry = assertWellFormed(raw); if (!(await verifyWireEntry(entry))) { throw new EventSignatureError(); } validated.push(entry); } let added = 0; for (const entry of validated) { const id = identity(entry); if (seen.has(id)) continue; seen.add(id); store.push(entry); added++; } return added; } /** * Return every stored entry at or after `cursor` (an index into the relay's * append order) together with the new cursor the caller should use next time. * A missing/invalid cursor is treated as 0 (pull everything). */ export function pullEvents(cursor: unknown): { entries: WireEventEntry[]; cursor: number; } { const from = typeof cursor === "number" && Number.isFinite(cursor) && cursor >= 0 ? Math.floor(cursor) : 0; return { entries: store.slice(from), cursor: store.length }; }