Files

362 lines
13 KiB
TypeScript

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<string, unknown>;
author: string;
device: string;
listing: Listing;
}
/** Creates a validly signed listing under a brand-new identity and device. */
export function signListing(fields: Record<string, unknown> = {}): Listing {
return newParty(fields).listing;
}
/** Like signListing, but keeps the keys so a test can act as the owner. */
export function newParty(fields: Record<string, unknown> = {}, certFields: Record<string, unknown> = {}): Party {
const idKey = ed25519.utils.randomSecretKey();
const devKey = ed25519.utils.randomSecretKey();
const cert: Record<string, unknown> = {
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<string, unknown> = {
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<string, unknown>) => void;
/** Edit the plaintext after signing (e.g. to break the signature). */
afterSign?: (plain: Record<string, unknown>) => 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<string, unknown>,
threadPub: string,
opts: ReplyOptions = {},
): Promise<Envelope> {
const now = opts.now ?? NOW;
const signer = opts.signer ?? owner;
const plain: Record<string, unknown> = {
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=<tag>, by tag. Tests fill it. */
mailboxes: Map<string, unknown[]>;
/** Make POST /api/v1/messages answer with this status and error. */
postFails?: { status: number; error: string };
/** What GET /api/v1/reports answers; unset, the route does not exist (an older node). */
reports?: unknown;
/** Bodies POSTed to /api/v1/signals (a visitor's tips), in order. */
tips: string[];
/** Make POST /api/v1/signals answer with this status and error. */
tipFails?: { status: number; error: string };
/** What GET /api/v1/messages/required answers (bits); unset, the route does not exist (an older node). */
requiredBits?: number;
/** Refuse the next POST once with 429, asking for this many bits of proof-of-work. */
refuseOnceAskingFor?: number;
/** 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<void>;
}
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[];
/** The device certificate the node reports in /status; unset, it says nothing (an older node). */
cert?: { expires_at: number; can_renew: boolean };
/** The addresses the node says others can join through; unset, it says nothing (an older node). */
share?: string[];
}
export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
const queries: string[] = [];
const posted: string[] = [];
const mailboxes = new Map<string, unknown[]>();
const gateway: Gateway = {
url: "",
queries,
posted,
mailboxes,
tips: [],
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)));
}
if (url.pathname === "/api/v1/reports" && req.method === "GET") {
return gateway.reports === undefined ? json(404, { error: "not found" }) : json(200, gateway.reports);
}
if (url.pathname === "/api/v1/signals" && req.method === "POST") {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
if (gateway.tipFails) return json(gateway.tipFails.status, { error: gateway.tipFails.error });
gateway.tips.push(body);
res.writeHead(202);
res.end();
});
return;
}
// 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|signals|reports|certificate)|^\/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/required" && gateway.requiredBits !== undefined) {
return json(200, { bits: gateway.requiredBits });
}
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 });
if (gateway.refuseOnceAskingFor !== undefined) {
const bits = gateway.refuseOnceAskingFor;
gateway.refuseOnceAskingFor = undefined;
return json(429, { error: "needs more work", required_bits: bits });
}
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,
...(opts.share ? { share: opts.share } : {}),
...(opts.cert ? { cert_expires_at: opts.cert.expires_at, can_renew: opts.cert.can_renew } : {}),
});
}
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<void>((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<void>;
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(),
};
}