SPB Git

Repository Public

helpers.ts 5.5 KB 79 lines typescript

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:8701";6export const sql = postgres(process.env.DATABASE_URL!, { max: 2, onnotice: () => {} });7export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));8let ipSeq = 0;9type Body = Record<string, unknown> & { error?: { code: string; message?: string; details?: unknown } };1011/** One browser: its own cookie jar, CSRF token, client address and software authenticator. */12export class Client {13  cookies = new Map<string, string>(); csrf = "";14  ip = `203.0.113.${++ipSeq % 250}`;15  auth = new SoftAuthenticator(BASE, new URL(BASE).hostname);1617  async req(path: string, init: { method?: string; json?: unknown; form?: FormData; headers?: Record<string, string>; noCsrf?: boolean; noOrigin?: boolean } = {}) {18    const method = init.method ?? (init.json !== undefined || init.form ? "POST" : "GET");19    const headers: Record<string, string> = { "X-Forwarded-For": this.ip };20    if (this.cookies.size) headers.Cookie = [...this.cookies].map(([k, v]) => `${k}=${v}`).join("; ");21    if (method !== "GET" && method !== "HEAD") { if (!init.noOrigin) headers.Origin = BASE; if (this.csrf && !init.noCsrf) headers["X-CSRF-Token"] = this.csrf; }22    if (init.json !== undefined) headers["Content-Type"] = "application/json";23    const send = () => fetch(BASE + path, { method, headers: { ...headers, ...(init.headers ?? {}) }, body: init.form ?? (init.json !== undefined ? JSON.stringify(init.json) : undefined), redirect: "manual" });24    // A keep-alive socket closed by the server after an early refusal (413) surfaces on the next request: retry once.25    const res = await send().catch(async () => { await sleep(100); return send(); });26    for (const c of res.headers.getSetCookie?.() ?? []) { const [pair] = c.split(";"); const i = pair.indexOf("="); const k = pair.slice(0, i), v = pair.slice(i + 1); if (!v || /max-age=0/i.test(c)) this.cookies.delete(k); else this.cookies.set(k, v); }27    return res;28  }29  async json<T = Body>(path: string, init: Parameters<Client["req"]>[1] = {}): Promise<{ status: number; body: T & Body; headers: Headers }> {30    const res = await this.req(path, init);31    const text = await res.text();32    let body: unknown = null; try { body = text ? JSON.parse(text) : null; } catch { body = { raw: text.slice(0, 300) }; }33    return { status: res.status, body: body as never, headers: res.headers };34  }35  async refreshSession() {36    const s = await this.json<{ authenticated: boolean; csrfToken?: string; limited?: boolean }>("/api/auth/session");37    this.csrf = s.body.csrfToken ?? "";38    return s.body;39  }40  /** Enrols a passkey with a one-time token, or (no token) from the current session. */41  async enrol(setupToken?: string, tamper: Tamper = {}) {42    const o = await this.json<{ challengeId: string; options: { challenge: string; user: { id: string } } }>("/api/auth/register/options", { json: { setupToken } });43    if (o.status !== 200) return { status: o.status, body: o.body as Body, challengeId: "", response: null as unknown };44    const response = this.auth.create(o.body.options, tamper);45    const v = await this.json<{ recoveryCodes: string[] | null }>("/api/auth/register/verify", { json: { challengeId: o.body.challengeId, response, name: "Test device", setupToken } });46    if (v.status === 200) await this.refreshSession();47    return { status: v.status, body: v.body as Body, challengeId: o.body.challengeId, response };48  }49  async login(credentialId?: string, tamper: Tamper = {}) {50    const o = await this.json<{ challengeId: string; options: { challenge: string } }>("/api/auth/login/options", { json: {} });51    if (o.status !== 200) return { status: o.status, body: o.body as Body, challengeId: "", response: null as unknown };52    const response = this.auth.get(o.body.options, credentialId, tamper);53    const v = await this.json("/api/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  async reauth(tamper: Tamper = {}) {58    const o = await this.json<{ challengeId: string; options: { challenge: string } }>("/api/auth/reauth/options", { json: {} });59    if (o.status !== 200) return o.status;60    return (await this.json("/api/auth/reauth/verify", { json: { challengeId: o.body.challengeId, response: this.auth.get(o.body.options, undefined, tamper) } })).status;61  }62  async upload(name: string, data: Buffer | string, type = "application/octet-stream") {63    const form = new FormData(); form.set("file", new File([typeof data === "string" ? data : new Uint8Array(data)], name, { type }));64    return this.json<{ id: string; kind: string; scanStatus: string }>("/api/admin/assets", { form });65  }66  /** Waits for a job to reach a final state. */67  async job(id: string, timeoutMs = 60_000) {68    const t0 = Date.now();69    for (;;) {70      const j = await this.json<{ status: string; stage: string; output: Record<string, unknown>; error: { code: string; message: string } | null; usage: { costUsd: number } }>(`/api/admin/generations/${id}`);71      if (["succeeded", "failed", "cancelled"].includes(j.body.status)) return j.body;72      if (Date.now() - t0 > timeoutMs) throw new Error(`job ${id} still ${j.body.status}/${j.body.stage}`);73      await sleep(200);74    }75  }76}7778export const setupToken = () => readFileSync(process.env.SETUP_URL_FILE!, "utf8").trim().split("#")[1];79
Files main
Menu

Theme