// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini import { expect, type Browser, type BrowserContext, type Page, type Response } from '@playwright/test'; import { runnerAddress, SESSION_COOKIE, type GroupConfig } from './env'; import type { LoginHooks } from './api'; import type { AuditLedger } from './ledger'; import type { Recorder } from './recorder'; import type { SecretRegistry } from './secrets'; export interface UiDeps { group: GroupConfig; ledger?: AuditLedger; recorder: Recorder; secrets: SecretRegistry; hooks?: LoginHooks; } export interface UiRow { name: string; fqdn: string; type: string; ttl: string; value: string; problems: string[]; checkable: boolean; } export interface RowMatch { name: string; type: string; value?: string; } export interface RecordInput { name: string; type: string; ttl?: string; fields: Record; } export interface ZoneInput { name: string; ns: string; mbox: string; extraNs?: string[]; refresh?: string; retry?: string; expire?: string; minttl?: string; ttl?: string; } export interface UiResponse { status: number; json: any; } export interface UiOpenOptions { colorScheme?: 'light' | 'dark'; viewport?: { width: number; height: number }; } async function responseJson(res: Response): Promise { try { return await res.json(); } catch { return undefined; } } async function bounded(p: Promise, fallback: T, ms = 5000): Promise { let timer: NodeJS.Timeout | undefined; const limit = new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), ms); }); try { return await Promise.race([p.catch(() => fallback), limit]); } finally { clearTimeout(timer); } } export class Ui { user = ''; private constructor( readonly context: BrowserContext, readonly page: Page, private readonly deps: UiDeps, ) {} static async open(browser: Browser, deps: UiDeps, opts: UiOpenOptions = {}): Promise { const context = await browser.newContext({ baseURL: deps.group.baseURL, colorScheme: opts.colorScheme ?? 'light', viewport: opts.viewport ?? { width: 1440, height: 900 }, acceptDownloads: true, }); const page = await context.newPage(); const ui = new Ui(context, page, deps); ui.attach(); return ui; } private attach(): void { const appOrigin = new URL(this.deps.group.baseURL).origin; this.context.on('response', (res) => { const p = this.observe(res, appOrigin); if (this.deps.ledger) this.deps.ledger.track(p); else p.catch(() => undefined); }); this.context.on('requestfailed', (req) => { const url = new URL(req.url()); if (url.origin !== appOrigin || !url.pathname.startsWith('/api/v1') || this.user === '') return; this.deps.recorder.note(`browser request failed: ${req.method()} ${url.pathname} ${req.failure()?.errorText ?? ''}`); this.deps.ledger?.add({ operation: '*', status: null, anyStatus: true, actor: this.user, origin: runnerAddress(), userIsActor: true, optional: true, source: `aborted browser ${req.method()} ${url.pathname}` }); }); } private async observe(res: Response, appOrigin: string): Promise { const url = new URL(res.url()); if (url.origin !== appOrigin) return; const req = res.request(); const method = req.method(); const path = url.pathname + url.search; if (method === 'GET' && req.isNavigationRequest() && url.pathname.endsWith('/export')) return; const status = res.status(); const reqHeaders = await bounded(req.allHeaders(), {} as Record); const fetchSite = reqHeaders['sec-fetch-site']; const origin = reqHeaders.origin; const referer = reqHeaders.referer; const otherOrigin = origin !== undefined ? origin !== appOrigin : referer !== undefined && new URL(referer).origin !== appOrigin; const crossOrigin = method !== 'GET' && method !== 'HEAD' && (fetchSite === undefined ? otherOrigin : fetchSite !== 'same-origin' && fetchSite !== 'none'); let body = ''; if (url.pathname.startsWith('/api/v1')) body = await bounded(res.text(), ''); this.deps.recorder.addHttp({ client: 'browser', actor: this.user, method, url: path, requestHeaders: this.deps.secrets.redactValue(reqHeaders), requestBodyBytes: req.postDataBuffer()?.length ?? 0, status, responseHeaders: this.deps.secrets.redactValue(await bounded(res.allHeaders(), {} as Record)), bodyPreview: this.deps.secrets.redact(body), durationMs: 0, }); if (crossOrigin) return; if (url.pathname === '/login' && method === 'POST') { const form = new URLSearchParams(req.postData() ?? ''); const username = form.get('username') ?? ''; const password = form.get('password'); if (password) this.deps.secrets.register(password, `password of ${username}`); this.deps.ledger?.login(username, status, runnerAddress(), `browser login ${username}`); this.deps.hooks?.afterLogin(username, status); if (status === 303) { this.user = username; const cookies = await this.context.cookies(); const c = cookies.find((x) => x.name === SESSION_COOKIE); if (c) this.deps.secrets.register(c.value, `session cookie of ${username}`); } return; } if (url.pathname === '/logout' && method === 'POST') { this.deps.ledger?.logout(this.user, status, runnerAddress(), this.user !== '', `browser logout ${this.user}`); this.user = ''; return; } if (!url.pathname.startsWith('/api/v1')) return; const valid = this.user !== '' && status !== 401; this.deps.ledger?.api({ method, path, status, actor: this.user, origin: runnerAddress(), body, sessionValid: valid, source: `browser ${method} ${path} as ${this.user}` }); if (status === 401) this.user = ''; } sessionEnded(): void { this.user = ''; } async settle(): Promise { await this.page.waitForLoadState('networkidle'); await this.deps.ledger?.settle(); } async goto(path: string): Promise { const res = await this.page.goto(path); await this.settle(); return res; } async login(username: string, password: string, opts: { expectSuccess?: boolean } = {}): Promise { await this.deps.hooks?.beforeLogin(username); if (!this.page.url().includes('/login')) await this.goto('/login'); await this.page.fill('#login-username', username); await this.page.fill('#login-password', password); const done = this.page.waitForResponse((r) => new URL(r.url()).pathname === '/login' && r.request().method() === 'POST'); await this.page.getByRole('button', { name: 'Sign in' }).click(); const res = await done; await this.settle(); if (opts.expectSuccess ?? true) { expect(res.status(), `login of ${username}`).toBe(303); await expect(this.page).not.toHaveURL(/\/login/); } } async logout(): Promise { const done = this.page.waitForResponse((r) => new URL(r.url()).pathname === '/logout'); await this.page.getByRole('button', { name: 'Log out' }).click(); await done; await this.settle(); } async cookie(): Promise { return (await this.context.cookies()).find((c) => c.name === SESSION_COOKIE)?.value; } async toasts(): Promise { return this.page.locator('#toasts .toast-text').allTextContents(); } async expectToast(text: string | RegExp): Promise { await expect(this.page.locator('#toasts .toast-text').filter({ hasText: text }).first()).toBeVisible(); } async createZone(z: ZoneInput, opts: { expectStatus?: number } = {}): Promise { if (new URL(this.page.url()).pathname !== '/') await this.goto('/'); await this.page.click('#new-zone'); await expect(this.page.locator('#zone-dialog')).toBeVisible(); await this.page.fill('#nz-name', z.name); await this.page.fill('#nz-ns', z.ns); await this.page.fill('#nz-mbox', z.mbox); await this.page.fill('#nz-extra', (z.extraNs ?? []).join('\n')); if (z.refresh !== undefined) await this.page.fill('#nz-refresh', z.refresh); if (z.retry !== undefined) await this.page.fill('#nz-retry', z.retry); if (z.expire !== undefined) await this.page.fill('#nz-expire', z.expire); if (z.minttl !== undefined) await this.page.fill('#nz-minttl', z.minttl); if (z.ttl !== undefined) await this.page.fill('#nz-ttl', z.ttl); const done = this.page.waitForResponse((r) => new URL(r.url()).pathname === '/api/v1/zones' && r.request().method() === 'POST'); await this.page.locator('#zone-form button[type=submit]').click(); const res = await done; const out = { status: res.status(), json: await responseJson(res) }; if (opts.expectStatus !== undefined) expect(out.status, `create zone ${z.name}: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); if (out.status === 201) await expect(this.page.locator('#zone-dialog')).toBeHidden(); await this.settle(); return out; } async openZone(zone: string): Promise { await this.goto(`/zones/${encodeURIComponent(zone)}`); await expect(this.page.locator('#records-status')).not.toHaveText('Loading records...'); } async rows(): Promise { return this.page.$$eval('#records-body tr', (trs) => trs.map((tr) => { const cells = [...tr.children] as HTMLElement[]; const box = tr.querySelector('input[type=checkbox]') as HTMLInputElement | null; return { name: (tr.querySelector('th .mono')?.textContent ?? '').trim(), fqdn: tr.querySelector('th')?.getAttribute('title') ?? '', type: (cells[2]?.textContent ?? '').trim(), ttl: (cells[3]?.textContent ?? '').trim(), value: (tr.querySelector('td.value > code')?.textContent ?? '').trim(), problems: [...tr.querySelectorAll('td.value li code')].map((c) => (c.textContent ?? '').trim()), checkable: box !== null && !box.disabled, }; }), ); } async rowIndex(m: RowMatch): Promise { const rows = await this.rows(); const idx = rows.findIndex((r) => r.name === m.name && r.type === m.type && (m.value === undefined || r.value === m.value)); if (idx < 0) throw new Error(`no row ${JSON.stringify(m)} in ${JSON.stringify(rows.map((r) => `${r.name} ${r.type} ${r.value}`))}`); return idx; } async row(m: RowMatch) { return this.page.locator('#records-body tr').nth(await this.rowIndex(m)); } async expectRow(m: RowMatch & { ttl?: string }): Promise { await expect .poll(async () => (await this.rows()).filter((r) => r.name === m.name && r.type === m.type && (m.value === undefined || r.value === m.value) && (m.ttl === undefined || r.ttl === m.ttl)).length, { message: `UI shows ${JSON.stringify(m)}`, }) .toBe(1); } async expectNoRow(m: RowMatch): Promise { await expect .poll(async () => (await this.rows()).filter((r) => r.name === m.name && r.type === m.type && (m.value === undefined || r.value === m.value)).length, { message: `UI no longer shows ${JSON.stringify(m)}`, }) .toBe(0); } private async fillRecordForm(input: RecordInput, editing: boolean): Promise { if (!editing || (await this.page.locator('#rec-type').isEnabled())) await this.page.selectOption('#rec-type', input.type); await this.page.fill('#rec-name', input.name); if (input.ttl !== undefined) await this.page.fill('#rec-ttl', input.ttl); for (const [key, value] of Object.entries(input.fields)) { const el = this.page.locator(`#rec-f-${key}`); const tag = await el.evaluate((e) => e.tagName); if (tag === 'SELECT') await el.selectOption(value); else await el.fill(value); } } private async submitRecord(method: string): Promise { const done = this.page.waitForResponse((r) => /\/api\/v1\/zones\/[^/]+\/records(\/\d+)?$/.test(new URL(r.url()).pathname) && r.request().method() === method); await this.page.click('#rec-submit'); const res = await done; const out = { status: res.status(), json: await responseJson(res) }; if (out.status < 300) await expect(this.page.locator('#record-dialog')).toBeHidden(); await this.settle(); return out; } async addRecord(input: RecordInput, opts: { expectStatus?: number } = {}): Promise { await this.page.click('#record-add'); await expect(this.page.locator('#record-dialog')).toBeVisible(); await this.fillRecordForm(input, false); const out = await this.submitRecord('POST'); if (opts.expectStatus !== undefined) expect(out.status, `add ${JSON.stringify(input)}: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); return out; } async openEdit(m: RowMatch): Promise { const row = await this.row(m); await row.getByRole('button', { name: /^Edit / }).click(); await expect(this.page.locator('#record-dialog')).toBeVisible(); } async editRecord(m: RowMatch, input: RecordInput, opts: { expectStatus?: number } = {}): Promise { await this.openEdit(m); await this.fillRecordForm(input, true); const out = await this.submitRecord('PUT'); if (opts.expectStatus !== undefined) expect(out.status, `edit ${JSON.stringify(m)}: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); return out; } async confirm(button: string): Promise { const dialog = this.page.locator('dialog[open]').filter({ has: this.page.getByRole('button', { name: button, exact: true }) }); await expect(dialog).toBeVisible(); await dialog.getByRole('button', { name: button, exact: true }).click(); } async deleteRecord(m: RowMatch, opts: { expectStatus?: number } = {}): Promise { const row = await this.row(m); await row.getByRole('button', { name: /^Delete / }).click(); const done = this.page.waitForResponse((r) => /\/records\/\d+$/.test(new URL(r.url()).pathname) && r.request().method() === 'DELETE'); await this.confirm('Delete'); const res = await done; await this.settle(); const out = { status: res.status(), json: await responseJson(res) }; if (opts.expectStatus !== undefined) expect(out.status, `delete ${JSON.stringify(m)}`).toBe(opts.expectStatus); return out; } async select(m: RowMatch): Promise { const row = await this.row(m); await row.locator('input[type=checkbox]').check(); } async bulkDelete(matches: RowMatch[], opts: { expectStatus?: number } = {}): Promise { for (const m of matches) await this.select(m); await expect(this.page.locator('#bulk-delete')).toHaveText(`Delete selected (${matches.length})`); await this.page.click('#bulk-delete'); const done = this.page.waitForResponse((r) => /\/records\/delete$/.test(new URL(r.url()).pathname) && r.request().method() === 'POST'); await this.confirm('Delete'); const res = await done; await this.settle(); const out = { status: res.status(), json: await responseJson(res) }; if (opts.expectStatus !== undefined) expect(out.status, 'bulk delete').toBe(opts.expectStatus); return out; } async editSoa(values: Partial>, opts: { expectStatus?: number } = {}): Promise { await this.page.click('#soa-edit'); await expect(this.page.locator('#soa-dialog')).toBeVisible(); for (const [k, v] of Object.entries(values)) await this.page.fill(`#soa-${k}`, v as string); const done = this.page.waitForResponse((r) => /\/soa$/.test(new URL(r.url()).pathname) && r.request().method() === 'PUT'); await this.page.locator('#soa-form button[type=submit]').click(); const res = await done; const out = { status: res.status(), json: await responseJson(res) }; if (out.status < 300) await expect(this.page.locator('#soa-dialog')).toBeHidden(); await this.settle(); if (opts.expectStatus !== undefined) expect(out.status, `edit SOA: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); return out; } async soaSummary(): Promise> { return this.page.$$eval('#soa-summary dt', (dts) => Object.fromEntries(dts.map((dt) => [(dt.textContent ?? '').trim(), (dt.nextElementSibling?.textContent ?? '').trim()]))); } async fieldErrors(formSelector: string): Promise> { return this.page.$$eval(`${formSelector} .field-error`, (els) => Object.fromEntries( els.map((el) => { const control = el.previousElementSibling as HTMLInputElement | null; return [control?.name ?? control?.id ?? '?', (el.textContent ?? '').trim()]; }), ), ); } private async submitAndWait(method: string, path: RegExp, click: () => Promise): Promise { const done = this.page.waitForResponse((r) => path.test(new URL(r.url()).pathname) && r.request().method() === method); await click(); const res = await done; const out = { status: res.status(), json: await responseJson(res) }; await this.settle(); return out; } async createUserUi(username: string, role: 'admin' | 'user', password: string, repeat = password): Promise { this.deps.secrets.register(password, `password of ${username}`); if (new URL(this.page.url()).pathname !== '/users') await this.goto('/users'); await this.page.click('#new-user'); await expect(this.page.locator('#user-dialog')).toBeVisible(); await this.page.fill('#nu-username', username); await this.page.selectOption('#nu-role', role); await this.page.fill('#nu-password', password); await this.page.fill('#nu-repeat', repeat); if (password !== repeat) { await this.page.click('#user-form button[type=submit]'); return { status: 0, json: undefined }; } const out = await this.submitAndWait('POST', /^\/api\/v1\/users$/, () => this.page.click('#user-form button[type=submit]')); if (out.status === 201) await expect(this.page.locator('#user-dialog')).toBeHidden(); return out; } async usersTable(): Promise> { return this.page.$$eval('#users-body tr', (trs) => trs.map((tr) => { const c = [...tr.children].map((x) => (x.textContent ?? '').trim()); return { username: c[0], role: c[1], zones: c[2], created: c[3], lastLogin: c[4], state: c[5] }; }), ); } async openUser(username: string): Promise { await this.goto(`/users/${encodeURIComponent(username)}`); await expect(this.page.locator('#user-status')).toHaveText(''); } async setRoleUi(role: 'admin' | 'user'): Promise { await this.page.selectOption('#user-role', role); return this.submitAndWait('PUT', /^\/api\/v1\/users\/[^/]+\/role$/, () => this.page.click('#role-form button[type=submit]')); } async setPasswordUi(password: string): Promise { this.deps.secrets.register(password, 'password set by an admin'); await this.page.fill('#up-password', password); await this.page.fill('#up-repeat', password); return this.submitAndWait('PUT', /^\/api\/v1\/users\/[^/]+\/password$/, () => this.page.click('#password-form button[type=submit]')); } async delegateFromUserPage(zone: string): Promise { await this.page.selectOption('#user-zone-pick', zone); return this.submitAndWait('PUT', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.page.click('#zone-add-form button[type=submit]')); } async revokeFromUserPage(zone: string): Promise { await this.page.getByRole('button', { name: `Remove zone ${zone}`, exact: true }).click(); return this.submitAndWait('DELETE', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.confirm('Remove')); } async userZones(): Promise { return this.page.$$eval('#user-zones li, #user-zones-readonly li', (lis) => lis.map((li) => (li.textContent ?? '').replace(/\s+Remove$/, '').trim())); } async deleteUserUi(username: string, typed = username): Promise { await this.page.fill('#user-delete-confirm', typed); if (await this.page.locator('#user-delete').isDisabled()) return null; const out = await this.submitAndWait('DELETE', /^\/api\/v1\/users\/[^/]+$/, () => this.page.click('#user-delete')); if (out.status === 204) await expect(this.page).toHaveURL(/\/users$/); await this.settle(); return out; } async zoneUsers(): Promise { return this.page.$$eval('#zone-users li .mono', (els) => els.map((e) => (e.textContent ?? '').trim())); } async delegateFromZonePage(username: string): Promise { await this.page.selectOption('#zone-user-pick', username); return this.submitAndWait('PUT', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.page.click('#zone-user-add')); } async revokeFromZonePage(username: string): Promise { await this.page.getByRole('button', { name: `Remove ${username} from this zone`, exact: true }).click(); return this.submitAndWait('DELETE', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.confirm('Remove')); } async deleteZoneUi(typed: string): Promise { await this.page.fill('#zone-delete-confirm', typed); if (await this.page.locator('#zone-delete').isDisabled()) return null; const out = await this.submitAndWait('DELETE', /^\/api\/v1\/zones\/[^/]+$/, () => this.page.click('#zone-delete')); if (out.status === 204) await expect(this.page).toHaveURL(/\/$/); await this.settle(); return out; } async changeOwnPasswordUi(current: string, password: string, repeat = password): Promise { this.deps.secrets.register(password, `new password of ${this.user}`); if (new URL(this.page.url()).pathname !== '/account') await this.goto('/account'); await this.page.fill('#pw-current', current); await this.page.fill('#pw-new', password); await this.page.fill('#pw-repeat', repeat); if (password !== repeat) { await this.page.click('#password-form button[type=submit]'); return null; } return this.submitAndWait('PUT', /^\/api\/v1\/account\/password$/, () => this.page.click('#password-form button[type=submit]')); } async zonesTable(): Promise> { await expect(this.page.locator('#zones-status')).not.toHaveText('Loading zones...'); await expect(this.page.locator('#zones-body td').filter({ hasText: 'loading...' })).toHaveCount(0); return this.page.$$eval('#zones-body tr', (trs) => trs.map((tr) => { const c = [...tr.children].map((x) => (x.textContent ?? '').replace(/\s+/g, ' ').trim()); return { zone: c[0], records: c[1], serial: c[2], problems: c[3] }; }), ); } async problems(): Promise> { return this.page.$$eval('#problems-list li', (lis) => lis.map((li) => ({ severity: (li.querySelector('.badge')?.textContent ?? '').trim(), code: (li.querySelector('code')?.textContent ?? '').trim(), where: (li.querySelector('.muted')?.textContent ?? '').trim(), })), ); } async auditRows(): Promise> { await expect(this.page.locator('#audit-status')).not.toHaveText('Loading...'); return this.page.$$eval('#audit-body tr:not(.detail-row)', (trs) => trs.map((tr) => { const c = [...tr.children].map((x) => (x.textContent ?? '').replace(/\s+/g, ' ').trim()); return { time: c[0], actor: c[1], origin: c[2], operation: c[3], status: c[4], target: c[5] }; }), ); } async filterAudit(filters: Partial>): Promise { if (new URL(this.page.url()).pathname !== '/audit') await this.goto('/audit'); if (filters.zone !== undefined) await this.page.fill('#af-zone', filters.zone); if (filters.actor !== undefined) await this.page.fill('#af-actor', filters.actor); if (filters.operation !== undefined) await this.page.selectOption('#af-operation', filters.operation); if (filters.kind !== undefined) await this.page.selectOption('#af-kind', filters.kind); if (filters.outcome !== undefined) await this.page.selectOption('#af-outcome', filters.outcome); await this.submitAndWait('GET', /^\/api\/v1\/audit$/, () => this.page.click('#audit-filters button[type=submit]')); } async importPreview(zone: string, content: string, mode: 'merge' | 'replace'): Promise { await this.goto(`/zones/${encodeURIComponent(zone)}/import`); await this.page.check(`input[name=mode][value=${mode}]`); await this.page.fill('#import-content', content); return this.submitAndWait('POST', /\/import\/preview$/, () => this.page.click('#import-preview')); } async importSummary(): Promise { return ((await this.page.locator('#import-summary').textContent()) ?? '').replace(/\s+/g, ' ').trim(); } async importApply(): Promise { await expect(this.page.locator('#import-apply')).toBeVisible(); const path = /\/import\/apply$/; let result: UiResponse | undefined; await this.page.route(path, async (route) => { const response = await route.fetch(); result = { status: response.status(), json: await response.json() }; await route.fulfill({ response }); }, { times: 1 }); const navigated = this.page .waitForURL((url) => /^\/zones\/[^/]+$/.test(url.pathname), { waitUntil: 'load' }) .then(() => true, () => false); await this.submitAndWait('POST', path, () => this.page.click('#import-apply')); if (!result) throw new Error('no import apply response'); if (result.status === 200) { if (!(await navigated)) throw new Error('import apply did not return to the zone page'); await expect(this.page.locator('#records-status')).not.toHaveText('Loading records...'); await this.settle(); } return result; } async exportZone(zone: string): Promise { if (!new URL(this.page.url()).pathname.startsWith(`/zones/`)) await this.openZone(zone); const download = this.page.waitForEvent('download'); await this.page.click('#export-link'); const d = await download; const file = await d.path(); this.deps.ledger?.api({ method: 'GET', path: new URL(d.url()).pathname, status: 200, actor: this.user, origin: runnerAddress(), body: '', sessionValid: this.user !== '', crossOrigin: false, source: 'browser zone export download', }); await this.settle(); const fs = await import('node:fs'); return fs.readFileSync(file, 'utf8'); } async close(): Promise { await this.deps.ledger?.settle(); await this.context.close(); } }