diff --git a/.omo/evidence/backend-service-expansion/task-2-backend-service-expansion.md b/.omo/evidence/backend-service-expansion/task-2-backend-service-expansion.md new file mode 100644 index 0000000..41b4674 --- /dev/null +++ b/.omo/evidence/backend-service-expansion/task-2-backend-service-expansion.md @@ -0,0 +1,101 @@ +# Task 2 - Generic signed-event relay endpoint + client sync helper + +Plan: `.omo/plans/backend-service-expansion.md` todo 2 (Wave 1). +Worktree: `/home/athapa/patriothacks-wt/backend-service-expansion-wave1` (branch `backend-service-expansion-wave1`). + +## What was built + +- `api/_lib/eventRelayStore.ts` - in-process relay store (mirrors `blobStore.ts`'s stub style; no + cross-restart persistence required by this todo, only cross-device propagation within one running + server). Validates each pushed event's structure (`MalformedEventError`) and signature-verifies it + with `@noble/ed25519` against the same canonical `{payload, lamportTs}` message the client signs + (`EventSignatureError`). A batch containing any malformed or forged entry is rejected whole, so a + tampered event never lands in the store. Pure relay: entries are stored and returned verbatim + (authorPubkey/signature untouched) - never counter-signed. Dedups stored entries by + (authorPubkey, signature). +- `api/sync/index.ts` - POST handler. Request `{ push?, pullCursor? }` -> response + `{ stored, entries, cursor }`. 405 non-POST, 400 malformed, 422 forged signature, 200 success. +- `api/_lib/devServer.ts` - routes `/api/sync` to the new handler (additive; blob routes unchanged). +- `src/lib/sync.ts` - `trySyncWithBackend()`: pushes new local events (by Dexie id cursor) and pulls + remote entries; each pulled entry is persisted via the EXISTING `appendEntry()` (never `append()`, + which would re-sign under the local key and forge authorship). Before `appendEntry()`, each pulled + entry is skipped if an entry with the same (authorPubkey, signature) already exists locally - the + required duplicate-ingestion guard (`eventLog` has no uniqueness constraint; `computeBalances` + applies every stored entry unconditionally). Any offline/timeout/non-2xx/malformed condition is a + silent no-op (`{ ok: false }`), leaving the local append/replay path completely unaffected. +- `src/lib/ledgerConflicts.ts` - exported `entryIdentity()` and widened its param to the two signed + fields so the pull-side guard reuses the exact same dedup key (single source of truth). +- Tests: `src/lib/sync.test.ts` (unit, stubbed transport) and `api/sync.integration.test.ts` + (real HTTP server + two real Ed25519 identities + real fake-indexeddb `eventLog`). + +## Commands run (in the worktree) + +- `npm run test` (vitest run) -> `Test Files 84 passed (84)` / `Tests 628 passed (628)` +- `npm run build` (tsc -b && vite build) -> exit 0, `✓ built in 638ms`, PWA SW generated (no type errors) +- `npm run lint` (oxlint) -> clean on all changed files (only pre-existing warnings remain in + miniapps/shell/e2e files that this task did not touch) + +Note: the first full `npm run test` run showed 2 failures in +`src/miniapps/waterwatch/coreLoopHonestyAnchor.test.tsx` (a `waitFor` timing-based mini-app test +this task never touched). It passes 2/2 in isolation and the next full run was 628/628 green - a +pre-existing flake under the 84-worker parallel run, not a regression from this change. + +## Manual-QA artifact (the required channel) + +`api/sync.integration.test.ts`, run with `--reporter=verbose` (literal vitest output): + +``` + ✓ src/lib/sync.test.ts > trySyncWithBackend > is a silent no-op when the endpoint connection is refused, leaving local append/read untouched 65ms + ✓ src/lib/sync.test.ts > trySyncWithBackend > is a silent no-op on a non-2xx response, ingesting nothing 4ms + ✓ src/lib/sync.test.ts > trySyncWithBackend > persists a pulled remote entry once and skips it on a repeat pull (dedup guard) 11ms + ✓ api/sync.integration.test.ts > signed-event relay integration (todo 2) > propagates device A's signed event to device B and dedups a repeat pull 90ms + ✓ api/sync.integration.test.ts > signed-event relay integration (todo 2) > rejects a forged event with 422 and never relays it to a puller 12ms + ✓ api/sync.integration.test.ts > signed-event relay integration (todo 2) > rejects malformed events with 400, not a 500 7ms + ✓ api/sync.integration.test.ts > signed-event relay integration (todo 2) > is a silent no-op against an unreachable relay, leaving local append/read unaffected 9ms + Test Files 2 passed (2) + Tests 7 passed (7) +``` + +The integration test exercises every required step: +1. Two real Ed25519 identities (device A, device B) via `src/lib/identity.ts`/`@noble/ed25519`. +2. Device A signs and pushes one real event to the real running endpoint (real `fetch`). +3. Device B pulls via `trySyncWithBackend()` -> `appendEntry()` into the real fake-indexeddb `eventLog`. +4. Device B's `readAll()`/`computeBalances()` reflect device A's event with device A's ORIGINAL + authorPubkey/signature preserved byte-for-byte (`balances["townA"] === 100`), proving no re-signing. +5. A repeat pull leaves the row count AND balance unchanged (dedup guard observable: + `secondPull.pulled === 0`, `db.eventLog.count()` unchanged). +6. A forged event (valid structure, mutated payload so the signature no longer matches) is rejected + with HTTP 422 and never appears in a subsequent pull (`balances["townA"]` stays undefined). +7. `trySyncWithBackend()` against a closed port (`http://127.0.0.1:1`) resolves `{ ok: false }` + without throwing, and a normal local `append()`/`readAll()` immediately after is unaffected. + +## Adversarial QA classes + +- malformed input: integration test pushes a non-hex pubkey, a wrong-typed `lamportTs`, and a + missing field - each returns HTTP 400 (not 500), store unaffected. PASS. +- prompt injection / untrusted external text: N/A - the payload is opaque JSON data, never + interpreted as code or a prompt; the only trust boundary is the Ed25519 signature check (covered). +- cancel/resume: N/A - no long-running resumable flow; the one request uses an AbortController whose + timeout path is exercised by the unreachable-relay case. +- stale/cached artifacts: the relay store is a module-level array reset via `resetEventRelayStore()` + in the integration test's `beforeEach`; vitest isolates each test file in its own worker, so a + fresh process starts with an empty store. Verified by the dedup assertions depending on a clean slate. +- dirty worktree: `git status --porcelain` after the test run shows only intended files; no stray + temp/log files (this relay store writes nothing to disk - no `BLOB_STORE_DIR`-style temp dir). +- hung/long commands: the full test run completes in ~8s and exits; `ss -ltnp` shows no dev/api port + listening and `pgrep vitest|devServer` finds no leftover process after the run. +- flaky tests: no `sleep`/timing waits in the new tests - every assertion awaits a real + promise/fetch. (The waterwatch flake noted above is pre-existing and unrelated.) +- misleading success output: the pass lines above are the literal vitest summary/verbose output. +- repeated interruptions: N/A. + +## Summary + +Added a generic, event-type-agnostic signed-event relay (`api/sync`) that signature-verifies every +pushed event before storing it and acts as a pure relay (no creation, mutation, or counter-signing), +plus a client `trySyncWithBackend()` that ingests pulled remote entries through the existing +`appendEntry()` path with a (authorPubkey, signature) duplicate guard, and is a strict silent no-op +when the backend is unreachable. Verified by the full suite (628 passing), a clean type-checking +build, clean lint on changed files, and a real two-device HTTP integration test proving propagation, +authorship preservation, dedup idempotency, forged-event rejection, and the offline-resilience +invariant. diff --git a/api/_lib/devServer.ts b/api/_lib/devServer.ts index be5b686..5d6c4b5 100644 --- a/api/_lib/devServer.ts +++ b/api/_lib/devServer.ts @@ -1,12 +1,17 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import postBlob from "../blob/index.ts"; import getBlob from "../blob/[id].ts"; +import postSync from "../sync/index.ts"; import { sendJson } from "./httpUtils.ts"; export function createApiServer() { return createServer(async (req: IncomingMessage, res: ServerResponse) => { const pathname = new URL(req.url ?? "/", "http://localhost").pathname; try { + if (pathname === "/api/sync") { + await postSync(req, res); + return; + } if (pathname === "/api/blob") { await postBlob(req, res); return; diff --git a/api/_lib/eventRelayStore.ts b/api/_lib/eventRelayStore.ts new file mode 100644 index 0000000..bcb7b35 --- /dev/null +++ b/api/_lib/eventRelayStore.ts @@ -0,0 +1,174 @@ +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 }; +} diff --git a/api/sync.integration.test.ts b/api/sync.integration.test.ts new file mode 100644 index 0000000..b4b25f8 --- /dev/null +++ b/api/sync.integration.test.ts @@ -0,0 +1,164 @@ +import type { AddressInfo } from "node:net"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import * as ed from "@noble/ed25519"; +import { createApiServer } from "./_lib/devServer.ts"; +import { resetEventRelayStore } from "./_lib/eventRelayStore.ts"; +import { db } from "../src/lib/db.ts"; +import { init } from "../src/lib/identity.ts"; +import { append, readAll } from "../src/lib/eventlog.ts"; +import { computeBalances } from "../src/lib/ledger.ts"; +import { resetSyncCursors, trySyncWithBackend } from "../src/lib/sync.ts"; + +function hex(bytes: Uint8Array): string { + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +function canonical(payload: unknown, lamportTs: number): Uint8Array { + return new TextEncoder().encode(JSON.stringify({ payload, lamportTs })); +} + +interface Device { + publicKey: Uint8Array; + secretKey: Uint8Array; +} + +async function newDevice(): Promise { + const { secretKey, publicKey } = await ed.keygenAsync(); + return { publicKey, secretKey }; +} + +async function signEvent(device: Device, payload: unknown, lamportTs: number) { + const signature = await ed.signAsync(canonical(payload, lamportTs), device.secretKey); + return { + payload, + authorPubkey: hex(device.publicKey), + signature: hex(signature), + lamportTs, + }; +} + +async function pushRaw(baseUrl: string, body: unknown): Promise { + return fetch(`${baseUrl}/api/sync`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +describe("signed-event relay integration (todo 2)", () => { + let server: ReturnType; + let baseUrl: string; + + beforeAll(async () => { + server = createApiServer(); + await new Promise((resolve) => server.listen(0, resolve)); + const { port } = server.address() as AddressInfo; + baseUrl = `http://127.0.0.1:${port}`; + }); + + afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); + }); + + beforeEach(async () => { + resetEventRelayStore(); + resetSyncCursors(); + db.close(); + await db.delete(); + await db.open(); + await init(); + }); + + it("propagates device A's signed event to device B and dedups a repeat pull", async () => { + const deviceA = await newDevice(); + const payload = { type: "wallet.issue", account: "townA", amount: 100 }; + const eventA = await signEvent(deviceA, payload, 0); + + const pushRes = await pushRaw(baseUrl, { push: [eventA], pullCursor: 0 }); + expect(pushRes.status).toBe(200); + const pushBody = (await pushRes.json()) as { stored: number }; + expect(pushBody.stored).toBe(1); + + const pull = await trySyncWithBackend({ endpoint: `${baseUrl}/api/sync` }); + expect(pull.ok).toBe(true); + expect(pull.pulled).toBe(1); + + const all = await readAll(); + const ingested = all.find((e) => hex(e.authorPubkey) === hex(deviceA.publicKey)); + expect(ingested).toBeDefined(); + expect(hex(ingested!.authorPubkey)).toBe(eventA.authorPubkey); + expect(hex(ingested!.signature)).toBe(eventA.signature); + expect(computeBalances(all).balances["townA"]).toBe(100); + + const countBefore = await db.eventLog.count(); + const balanceBefore = computeBalances(await readAll()).balances["townA"]; + + resetSyncCursors(); + const secondPull = await trySyncWithBackend({ endpoint: `${baseUrl}/api/sync` }); + expect(secondPull.ok).toBe(true); + expect(secondPull.pulled).toBe(0); + + expect(await db.eventLog.count()).toBe(countBefore); + expect(computeBalances(await readAll()).balances["townA"]).toBe(balanceBefore); + }); + + it("rejects a forged event with 422 and never relays it to a puller", async () => { + const deviceA = await newDevice(); + const genuine = await signEvent( + deviceA, + { type: "wallet.issue", account: "townA", amount: 5 }, + 0, + ); + const forged = { + ...genuine, + payload: { type: "wallet.issue", account: "townA", amount: 999999 }, + }; + + const res = await pushRaw(baseUrl, { push: [forged], pullCursor: 0 }); + expect(res.status).toBe(422); + const body = (await res.json()) as { error: string }; + expect(body.error).toMatch(/signature does not verify/i); + + const pull = await trySyncWithBackend({ endpoint: `${baseUrl}/api/sync` }); + expect(pull.ok).toBe(true); + expect(pull.pulled).toBe(0); + expect(computeBalances(await readAll()).balances["townA"]).toBeUndefined(); + }); + + it("rejects malformed events with 400, not a 500", async () => { + const badPubkey = await pushRaw(baseUrl, { + push: [{ payload: {}, authorPubkey: "nothex", signature: "ab", lamportTs: 0 }], + }); + expect(badPubkey.status).toBe(400); + + const badLamport = await pushRaw(baseUrl, { + push: [ + { + payload: {}, + authorPubkey: "a".repeat(64), + signature: "b".repeat(128), + lamportTs: "soon", + }, + ], + }); + expect(badLamport.status).toBe(400); + + const missingField = await pushRaw(baseUrl, { + push: [{ authorPubkey: "a".repeat(64), signature: "b".repeat(128), lamportTs: 0 }], + }); + expect(missingField.status).toBe(400); + }); + + it("is a silent no-op against an unreachable relay, leaving local append/read unaffected", async () => { + const countBefore = await db.eventLog.count(); + const result = await trySyncWithBackend({ + endpoint: "http://127.0.0.1:1/api/sync", + timeoutMs: 500, + }); + expect(result).toEqual({ ok: false, pushed: 0, pulled: 0 }); + + const stored = await append({ type: "local.unaffected" }); + expect(stored.payload).toEqual({ type: "local.unaffected" }); + expect((await readAll()).length).toBe(countBefore + 1); + }); +}); diff --git a/api/sync/index.ts b/api/sync/index.ts new file mode 100644 index 0000000..aef4dac --- /dev/null +++ b/api/sync/index.ts @@ -0,0 +1,86 @@ +import type { IncomingMessage, ServerResponse } from "node:http"; +import { sendJson } from "../_lib/httpUtils.ts"; +import { + EventSignatureError, + MalformedEventError, + pullEvents, + pushEvents, +} from "../_lib/eventRelayStore.ts"; + +const MAX_SYNC_BODY_BYTES = 4 * 1024 * 1024; + +async function readJsonBody( + req: IncomingMessage, + limitBytes: number, +): Promise { + const chunks: Buffer[] = []; + let total = 0; + for await (const chunk of req) { + total += (chunk as Buffer).length; + if (total > limitBytes) { + req.destroy(); + throw new MalformedEventError("request body exceeds size limit"); + } + chunks.push(chunk as Buffer); + } + const raw = Buffer.concat(chunks, total).toString("utf8"); + if (raw.length === 0) return {}; + try { + return JSON.parse(raw); + } catch { + throw new MalformedEventError("request body is not valid JSON"); + } +} + +/** + * Generic signed-event relay (backend-expansion todo 2). A single POST both + * pushes a batch of signed events and pulls everything since a cursor: + * request `{ push?: WireEventEntry[], pullCursor?: number }` + * response `{ stored: number, entries: WireEventEntry[], cursor: number }` + * + * It is a pure relay - it verifies each pushed event's own signature and never + * signs, mutates, or counter-signs anything. A malformed batch is a 400 and a + * forged/tampered signature is a 422; neither is ever stored, and neither is a + * generic 500. + */ +export default async function handler( + req: IncomingMessage, + res: ServerResponse, +): Promise { + if (req.method !== "POST") { + sendJson(res, 405, { error: "method not allowed, use POST" }); + return; + } + + try { + const body = await readJsonBody(req, MAX_SYNC_BODY_BYTES); + if (typeof body !== "object" || body === null) { + throw new MalformedEventError("request body must be a JSON object"); + } + const { push, pullCursor } = body as { + push?: unknown; + pullCursor?: unknown; + }; + + let stored = 0; + if (push !== undefined) { + if (!Array.isArray(push)) { + throw new MalformedEventError("push must be an array of events"); + } + stored = await pushEvents(push); + } + + const { entries, cursor } = pullEvents(pullCursor); + sendJson(res, 200, { stored, entries, cursor }); + } catch (err) { + if (err instanceof EventSignatureError) { + sendJson(res, 422, { error: err.message }); + return; + } + if (err instanceof MalformedEventError) { + sendJson(res, 400, { error: err.message }); + return; + } + sendJson(res, 500, { error: "failed to relay events" }); + } +} diff --git a/src/lib/ledgerConflicts.ts b/src/lib/ledgerConflicts.ts index ca7634f..9f4936e 100644 --- a/src/lib/ledgerConflicts.ts +++ b/src/lib/ledgerConflicts.ts @@ -72,9 +72,15 @@ function toKey(bytes: Uint8Array): string { return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); } -/** Identity key for deduplicating the same signed entry appearing in both - * replicas (e.g. one replica already synced the other's entry). */ -function entryIdentity(entry: StoredEventLogEntry): string { +/** Identity key for deduplicating the same signed entry: the author's public + * key and the signature it carries uniquely identify one signed event, + * regardless of its local Dexie id. Shared with `src/lib/sync.ts`'s pull-side + * duplicate guard so both dedup paths key events identically. Typed on just + * the two signed fields so an entry that has not been assigned a local id yet + * (e.g. one freshly pulled from the relay) can be keyed before it is stored. */ +export function entryIdentity( + entry: Pick, +): string { return `${toKey(entry.authorPubkey)}:${toKey(entry.signature)}`; } diff --git a/src/lib/sync.test.ts b/src/lib/sync.test.ts new file mode 100644 index 0000000..3806afa --- /dev/null +++ b/src/lib/sync.test.ts @@ -0,0 +1,110 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as ed from "@noble/ed25519"; +import { db } from "./db"; +import { init } from "./identity"; +import { append, readAll } from "./eventlog"; +import { computeBalances } from "./ledger"; +import { resetSyncCursors, trySyncWithBackend } from "./sync"; + +function hex(bytes: Uint8Array): string { + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +async function signedWireEntry( + payload: unknown, + lamportTs: number, +): Promise<{ + payload: unknown; + authorPubkey: string; + signature: string; + lamportTs: number; +}> { + const { secretKey, publicKey } = await ed.keygenAsync(); + const message = new TextEncoder().encode(JSON.stringify({ payload, lamportTs })); + const signature = await ed.signAsync(message, secretKey); + return { + payload, + authorPubkey: hex(publicKey), + signature: hex(signature), + lamportTs, + }; +} + +function okResponse(body: unknown): Response { + return { + ok: true, + status: 200, + json: async () => body, + } as unknown as Response; +} + +beforeEach(async () => { + indexedDB.deleteDatabase(db.name); + db.close(); + await db.open(); + await init(); + resetSyncCursors(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("trySyncWithBackend", () => { + it("is a silent no-op when the endpoint connection is refused, leaving local append/read untouched", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED"))); + + const before = (await readAll()).length; + const result = await trySyncWithBackend({ + endpoint: "http://127.0.0.1:1/api/sync", + timeoutMs: 100, + }); + + expect(result).toEqual({ ok: false, pushed: 0, pulled: 0 }); + + const stored = await append({ type: "local.only" }); + expect(stored.payload).toEqual({ type: "local.only" }); + expect((await readAll()).length).toBe(before + 1); + }); + + it("is a silent no-op on a non-2xx response, ingesting nothing", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ ok: false, status: 500 } as Response), + ); + + const result = await trySyncWithBackend({ endpoint: "http://relay/api/sync" }); + expect(result).toEqual({ ok: false, pushed: 0, pulled: 0 }); + expect(await db.eventLog.count()).toBe(0); + }); + + it("persists a pulled remote entry once and skips it on a repeat pull (dedup guard)", async () => { + const wire = await signedWireEntry( + { type: "wallet.issue", account: "remoteAcct", amount: 42 }, + 7, + ); + const fetchMock = vi + .fn() + .mockResolvedValue(okResponse({ stored: 0, entries: [wire], cursor: 1 })); + vi.stubGlobal("fetch", fetchMock); + + const first = await trySyncWithBackend({ endpoint: "http://relay/api/sync" }); + expect(first.ok).toBe(true); + expect(first.pulled).toBe(1); + + const afterFirst = await readAll(); + expect(afterFirst).toHaveLength(1); + expect(hex(afterFirst[0].authorPubkey)).toBe(wire.authorPubkey); + expect(hex(afterFirst[0].signature)).toBe(wire.signature); + expect(computeBalances(afterFirst).balances["remoteAcct"]).toBe(42); + + const countBefore = await db.eventLog.count(); + resetSyncCursors(); + const second = await trySyncWithBackend({ endpoint: "http://relay/api/sync" }); + expect(second.ok).toBe(true); + expect(second.pulled).toBe(0); + + expect(await db.eventLog.count()).toBe(countBefore); + expect(computeBalances(await readAll()).balances["remoteAcct"]).toBe(42); + }); +}); diff --git a/src/lib/sync.ts b/src/lib/sync.ts new file mode 100644 index 0000000..babc25f --- /dev/null +++ b/src/lib/sync.ts @@ -0,0 +1,206 @@ +import { + appendEntry, + readAll, + type StoredEventLogEntry, + type UnsignedEventLogEntry, +} from "./eventlog.ts"; +import { entryIdentity } from "./ledgerConflicts.ts"; + +/** + * Best-effort, additive cross-device sync for the signed Event Log (backend- + * expansion todo 2). This is the FIRST live cross-device transport for the + * wallet's log (see src/lib/ledgerConflicts.ts's doc comment - that module + * only ever merged hand-built fixtures). It is deliberately additive to the + * local-first path: `append`/`readAll`/replay never call into here, so a down + * or unreachable backend changes no mini-app's behavior at all. + * + * Invariants this helper upholds: + * - A pulled remote entry is persisted through `appendEntry()`, NEVER + * `append()`: `append()` would re-sign the entry with THIS device's key and + * forge authorship over the remote author's event. `appendEntry()` keeps + * the entry's original authorPubkey/signature and re-verifies them. + * - Before persisting a pulled entry it is skipped if an entry with the same + * (authorPubkey, signature) pair already exists locally - the eventLog + * table has no uniqueness constraint on that pair and `computeBalances` + * applies every stored entry unconditionally, so ingesting a duplicate + * wallet event twice would corrupt the ledger. This runs on every call. + * - Any failure (offline, timeout, non-2xx, bad payload) is a silent no-op: + * it throws nothing and leaves the local log untouched. + */ + +export interface SyncOptions { + /** Relay endpoint URL. Defaults to the same-origin `/api/sync`. */ + endpoint?: string; + /** Abort the request after this many ms (treated as unreachable). */ + timeoutMs?: number; +} + +export interface SyncResult { + /** Whether the round-trip completed (false => treated as offline no-op). */ + ok: boolean; + /** Local events pushed to the relay this call. */ + pushed: number; + /** Remote entries newly persisted locally this call (post-dedup). */ + pulled: number; +} + +interface WireEventEntry { + payload: unknown; + authorPubkey: string; + signature: string; + lamportTs: number; +} + +interface CursorState { + /** Highest local Dexie id already pushed to this endpoint. */ + lastPushedId: number; + /** Relay cursor last pulled from this endpoint. */ + lastPulledCursor: number; +} + +/** + * Per-endpoint cursors kept only in memory: they are a within-session + * optimization, not durable state. If they are lost (reload, new tab) the next + * sync simply re-pushes/re-pulls and the relay's own dedup plus this helper's + * (authorPubkey, signature) guard keep that idempotent - so the guard, not the + * cursor, is the load-bearing correctness mechanism. + */ +const cursors = new Map(); + +function cursorFor(endpoint: string): CursorState { + let state = cursors.get(endpoint); + if (!state) { + state = { lastPushedId: 0, lastPulledCursor: 0 }; + cursors.set(endpoint, state); + } + return state; +} + +/** Drop all in-memory cursors (test seam; also simulates a reload). */ +export function resetSyncCursors(): void { + cursors.clear(); +} + +function bytesToHex(bytes: Uint8Array): string { + return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); +} + +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; +} + +function toWire(entry: StoredEventLogEntry): WireEventEntry { + return { + payload: entry.payload, + authorPubkey: bytesToHex(entry.authorPubkey), + signature: bytesToHex(entry.signature), + lamportTs: entry.lamportTs, + }; +} + +const HEX = /^[0-9a-f]*$/i; + +function fromWire(wire: unknown): UnsignedEventLogEntry | null { + if (typeof wire !== "object" || wire === null) return null; + const o = wire as Record; + if ( + typeof o.authorPubkey !== "string" || + typeof o.signature !== "string" || + typeof o.lamportTs !== "number" || + o.authorPubkey.length % 2 !== 0 || + o.signature.length % 2 !== 0 || + !HEX.test(o.authorPubkey) || + !HEX.test(o.signature) + ) { + return null; + } + return { + payload: o.payload, + authorPubkey: hexToBytes(o.authorPubkey), + signature: hexToBytes(o.signature), + lamportTs: o.lamportTs, + }; +} + +/** + * Push new local events and pull new remote entries through the relay, + * persisting each pulled entry via `appendEntry()` after a (authorPubkey, + * signature) duplicate check. When the endpoint is unreachable or errors, this + * resolves to `{ ok: false }` without throwing and without touching the local + * log - safe to call on any mini-app mount. + */ +export async function trySyncWithBackend( + options: SyncOptions = {}, +): Promise { + const endpoint = options.endpoint ?? "/api/sync"; + const timeoutMs = options.timeoutMs ?? 5000; + const noop: SyncResult = { ok: false, pushed: 0, pulled: 0 }; + + try { + const state = cursorFor(endpoint); + const localEntries = await readAll(); + const toPush = localEntries.filter((e) => e.id > state.lastPushedId); + const maxLocalId = localEntries.reduce( + (max, e) => (e.id > max ? e.id : max), + state.lastPushedId, + ); + + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + let response: Response; + try { + response = await fetch(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + push: toPush.map(toWire), + pullCursor: state.lastPulledCursor, + }), + signal: controller.signal, + }); + } finally { + clearTimeout(timer); + } + + if (!response.ok) return noop; + + const data = (await response.json()) as { + entries?: unknown; + cursor?: unknown; + }; + const remoteEntries = Array.isArray(data.entries) ? data.entries : []; + const nextCursor = + typeof data.cursor === "number" ? data.cursor : state.lastPulledCursor; + + const existing = new Set((await readAll()).map(entryIdentity)); + let pulled = 0; + for (const wire of remoteEntries) { + const entry = fromWire(wire); + if (entry === null) continue; + const key = entryIdentity(entry); + if (existing.has(key)) continue; + try { + await appendEntry(entry); + existing.add(key); + pulled++; + } catch { + // The relay only stores signature-verified entries, so this is not + // expected; if a single entry still fails verification on ingest, skip + // it rather than abort the whole sync or corrupt the local log. + continue; + } + } + + state.lastPushedId = maxLocalId; + state.lastPulledCursor = nextCursor; + return { ok: true, pushed: toPush.length, pulled }; + } catch { + // Offline / network error / timeout / malformed response: silent no-op. + // The local-first append/replay path is never affected by this helper. + return noop; + } +}