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.
173 lines
6.0 KiB
TypeScript
173 lines
6.0 KiB
TypeScript
import type { AddressInfo } from "node:net";
|
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
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<Device> {
|
|
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<Response> {
|
|
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<typeof createApiServer>;
|
|
let baseUrl: string;
|
|
let storeDir: string;
|
|
|
|
beforeAll(async () => {
|
|
storeDir = await mkdtemp(join(tmpdir(), "commons-events-test-"));
|
|
process.env.EVENT_DB_PATH = join(storeDir, "events.sqlite3");
|
|
server = createApiServer();
|
|
await new Promise<void>((resolve) => server.listen(0, resolve));
|
|
const { port } = server.address() as AddressInfo;
|
|
baseUrl = `http://127.0.0.1:${port}`;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
delete process.env.EVENT_DB_PATH;
|
|
await rm(storeDir, { recursive: true, force: true });
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|