The event relay was an in-memory array that started empty on every process, so synced history vanished on every API-server restart. Persist it to a gitignored .data/events.sqlite3 via node:sqlite like the blob store (EVENT_DB_PATH override; seq rowid pull cursor; UNIQUE(authorPubkey,signature) push idempotency), keeping the exact exported API. Synced history now survives restarts and keeps growing, and a fresh device pulls the whole lived-in history on load; ShellLayout adds a light 6s poll for live cross-device reflection. Adds a dev:all script, isolates the two integration tests to a temp EVENT_DB_PATH, documents EVENT_DB_PATH.
244 lines
9.0 KiB
TypeScript
244 lines
9.0 KiB
TypeScript
import { mkdirSync } from "node:fs";
|
|
import { dirname, join } from "node:path";
|
|
import { DatabaseSync } from "node:sqlite";
|
|
import * as ed from "@noble/ed25519";
|
|
|
|
/**
|
|
* Persistent 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.
|
|
*
|
|
* Durability (2026-11-20): the relay now persists to a local SQLite file via
|
|
* Node's built-in `node:sqlite` (`DatabaseSync`, stable since Node 22.5,
|
|
* present in this environment's Node 24), exactly like `api/_lib/blobStore.ts`
|
|
* - so synced history SURVIVES a server restart and keeps GROWING across runs
|
|
* ("lived in" demos), instead of the old in-memory module array that started
|
|
* empty on every process. No external account or credential is required: the
|
|
* db file is configurable via `EVENT_DB_PATH` and defaults to
|
|
* `.data/events.sqlite3` under the process cwd (this repo's `.gitignore`
|
|
* convention for local persistent state). Tests that need a clean slate point
|
|
* `EVENT_DB_PATH` at a temp dir and call `resetEventRelayStore()` between
|
|
* cases (the per-run isolation analogue the blob store does with
|
|
* `BLOB_DB_PATH`).
|
|
*/
|
|
|
|
/** 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;
|
|
|
|
const DEFAULT_DB_PATH = join(process.cwd(), ".data", "events.sqlite3");
|
|
|
|
// Resolved lazily (inside getDb(), on first call) rather than as a
|
|
// module-load-time constant, so a test's `beforeAll` can point
|
|
// `EVENT_DB_PATH` at a temp dir before the first store access - the same
|
|
// reason `blobStore.ts` resolves its path lazily.
|
|
function resolveDbPath(): string {
|
|
return process.env.EVENT_DB_PATH ?? DEFAULT_DB_PATH;
|
|
}
|
|
|
|
let db: DatabaseSync | undefined;
|
|
|
|
function getDb(): DatabaseSync {
|
|
if (db) {
|
|
return db;
|
|
}
|
|
const dbPath = resolveDbPath();
|
|
mkdirSync(dirname(dbPath), { recursive: true });
|
|
const opened = new DatabaseSync(dbPath);
|
|
// `seq` is the rowid alias and the relay's append-order cursor: it increases
|
|
// monotonically with insertion and, after a full `DELETE`, restarts at 1 (no
|
|
// AUTOINCREMENT), matching the old in-memory array index semantics. The
|
|
// UNIQUE(authorPubkey, signature) pair is the push-idempotency guard the old
|
|
// `seen` Set provided.
|
|
opened.exec(`
|
|
CREATE TABLE IF NOT EXISTS events (
|
|
seq INTEGER PRIMARY KEY,
|
|
payload TEXT NOT NULL,
|
|
authorPubkey TEXT NOT NULL,
|
|
signature TEXT NOT NULL,
|
|
lamportTs INTEGER NOT NULL,
|
|
UNIQUE(authorPubkey, signature)
|
|
)
|
|
`);
|
|
db = opened;
|
|
return opened;
|
|
}
|
|
|
|
/** Clear the relay's stored events (test isolation; see module doc comment).
|
|
* After deleting every row the `seq` cursor restarts at 1 on the next insert. */
|
|
export function resetEventRelayStore(): void {
|
|
getDb().exec("DELETE FROM events");
|
|
}
|
|
|
|
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<string, unknown>;
|
|
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<boolean> {
|
|
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 via `INSERT OR IGNORE` on the UNIQUE pair, keeping push idempotent.
|
|
* Returns the count newly stored.
|
|
*/
|
|
export async function pushEvents(rawEntries: readonly unknown[]): Promise<number> {
|
|
const validated: WireEventEntry[] = [];
|
|
for (const raw of rawEntries) {
|
|
const entry = assertWellFormed(raw);
|
|
if (!(await verifyWireEntry(entry))) {
|
|
throw new EventSignatureError();
|
|
}
|
|
validated.push(entry);
|
|
}
|
|
|
|
const insert = getDb().prepare(
|
|
"INSERT OR IGNORE INTO events (payload, authorPubkey, signature, lamportTs) VALUES (?, ?, ?, ?)",
|
|
);
|
|
let added = 0;
|
|
for (const entry of validated) {
|
|
const result = insert.run(
|
|
JSON.stringify(entry.payload),
|
|
entry.authorPubkey.toLowerCase(),
|
|
entry.signature.toLowerCase(),
|
|
entry.lamportTs,
|
|
);
|
|
if (Number(result.changes) === 1) added++;
|
|
}
|
|
return added;
|
|
}
|
|
|
|
interface EventRow {
|
|
seq: number;
|
|
payload: string;
|
|
authorPubkey: string;
|
|
signature: string;
|
|
lamportTs: number;
|
|
}
|
|
|
|
/**
|
|
* Return every stored entry whose `seq` is greater than `cursor` (the relay's
|
|
* monotonic append-order high-water mark) together with the new cursor the
|
|
* caller should use next time. A missing/invalid cursor is treated as 0 (pull
|
|
* everything). The returned cursor is the last entry's `seq`, or the given
|
|
* cursor unchanged when nothing new is available - so a subsequent pull with
|
|
* it returns only genuinely newer entries and survives a server restart.
|
|
*/
|
|
export function pullEvents(cursor: unknown): {
|
|
entries: WireEventEntry[];
|
|
cursor: number;
|
|
} {
|
|
const from =
|
|
typeof cursor === "number" && Number.isFinite(cursor) && cursor >= 0
|
|
? Math.floor(cursor)
|
|
: 0;
|
|
const rows = getDb()
|
|
.prepare(
|
|
"SELECT seq, payload, authorPubkey, signature, lamportTs FROM events WHERE seq > ? ORDER BY seq ASC",
|
|
)
|
|
.all(from) as unknown as EventRow[];
|
|
const entries: WireEventEntry[] = rows.map((row) => ({
|
|
payload: JSON.parse(row.payload),
|
|
authorPubkey: row.authorPubkey,
|
|
signature: row.signature,
|
|
lamportTs: Number(row.lamportTs),
|
|
}));
|
|
const nextCursor = rows.length > 0 ? Number(rows[rows.length - 1].seq) : from;
|
|
return { entries, cursor: nextCursor };
|
|
}
|