Repository Public
1// Test harness: a real server process, a real PostgreSQL database, a software WebAuthn authenticator and a2// cookie-keeping Node transport. Nothing in the server is stubbed or bypassed.3import { spawn, type ChildProcess } from "node:child_process";4import crypto from "node:crypto";5import fs from "node:fs";6import os from "node:os";7import path from "node:path";8import postgres from "postgres";9import { ApiError, Engine, MemoryStore, type Passkeys, type Store, type Transport } from "../apps/web/src/core/engine.ts";1011export const PORT = Number(process.env.SPV_TEST_PORT ?? 8741);12export const ORIGIN = `http://localhost:${PORT}`;13export const DB = process.env.SPV_TEST_DB ?? "postgres://127.0.0.1/sp_vault_test";14if (!/_test$/.test(DB)) throw new Error("tests refuse to run outside a *_test database");15export const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "spv-test-"));16export const sql = postgres(DB, { onnotice: () => {} });1718let server: ChildProcess | undefined, managedProc: ChildProcess | undefined;19export const MANAGED_PORT = PORT + 1;20/** Starts the server together with the isolated managed-secrets process (throwaway key and token). */21export async function startServerWithManaged() {22 await sql.unsafe("drop schema public cascade; create schema public;");23 const keyFile = path.join(dataDir, "managed.key"), tokenFile = path.join(dataDir, "managed.token");24 fs.writeFileSync(keyFile, crypto.randomBytes(32).toString("base64"), { mode: 0o600 }); fs.writeFileSync(tokenFile, crypto.randomBytes(32).toString("base64url"), { mode: 0o600 });25 managedProc = spawn("node_modules/.bin/tsx", ["services/managed-secrets/src/index.ts"], { stdio: ["ignore", "inherit", "inherit"],26 env: { ...process.env, SPV_MANAGED_PORT: String(MANAGED_PORT), SPV_MANAGED_KEY_FILE: keyFile, SPV_MANAGED_TOKEN_FILE: tokenFile, SPV_MANAGED_DATABASE_URL: DB, SPV_MANAGED_ALLOW_PRIVATE: "1", SPV_LOG_LEVEL: "warn" } });27 await startServer({ SPV_MANAGED_URL: `http://127.0.0.1:${MANAGED_PORT}`, SPV_MANAGED_TOKEN_FILE: tokenFile }, false);28 for (let i = 0; i < 60; i++) { try { const r = await fetch(`http://127.0.0.1:${MANAGED_PORT}/health`); if (r.status === 401) return; } catch { /* starting */ } await sleep(150); }29 throw new Error("managed-secrets did not start");30}31export async function startServer(extraEnv: Record<string, string> = {}, reset = true) {32 if (reset) await sql.unsafe("drop schema public cascade; create schema public;");33 server = spawn("node_modules/.bin/tsx", ["services/api/src/index.ts"], {34 env: { ...process.env, DATABASE_URL: DB, PORT: String(PORT), SPV_ORIGIN: ORIGIN, SPV_RP_ID: "localhost", SPV_DATA_DIR: dataDir, SPV_LOG_LEVEL: "warn", SPV_RATE_SCALE: "50",35 SPV_BREACH_UPSTREAM: `${ORIGIN}/api/health/ready?`, ...extraEnv },36 stdio: extraEnv.SPV_TEST_LOG_FILE ? ["ignore", fs.openSync(extraEnv.SPV_TEST_LOG_FILE, "a"), "inherit"] : ["ignore", "inherit", "inherit"],37 });38 for (let i = 0; i < 100; i++) {39 try { if ((await fetch(`${ORIGIN}/api/health/ready`)).ok) return; } catch { /* starting */ }40 await sleep(150);41 }42 throw new Error("server did not start");43}44export async function stopServer() { server?.kill("SIGTERM"); managedProc?.kill("SIGTERM"); await sql.end(); fs.rmSync(dataDir, { recursive: true, force: true }); }45export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));4647export async function invite(): Promise<string> {48 const token = crypto.randomBytes(24).toString("base64url");49 await sql`insert into invites (token_hash, label, expires_at) values (${crypto.createHash("sha256").update(token).digest("base64url")}, 'test', now() + interval '1 hour')`;50 return token;51}5253// ── software authenticator (ES256, "none" attestation, user verified) ─────────────────────────────────────────54const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString("base64url");55const cborBytes = (b: Buffer) => (b.length < 24 ? Buffer.concat([Buffer.from([0x40 + b.length]), b]) : b.length < 256 ? Buffer.concat([Buffer.from([0x58, b.length]), b]) : Buffer.concat([Buffer.from([0x59, b.length >> 8, b.length & 255]), b]));56const cborText = (s: string) => Buffer.concat([Buffer.from([0x60 + s.length]), Buffer.from(s)]);57export class Authenticator implements Passkeys {58 creds = new Map<string, { key: crypto.KeyObject; userHandle: string; counter: number }>();59 origin = ORIGIN;60 async create(options: any) {61 const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" });62 const jwk = publicKey.export({ format: "jwk" });63 const id = crypto.randomBytes(16);64 const cose = Buffer.concat([Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21]), cborBytes(Buffer.from(jwk.x!, "base64url")), Buffer.from([0x22]), cborBytes(Buffer.from(jwk.y!, "base64url"))]);65 const authData = Buffer.concat([crypto.createHash("sha256").update(options.rp.id).digest(), Buffer.from([0x5d]), Buffer.alloc(4), Buffer.alloc(16), Buffer.from([0, id.length]), id, cose]);66 const attestationObject = Buffer.concat([Buffer.from([0xa3]), cborText("fmt"), cborText("none"), cborText("attStmt"), Buffer.from([0xa0]), cborText("authData"), cborBytes(authData)]);67 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.create", challenge: options.challenge, origin: this.origin, crossOrigin: false }));68 this.creds.set(b64u(id), { key: privateKey, userHandle: options.user.id, counter: 0 });69 return { id: b64u(id), rawId: b64u(id), type: "public-key", clientExtensionResults: {}, authenticatorAttachment: "platform", response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ["internal"] } };70 }71 async get(options: any) {72 const allowed = (options.allowCredentials ?? []).map((c: any) => c.id);73 const id = [...this.creds.keys()].reverse().find((k) => !allowed.length || allowed.includes(k));74 if (!id) throw new Error("no passkey for this site");75 const c = this.creds.get(id)!;76 c.counter++;77 const counter = Buffer.alloc(4); counter.writeUInt32BE(c.counter);78 const authData = Buffer.concat([crypto.createHash("sha256").update(options.rpId).digest(), Buffer.from([0x1d]), counter]);79 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.get", challenge: options.challenge, origin: this.origin, crossOrigin: false }));80 const signature = crypto.sign("sha256", Buffer.concat([authData, crypto.createHash("sha256").update(clientDataJSON).digest()]), c.key);81 return { id, rawId: id, type: "public-key", clientExtensionResults: {}, authenticatorAttachment: "platform", response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: c.userHandle } };82 }83}8485// ── transport ─────────────────────────────────────────────────────────────────────────────────────────────────86export class NodeTransport implements Transport {87 cookie = "";88 offline = false;89 headers: Record<string, string> = { origin: ORIGIN, "x-spv": "1" };90 log: { method: string; path: string; body: string }[] = [];91 async fetch(method: string, p: string, body?: unknown, opts: { headers?: Record<string, string>; binary?: Uint8Array } = {}): Promise<Response> {92 if (this.offline) throw new ApiError(0, "offline");93 const payload = opts.binary ? Buffer.from(opts.binary) : body === undefined ? undefined : JSON.stringify(body);94 this.log.push({ method, path: p, body: opts.binary ? "<binary>" : (payload as string) ?? "" });95 const res = await fetch(ORIGIN + p, { method, body: payload as any, headers: { ...this.headers, ...(this.cookie ? { cookie: this.cookie } : {}), ...(payload !== undefined ? { "content-type": opts.binary ? "application/octet-stream" : "application/json" } : {}), ...opts.headers } });96 for (const c of res.headers.getSetCookie?.() ?? []) { const [pair] = c.split(";"); this.cookie = pair!.endsWith("=") ? "" : pair!; }97 return res;98 }99 async request(method: string, p: string, body?: unknown, opts: { headers?: Record<string, string>; binary?: Uint8Array; raw?: boolean } = {}): Promise<any> {100 const res = await this.fetch(method, p, body, opts);101 if (!res.ok) { const j: any = await res.json().catch(() => ({})); throw new ApiError(res.status, j.error ?? "error", j.message, j); }102 if (opts.raw) return new Uint8Array(await res.arrayBuffer());103 return res.json();104 }105}106107export interface Device { engine: Engine; api: NodeTransport; store: Store; auth: Authenticator }108export function device(auth = new Authenticator(), platform = "Test device", store: Store = new MemoryStore()): Device {109 const api = new NodeTransport();110 return { engine: new Engine(api, store, auth, platform), api, store, auth };111}112export async function newAccount(handle: string): Promise<Device & { recoveryKey: string }> {113 const d = device();114 const recoveryKey = await d.engine.register(await invite(), handle);115 return { ...d, recoveryKey };116}117/** Enrols a second device of the same account through the pairing flow. */118export async function pair(trusted: Device, platform = "Second device"): Promise<Device> {119 const d = device(trusted.auth, platform);120 if ((await d.engine.signIn()) !== "pending") throw new Error("expected a pending session");121 const { code, sas } = await d.engine.startPairing();122 const req = await trusted.engine.inspectPairing(code);123 if (req.sas !== sas) throw new Error("SAS mismatch");124 await req.approve();125 if ((await d.engine.checkPairing()) !== "done") throw new Error("pairing did not complete");126 return d;127}128