// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini import { request, type APIRequestContext, type APIResponse } from '@playwright/test'; import { runnerAddress, SESSION_COOKIE, type GroupConfig } from './env'; import type { AuditLedger } from './ledger'; import type { Recorder } from './recorder'; import type { SecretRegistry } from './secrets'; export interface ApiResult { status: number; headers: Record; text: string; json: any; etag: string | null; durationMs: number; setCookie: string; } export interface RequestOptions { body?: unknown; raw?: string | Buffer; contentType?: string | null; headers?: Record; query?: Record; ifMatch?: string; origin?: 'same' | 'none' | string; audit?: 'auto' | 'none' | 'optional'; timeoutMs?: number; } export interface LoginHooks { beforeLogin(username: string): Promise; afterLogin(username: string, status: number): void; } export interface ApiDeps { recorder: Recorder; secrets: SecretRegistry; ledger?: AuditLedger; hooks?: LoginHooks; } const UNSAFE = new Set(['POST', 'PUT', 'DELETE', 'PATCH']); export class ApiClient { username = ''; private disposed = false; private constructor( readonly group: GroupConfig, public ctx: APIRequestContext, private readonly deps: ApiDeps, ) {} static async create(group: GroupConfig, deps: ApiDeps): Promise { const ctx = await request.newContext({ baseURL: group.baseURL, extraHTTPHeaders: { Accept: 'application/json' }, timeout: 90_000 }); return new ApiClient(group, ctx, deps); } get origin(): string { return new URL(this.group.baseURL).origin; } async cookie(): Promise { const state = await this.ctx.storageState(); return state.cookies.find((c) => c.name === SESSION_COOKIE)?.value; } async cookieAttributes(): Promise<{ httpOnly: boolean; sameSite: string; path: string; secure: boolean } | undefined> { const state = await this.ctx.storageState(); const c = state.cookies.find((x) => x.name === SESSION_COOKIE); return c ? { httpOnly: c.httpOnly, sameSite: c.sameSite, path: c.path, secure: c.secure } : undefined; } async setCookie(value: string | null): Promise { const host = new URL(this.group.baseURL).hostname; const state = await this.ctx.storageState(); const others = state.cookies.filter((c) => c.name !== SESSION_COOKIE); const cookies = value === null ? others : [...others, { name: SESSION_COOKIE, value, domain: host, path: '/', expires: -1, httpOnly: true, secure: false, sameSite: 'Strict' as const }]; const fresh = await request.newContext({ baseURL: this.group.baseURL, extraHTTPHeaders: { Accept: 'application/json' }, timeout: 90_000, storageState: { cookies, origins: [] }, }); await this.ctx.dispose(); this.ctx = fresh; } async login(username: string, password: string, opts: { next?: string; headers?: Record; expectStatus?: number; preserveRateLimit?: boolean } = {}): Promise { this.deps.secrets.register(password, `password of ${username}`); if (!opts.preserveRateLimit) await this.deps.hooks?.beforeLogin(username); const started = Date.now(); const res = await this.ctx.post('/login', { form: { username, password, next: opts.next ?? '/' }, headers: { Origin: this.origin, Accept: 'text/html', ...(opts.headers ?? {}) }, maxRedirects: 0, }); const result = await this.wrap(res, started); this.recordHttp('POST', '/login', { 'content-type': 'application/x-www-form-urlencoded' }, 0, result, username); this.deps.ledger?.login(username, result.status, runnerAddress(), `api login ${username}`); this.deps.hooks?.afterLogin(username, result.status); if (result.status === 303) { this.username = username; const c = await this.cookie(); if (c) this.deps.secrets.register(c, `session cookie of ${username}`); } return result; } async logout(opts: { sessionValid?: boolean } = {}): Promise { const started = Date.now(); const res = await this.ctx.post('/logout', { headers: { Origin: this.origin, Accept: 'text/html' }, maxRedirects: 0 }); const result = await this.wrap(res, started); this.recordHttp('POST', '/logout', {}, 0, result, this.username); this.deps.ledger?.logout(this.username, result.status, runnerAddress(), opts.sessionValid ?? true, `api logout ${this.username}`); this.username = ''; return result; } async page(path: string, opts: RequestOptions = {}): Promise { return this.raw('GET', path, { ...opts, audit: 'none' }); } async raw(method: string, path: string, opts: RequestOptions = {}): Promise { const headers: Record = { ...(opts.headers ?? {}) }; const origin = opts.origin ?? 'same'; if (UNSAFE.has(method.toUpperCase()) && origin !== 'none') headers.Origin = origin === 'same' ? this.origin : origin; if (opts.ifMatch !== undefined) headers['If-Match'] = opts.ifMatch; let data: string | Buffer | undefined; if (opts.raw !== undefined) { data = opts.raw; if (opts.contentType !== null) headers['Content-Type'] = opts.contentType ?? 'application/json'; } else if (opts.body !== undefined) { data = JSON.stringify(opts.body); if (opts.contentType !== null) headers['Content-Type'] = opts.contentType ?? 'application/json'; } let url = path; if (opts.query) { const params = new URLSearchParams(); for (const [k, v] of Object.entries(opts.query)) if (v !== undefined) params.set(k, String(v)); const qs = params.toString(); if (qs) url += (url.includes('?') ? '&' : '?') + qs; } const started = Date.now(); const res = await this.ctx.fetch(url, { method, headers, data, maxRedirects: 0, timeout: opts.timeoutMs ?? 90_000 }); const result = await this.wrap(res, started); const bodyBytes = data === undefined ? 0 : Buffer.byteLength(data); this.recordHttp(method, url, headers, bodyBytes, result, this.username); const audit = opts.audit ?? 'auto'; if (audit !== 'none' && this.deps.ledger) { const crossOrigin = origin !== 'same' && origin !== 'none' && UNSAFE.has(method.toUpperCase()); const fetchSite = Object.entries(headers).find(([k]) => k.toLowerCase() === 'sec-fetch-site')?.[1]; this.deps.ledger.api({ method, path: url, status: result.status, actor: this.username, origin: runnerAddress(), body: result.text, sessionValid: this.username !== '' && result.status !== 401, crossOrigin: crossOrigin || (fetchSite !== undefined && fetchSite !== 'same-origin' && fetchSite !== 'none' && UNSAFE.has(method.toUpperCase())), optional: audit === 'optional', source: `api ${method} ${url} as ${this.username || '(no session)'}`, }); } return result; } get(path: string, opts: RequestOptions = {}): Promise { return this.raw('GET', `/api/v1${path}`, opts); } post(path: string, body?: unknown, opts: RequestOptions = {}): Promise { return this.raw('POST', `/api/v1${path}`, { body, ...opts }); } put(path: string, body?: unknown, opts: RequestOptions = {}): Promise { return this.raw('PUT', `/api/v1${path}`, { body, ...opts }); } delete(path: string, body?: unknown, opts: RequestOptions = {}): Promise { return this.raw('DELETE', `/api/v1${path}`, { body, ...opts }); } forgetSession(): void { this.username = ''; } private async wrap(res: APIResponse, started: number): Promise { const text = await res.text().catch(() => ''); let json: any = undefined; try { json = text ? JSON.parse(text) : undefined; } catch { json = undefined; } const headers = res.headers(); const setCookie = res .headersArray() .filter((h) => h.name.toLowerCase() === 'set-cookie') .map((h) => h.value) .join('\n'); return { status: res.status(), headers, text, json, etag: headers['etag'] ?? null, durationMs: Date.now() - started, setCookie }; } private recordHttp(method: string, url: string, headers: Record, bodyBytes: number, r: ApiResult, actor: string): void { this.deps.recorder.addHttp({ client: 'api', actor, method, url, requestHeaders: this.deps.secrets.redactValue(headers), requestBodyBytes: bodyBytes, status: r.status, responseHeaders: this.deps.secrets.redactValue(r.headers), bodyPreview: this.deps.secrets.redact(r.text), durationMs: r.durationMs, }); } async dispose(): Promise { if (this.disposed) return; this.disposed = true; await this.ctx.dispose(); } } export function zp(zone: string): string { return `/zones/${encodeURIComponent(zone)}`; } export function up(username: string): string { return `/users/${encodeURIComponent(username)}`; }