import { createServer, type Server } from "node:http"; import { readFileSync } from "node:fs"; import type { AddressInfo } from "node:net"; import { chacha20poly1305 } from "@noble/ciphers/chacha.js"; import { ed25519, x25519 } from "@noble/curves/ed25519.js"; import { hkdf } from "@noble/hashes/hkdf.js"; import { sha256 } from "@noble/hashes/sha2.js"; import { JSDOM, type DOMWindow } from "jsdom"; import { canonicalize } from "../src/jcs.ts"; import { mailbox, sealEnvelope, type Envelope, type Plain, type Ref } from "../src/message.ts"; import { leadingZeroBits, type Listing } from "../src/verify.ts"; /** The clock the browser sees in these tests (unix seconds). */ export const NOW = 1_800_000_000; export const DIFFICULTY = 8; const enc = new TextEncoder(); const hex = (b: Uint8Array) => Buffer.from(b).toString("hex"); /** An owner: identity and device keys, and the certificate between them. */ export interface Party { idKey: Uint8Array; devKey: Uint8Array; cert: Record; author: string; device: string; listing: Listing; } /** Creates a validly signed listing under a brand-new identity and device. */ export function signListing(fields: Record = {}): Listing { return newParty(fields).listing; } /** Like signListing, but keeps the keys so a test can act as the owner. */ export function newParty(fields: Record = {}, certFields: Record = {}): Party { const idKey = ed25519.utils.randomSecretKey(); const devKey = ed25519.utils.randomSecretKey(); const cert: Record = { v: 1, author: hex(ed25519.getPublicKey(idKey)), device: hex(ed25519.getPublicKey(devKey)), issued_at: NOW - 3600, expires_at: NOW + 90 * 86_400, ...certFields, }; cert.sig = hex(ed25519.sign(enc.encode("allmende-cert-v1\n" + canonicalize(cert)), idKey)); const l: Record = { v: 1, id: hex(ed25519.utils.randomSecretKey()).slice(0, 32), author: cert.author, device: cert.device, seq: 1, created_at: NOW, expires_at: NOW + 10 * 86_400, kind: "rent", category: "apartment", geohash: "u1xjhx", price: { amount_cents: 90_000, currency: "EUR", period: "month" }, area_m2: 40, rooms_x2: 4, title: "Wohnung", pow: 0, cert, ...fields, }; for (let pow = 0; ; pow++) { l.pow = pow; if (leadingZeroBits(sha256(enc.encode(canonicalize(l)))) >= DIFFICULTY) break; } l.sig = hex(ed25519.sign(enc.encode("allmende-listing-v1\n" + canonicalize(l)), devKey)); return { idKey, devKey, cert, author: cert.author as string, device: cert.device as string, listing: l as unknown as Listing, }; } // --- playing the owner ------------------------------------------------------- /** What an owner's node does with a buyer's envelope: decrypt it with the device key. */ export function openAsOwner(env: Envelope, p: Party): Plain { const sk = ed25519.utils.toMontgomerySecret(p.devKey); const epk = fromHex(env.epk); const rpk = x25519.getPublicKey(sk); const key = hkdf(sha256, x25519.getSharedSecret(sk, epk), concatBytes(epk, rpk), enc.encode("allmende-seal-v1"), 32); const aad = enc.encode( canonicalize({ v: env.v, listing: env.listing, to: env.to, rcpt: env.rcpt, epk: env.epk, created_at: env.created_at, expires_at: env.expires_at, }), ); const padded = chacha20poly1305(key, new Uint8Array(12), aad).decrypt(fromHex(env.ct)); let end = padded.length; while (end > 0 && padded[end - 1] === 0) end--; if (padded[end - 1] !== 0x80) throw new Error("bad padding"); return JSON.parse(new TextDecoder().decode(padded.slice(0, end - 1))) as Plain; } export interface ReplyOptions { /** Edit the plaintext before it is signed (e.g. to build an invalid message). */ beforeSign?: (plain: Record) => void; /** Edit the plaintext after signing (e.g. to break the signature). */ afterSign?: (plain: Record) => void; /** Sign with another party's device key (a forgery). */ signer?: Party; now?: number; difficulty?: number; } /** * Builds a reply the way an owner's node does (internal/message SealToBuyer): * signs the plaintext with the device key and seals it to the thread key. */ export async function sealReply( owner: Party, ref: Ref, fields: Record, threadPub: string, opts: ReplyOptions = {}, ): Promise { const now = opts.now ?? NOW; const signer = opts.signer ?? owner; const plain: Record = { thread: threadPub, sent_at: now, listing: ref, device: signer.device, cert: signer.cert, ...fields, }; opts.beforeSign?.(plain); plain.sig = hex(ed25519.sign(enc.encode("allmende-reply-v1\n" + canonicalize(plain)), signer.devKey)); opts.afterSign?.(plain); return sealEnvelope({ listing: ref, to: "buyer", rcpt: mailbox(threadPub), rpk: fromHex(threadPub), body: enc.encode(canonicalize(plain)), now, difficulty: opts.difficulty ?? 6, }); } function fromHex(s: string): Uint8Array { return Uint8Array.from(Buffer.from(s, "hex")); } function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array { const out = new Uint8Array(a.length + b.length); out.set(a); out.set(b, a.length); return out; } // --- a stand-in for a node's HTTP API ------------------------------------- export interface Gateway { url: string; /** Query strings of every /api/v1/listings search received. */ queries: string[]; /** Bodies of every POST /api/v1/messages, as received. */ posted: string[]; /** Envelopes served from GET /api/v1/messages?mailbox=, by tag. Tests fill it. */ mailboxes: Map; /** Make POST /api/v1/messages answer with this status and error. */ postFails?: { status: number; error: string }; /** Plays the node's owner endpoints (/mine, /inbox, .../address); unset, they answer 404. */ owner?: (req: { method: string; path: string; query: URLSearchParams; body: string; auth: string; }) => { status: number; body?: unknown } | undefined; close(): Promise; } export interface GatewayOptions { listings: unknown[]; /** For a requested listing id, answer with this other listing instead. */ swap?: unknown; statusFails?: boolean; /** The regions the node reports; default ["u1x"]. */ regions?: string[]; } export async function startGateway(opts: GatewayOptions): Promise { const queries: string[] = []; const posted: string[] = []; const mailboxes = new Map(); const gateway: Gateway = { url: "", queries, posted, mailboxes, close: () => new Promise((ok) => server.close(() => ok())), }; const server: Server = createServer((req, res) => { const url = new URL(req.url ?? "/", "http://x"); const json = (code: number, body: unknown) => { res.writeHead(code, { "Content-Type": "application/json" }); res.end(JSON.stringify(body)); }; if (url.pathname === "/places.tsv") { // A static file of the UI, as the real node serves it. res.writeHead(200, { "Content-Type": "text/tab-separated-values" }); return void res.end(readFileSync(new URL("../static/places.tsv", import.meta.url))); } // The owner's token-protected routes are played by the test, if it sets `owner`. const writesListing = req.method !== "GET" && /^\/api\/v1\/listings(\/[0-9a-f]{32})?$/.test(url.pathname); if (writesListing || /^\/api\/v1\/(mine|inbox|regions|blocked)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const auth = req.headers.authorization ?? ""; const r = gateway.owner?.({ method: req.method ?? "GET", path: url.pathname, query: url.searchParams, body, auth }); if (!r) return json(404, { error: "not found" }); if (r.status === 204) { res.writeHead(204); return res.end(); } json(r.status, r.body ?? null); }); return; } if (url.pathname === "/api/v1/messages") { if (req.method === "POST") { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { if (gateway.postFails) return json(gateway.postFails.status, { error: gateway.postFails.error }); posted.push(body); json(202, { hash: "x" }); }); return; } return json(200, mailboxes.get(url.searchParams.get("mailbox") ?? "") ?? []); } if (url.pathname === "/api/v1/status") { if (opts.statusFails) return json(500, { error: "down" }); return json(200, { peer_id: "12D3KooWTest", author: "a".repeat(64), device: "b".repeat(64), regions: opts.regions ?? ["u1x"], peers: 2, listings: opts.listings.length, difficulty: DIFFICULTY, message_difficulty: 6, }); } if (url.pathname === "/api/v1/listings") { queries.push(url.search); return json(200, opts.listings); } const m = /^\/api\/v1\/listings\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(url.pathname); if (m) { if (opts.swap) return json(200, opts.swap); const hit = (opts.listings as Listing[]).find((l) => l.author === m[1] && l.id === m[2]); return hit ? json(200, hit) : json(404, { error: "not found" }); } json(404, { error: "not found" }); }); await new Promise((ok) => server.listen(0, "127.0.0.1", ok)); const { port } = server.address() as AddressInfo; gateway.url = `http://127.0.0.1:${port}`; return gateway; } // --- running the real built UI -------------------------------------------- export interface Page { window: DOMWindow; document: Document; waitFor(pred: () => boolean, what: string, ms?: number): Promise; close(): void; } /** Loads web/dist/index.html in jsdom and runs the built bundle against `gateway`. */ export function openPage(gateway: string, hash = "", lang = "en"): Page { const dist = new URL("../dist/", import.meta.url); const html = readFileSync(new URL("index.html", dist), "utf8"); const bundle = readFileSync(new URL("app.js", dist), "utf8"); const dom = new JSDOM(html, { url: `${gateway}/?lang=${lang}${hash}`, runScripts: "outside-only", pretendToBeVisual: true, }); const w = dom.window; w.fetch = ((input: string | URL, init?: RequestInit) => fetch(new URL(String(input), gateway), init)) as unknown as typeof w.fetch; w.scrollTo = () => {}; w.Date.now = () => NOW * 1000; w.eval(bundle); return { window: w, document: w.document, async waitFor(pred, what, ms = 4000) { const end = Date.now() + ms; while (Date.now() < end) { if (pred()) return; await new Promise((r) => setTimeout(r, 10)); } throw new Error(`timed out waiting for: ${what}\n${w.document.body.textContent?.slice(0, 600)}`); }, close: () => w.close(), }; }