Repository Public
1import { readFileSync } from "node:fs";2import postgres from "postgres";3import { SoftAuthenticator, type Tamper } from "./webauthn";45export const BASE = process.env.TEST_BASE_URL ?? "http://localhost:8691";6export const FIX = process.env.TEST_FIXTURES!;7export const STORAGE = process.env.STORAGE_ROOT!;8export const sql = postgres(process.env.DATABASE_URL!, { max: 2, onnotice: () => {} });9export const fixture = (name: string) => readFileSync(`${FIX}/${name}`);10export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));11let ipSeq = 0;1213/** One browser: its own cookie jar, CSRF token, client address and authenticator. */14export class Client {15 cookie = ""; csrf = "";16 ip = `10.9.${Math.floor(Math.random() * 250)}.${++ipSeq % 250}`;17 auth = new SoftAuthenticator(BASE, new URL(BASE).hostname);1819 async req(path: string, init: { method?: string; json?: unknown; raw?: Buffer | Uint8Array; headers?: Record<string, string>; noCsrf?: boolean; redirect?: RequestRedirect } = {}) {20 const method = init.method ?? (init.json !== undefined || init.raw ? "POST" : "GET");21 const headers: Record<string, string> = { "X-Forwarded-For": this.ip, ...(this.cookie ? { Cookie: this.cookie } : {}) };22 if (method !== "GET" && method !== "HEAD") { headers.Origin = BASE; if (this.csrf && !init.noCsrf) headers["X-CSRF-Token"] = this.csrf; }23 if (init.json !== undefined) headers["Content-Type"] = "application/json";24 if (init.raw) headers["Content-Type"] = "application/octet-stream";25 const res = await fetch(BASE + path, { method, headers: { ...headers, ...(init.headers ?? {}) }, body: init.raw ? new Uint8Array(init.raw) : init.json !== undefined ? JSON.stringify(init.json) : undefined, redirect: init.redirect ?? "manual" });26 const set = res.headers.getSetCookie?.() ?? [];27 for (const c of set) { const [pair] = c.split(";"); if (pair.startsWith("spmusic_session=")) this.cookie = pair.endsWith("=") ? "" : pair; }28 return res;29 }30 async json<T = Record<string, unknown>>(path: string, init: Parameters<Client["req"]>[1] = {}): Promise<{ status: number; body: T & { error?: { code: string; details?: Record<string, unknown> } } }> {31 const res = await this.req(path, init);32 const text = await res.text();33 let body: unknown = null; try { body = text ? JSON.parse(text) : null; } catch { body = { raw: text.slice(0, 200) }; }34 return { status: res.status, body: body as never };35 }36 async refreshSession() {37 const s = await this.json<{ authenticated: boolean; csrfToken?: string; user?: { id: string; role: string } }>("/api/v1/auth/session");38 this.csrf = s.body.csrfToken ?? "";39 return s.body;40 }41 /** Enrols a passkey with a one-time token (owner setup, invitation, recovery). */42 async enrol(setupToken: string, tamper: Tamper = {}) {43 const o = await this.json<{ challengeId: string; options: { challenge: string; user: { id: string } } }>("/api/v1/auth/register/options", { json: { setupToken } });44 if (o.status !== 200) return { status: o.status, body: o.body as Record<string, unknown> & { error?: { code: string } }, challengeId: "", response: null as unknown };45 const response = this.auth.create(o.body.options, tamper);46 const v = await this.json<{ recoveryCodes: string[] | null }>("/api/v1/auth/register/verify", { json: { challengeId: o.body.challengeId, response, name: "Test device", setupToken } });47 if (v.status === 200) await this.refreshSession();48 return { status: v.status, body: v.body, challengeId: o.body.challengeId, response };49 }50 async login(credentialId?: string, tamper: Tamper = {}) {51 const o = await this.json<{ challengeId: string; options: { challenge: string } }>("/api/v1/auth/login/options", { json: {} });52 const response = this.auth.get(o.body.options, credentialId, tamper);53 const v = await this.json("/api/v1/auth/login/verify", { json: { challengeId: o.body.challengeId, response } });54 if (v.status === 200) await this.refreshSession();55 return { status: v.status, body: v.body, challengeId: o.body.challengeId, response };56 }57 /** Chunked upload, then waits for the worker's verdict. */58 59 async upload(name: string, data: Buffer, chunk = 256 * 1024): Promise<{ status: number; id: string; body: Record<string, any> }> {60 const c = await this.json<{ id: string }>("/api/v1/admin/uploads", { json: { filename: name, size: data.length } });61 if (c.status !== 200) return { status: c.status, body: c.body, id: "" };62 for (let off = 0; off < data.length; off += chunk) {63 const r = await this.json(`/api/v1/admin/uploads/${c.body.id}?offset=${off}`, { method: "PATCH", raw: data.subarray(off, off + chunk) });64 if (r.status !== 200) return { status: r.status, body: r.body, id: c.body.id };65 }66 return { status: 200, id: c.body.id, body: await this.waitUpload(c.body.id) };67 }68 async waitUpload(id: string, timeoutMs = 60_000) {69 const t0 = Date.now();70 for (;;) {71 const u = await this.json<{ status: string; errorCode: string | null; trackId: string | null; duplicateOf: string | null; errorDetail: string | null }>(`/api/v1/admin/uploads/${id}`);72 if (["ready", "error", "duplicate", "cancelled"].includes(u.body.status)) return u.body;73 if (Date.now() - t0 > timeoutMs) throw new Error(`upload ${id} still ${u.body.status}`);74 await sleep(300);75 }76 }77}7879export function setupTokenFromFile(): string {80 const url = readFileSync(process.env.SETUP_URL_FILE!, "utf8").trim();81 return url.split("#")[1];82}83export const tokenOf = (inviteUrl: string) => inviteUrl.split("#")[1];84