Repository Public
1// Test harness: a real server process, a real PostgreSQL database, a software WebAuthn authenticator2// and a 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 WebSocket from "ws"10import { Engine } from "../web/src/core/engine"11import { MemoryStore, type Store } from "../web/src/core/store"12import { ApiError, type Me, type Transport } from "../web/src/core/types"1314export const PORT = Number(process.env.SPM_TEST_PORT ?? 8731)15export const ORIGIN = process.env.SPM_TEST_ORIGIN ?? `http://localhost:${PORT}`16export const DB = process.env.SPM_TEST_DB ?? "postgres://127.0.0.1/sp_message_test"17if (!process.env.SPM_TEST_ORIGIN && !/_test$/.test(DB)) throw new Error("tests refuse to run outside a *_test database")18export const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "spm-test-"))19export const sql = postgres(DB, { onnotice: () => {} })2021let server: ChildProcess | undefined22export async function startServer() {23 await sql.unsafe("drop schema public cascade; create schema public;")24 server = spawn("node_modules/.bin/tsx", ["server/src/index.ts"], {25 env: { ...process.env, DATABASE_URL: DB, PORT: String(PORT), SPM_ORIGIN: ORIGIN, SPM_RP_ID: "localhost", SPM_DATA_DIR: dataDir, SPM_LOG_LEVEL: "warn", SPM_WEB_DIR: "/nonexistent", SPM_TURN_SECRET: "test-secret", SPM_RATE_SCALE: "20", SPM_TURN_URLS: "turn:localhost:3478" },26 stdio: ["ignore", "inherit", "inherit"],27 })28 for (let i = 0; i < 80; i++) {29 try {30 if ((await fetch(`${ORIGIN}/api/health/ready`)).ok) return31 } catch {}32 await sleep(150)33 }34 throw new Error("server did not start")35}36export async function stopServer() {37 server?.kill("SIGTERM")38 await sql.end()39 fs.rmSync(dataDir, { recursive: true, force: true })40}41export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))42export async function until(cond: () => boolean | Promise<boolean>, what: string, timeout = 15000) {43 const t0 = Date.now()44 while (Date.now() - t0 < timeout) {45 if (await cond()) return46 await sleep(40)47 }48 throw new Error(`timed out waiting for: ${what}`)49}5051// ---------------------------------------------------------------- software authenticator (ES256, "none" attestation)52const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString("base64url")53function cborBytes(b: Buffer) {54 return 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])55}56const cborText = (s: string) => Buffer.concat([Buffer.from([0x60 + s.length]), Buffer.from(s)])57export class Authenticator {58 creds = new Map<string, { key: crypto.KeyObject; userHandle: string; counter: number }>()59 async create(options: any) {60 const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" })61 const jwk = publicKey.export({ format: "jwk" })62 const id = crypto.randomBytes(16)63 const cose = Buffer.concat([64 Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21]), cborBytes(Buffer.from(jwk.x!, "base64url")),65 Buffer.from([0x22]), cborBytes(Buffer.from(jwk.y!, "base64url")),66 ])67 const authData = Buffer.concat([68 crypto.createHash("sha256").update(options.rp.id).digest(), Buffer.from([0x5d]), Buffer.alloc(4), Buffer.alloc(16),69 Buffer.from([0, id.length]), id, cose,70 ])71 const attestationObject = Buffer.concat([72 Buffer.from([0xa3]), cborText("fmt"), cborText("none"), cborText("attStmt"), Buffer.from([0xa0]), cborText("authData"), cborBytes(authData),73 ])74 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.create", challenge: options.challenge, origin: ORIGIN, crossOrigin: false }))75 this.creds.set(b64u(id), { key: privateKey, userHandle: options.user.id, counter: 0 })76 return {77 id: b64u(id), rawId: b64u(id), type: "public-key", clientExtensionResults: {}, authenticatorAttachment: "platform",78 response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ["internal"] },79 }80 }81 async get(options: any, credId?: string) {82 const id = credId ?? [...this.creds.keys()][0]83 const c = this.creds.get(id)!84 c.counter++85 const counter = Buffer.alloc(4)86 counter.writeUInt32BE(c.counter)87 const authData = Buffer.concat([crypto.createHash("sha256").update(options.rpId).digest(), Buffer.from([0x1d]), counter])88 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.get", challenge: options.challenge, origin: ORIGIN, crossOrigin: false }))89 const signature = crypto.sign("sha256", Buffer.concat([authData, crypto.createHash("sha256").update(clientDataJSON).digest()]), c.key)90 return {91 id, rawId: id, type: "public-key", clientExtensionResults: {}, authenticatorAttachment: "platform",92 response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: c.userHandle },93 }94 }95}9697// ---------------------------------------------------------------- Node transport98export class NodeTransport implements Transport {99 cookie = ""100 headers: Record<string, string> = { origin: ORIGIN, "x-spm": "1" }101 sockets = new Set<WebSocket>()102 private async raw(method: string, p: string, init: RequestInit): Promise<Response> {103 const res = await fetch(ORIGIN + p, { method, ...init, headers: { ...this.headers, ...(this.cookie ? { cookie: this.cookie } : {}), ...(init.headers as object) } })104 const set = res.headers.getSetCookie?.() ?? []105 for (const c of set) {106 const [pair] = c.split(";")107 this.cookie = pair.endsWith("=") ? "" : pair108 }109 if (!res.ok) {110 const j: any = await res.json().catch(() => ({}))111 throw new ApiError(res.status, j.error ?? "error", j.message)112 }113 return res114 }115 async request<T>(method: string, p: string, body?: unknown): Promise<T> {116 const res = await this.raw(method, p, body === undefined ? {} : { body: JSON.stringify(body), headers: { "content-type": "application/json" } })117 return (await res.json()) as T118 }119 async getBytes(p: string) {120 return new Uint8Array(await (await this.raw("GET", p, {})).arrayBuffer())121 }122 async putBytes(p: string, data: Uint8Array) {123 await this.raw("PUT", p, { body: data as unknown as BodyInit, headers: { "content-type": "application/octet-stream" } })124 }125 socket(onMessage: (m: any) => void, onState: (open: boolean) => void) {126 const ws = new WebSocket(ORIGIN.replace("http", "ws") + "/ws", { headers: { cookie: this.cookie, origin: ORIGIN } })127 this.sockets.add(ws)128 ws.on("open", () => onState(true))129 ws.on("message", (d) => onMessage(JSON.parse(d.toString())))130 ws.on("close", () => (this.sockets.delete(ws), onState(false)))131 ws.on("error", () => {})132 return { send: (m: unknown) => ws.readyState === 1 && ws.send(JSON.stringify(m)), close: () => ws.close() }133 }134}135136// ---------------------------------------------------------------- actors137export class Actor {138 t = new NodeTransport()139 auth = new Authenticator()140 store: Store = new MemoryStore()141 me!: Me142 engine!: Engine143 sessionId = ""144 constructor(public handle: string) {}145146 async register(token: string, bootstrap = false) {147 const { challenge_id, options } = await this.t.request<any>("POST", "/api/register/options", { token, bootstrap, handle: this.handle, display_name: this.handle[0].toUpperCase() + this.handle.slice(1) })148 const r = await this.t.request<any>("POST", "/api/register/verify", { challenge_id, response: await this.auth.create(options) })149 await this.loadMe()150 return r151 }152 async login(auth = this.auth) {153 const { challenge_id, options } = await this.t.request<any>("POST", "/api/login/options", {})154 await this.t.request("POST", "/api/login/verify", { challenge_id, response: await auth.get(options) })155 await this.loadMe()156 }157 async loadMe() {158 const r = await this.t.request<any>("GET", "/api/me")159 this.me = r.user160 this.sessionId = r.session.id161 return r162 }163 /** First device: identity creation. Returns the recovery key. */164 async setup() {165 const { dev, recoveryKey } = await Engine.createIdentity(this.t, this.store, this.me, `${this.handle} first device`)166 await this.loadMe()167 this.engine = new Engine(this.t, this.store, this.me, dev)168 await this.engine.start()169 await until(() => this.engine.online, `${this.handle} online`)170 await this.engine.sync()171 return recoveryKey172 }173 async startEngine() {174 const dev = (await Engine.loadDevice(this.store, this.me))!175 this.engine = new Engine(this.t, this.store, this.me, dev)176 await this.engine.start()177 await until(() => this.engine.online, `${this.handle} online`)178 await this.engine.sync()179 }180 conv(id: string) {181 return this.engine.convs.get(id)!182 }183 texts(id: string) {184 return this.conv(id).messages.filter((m) => m.kind === "text").map((m) => m.body)185 }186}187188export async function issueBootstrap(): Promise<string> {189 const token = crypto.randomBytes(32).toString("base64url")190 await sql`insert into bootstrap_tokens (token_hash, expires_at) values (${crypto.createHash("sha256").update(token).digest()}, now() + interval '10 minutes')`191 return token192}193export function tokenOf(url: string) {194 return url.split("#")[1]195}196