Repository Public
1// Test helpers: an in-process app on a temporary database, a fake search provider (HTTP), and a software2// WebAuthn authenticator. The authenticator performs real ES256 signatures; only the hardware is replaced.3import { createHash, createSign, generateKeyPairSync, randomBytes, type KeyObject } from "node:crypto";4import { createServer, type Server } from "node:http";5import { mkdtempSync } from "node:fs";6import { tmpdir } from "node:os";7import { join } from "node:path";8import { buildApp, type App } from "../src/server.ts";9import type { Config } from "../src/config.ts";1011export const ORIGIN = "https://browser.test";12export const RP_ID = "browser.test";1314export function makeApp(overrides: Partial<Config> = {}): App {15 return buildApp({16 dataDir: mkdtempSync(join(tmpdir(), "spb-test-")), publicOrigin: ORIGIN, rpID: RP_ID, tavilyKey: "tvly-test",17 serverSecret: "test-secret", adminToken: "admin-test", openRegistration: true, anonSearch: true, anonSearchPerHour: 1000,18 dailyCreditBudget: 1000, appleAppIDs: ["TEAM.app.test"], ...overrides,19 });20}2122export interface FakeProvider { url: string; calls: any[]; close: () => Promise<void>; handler: (path: string, body: any, query: URLSearchParams) => { status?: number; body: any; headers?: Record<string, string> } }2324export async function fakeProvider(): Promise<FakeProvider> {25 const state: FakeProvider = { url: "", calls: [], close: async () => {}, handler: () => ({ body: {} }) };26 const server: Server = createServer((req, res) => {27 let raw = "";28 req.on("data", (c) => (raw += c));29 req.on("end", () => {30 const url = new URL(req.url!, "http://x");31 const body = raw ? JSON.parse(raw) : null;32 state.calls.push({ path: url.pathname, body, query: url.searchParams, auth: req.headers.authorization });33 const out = state.handler(url.pathname, body, url.searchParams);34 res.writeHead(out.status ?? 200, { "content-type": "application/json", ...(out.headers ?? {}) });35 res.end(JSON.stringify(out.body));36 });37 });38 await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));39 state.url = `http://127.0.0.1:${(server.address() as any).port}`;40 state.close = () => new Promise((r) => { server.closeAllConnections(); server.close(() => r()); });41 return state;42}4344// ---- minimal CBOR (maps with int/text keys, byte strings, text, ints) ----45function head(major: number, n: number): Buffer {46 if (n < 24) return Buffer.from([(major << 5) | n]);47 if (n < 256) return Buffer.from([(major << 5) | 24, n]);48 return Buffer.from([(major << 5) | 25, n >> 8, n & 0xff]);49}50function cbor(value: any): Buffer {51 if (typeof value === "number") return value >= 0 ? head(0, value) : head(1, -1 - value);52 if (typeof value === "string") { const b = Buffer.from(value); return Buffer.concat([head(3, b.length), b]); }53 if (Buffer.isBuffer(value)) return Buffer.concat([head(2, value.length), value]);54 if (value instanceof Map) return Buffer.concat([head(5, value.size), ...[...value].flatMap(([k, v]) => [cbor(k), cbor(v)])]);55 throw new Error("unsupported");56}5758const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString("base64url");5960export class SoftAuthenticator {61 private keys = new Map<string, { privateKey: KeyObject; userHandle: string; counter: number }>();6263 register(options: any) {64 const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });65 const jwk = publicKey.export({ format: "jwk" });66 const credId = randomBytes(20);67 const cose = cbor(new Map<any, any>([[1, 2], [3, -7], [-1, 1], [-2, Buffer.from(jwk.x!, "base64url")], [-3, Buffer.from(jwk.y!, "base64url")]]));68 const len = Buffer.alloc(2); len.writeUInt16BE(credId.length);69 const authData = Buffer.concat([70 createHash("sha256").update(options.rp.id).digest(), Buffer.from([0x5d]), Buffer.alloc(4),71 Buffer.alloc(16), len, credId, cose,72 ]);73 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.create", challenge: options.challenge, origin: ORIGIN, crossOrigin: false }));74 const attestationObject = cbor(new Map<any, any>([["fmt", "none"], ["attStmt", new Map()], ["authData", authData]]));75 this.keys.set(b64u(credId), { privateKey, userHandle: options.user.id, counter: 0 });76 return {77 id: b64u(credId), rawId: b64u(credId), type: "public-key", authenticatorAttachment: "platform", clientExtensionResults: {},78 response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ["internal"] },79 };80 }8182 assert(options: any, overrides: { origin?: string; credentialId?: string } = {}) {83 const allowed: string[] = (options.allowCredentials ?? []).map((c: any) => c.id);84 const id = overrides.credentialId ?? [...this.keys.keys()].find((k) => !allowed.length || allowed.includes(k));85 if (!id || !this.keys.has(id)) throw new Error("no credential");86 const key = this.keys.get(id)!;87 const authData = Buffer.concat([createHash("sha256").update(options.rpId).digest(), Buffer.from([0x1d]), Buffer.alloc(4)]);88 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.get", challenge: options.challenge, origin: overrides.origin ?? ORIGIN, crossOrigin: false }));89 const signature = createSign("sha256").update(Buffer.concat([authData, createHash("sha256").update(clientDataJSON).digest()])).sign(key.privateKey);90 return {91 id, rawId: id, type: "public-key", authenticatorAttachment: "platform", clientExtensionResults: {},92 response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: key.userHandle },93 };94 }95}9697export function device(name: string, platform = "macos") {98 return { name, platform, model: "Test", appVersion: "2.0.0", encPublicKey: randomBytes(32).toString("base64") };99}100101export class Client {102 token = "";103 app: App;104 constructor(app: App) { this.app = app; }105 async call(method: string, url: string, payload?: any, headers: Record<string, string> = {}) {106 const response = await this.app.server.inject({107 method: method as any, url, payload,108 headers: { ...(this.token ? { authorization: `Bearer ${this.token}` } : {}), ...headers },109 });110 let json: any = null;111 try { json = response.json(); } catch { /* not json */ }112 return { status: response.statusCode, json, headers: response.headers };113 }114 async register(auth: SoftAuthenticator, dev: any, displayName = "Tester", inviteCode?: string) {115 const options = await this.call("POST", "/api/auth/register/options", { displayName, inviteCode });116 if (options.status !== 200) return options;117 const verify = await this.call("POST", "/api/auth/register/verify", { challengeId: options.json.challengeId, credential: auth.register(options.json.options), device: dev });118 if (verify.status === 200) this.token = verify.json.sessionToken;119 return verify;120 }121 async login(auth: SoftAuthenticator, dev: any) {122 const options = await this.call("POST", "/api/auth/login/options", {});123 const verify = await this.call("POST", "/api/auth/login/verify", { challengeId: options.json.challengeId, credential: auth.assert(options.json.options), device: dev });124 if (verify.status === 200) this.token = verify.json.sessionToken;125 return verify;126 }127 async reauth(auth: SoftAuthenticator) {128 const options = await this.call("POST", "/api/auth/reauth/options", {});129 return this.call("POST", "/api/auth/reauth/verify", { challengeId: options.json.challengeId, credential: auth.assert(options.json.options) });130 }131}132