import { createServer, type Server } from "node:http"; import { readFileSync } from "node:fs"; import type { AddressInfo } from "node:net"; import { ed25519 } from "@noble/curves/ed25519.js"; import { sha256 } from "@noble/hashes/sha2.js"; import { JSDOM, type DOMWindow } from "jsdom"; import { canonicalize } from "../src/jcs.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"); /** Creates a validly signed listing under a brand-new identity and device. */ export function signListing(fields: Record = {}): Listing { 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, }; 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 l as unknown as Listing; } // --- 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[]; close(): Promise; } export interface GatewayOptions { listings: unknown[]; /** For a requested listing id, answer with this other listing instead. */ swap?: unknown; statusFails?: boolean; } export async function startGateway(opts: GatewayOptions): Promise { const queries: string[] = []; 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 === "/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: ["u1x"], peers: 2, listings: opts.listings.length, difficulty: DIFFICULTY, }); } 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; return { url: `http://127.0.0.1:${port}`, queries, close: () => new Promise((ok) => server.close(() => ok())), }; } // --- 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(), }; }