diff --git a/.dockerignore b/.dockerignore
index 3839cad..e347a55 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -6,6 +6,7 @@
vendor
GEMINI.md
docs
+e2e
data
who
whoami
diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml
index cd47146..3c71f93 100644
--- a/.github/workflows/docker-build.yml
+++ b/.github/workflows/docker-build.yml
@@ -31,8 +31,67 @@ jobs:
- name: Run Go tests
run: go test -race -v ./...
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: "24"
+
+ - name: Enable pnpm
+ env:
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: "0"
+ run: corepack enable && corepack prepare pnpm@10.33.0 --activate
+
+ - name: Run UI checks
+ run: pnpm --dir ui install --frozen-lockfile && pnpm --dir ui run check
+
+ e2e:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ permissions:
+ contents: read
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Set up Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: "24"
+
+ - name: Enable pnpm
+ env:
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: "0"
+ run: corepack enable && corepack prepare pnpm@10.33.0 --activate
+
+ - name: Install E2E dependencies
+ run: pnpm --dir e2e install --frozen-lockfile
+
+ - name: Cache Playwright browsers
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/ms-playwright
+ key: ${{ runner.os }}-playwright-${{ hashFiles('e2e/pnpm-lock.yaml') }}
+
+ - name: Install Playwright Chromium
+ run: pnpm --dir e2e exec playwright install --with-deps chromium
+
+ - name: Run E2E tests
+ run: bash e2e/scripts/run.sh
+
+ - name: Upload E2E diagnostics on failure
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: e2e-diagnostics
+ path: |
+ e2e/playwright-report
+ e2e/test-results
+ e2e/.generated/compose-logs.txt
+ if-no-files-found: ignore
+
build-and-push:
- needs: [test]
+ needs: [test, e2e]
runs-on: ubuntu-latest
permissions:
contents: read
diff --git a/.gitignore b/.gitignore
index cb5f03a..5e24324 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,8 @@ config.json
*.db-wal
.claude
docs/
+e2e/node_modules/
+e2e/.generated/
+e2e/.auth/
+e2e/playwright-report/
+e2e/test-results/
diff --git a/Makefile b/Makefile
index d40b21e..6e77a5a 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: default ui check test build image
+.PHONY: default ui check test build image e2e e2e-up e2e-down
IMAGE_NAME := ghcr.io/tracyhatemice/who
@@ -18,3 +18,12 @@ check:
image:
docker build -t $(IMAGE_NAME) .
+
+e2e:
+ bash e2e/scripts/run.sh
+
+e2e-up:
+ bash e2e/scripts/run.sh --up-only
+
+e2e-down:
+ bash e2e/scripts/run.sh --down-only
diff --git a/README.md b/README.md
index 105fda1..cb7971e 100644
--- a/README.md
+++ b/README.md
@@ -64,6 +64,7 @@ Every CLI flag has a matching `WHO_*` environment variable (CLI flags take prece
| `--data-dir` | `WHO_DATA_DIR` | `./data` (`/data` in Docker) | Directory holding the `who.db` SQLite database |
| `--config` | `WHO_CONFIG` | *(empty)* | Optional seed `config.json` imported once when `who.db` is empty |
| `--base-path` | `WHO_BASE_PATH` | `/` | Sub-path prefix for Admin UI, `/auth/*`, and `/api/v1/*` (e.g. `/admin`) |
+| `--ddns-endpoint` | `WHO_DDNS_ENDPOINT` | *(empty)* | Optional DDNS provider endpoint override (defaults to AWS Route53; used for local/E2E mock endpoints) |
| `--oidc-issuer` | `WHO_OIDC_ISSUER` | *(empty)* | OIDC provider issuer URL (e.g. Pocket ID, Authelia, Authentik, Keycloak) |
| `--oidc-client-id` | `WHO_OIDC_CLIENT_ID` | *(empty)* | OIDC relying-party client ID |
| `--oidc-client-secret` | `WHO_OIDC_CLIENT_SECRET` | *(empty)* | OIDC client secret (optional for public PKCE clients) |
@@ -317,3 +318,29 @@ $ make
# Build container image locally
$ make image
```
+
+## End-to-End Testing (`make e2e`)
+
+The `e2e/` workspace runs full-stack browser and API verification with Playwright Chromium against a self-contained Docker Compose stack (`e2e/docker-compose.yml`):
+
+- **Traefik (`traefik:v3.6`)**: TLS termination on `https://app.who.localhost:18443` and `https://auth.who.localhost:18443` using ephemerally generated CA and server certificates in `e2e/.generated/`.
+- **GLAuth (`ghcr.io/glauth/glauth:v2.5.4`)**: Lightweight LDAP directory backing `admin@who.localhost` and `denied@who.localhost`.
+- **Authelia (`authelia/authelia:4.39`)**: OIDC Identity Provider (Authorization Code + `S256` PKCE + `UserInfo`) backed by GLAuth and generated RSA JWKS.
+- **`who` (built from root `Dockerfile`)**: Configured with `WHO_BASE_PATH=/who`, `WHO_OIDC_ALLOWED_EMAILS=admin@who.localhost`, and `WHO_DDNS_ENDPOINT=http://mock-sink:9999`.
+- **`mock-sink` (`node:24-alpine`)**: HTTP sink capturing outbound Route53 XML `UPSERT` requests and webhook deliveries on `http://127.0.0.1:19999`.
+
+```console
+# One-time Playwright setup (installs e2e deps and Chromium browser binary)
+$ pnpm --dir e2e install --frozen-lockfile
+$ pnpm --dir e2e exec playwright install --with-deps chromium
+
+# Cold-boot the full Compose stack, run all 5 Playwright projects, and tear down cleanly
+$ make e2e
+
+# Keep stack running while iterating on individual Playwright specs
+$ make e2e-up
+$ NODE_EXTRA_CA_CERTS="$PWD/e2e/.generated/certs/ca.crt" pnpm --dir e2e exec playwright test tests/mobile-layout.spec.mjs
+$ make e2e-down
+```
+
+GitHub Actions (`.github/workflows/docker-build.yml`) runs both `test` (`go test -race -v ./...` and `pnpm --dir ui run check`) and `e2e` (`bash e2e/scripts/run.sh`, uploading `e2e/playwright-report`, `e2e/test-results`, and `e2e/.generated/compose-logs.txt` on failure) before `build-and-push`.
diff --git a/e2e/authelia/configuration.yml.tmpl b/e2e/authelia/configuration.yml.tmpl
new file mode 100644
index 0000000..e96bf5f
--- /dev/null
+++ b/e2e/authelia/configuration.yml.tmpl
@@ -0,0 +1,67 @@
+theme: 'light'
+
+server:
+ address: 'tcp://:9091'
+
+log:
+ level: 'info'
+
+identity_validation:
+ reset_password:
+ jwt_secret: 'e2e-reset-password-jwt-secret-0123456789abcdef'
+
+authentication_backend:
+ password_reset:
+ disable: true
+ ldap:
+ implementation: 'glauth'
+ address: 'ldap://glauth:3893'
+ base_dn: 'dc=who,dc=localhost'
+ user: 'cn=authelia,ou=svcaccts,dc=who,dc=localhost'
+ password: 'BindPass123!'
+ users_filter: '(&(|({username_attribute}={input})({mail_attribute}={input}))(objectClass=posixAccount))'
+
+session:
+ secret: 'e2e-session-secret-0123456789abcdef0123456789'
+ cookies:
+ - domain: 'who.localhost'
+ authelia_url: 'https://auth.who.localhost:18443'
+ default_redirection_url: 'https://app.who.localhost:18443/who/'
+
+storage:
+ encryption_key: 'e2e-storage-encryption-key-0123456789abcdef01'
+ local:
+ path: '/tmp/authelia.sqlite3'
+
+notifier:
+ disable_startup_check: true
+ filesystem:
+ filename: '/tmp/authelia-notification.txt'
+
+access_control:
+ default_policy: 'one_factor'
+
+identity_providers:
+ oidc:
+ hmac_secret: 'e2e-oidc-hmac-secret-0123456789abcdef0123456789'
+ jwks:
+ - algorithm: 'RS256'
+ use: 'sig'
+ key: |
+{{JWKS_PEM_INDENTED}}
+ clients:
+ - client_id: 'who-e2e'
+ client_name: 'who E2E'
+ client_secret: '{{CLIENT_SECRET_HASH}}'
+ public: false
+ authorization_policy: 'one_factor'
+ consent_mode: 'implicit'
+ require_pkce: true
+ pkce_challenge_method: 'S256'
+ redirect_uris:
+ - 'https://app.who.localhost:18443/who/auth/oidc/callback'
+ scopes:
+ - 'openid'
+ - 'profile'
+ - 'email'
+ token_endpoint_auth_method: 'client_secret_basic'
diff --git a/e2e/docker-compose.yml b/e2e/docker-compose.yml
new file mode 100644
index 0000000..7f8fdc4
--- /dev/null
+++ b/e2e/docker-compose.yml
@@ -0,0 +1,94 @@
+name: who-e2e
+
+networks:
+ e2e:
+ driver: bridge
+
+services:
+ traefik:
+ image: traefik:v3.6
+ ports:
+ - "127.0.0.1:18443:18443"
+ volumes:
+ - ./traefik/traefik.yml:/etc/traefik/traefik.yml:ro
+ - ./traefik/dynamic.yml:/etc/traefik/dynamic.yml:ro
+ - ./.generated/certs:/certs:ro
+ networks:
+ e2e:
+ aliases:
+ - app.who.localhost
+ - auth.who.localhost
+ depends_on:
+ - who
+ - authelia
+
+ glauth:
+ image: ghcr.io/glauth/glauth:v2.5.4
+ command: ["/app/glauth", "-c", "/app/config/config.cfg"]
+ volumes:
+ - ./glauth/glauth.cfg:/app/config/config.cfg:ro
+ networks:
+ - e2e
+
+ authelia:
+ image: authelia/authelia:4.39
+ command: ["authelia", "--config", "/config/configuration.yml"]
+ environment:
+ X_AUTHELIA_HEALTHCHECK: "1"
+ volumes:
+ - ./.generated/authelia-config.yml:/config/configuration.yml:ro
+ depends_on:
+ - glauth
+ restart: on-failure:5
+ healthcheck:
+ test: ["CMD-SHELL", "/app/healthcheck.sh"]
+ interval: 2s
+ timeout: 3s
+ retries: 20
+ start_period: 3s
+ networks:
+ - e2e
+
+ mock-sink:
+ image: node:24-alpine
+ command: ["node", "/app/server.mjs"]
+ environment:
+ PORT: "9999"
+ ports:
+ - "127.0.0.1:19999:9999"
+ volumes:
+ - ./mock-sink/server.mjs:/app/server.mjs:ro
+ healthcheck:
+ test:
+ [
+ "CMD",
+ "node",
+ "-e",
+ "fetch('http://127.0.0.1:9999/healthz').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))",
+ ]
+ interval: 2s
+ timeout: 3s
+ retries: 15
+ networks:
+ - e2e
+
+ who:
+ build:
+ context: ..
+ dockerfile: Dockerfile
+ environment:
+ WHO_VERBOSE: "1"
+ WHO_BASE_PATH: /who
+ WHO_OIDC_ISSUER: https://auth.who.localhost:18443
+ WHO_OIDC_CLIENT_ID: who-e2e
+ WHO_OIDC_CLIENT_SECRET: who-e2e-client-secret-0123456789
+ WHO_OIDC_REDIRECT_URL: https://app.who.localhost:18443/who/auth/oidc/callback
+ WHO_OIDC_ALLOWED_EMAILS: admin@who.localhost
+ WHO_DDNS_ENDPOINT: http://mock-sink:9999
+ SSL_CERT_FILE: /certs/ca.crt
+ volumes:
+ - ./.generated/certs/ca.crt:/certs/ca.crt:ro
+ - ./.generated/who-data:/data
+ - ./.generated/touch:/touch
+ networks:
+ - e2e
diff --git a/e2e/glauth/glauth.cfg b/e2e/glauth/glauth.cfg
new file mode 100644
index 0000000..dd69ed4
--- /dev/null
+++ b/e2e/glauth/glauth.cfg
@@ -0,0 +1,58 @@
+debug = false
+
+[ldap]
+ enabled = true
+ listen = "0.0.0.0:3893"
+ tls = false
+
+[ldaps]
+ enabled = false
+
+[api]
+ enabled = false
+
+[behaviors]
+ IgnoreCapabilities = false
+ LimitFailedBinds = false
+
+[backend]
+ datastore = "config"
+ baseDN = "dc=who,dc=localhost"
+ nameformat = "cn"
+ groupformat = "ou"
+ anonymousdse = true
+
+[[groups]]
+ name = "svcaccts"
+ gidnumber = 5501
+
+[[groups]]
+ name = "users"
+ gidnumber = 5502
+
+[[users]]
+ name = "authelia"
+ uidnumber = 5001
+ primarygroup = 5501
+ passsha256 = "1c47e1c50ce3ebe4d4b46a444229ab3b94743b08d5f5367e23db48d4474c1c29"
+ [[users.capabilities]]
+ action = "search"
+ object = "dc=who,dc=localhost"
+
+[[users]]
+ name = "admin"
+ givenname = "Admin"
+ sn = "User"
+ mail = "admin@who.localhost"
+ uidnumber = 5002
+ primarygroup = 5502
+ passsha256 = "a44ca5d29f6dab4320ab986479fa985b2d584b11a7da934f7e80bb1449913a07"
+
+[[users]]
+ name = "denied"
+ givenname = "Denied"
+ sn = "User"
+ mail = "denied@who.localhost"
+ uidnumber = 5003
+ primarygroup = 5502
+ passsha256 = "5dc5fc273b31346ca6edff628469eb9ba0e67e381b9237f1791364c0d356e5fb"
diff --git a/e2e/mock-sink/server.mjs b/e2e/mock-sink/server.mjs
new file mode 100644
index 0000000..57908cf
--- /dev/null
+++ b/e2e/mock-sink/server.mjs
@@ -0,0 +1,126 @@
+import http from "node:http";
+
+const port = Number.parseInt(process.env.PORT || "9999", 10);
+const requests = [];
+
+function readBody(req) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ req.on("data", (chunk) => chunks.push(chunk));
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
+ req.on("error", reject);
+ });
+}
+
+function send(res, statusCode, contentType, body) {
+ res.writeHead(statusCode, { "Content-Type": contentType });
+ res.end(body);
+}
+
+const server = http.createServer(async (req, res) => {
+ try {
+ const url = new URL(req.url || "/", "http://localhost");
+ const { pathname } = url;
+
+ if (req.method === "GET" && pathname === "/healthz") {
+ return send(res, 200, "text/plain; charset=utf-8", "ok\n");
+ }
+
+ if (req.method === "GET" && pathname === "/_requests") {
+ const kind = url.searchParams.get("kind");
+ const filtered = kind ? requests.filter((entry) => entry.kind === kind) : requests;
+ return send(res, 200, "application/json; charset=utf-8", JSON.stringify(filtered));
+ }
+
+ if (req.method === "DELETE" && pathname === "/_requests") {
+ requests.length = 0;
+ return send(res, 200, "application/json; charset=utf-8", JSON.stringify({ ok: true }));
+ }
+
+ const ddnsMatch = /^\/2013-04-01\/hostedzone\/([^/]+)\/rrset$/.exec(pathname);
+ if (req.method === "POST" && ddnsMatch) {
+ const zoneId = decodeURIComponent(ddnsMatch[1]);
+ const body = await readBody(req);
+ requests.push({
+ kind: "ddns",
+ method: req.method,
+ path: pathname,
+ zoneId,
+ headers: req.headers,
+ body,
+ receivedAt: new Date().toISOString(),
+ });
+
+ if (zoneId === "FAILZONE") {
+ return send(
+ res,
+ 400,
+ "application/xml; charset=utf-8",
+ `
+
+
+ Sender
+ NoSuchHostedZone
+ No hosted zone found with ID: FAILZONE
+
+ e2e-failzone
+`,
+ );
+ }
+
+ return send(
+ res,
+ 200,
+ "application/xml; charset=utf-8",
+ `
+/change/C1E2EPENDING`,
+ );
+ }
+
+ if (pathname === "/hook" || pathname.startsWith("/hook/")) {
+ const body = await readBody(req);
+ requests.push({
+ kind: "webhook",
+ method: req.method || "GET",
+ path: pathname,
+ headers: req.headers,
+ body,
+ receivedAt: new Date().toISOString(),
+ });
+
+ if (pathname === "/hook/fail" || pathname.startsWith("/hook/fail/")) {
+ return send(
+ res,
+ 500,
+ "application/json; charset=utf-8",
+ JSON.stringify({ ok: false, error: "simulated webhook failure" }),
+ );
+ }
+
+ return send(res, 200, "application/json; charset=utf-8", JSON.stringify({ ok: true }));
+ }
+
+ return send(res, 404, "application/json; charset=utf-8", JSON.stringify({ error: "not found" }));
+ } catch (err) {
+ if (!res.headersSent) {
+ const statusCode = err instanceof URIError ? 400 : 500;
+ return send(
+ res,
+ statusCode,
+ "application/json; charset=utf-8",
+ JSON.stringify({ error: statusCode === 400 ? "bad request" : "internal server error" }),
+ );
+ }
+ res.destroy();
+ }
+});
+
+server.listen(port, "0.0.0.0", () => {
+ console.log(`mock-sink listening on :${port}`);
+});
+
+for (const signal of ["SIGINT", "SIGTERM"]) {
+ process.on(signal, () => {
+ server.close(() => process.exit(0));
+ });
+}
diff --git a/e2e/package.json b/e2e/package.json
new file mode 100644
index 0000000..f9a17a7
--- /dev/null
+++ b/e2e/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "who-e2e",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "scripts": {
+ "prepare:fixtures": "node scripts/prepare.mjs",
+ "test": "playwright test"
+ },
+ "devDependencies": {
+ "@playwright/test": "^1.52.0"
+ }
+}
diff --git a/e2e/playwright.config.mjs b/e2e/playwright.config.mjs
new file mode 100644
index 0000000..236c5eb
--- /dev/null
+++ b/e2e/playwright.config.mjs
@@ -0,0 +1,81 @@
+import path from "node:path";
+import { defineConfig, devices } from "@playwright/test";
+
+const e2eRoot = import.meta.dirname;
+const adminStorageState = path.join(e2eRoot, ".auth", "admin.json");
+
+export default defineConfig({
+ testDir: path.join(e2eRoot, "tests"),
+ fullyParallel: false,
+ workers: 1,
+ forbidOnly: Boolean(process.env.CI),
+ retries: process.env.CI ? 1 : 0,
+ timeout: 30_000,
+ expect: {
+ timeout: 10_000,
+ },
+ reporter: [["list"], ["html", { open: "never" }]],
+ use: {
+ baseURL: "https://app.who.localhost:18443",
+ ignoreHTTPSErrors: true,
+ trace: "retain-on-failure",
+ screenshot: "only-on-failure",
+ video: "retain-on-failure",
+ },
+ projects: [
+ {
+ name: "setup",
+ testMatch: /.*\.setup\.spec\.mjs/,
+ use: {
+ ...devices["Desktop Chrome"],
+ viewport: { width: 1280, height: 800 },
+ },
+ },
+ {
+ name: "unauthenticated",
+ testMatch: /auth-security\.spec\.mjs/,
+ dependencies: ["setup"],
+ use: {
+ ...devices["Desktop Chrome"],
+ viewport: { width: 1280, height: 800 },
+ storageState: { cookies: [], origins: [] },
+ },
+ },
+ {
+ name: "public-endpoints",
+ testMatch: /public-endpoints\.spec\.mjs/,
+ dependencies: ["setup"],
+ use: {
+ ...devices["Desktop Chrome"],
+ viewport: { width: 1280, height: 800 },
+ storageState: { cookies: [], origins: [] },
+ },
+ },
+ {
+ name: "desktop-ui",
+ testMatch: [
+ /navigation-and-overview\.spec\.mjs/,
+ /records-and-drawer\.spec\.mjs/,
+ /ddns-webhooks-touch\.spec\.mjs/,
+ /logs-and-settings\.spec\.mjs/,
+ ],
+ dependencies: ["setup"],
+ use: {
+ ...devices["Desktop Chrome"],
+ viewport: { width: 1280, height: 800 },
+ storageState: adminStorageState,
+ },
+ },
+ {
+ name: "mobile-ui",
+ testMatch: /mobile-layout\.spec\.mjs/,
+ dependencies: ["setup"],
+ use: {
+ ...devices["Pixel 5"],
+ viewport: { width: 390, height: 844 },
+ screen: { width: 390, height: 844 },
+ storageState: adminStorageState,
+ },
+ },
+ ],
+});
diff --git a/e2e/pnpm-lock.yaml b/e2e/pnpm-lock.yaml
new file mode 100644
index 0000000..8be4e6f
--- /dev/null
+++ b/e2e/pnpm-lock.yaml
@@ -0,0 +1,42 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ devDependencies:
+ '@playwright/test':
+ specifier: ^1.52.0
+ version: 1.65.1
+
+packages:
+
+ '@playwright/test@1.65.1':
+ resolution: {integrity: sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==}
+ engines: {node: '>=20'}
+ hasBin: true
+
+ playwright-core@1.65.1:
+ resolution: {integrity: sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==}
+ engines: {node: '>=20'}
+ hasBin: true
+
+ playwright@1.65.1:
+ resolution: {integrity: sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==}
+ engines: {node: '>=20'}
+ hasBin: true
+
+snapshots:
+
+ '@playwright/test@1.65.1':
+ dependencies:
+ playwright: 1.65.1
+
+ playwright-core@1.65.1: {}
+
+ playwright@1.65.1:
+ dependencies:
+ playwright-core: 1.65.1
diff --git a/e2e/scripts/prepare.mjs b/e2e/scripts/prepare.mjs
new file mode 100644
index 0000000..dcf3d6b
--- /dev/null
+++ b/e2e/scripts/prepare.mjs
@@ -0,0 +1,158 @@
+import { execFileSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+const CLIENT_SECRET = "who-e2e-client-secret-0123456789";
+
+const e2eDir = path.resolve(import.meta.dirname, "..");
+const generatedDir = path.join(e2eDir, ".generated");
+const certsDir = path.join(generatedDir, "certs");
+const whoDataDir = path.join(generatedDir, "who-data");
+const touchDir = path.join(generatedDir, "touch");
+const autheliaTemplatePath = path.join(e2eDir, "authelia", "configuration.yml.tmpl");
+const autheliaConfigPath = path.join(generatedDir, "authelia-config.yml");
+
+const keepCerts = process.argv.includes("--keep-certs");
+
+function resetWritableDir(dirPath) {
+ fs.rmSync(dirPath, { recursive: true, force: true });
+ fs.mkdirSync(dirPath, { recursive: true });
+ fs.chmodSync(dirPath, 0o777);
+}
+
+function generateCerts() {
+ const caKey = path.join(certsDir, "ca.key");
+ const caCrt = path.join(certsDir, "ca.crt");
+ const serverKey = path.join(certsDir, "server.key");
+ const serverCrt = path.join(certsDir, "server.crt");
+
+ if (
+ keepCerts &&
+ fs.existsSync(caKey) &&
+ fs.existsSync(caCrt) &&
+ fs.existsSync(serverKey) &&
+ fs.existsSync(serverCrt)
+ ) {
+ return;
+ }
+
+ fs.rmSync(certsDir, { recursive: true, force: true });
+ fs.mkdirSync(certsDir, { recursive: true });
+
+ const serverCsr = path.join(certsDir, "server.csr");
+ const serverExt = path.join(certsDir, "server.ext");
+ const caSrl = path.join(certsDir, "ca.srl");
+
+ execFileSync("openssl", ["genrsa", "-out", caKey, "2048"], { stdio: "pipe" });
+ execFileSync(
+ "openssl",
+ [
+ "req",
+ "-x509",
+ "-new",
+ "-nodes",
+ "-key",
+ caKey,
+ "-sha256",
+ "-days",
+ "7",
+ "-subj",
+ "/CN=who-e2e-ca",
+ "-addext",
+ "basicConstraints=critical,CA:TRUE",
+ "-addext",
+ "keyUsage=critical,keyCertSign,cRLSign",
+ "-out",
+ caCrt,
+ ],
+ { stdio: "pipe" },
+ );
+
+ execFileSync("openssl", ["genrsa", "-out", serverKey, "2048"], { stdio: "pipe" });
+ execFileSync(
+ "openssl",
+ ["req", "-new", "-key", serverKey, "-subj", "/CN=app.who.localhost", "-out", serverCsr],
+ { stdio: "pipe" },
+ );
+
+ fs.writeFileSync(
+ serverExt,
+ [
+ "basicConstraints=CA:FALSE",
+ "keyUsage=digitalSignature,keyEncipherment",
+ "extendedKeyUsage=serverAuth",
+ "subjectAltName=DNS:app.who.localhost,DNS:auth.who.localhost,DNS:who.localhost",
+ "",
+ ].join("\n"),
+ );
+
+ execFileSync(
+ "openssl",
+ [
+ "x509",
+ "-req",
+ "-in",
+ serverCsr,
+ "-CA",
+ caCrt,
+ "-CAkey",
+ caKey,
+ "-CAcreateserial",
+ "-out",
+ serverCrt,
+ "-days",
+ "7",
+ "-sha256",
+ "-extfile",
+ serverExt,
+ ],
+ { stdio: "pipe" },
+ );
+
+ for (const tempFile of [serverCsr, serverExt, caSrl]) {
+ fs.rmSync(tempFile, { force: true });
+ }
+
+ fs.chmodSync(caKey, 0o600);
+ fs.chmodSync(caCrt, 0o644);
+ fs.chmodSync(serverKey, 0o644);
+ fs.chmodSync(serverCrt, 0o644);
+}
+
+function autheliaPBKDF2Hash(secret, iterations = 100000) {
+ const salt = crypto.randomBytes(16);
+ const dk = crypto.pbkdf2Sync(secret, salt, iterations, 64, "sha512");
+ const ab64 = (buf) => buf.toString("base64").replace(/\+/g, ".").replace(/=+$/, "");
+ return `$pbkdf2-sha512$${iterations}$${ab64(salt)}$${ab64(dk)}`;
+}
+
+function renderAutheliaConfig() {
+ const { privateKey } = crypto.generateKeyPairSync("rsa", {
+ modulusLength: 2048,
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
+ publicKeyEncoding: { type: "spki", format: "pem" },
+ });
+
+ const indentedPem = privateKey
+ .trimEnd()
+ .split("\n")
+ .map((line) => ` ${line}`)
+ .join("\n");
+
+ const template = fs.readFileSync(autheliaTemplatePath, "utf8");
+ const rendered = template
+ .replace("{{JWKS_PEM_INDENTED}}", () => indentedPem)
+ .replace("{{CLIENT_SECRET_HASH}}", () => autheliaPBKDF2Hash(CLIENT_SECRET));
+
+ fs.writeFileSync(autheliaConfigPath, rendered, "utf8");
+ fs.chmodSync(autheliaConfigPath, 0o644);
+}
+
+fs.mkdirSync(generatedDir, { recursive: true });
+resetWritableDir(whoDataDir);
+resetWritableDir(touchDir);
+generateCerts();
+renderAutheliaConfig();
+
+console.log(`Prepared E2E fixtures in ${generatedDir}`);
diff --git a/e2e/scripts/run.sh b/e2e/scripts/run.sh
new file mode 100755
index 0000000..f7149c7
--- /dev/null
+++ b/e2e/scripts/run.sh
@@ -0,0 +1,119 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
+E2E_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd)"
+COMPOSE_FILE="$E2E_DIR/docker-compose.yml"
+CA_CERT="$E2E_DIR/.generated/certs/ca.crt"
+LOGS_OUT="$E2E_DIR/.generated/compose-logs.txt"
+
+if ! command -v node >/dev/null 2>&1 || ! command -v pnpm >/dev/null 2>&1; then
+ nvm_root="${NVM_DIR:-$HOME/.nvm}"
+ for nvm_bin in "$nvm_root"/versions/node/v24*/bin "$nvm_root"/versions/node/*/bin; do
+ if [[ -x "$nvm_bin/node" && -x "$nvm_bin/pnpm" ]]; then
+ export PATH="$nvm_bin:$PATH"
+ break
+ fi
+ done
+fi
+
+compose() {
+ docker compose -f "$COMPOSE_FILE" "$@"
+}
+
+dump_logs() {
+ mkdir -p "$E2E_DIR/.generated"
+ compose logs --no-color > "$LOGS_OUT" 2>&1 || true
+ echo "Wrote compose logs to $LOGS_OUT" >&2
+}
+
+mode="full"
+case "${1:-}" in
+ --up-only)
+ mode="up-only"
+ shift
+ ;;
+ --down-only)
+ mode="down-only"
+ shift
+ ;;
+esac
+
+if [[ "$mode" != "full" && "$#" -gt 0 ]]; then
+ echo "Unexpected arguments for --${mode}: $*" >&2
+ exit 2
+fi
+
+if [[ "$mode" == "down-only" ]]; then
+ compose down -v --remove-orphans
+ exit 0
+fi
+
+cleanup() {
+ local exit_code=$?
+ trap - EXIT INT TERM
+ if [[ "$exit_code" -ne 0 ]]; then
+ dump_logs
+ fi
+ compose down -v --remove-orphans || true
+ exit "$exit_code"
+}
+
+if [[ "$mode" == "full" ]]; then
+ trap cleanup EXIT
+ trap 'exit 130' INT
+ trap 'exit 143' TERM
+fi
+
+wait_for_stack() {
+ local deadline=$((SECONDS + 90))
+ local endpoints=(
+ "http://127.0.0.1:19999/healthz"
+ "https://auth.who.localhost:18443/api/health"
+ "https://auth.who.localhost:18443/.well-known/openid-configuration"
+ "https://app.who.localhost:18443/healthz"
+ )
+
+ for url in "${endpoints[@]}"; do
+ while true; do
+ if [[ "$url" == https://* ]]; then
+ if curl -fsS --cacert "$CA_CERT" \
+ --resolve "app.who.localhost:18443:127.0.0.1" \
+ --resolve "auth.who.localhost:18443:127.0.0.1" \
+ --max-time 5 "$url" >/dev/null 2>&1; then
+ break
+ fi
+ else
+ if curl -fsS --max-time 5 "$url" >/dev/null 2>&1; then
+ break
+ fi
+ fi
+
+ if (( SECONDS >= deadline )); then
+ echo "Timed out after 90s waiting for $url" >&2
+ if [[ "$mode" == "up-only" ]]; then
+ dump_logs
+ fi
+ return 1
+ fi
+ sleep 1
+ done
+ done
+}
+
+node "$E2E_DIR/scripts/prepare.mjs"
+rm -f "$LOGS_OUT"
+compose up -d --build
+wait_for_stack
+
+if [[ "$mode" == "up-only" ]]; then
+ echo "E2E stack is ready."
+ exit 0
+fi
+
+if [[ ! -d "$E2E_DIR/node_modules" ]]; then
+ pnpm --dir "$E2E_DIR" install --frozen-lockfile
+fi
+
+export NODE_EXTRA_CA_CERTS="$CA_CERT"
+pnpm --dir "$E2E_DIR" exec playwright test "$@"
diff --git a/e2e/tests/auth-security.spec.mjs b/e2e/tests/auth-security.spec.mjs
new file mode 100644
index 0000000..b9fa207
--- /dev/null
+++ b/e2e/tests/auth-security.spec.mjs
@@ -0,0 +1,162 @@
+import { expect, test } from "@playwright/test";
+import {
+ ADMIN_USER,
+ APP_URL,
+ DENIED_USER,
+ apiFetch,
+ loginViaAuthelia,
+ rawAppFetch,
+} from "./helpers.mjs";
+
+test.describe("Auth & CSRF Security Boundaries", () => {
+ test("pre-auth /who/ shell hides admin assets and API routes", async ({ page }) => {
+ const res = await rawAppFetch("GET", "/who/");
+ expect(res.status).toBe(200);
+ expect(res.headers["cache-control"]).toBe("no-store");
+ expect(res.headers["content-type"]).toContain("text/html");
+ expect(res.text).toContain("Continue with OIDC");
+ expect(res.text).toContain('href="./auth/oidc/login"');
+ expect(res.text).not.toContain("/api/v1/");
+ expect(res.text).not.toContain("/who/assets/");
+
+ await page.goto("/who/");
+ await expect(page.getByRole("heading", { name: "Sign in", level: 1 })).toBeVisible();
+ const loginLink = page.locator('a[href="./auth/oidc/login"]');
+ await expect(loginLink).toBeVisible();
+ await expect(loginLink).toContainText(/Continue with OIDC/i);
+ });
+
+ test("unauthenticated static assets and admin API endpoints return 401", async () => {
+ const assetRes = await rawAppFetch("GET", "/who/assets/nonexistent.js");
+ expect(assetRes.status).toBe(401);
+ expect(assetRes.headers["cache-control"]).toBe("no-store");
+
+ const apiRes = await rawAppFetch("GET", "/who/api/v1/records");
+ expect(apiRes.status).toBe(401);
+ expect(apiRes.headers["cache-control"]).toBe("no-store");
+
+ const statusRes = await rawAppFetch("GET", "/who/auth/status");
+ expect(statusRes.status).toBe(200);
+ expect(statusRes.data).toEqual({
+ oidcEnabled: true,
+ authenticated: false,
+ user: null,
+ });
+ });
+
+ test("authenticated admin API enforces X-Who-CSRF and rejects Sec-Fetch-Site: cross-site", async () => {
+ const recordsRes = await apiFetch("GET", "/records");
+ expect(recordsRes.status).toBe(200);
+
+ const missingPostCsrf = await rawAppFetch("POST", "/who/api/v1/records", {
+ useAdminAuth: true,
+ body: { iam: "e2e-csrf-blocked", ip: "198.51.100.1" },
+ });
+ expect(missingPostCsrf.status).toBe(403);
+
+ const missingExportCsrf = await rawAppFetch("GET", "/who/api/v1/backup/export", {
+ useAdminAuth: true,
+ });
+ expect(missingExportCsrf.status).toBe(403);
+
+ const exportWithCsrf = await rawAppFetch("GET", "/who/api/v1/backup/export", {
+ useAdminAuth: true,
+ headers: { "X-Who-CSRF": "1" },
+ });
+ expect(exportWithCsrf.status).toBe(200);
+ expect(exportWithCsrf.headers["content-disposition"]).toContain("who-backup.json");
+ expect(exportWithCsrf.data).toMatchObject({
+ who: expect.any(Array),
+ secrets: expect.any(Array),
+ ddns: expect.any(Array),
+ webhooks: expect.any(Array),
+ touch: expect.any(Array),
+ });
+
+ const crossSiteRes = await rawAppFetch("GET", "/who/api/v1/records", {
+ useAdminAuth: true,
+ headers: { "Sec-Fetch-Site": "cross-site" },
+ });
+ expect(crossSiteRes.status).toBe(403);
+ });
+
+ test("denied OIDC user is redirected with access_denied alert and no session cookie", async ({
+ browser,
+ }) => {
+ const freshContext = await browser.newContext({ ignoreHTTPSErrors: true });
+ try {
+ const freshPage = await freshContext.newPage();
+ await loginViaAuthelia(freshPage, DENIED_USER);
+
+ await expect(freshPage).toHaveURL(`${APP_URL}/who/?auth_error=access_denied`);
+ await expect(freshPage.locator('a[href="./auth/oidc/login"]')).toBeVisible();
+ await expect(freshPage.getByRole("alert")).toContainText(/Access denied/i);
+
+ const cookies = await freshContext.cookies(`${APP_URL}/who/`);
+ expect(cookies.some((c) => c.name === "who_session")).toBe(false);
+ } finally {
+ await freshContext.close();
+ }
+ });
+
+ test("sign out revokes only the active session and isolates the shared admin session", async ({
+ browser,
+ }) => {
+ const freshContext = await browser.newContext({ ignoreHTTPSErrors: true });
+ try {
+ const freshPage = await freshContext.newPage();
+ await loginViaAuthelia(freshPage, ADMIN_USER);
+
+ await expect(freshPage).toHaveURL(`${APP_URL}/who/#/overview`);
+ await expect(
+ freshPage.getByRole("heading", { name: "Overview", level: 1 }),
+ ).toBeVisible();
+
+ const beforeCookies = await freshContext.cookies(`${APP_URL}/who/`);
+ const freshSession = beforeCookies.find((c) => c.name === "who_session");
+ expect(freshSession?.value).toBeTruthy();
+
+ const [logoutResponse] = await Promise.all([
+ freshPage.waitForResponse(
+ (res) =>
+ res.url() === `${APP_URL}/who/auth/logout` &&
+ res.request().method() === "POST",
+ ),
+ freshPage
+ .locator('aside[aria-label="Main navigation"]')
+ .getByRole("button", { name: "Sign out" })
+ .click(),
+ ]);
+ expect(logoutResponse.status()).toBe(200);
+ expect(logoutResponse.request().method()).toBe("POST");
+ expect(logoutResponse.request().headers()["x-who-csrf"]).toBe("1");
+ expect(logoutResponse.headers()["content-type"]).toContain("application/json");
+
+ await expect(freshPage).toHaveURL(`${APP_URL}/who/`);
+ await expect(freshPage.locator('a[href="./auth/oidc/login"]')).toBeVisible();
+ await expect(freshPage.getByRole("alert")).toHaveCount(0);
+
+ const postLogoutHtml = await freshPage.content();
+ expect(postLogoutHtml).not.toContain("/who/assets/");
+ expect(postLogoutHtml).not.toContain("/api/v1/");
+
+ const afterCookies = await freshContext.cookies(`${APP_URL}/who/`);
+ expect(afterCookies.some((c) => c.name === "who_session")).toBe(false);
+
+ const revokedAssetRes = await rawAppFetch("GET", "/who/assets/nonexistent.js", {
+ cookieHeader: `who_session=${freshSession.value}`,
+ });
+ expect(revokedAssetRes.status).toBe(401);
+
+ const revokedRes = await rawAppFetch("GET", "/who/api/v1/records", {
+ cookieHeader: `who_session=${freshSession.value}`,
+ });
+ expect(revokedRes.status).toBe(401);
+
+ const sharedSessionRes = await apiFetch("GET", "/records");
+ expect(sharedSessionRes.status).toBe(200);
+ } finally {
+ await freshContext.close();
+ }
+ });
+});
diff --git a/e2e/tests/auth.setup.spec.mjs b/e2e/tests/auth.setup.spec.mjs
new file mode 100644
index 0000000..5304220
--- /dev/null
+++ b/e2e/tests/auth.setup.spec.mjs
@@ -0,0 +1,35 @@
+import fs from "node:fs";
+import path from "node:path";
+import { expect, test } from "@playwright/test";
+import {
+ ADMIN_STORAGE_STATE,
+ ADMIN_USER,
+ APP_URL,
+ loginViaAuthelia,
+ rawAppFetch,
+} from "./helpers.mjs";
+
+test("authenticate admin via Authelia OIDC and persist storageState", async ({ page }) => {
+ const preAuth = await rawAppFetch("GET", "/who/");
+ expect(preAuth.status).toBe(200);
+ expect(preAuth.text).toContain("Continue with OIDC");
+ expect(preAuth.text).not.toContain("/api/v1/");
+ expect(preAuth.text).not.toContain("/who/assets/");
+
+ await loginViaAuthelia(page, ADMIN_USER);
+
+ await expect(page).toHaveURL(`${APP_URL}/who/#/overview`);
+ await expect(
+ page.getByRole("heading", { name: "Overview", level: 1 }),
+ ).toBeVisible();
+
+ const desktopSidebar = page.locator('aside[aria-label="Main navigation"]');
+ await expect(desktopSidebar.getByText(ADMIN_USER.email)).toBeVisible();
+
+ const cookies = await page.context().cookies(`${APP_URL}/who/`);
+ expect(cookies.some((c) => c.name === "who_session" && Boolean(c.value))).toBe(true);
+
+ fs.mkdirSync(path.dirname(ADMIN_STORAGE_STATE), { recursive: true });
+ await page.context().storageState({ path: ADMIN_STORAGE_STATE });
+ expect(fs.existsSync(ADMIN_STORAGE_STATE)).toBe(true);
+});
diff --git a/e2e/tests/ddns-webhooks-touch.spec.mjs b/e2e/tests/ddns-webhooks-touch.spec.mjs
new file mode 100644
index 0000000..032fb25
--- /dev/null
+++ b/e2e/tests/ddns-webhooks-touch.spec.mjs
@@ -0,0 +1,575 @@
+import fs from "node:fs";
+import path from "node:path";
+import { expect, test } from "@playwright/test";
+import {
+ TOUCH_HOST_DIR,
+ apiFetch,
+ getSinkRequests,
+ rawAppFetch,
+ readTouchFile,
+ resetMockSink,
+ waitForSinkRequest,
+} from "./helpers.mjs";
+
+const HOST_IAM = "e2e-fx-host";
+const ALIAS_IAM = "e2e-fx-alias";
+const SECRET_NAME = "e2e-r53-sec";
+const ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE";
+const SECRET_KEY = "e2e-secret-access-key-0123456789";
+const DDNS_DOMAIN = "ddns.e2e.example";
+const HOOK_OK_URL = "http://mock-sink:9999/hook/e2e";
+const HOOK_FAIL_URL = "http://mock-sink:9999/hook/fail";
+const TOUCH_PATH_1 = "/touch/e2e-alias.json";
+const TOUCH_FILE_1 = "e2e-alias.json";
+const TOUCH_PATH_2 = "/touch/e2e-alias-v2.json";
+const TOUCH_FILE_2 = "e2e-alias-v2.json";
+
+function attachErrorCollector(page) {
+ const pageErrors = [];
+ const consoleErrors = [];
+ page.on("pageerror", (err) => {
+ pageErrors.push(err?.message || String(err));
+ });
+ page.on("console", (msg) => {
+ if (msg.type() === "error") {
+ consoleErrors.push(msg.text());
+ }
+ });
+ return { pageErrors, consoleErrors };
+}
+
+async function cleanupSideEffectFixtures() {
+ const touchRes = await apiFetch("GET", "/touch");
+ if (touchRes.ok) {
+ for (const item of touchRes.data?.items ?? []) {
+ if (
+ item.iam === ALIAS_IAM ||
+ item.iam === HOST_IAM ||
+ item.path === TOUCH_PATH_1 ||
+ item.path === TOUCH_PATH_2
+ ) {
+ const del = await apiFetch("DELETE", `/touch/${item.id}`);
+ expect([200, 204, 404]).toContain(del.status);
+ }
+ }
+ }
+
+ const whRes = await apiFetch("GET", "/webhooks");
+ if (whRes.ok) {
+ for (const item of whRes.data?.items ?? []) {
+ if (
+ item.iam === HOST_IAM ||
+ item.url === HOOK_OK_URL ||
+ item.url === HOOK_FAIL_URL
+ ) {
+ const del = await apiFetch("DELETE", `/webhooks/${item.id}`);
+ expect([200, 204, 404]).toContain(del.status);
+ }
+ }
+ }
+
+ const ddnsRes = await apiFetch("GET", "/ddns");
+ if (ddnsRes.ok) {
+ for (const item of ddnsRes.data?.items ?? []) {
+ if (item.iam === HOST_IAM || item.domain === DDNS_DOMAIN) {
+ const del = await apiFetch("DELETE", `/ddns/${item.id}`);
+ expect([200, 204, 404]).toContain(del.status);
+ }
+ }
+ }
+
+ const secRes = await apiFetch("GET", "/secrets");
+ if (secRes.ok) {
+ for (const sec of secRes.data?.items ?? []) {
+ if (sec.name === SECRET_NAME) {
+ const del = await apiFetch("DELETE", `/secrets/${sec.id}`);
+ expect([200, 204, 404]).toContain(del.status);
+ }
+ }
+ }
+
+ for (const iam of [ALIAS_IAM, HOST_IAM]) {
+ const del = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ expect([200, 204, 404]).toContain(del.status);
+ }
+
+ for (const filename of [TOUCH_FILE_1, TOUCH_FILE_2]) {
+ await fs.promises.rm(path.join(TOUCH_HOST_DIR, filename), { force: true });
+ }
+}
+
+test.describe("DDNS, Webhooks, Touch Files CRUD & Live Side Effects", () => {
+ test.beforeAll(async () => {
+ await cleanupSideEffectFixtures();
+ await resetMockSink();
+
+ const hostCreate = await apiFetch("POST", "/records", {
+ body: { iam: HOST_IAM, isAlias: false, ip: "198.51.100.70" },
+ });
+ expect(hostCreate.status).toBe(201);
+
+ const aliasCreate = await apiFetch("POST", "/records", {
+ body: { iam: ALIAS_IAM, isAlias: true, alias: [HOST_IAM] },
+ });
+ expect(aliasCreate.status).toBe(201);
+ });
+
+ test.afterAll(async () => {
+ await cleanupSideEffectFixtures();
+ await resetMockSink();
+ });
+
+ test("verifies Provider Secrets, DDNS Route53 XML, Webhooks, and Touch disk JSON end-to-end", async ({
+ page,
+ }) => {
+ test.setTimeout(60_000);
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ // =========================================================================
+ // 1. Provider Secrets + DDNS CRUD & Live Route53 Side Effects
+ // =========================================================================
+ await page.goto("/who/#/ddns");
+ await expect(page.locator("#main header h1")).toHaveText("DDNS");
+
+ await page.getByRole("button", { name: "New DDNS Rule" }).click();
+ const ddnsDialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: /DDNS Rule/i, level: 1 }),
+ });
+ await expect(ddnsDialog).toBeVisible();
+
+ await ddnsDialog.getByRole("button", { name: "New Secret" }).click();
+ const secretDialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "New Provider Secret", level: 1 }),
+ });
+ await expect(secretDialog).toBeVisible();
+
+ await secretDialog.getByLabel(/Secret Name/i).fill(SECRET_NAME);
+ await secretDialog.getByLabel(/AWS Access Key ID/i).fill(ACCESS_KEY);
+ await secretDialog.getByLabel(/AWS Secret Access Key/i).fill(SECRET_KEY);
+ await secretDialog.getByRole("button", { name: "Create Secret" }).click();
+ await expect(secretDialog).toBeHidden();
+
+ await expect(ddnsDialog.locator('select[name="secretId"]')).toContainText(SECRET_NAME);
+ await ddnsDialog.getByLabel(/IAM Host Record/i).fill(HOST_IAM);
+ await ddnsDialog.getByLabel(/DNS Domain/i).fill(DDNS_DOMAIN);
+ await ddnsDialog.getByLabel(/Hosted Zone ID/i).fill("Z1E2EZONE");
+ await ddnsDialog.getByLabel(/TTL \(seconds\)/i).fill("120");
+ await expect(ddnsDialog.getByLabel("Auto (A/AAAA)")).toBeChecked();
+ await ddnsDialog.getByRole("button", { name: "Create Rule" }).click();
+ await expect(ddnsDialog).toBeHidden();
+
+ const ddnsRow = page.locator("tbody tr", { hasText: DDNS_DOMAIN });
+ await expect(ddnsRow).toBeVisible();
+ const ddnsDomainCell = ddnsRow.locator('th[scope="row"]');
+ await expect(ddnsDomainCell).toContainText(DDNS_DOMAIN);
+ await expect(ddnsDomainCell).not.toContainText("Zone:");
+ await expect(ddnsDomainCell).not.toContainText("Z1E2EZONE");
+
+ const ddnsProviderCell = ddnsRow.locator('td[data-col="Provider"]');
+ await expect(ddnsProviderCell).toContainText("AWS Route53");
+ await expect(ddnsProviderCell).not.toContainText(SECRET_NAME);
+
+ // Verify ON DELETE RESTRICT guard in Settings -> Provider Secrets
+ await page.goto("/who/#/settings/secrets");
+ await expect(page.locator("#main header h1")).toHaveText("Settings");
+ const secretRow = page.locator("#settings-secrets tbody tr", {
+ has: page.locator('th[scope="row"]', { hasText: SECRET_NAME }),
+ });
+ await expect(secretRow).toBeVisible();
+ await expect(secretRow).toContainText(ACCESS_KEY);
+ await expect(secretRow).not.toContainText(SECRET_KEY);
+ await expect(secretRow).toContainText("1 rule");
+ const secretDeleteBtn = secretRow.getByRole("button", {
+ name: `Delete secret ${SECRET_NAME}`,
+ });
+ await expect(secretDeleteBtn).toBeDisabled();
+
+ // Check UI masking inside Edit SecretModal plus API masking
+ await secretRow.getByRole("button", { name: `Edit secret ${SECRET_NAME}` }).click();
+ const editSecretDialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "Edit Provider Secret", level: 1 }),
+ });
+ await expect(editSecretDialog).toBeVisible();
+ await expect(editSecretDialog.locator('input[name="access_key"]')).toHaveValue(
+ ACCESS_KEY,
+ );
+ const editSecretKeyInput = editSecretDialog.locator('input[name="secret_key"]');
+ await expect(editSecretKeyInput).toHaveAttribute("placeholder", /^••••••••/);
+ await expect(editSecretKeyInput).toHaveValue("");
+ await expect(editSecretDialog).not.toContainText(SECRET_KEY);
+ await editSecretDialog.getByRole("button", { name: "Cancel" }).click();
+ await expect(editSecretDialog).toBeHidden();
+
+ const secretsApiRes = await apiFetch("GET", "/secrets");
+ expect(secretsApiRes.status).toBe(200);
+ const createdSecret = (secretsApiRes.data?.items ?? []).find(
+ (s) => s.name === SECRET_NAME,
+ );
+ expect(createdSecret).toBeTruthy();
+ expect(createdSecret.credentials?.secret_key).toBe("••••••••");
+ const blockedDeleteRes = await apiFetch("DELETE", `/secrets/${createdSecret.id}`);
+ expect(blockedDeleteRes.status).toBe(409);
+
+ // Trigger live DDNS Route53 XML UPSERT via /iam
+ await resetMockSink();
+ const ddnsIamRes = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.71`);
+ expect(ddnsIamRes.status).toBe(200);
+
+ const ddnsReq = await waitForSinkRequest(
+ (entry) =>
+ entry.path === "/2013-04-01/hostedzone/Z1E2EZONE/rrset" &&
+ entry.body.includes("198.51.100.71"),
+ { kind: "ddns", timeoutMs: 10_000 },
+ );
+ expect(ddnsReq.headers.authorization).toMatch(
+ new RegExp(
+ `^AWS4-HMAC-SHA256 Credential=${ACCESS_KEY}/\\d{8}/us-east-1/route53/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=[0-9a-f]{64}$`,
+ ),
+ );
+ expect(ddnsReq.body).toContain(`${DDNS_DOMAIN}.`);
+ expect(ddnsReq.body).toContain("UPSERT");
+ expect(ddnsReq.body).toContain("A");
+ expect(ddnsReq.body).toContain("120");
+ expect(ddnsReq.body).toContain("198.51.100.71");
+
+ // Return to DDNS page and confirm 200 OK badge + RecordDrawer delivery entry
+ await page.goto("/who/#/ddns");
+ await expect(page.locator("#main header h1")).toHaveText("DDNS");
+ await expect
+ .poll(
+ async () => {
+ await page.getByRole("button", { name: "Refresh" }).click();
+ return await ddnsRow.locator('td[data-col="Last Delivery"]').textContent();
+ },
+ { timeout: 10_000, intervals: [300] },
+ )
+ .toContain("200 OK");
+
+ await ddnsRow.getByRole("button", { name: HOST_IAM, exact: true }).click();
+ const drawer = page.locator("dialog.who-drawer[open]");
+ await expect(drawer).toBeVisible();
+ await expect(
+ drawer.getByRole("heading", { name: HOST_IAM, level: 1 }),
+ ).toBeVisible();
+ const ddnsHistoryItem = drawer
+ .locator("ol > li")
+ .filter({ hasText: "198.51.100.71" })
+ .first();
+ await expect(ddnsHistoryItem).toContainText("DDNS");
+ await expect(ddnsHistoryItem).toContainText(DDNS_DOMAIN);
+ await expect(ddnsHistoryItem).toContainText("200 OK");
+ await drawer.getByRole("button", { name: "Close drawer" }).click();
+ await expect(drawer).toHaveCount(0);
+ await expect(page.locator("dialog.who-drawer")).toBeHidden();
+
+ // Edit DDNS TTL to 300 and trigger Sync
+ await ddnsRow.getByRole("button", { name: `Edit ${DDNS_DOMAIN}` }).click();
+ await expect(ddnsDialog).toBeVisible();
+ await ddnsDialog.getByLabel(/TTL \(seconds\)/i).fill("300");
+ await ddnsDialog.getByRole("button", { name: "Save Changes" }).click();
+ await expect(ddnsDialog).toBeHidden();
+ await expect(ddnsRow.locator('td[data-col="Type & TTL"]')).toContainText("300s");
+
+ await resetMockSink();
+ await ddnsRow.getByRole("button", { name: `Sync ${DDNS_DOMAIN}` }).click();
+ const ttlSyncReq = await waitForSinkRequest(
+ (entry) =>
+ entry.path === "/2013-04-01/hostedzone/Z1E2EZONE/rrset" &&
+ entry.body.includes("300"),
+ { kind: "ddns", timeoutMs: 10_000 },
+ );
+ expect(ttlSyncReq.body).toContain("198.51.100.71");
+
+ // Pause DDNS rule -> verify zero deliveries while paused
+ const ddnsSwitch = ddnsRow.getByRole("switch", {
+ name: `DDNS rule for ${DDNS_DOMAIN}`,
+ });
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.request().method() === "PUT" &&
+ res.url().includes("/who/api/v1/ddns/") &&
+ res.status() === 200,
+ ),
+ ddnsSwitch.click(),
+ ]);
+ await expect(ddnsSwitch).toHaveAttribute("aria-checked", "false");
+
+ await resetMockSink();
+ const pausedDdnsIam = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.72`);
+ expect(pausedDdnsIam.status).toBe(200);
+ await page.waitForTimeout(800);
+ expect(await getSinkRequests("ddns")).toEqual([]);
+
+ // Edit zoneId to FAILZONE, re-enable, Sync -> verify 400 error badge
+ await ddnsRow.getByRole("button", { name: `Edit ${DDNS_DOMAIN}` }).click();
+ await expect(ddnsDialog).toBeVisible();
+ await ddnsDialog.getByLabel(/Hosted Zone ID/i).fill("FAILZONE");
+ await ddnsDialog.getByRole("switch", { name: "Enable DDNS rule" }).click();
+ await ddnsDialog.getByRole("button", { name: "Save Changes" }).click();
+ await expect(ddnsDialog).toBeHidden();
+ await expect(ddnsSwitch).toHaveAttribute("aria-checked", "true");
+
+ await ddnsRow.getByRole("button", { name: `Sync ${DDNS_DOMAIN}` }).click();
+ await expect(ddnsRow.locator('td[data-col="Last Delivery"]')).toContainText(
+ "400 Error",
+ );
+
+ // Delete DDNS rule, then delete secret cleanly in Settings
+ await ddnsRow.getByRole("button", { name: `Delete ${DDNS_DOMAIN}` }).click();
+ const ddnsDelConfirm = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", {
+ name: `Delete DDNS rule for ${DDNS_DOMAIN}?`,
+ level: 1,
+ }),
+ });
+ await expect(ddnsDelConfirm).toBeVisible();
+ await ddnsDelConfirm.getByRole("button", { name: "Delete Rule" }).click();
+ await expect(ddnsDelConfirm).toBeHidden();
+ await expect(ddnsRow).toHaveCount(0);
+
+ await page.goto("/who/#/settings/secrets");
+ await expect(secretRow).toContainText("Unused");
+ await expect(secretDeleteBtn).toBeEnabled();
+ await secretDeleteBtn.click();
+ const secDelConfirm = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", {
+ name: `Delete secret "${SECRET_NAME}"?`,
+ level: 1,
+ }),
+ });
+ await expect(secDelConfirm).toBeVisible();
+ await secDelConfirm.getByRole("button", { name: "Delete Secret" }).click();
+ await expect(secDelConfirm).toBeHidden();
+ await expect(secretRow).toHaveCount(0);
+
+ // =========================================================================
+ // 2. Webhooks CRUD & Live Delivery Side Effects
+ // =========================================================================
+ await page.goto("/who/#/webhooks");
+ await expect(page.locator("#main header h1")).toHaveText("Webhooks");
+
+ await page.getByRole("button", { name: "New Webhook" }).click();
+ const webhookDialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: /Webhook/i, level: 1 }),
+ });
+ await expect(webhookDialog).toBeVisible();
+
+ await webhookDialog.getByLabel(/IAM Host Record/i).fill(HOST_IAM);
+ await webhookDialog.getByLabel("Method").selectOption("POST");
+ await webhookDialog.getByLabel(/Destination URL/i).fill(HOOK_OK_URL);
+ await webhookDialog.getByRole("button", { name: "Add Header" }).click();
+ await webhookDialog.getByLabel("Header 1 name").fill("X-E2E-Hook");
+ await webhookDialog.getByLabel("Header 1 value").fill("secret-val");
+ await webhookDialog.getByRole("button", { name: "Create Webhook" }).click();
+ await expect(webhookDialog).toBeHidden();
+
+ const hookRow = page.locator("tbody tr", { hasText: HOOK_OK_URL });
+ await expect(hookRow).toBeVisible();
+ await expect(hookRow.locator('td[data-col="Headers"]')).toContainText("1 header");
+
+ await resetMockSink();
+ const hookIamRes = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.73`);
+ expect(hookIamRes.status).toBe(200);
+
+ const hookReq = await waitForSinkRequest(
+ (entry) =>
+ entry.path === "/hook/e2e" && entry.body.includes("198.51.100.73"),
+ { kind: "webhook", timeoutMs: 10_000 },
+ );
+ expect(hookReq.method).toBe("POST");
+ expect(hookReq.headers["x-e2e-hook"]).toBe("secret-val");
+ const hookPayload = JSON.parse(hookReq.body);
+ expect(hookPayload).toMatchObject({
+ iam: HOST_IAM,
+ ip: "198.51.100.73",
+ timestamp: expect.any(String),
+ });
+ expect(Number.isNaN(Date.parse(hookPayload.timestamp))).toBe(false);
+
+ await expect
+ .poll(
+ async () => {
+ await page.getByRole("button", { name: "Refresh" }).click();
+ return await hookRow.locator('td[data-col="Last Delivery"]').textContent();
+ },
+ { timeout: 10_000, intervals: [300] },
+ )
+ .toContain("200 OK");
+
+ await hookRow.getByRole("button", { name: HOST_IAM, exact: true }).click();
+ await expect(drawer).toBeVisible();
+ const hookHistoryItem = drawer
+ .locator("ol > li")
+ .filter({ hasText: "198.51.100.73" })
+ .first();
+ await expect(hookHistoryItem).toContainText("Webhook");
+ await expect(hookHistoryItem).toContainText(HOOK_OK_URL);
+ await expect(hookHistoryItem).toContainText("200 OK");
+ await drawer.getByRole("button", { name: "Close drawer" }).click();
+ await expect(drawer).toHaveCount(0);
+ await expect(page.locator("dialog.who-drawer")).toBeHidden();
+
+ // Exercise row Test button
+ await resetMockSink();
+ await hookRow.getByRole("button", { name: `Test ${HOOK_OK_URL}` }).click();
+ const testHookReq = await waitForSinkRequest(
+ (entry) =>
+ entry.path === "/hook/e2e" && entry.body.includes("198.51.100.73"),
+ { kind: "webhook", timeoutMs: 10_000 },
+ );
+ expect(testHookReq.headers["x-e2e-hook"]).toBe("secret-val");
+
+ // Pause webhook -> update IP (keep .74 unused for Touch Files) -> assert 0 deliveries
+ const hookSwitch = hookRow.getByRole("switch", {
+ name: `Webhook to ${HOOK_OK_URL}`,
+ });
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.request().method() === "PUT" &&
+ res.url().includes("/who/api/v1/webhooks/") &&
+ res.status() === 200,
+ ),
+ hookSwitch.click(),
+ ]);
+ await expect(hookSwitch).toHaveAttribute("aria-checked", "false");
+
+ await resetMockSink();
+ const pausedHookIam = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.83`);
+ expect(pausedHookIam.status).toBe(200);
+ await page.waitForTimeout(800);
+ expect(await getSinkRequests("webhook")).toEqual([]);
+
+ // Edit URL to /hook/fail, re-enable, Test -> verify 500 error badge
+ await hookRow.getByRole("button", { name: `Edit ${HOOK_OK_URL}` }).click();
+ await expect(webhookDialog).toBeVisible();
+ await webhookDialog.getByLabel(/Destination URL/i).fill(HOOK_FAIL_URL);
+ await webhookDialog.getByRole("switch", { name: "Enable webhook" }).click();
+ await webhookDialog.getByRole("button", { name: "Save Changes" }).click();
+ await expect(webhookDialog).toBeHidden();
+
+ const failHookRow = page.locator("tbody tr", { hasText: HOOK_FAIL_URL });
+ await expect(failHookRow).toBeVisible();
+ await failHookRow.getByRole("button", { name: `Test ${HOOK_FAIL_URL}` }).click();
+ await expect(failHookRow.locator('td[data-col="Last Delivery"]')).toContainText(
+ "500 Error",
+ );
+
+ await failHookRow.getByRole("button", { name: `Delete ${HOOK_FAIL_URL}` }).click();
+ const hookDelConfirm = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "Delete webhook?", level: 1 }),
+ });
+ await expect(hookDelConfirm).toBeVisible();
+ await hookDelConfirm.getByRole("button", { name: "Delete Webhook" }).click();
+ await expect(hookDelConfirm).toBeHidden();
+ await expect(failHookRow).toHaveCount(0);
+
+ // =========================================================================
+ // 3. Touch Files CRUD & Live Disk JSON Output
+ // =========================================================================
+ await page.goto("/who/#/touch");
+ await expect(page.locator("#main header h1")).toHaveText("Touch Files");
+
+ await page.getByRole("button", { name: "New Touch File" }).click();
+ const touchDialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: /Touch File/i, level: 1 }),
+ });
+ await expect(touchDialog).toBeVisible();
+
+ await touchDialog.getByLabel(/IAM Record or Alias/i).fill(ALIAS_IAM);
+ await touchDialog.getByLabel(/Destination File Path/i).fill(TOUCH_PATH_1);
+ await touchDialog.getByRole("button", { name: "Create Touch File" }).click();
+ await expect(touchDialog).toBeHidden();
+
+ const touchRow1 = page.locator("tbody tr", { hasText: TOUCH_PATH_1 });
+ await expect(touchRow1).toBeVisible();
+
+ const touchIamRes = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.74`);
+ expect(touchIamRes.status).toBe(200);
+
+ await expect
+ .poll(async () => await readTouchFile(TOUCH_FILE_1), {
+ timeout: 10_000,
+ intervals: [150],
+ })
+ .toMatchObject({
+ iam: ALIAS_IAM,
+ ip: ["198.51.100.74"],
+ last_update: expect.any(Number),
+ });
+ const written1 = await readTouchFile(TOUCH_FILE_1);
+ expect(written1.last_update).toBeGreaterThan(0);
+
+ await page.getByRole("button", { name: "Refresh" }).click();
+ await touchRow1
+ .getByRole("button", { name: `Preview JSON for ${TOUCH_PATH_1}` })
+ .click();
+ const previewDialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "Live TouchRecord Preview", level: 1 }),
+ });
+ await expect(previewDialog).toBeVisible();
+ await expect(previewDialog.locator("pre")).toContainText(ALIAS_IAM);
+ await expect(previewDialog.locator("pre")).toContainText("198.51.100.74");
+ await previewDialog.getByRole("button", { name: "Done" }).click();
+ await expect(previewDialog).toBeHidden();
+
+ // Edit touch path to v2 and click Write Now
+ await touchRow1.getByRole("button", { name: `Edit ${TOUCH_PATH_1}` }).click();
+ await expect(touchDialog).toBeVisible();
+ await touchDialog.getByLabel(/Destination File Path/i).fill(TOUCH_PATH_2);
+ await touchDialog.getByRole("button", { name: "Save Changes" }).click();
+ await expect(touchDialog).toBeHidden();
+
+ const touchRow2 = page.locator("tbody tr", { hasText: TOUCH_PATH_2 });
+ await expect(touchRow2).toBeVisible();
+ await touchRow2
+ .getByRole("button", { name: `Write Now ${TOUCH_PATH_2}` })
+ .click();
+
+ await expect
+ .poll(async () => await readTouchFile(TOUCH_FILE_2), {
+ timeout: 10_000,
+ intervals: [150],
+ })
+ .toMatchObject({
+ iam: ALIAS_IAM,
+ ip: ["198.51.100.74"],
+ last_update: expect.any(Number),
+ });
+
+ // Pause touch rule -> update IP -> assert v2 JSON file retains old IP
+ const touchSwitch = touchRow2.getByRole("switch", {
+ name: `Touch file ${TOUCH_PATH_2}`,
+ });
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.request().method() === "PUT" &&
+ res.url().includes("/who/api/v1/touch/") &&
+ res.status() === 200,
+ ),
+ touchSwitch.click(),
+ ]);
+ await expect(touchSwitch).toHaveAttribute("aria-checked", "false");
+
+ const pausedTouchIam = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.75`);
+ expect(pausedTouchIam.status).toBe(200);
+ await page.waitForTimeout(800);
+ const v2AfterPause = await readTouchFile(TOUCH_FILE_2);
+ expect(v2AfterPause?.ip).toEqual(["198.51.100.74"]);
+
+ // Delete touch rule
+ await touchRow2.getByRole("button", { name: `Delete ${TOUCH_PATH_2}` }).click();
+ const touchDelConfirm = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "Delete touch file rule?", level: 1 }),
+ });
+ await expect(touchDelConfirm).toBeVisible();
+ await touchDelConfirm.getByRole("button", { name: "Delete Rule" }).click();
+ await expect(touchDelConfirm).toBeHidden();
+ await expect(touchRow2).toHaveCount(0);
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+});
diff --git a/e2e/tests/helpers.mjs b/e2e/tests/helpers.mjs
new file mode 100644
index 0000000..c4bf4a5
--- /dev/null
+++ b/e2e/tests/helpers.mjs
@@ -0,0 +1,385 @@
+import fs from "node:fs";
+import https from "node:https";
+import path from "node:path";
+import { expect } from "@playwright/test";
+
+const E2E_ROOT = path.resolve(import.meta.dirname, "..");
+const APP_HOST = "app.who.localhost";
+const APP_PORT = 18443;
+const APP_HOST_HEADER = `${APP_HOST}:${APP_PORT}`;
+const CA_CERT_PATH = path.join(E2E_ROOT, ".generated", "certs", "ca.crt");
+const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
+
+export const APP_URL = `https://${APP_HOST_HEADER}`;
+export const AUTH_URL = `https://auth.who.localhost:${APP_PORT}`;
+export const SINK_URL = "http://127.0.0.1:19999";
+export const TOUCH_HOST_DIR = path.join(E2E_ROOT, ".generated", "touch");
+export const ADMIN_STORAGE_STATE = path.join(E2E_ROOT, ".auth", "admin.json");
+
+export const ADMIN_USER = Object.freeze({
+ username: "admin",
+ password: "AdminPass123!",
+ email: "admin@who.localhost",
+ displayName: "Admin User",
+});
+
+export const DENIED_USER = Object.freeze({
+ username: "denied",
+ password: "DeniedPass123!",
+ email: "denied@who.localhost",
+ displayName: "Denied User",
+});
+
+let cachedCA = null;
+
+function loadCACert() {
+ let stat;
+ try {
+ stat = fs.statSync(CA_CERT_PATH);
+ } catch (err) {
+ throw new Error(
+ `E2E CA certificate not found at ${CA_CERT_PATH}; run e2e/scripts/prepare.mjs or start the Compose stack first (${err.message})`,
+ );
+ }
+ if (!cachedCA || cachedCA.mtimeMs !== stat.mtimeMs) {
+ cachedCA = {
+ mtimeMs: stat.mtimeMs,
+ pem: fs.readFileSync(CA_CERT_PATH),
+ };
+ }
+ return cachedCA.pem;
+}
+
+function hasHeader(headers, targetLower) {
+ return Object.keys(headers).some((k) => k.toLowerCase() === targetLower);
+}
+
+function normalizeAppPath(rawPath) {
+ const value = String(rawPath || "/");
+ if (/^https?:\/\//i.test(value)) {
+ const parsed = new URL(value);
+ return `${parsed.pathname}${parsed.search}`;
+ }
+ return value.startsWith("/") ? value : `/${value}`;
+}
+
+function normalizeAdminApiPath(rawPath) {
+ const normalized = normalizeAppPath(rawPath);
+ if (normalized === "/who/api/v1" || normalized.startsWith("/who/api/v1/") || normalized.startsWith("/who/api/v1?")) {
+ return normalized;
+ }
+ if (normalized === "/api/v1" || normalized.startsWith("/api/v1/") || normalized.startsWith("/api/v1?")) {
+ return `/who${normalized}`;
+ }
+ return `/who/api/v1/${normalized.replace(/^\/+/, "")}`;
+}
+
+function cookieMatchesHost(cookieDomain, host) {
+ const cleanDomain = String(cookieDomain || "").toLowerCase();
+ const cleanHost = host.toLowerCase();
+ if (!cleanDomain) return false;
+ if (cleanDomain.startsWith(".")) {
+ return cleanHost === cleanDomain.slice(1) || cleanHost.endsWith(cleanDomain);
+ }
+ return cleanHost === cleanDomain;
+}
+
+function readAdminCookieHeader(urlPath = "/who/") {
+ let raw;
+ try {
+ raw = fs.readFileSync(ADMIN_STORAGE_STATE, "utf8");
+ } catch (err) {
+ throw new Error(
+ `Admin storageState not found at ${ADMIN_STORAGE_STATE}; run the Playwright setup project first (${err.message})`,
+ );
+ }
+
+ const state = JSON.parse(raw);
+ const nowSec = Date.now() / 1000;
+ const pathOnly = normalizeAppPath(urlPath).split("?")[0];
+ const matching = (state.cookies || []).filter((cookie) => {
+ if (!cookieMatchesHost(cookie.domain, APP_HOST)) return false;
+ if (cookie.expires && cookie.expires !== -1 && cookie.expires <= nowSec) return false;
+ const cookiePath = cookie.path || "/";
+ return pathOnly.startsWith(cookiePath);
+ });
+
+ if (!matching.some((cookie) => cookie.name === "who_session" && cookie.value)) {
+ throw new Error(
+ `No active who_session cookie found for ${pathOnly} in ${ADMIN_STORAGE_STATE}`,
+ );
+ }
+
+ return matching.map((cookie) => `${cookie.name}=${cookie.value}`).join("; ");
+}
+
+function tryParseJSON(text) {
+ if (!text) return null;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Issue a raw HTTPS request directly to Traefik on 127.0.0.1:18443 using SNI
+ * `app.who.localhost` and the generated E2E CA, bypassing Node DNS lookup for
+ * `*.who.localhost` (which fails on WSL2 without nss-myhostname).
+ *
+ * @param {string} method
+ * @param {string} urlPath
+ * @param {object} [options]
+ * @param {unknown} [options.body]
+ * @param {Record} [options.headers]
+ * @param {string} [options.cookieHeader]
+ * @param {boolean} [options.useAdminAuth]
+ * @returns {Promise<{
+ * status: number,
+ * ok: boolean,
+ * headers: import("node:http").IncomingHttpHeaders,
+ * text: string,
+ * data: any,
+ * json: () => any,
+ * }>}
+ */
+export async function rawAppFetch(method, urlPath, options = {}) {
+ const {
+ body,
+ headers = {},
+ cookieHeader,
+ useAdminAuth = false,
+ } = options;
+
+ const upperMethod = String(method || "GET").toUpperCase();
+ const requestPath = normalizeAppPath(urlPath);
+ const reqHeaders = {};
+
+ for (const [key, value] of Object.entries(headers)) {
+ if (value !== undefined && value !== null) {
+ reqHeaders[key] = String(value);
+ }
+ }
+ if (!hasHeader(reqHeaders, "host")) {
+ reqHeaders.Host = APP_HOST_HEADER;
+ }
+ if (cookieHeader) {
+ reqHeaders.Cookie = cookieHeader;
+ } else if (useAdminAuth && !hasHeader(reqHeaders, "cookie")) {
+ reqHeaders.Cookie = readAdminCookieHeader(requestPath);
+ }
+
+ let payloadBuffer = null;
+ if (body !== undefined && body !== null) {
+ if (Buffer.isBuffer(body)) {
+ payloadBuffer = body;
+ } else if (typeof body === "string") {
+ payloadBuffer = Buffer.from(body, "utf8");
+ } else {
+ payloadBuffer = Buffer.from(JSON.stringify(body), "utf8");
+ if (!hasHeader(reqHeaders, "content-type")) {
+ reqHeaders["Content-Type"] = "application/json";
+ }
+ }
+ if (!hasHeader(reqHeaders, "content-length")) {
+ reqHeaders["Content-Length"] = String(payloadBuffer.byteLength);
+ }
+ }
+
+ const ca = loadCACert();
+
+ return await new Promise((resolve, reject) => {
+ const req = https.request(
+ {
+ host: "127.0.0.1",
+ port: APP_PORT,
+ servername: APP_HOST,
+ ca,
+ rejectUnauthorized: true,
+ method: upperMethod,
+ path: requestPath,
+ headers: reqHeaders,
+ },
+ (res) => {
+ const chunks = [];
+ res.on("data", (chunk) => chunks.push(chunk));
+ res.on("end", () => {
+ const text = Buffer.concat(chunks).toString("utf8");
+ const status = res.statusCode ?? 0;
+ resolve({
+ status,
+ ok: status >= 200 && status < 300,
+ headers: res.headers,
+ text,
+ data: tryParseJSON(text),
+ json() {
+ return JSON.parse(text);
+ },
+ });
+ });
+ },
+ );
+ req.on("error", reject);
+ if (payloadBuffer) {
+ req.write(payloadBuffer);
+ }
+ req.end();
+ });
+}
+
+/**
+ * Call the authenticated `/who/api/v1/*` JSON management API using the saved
+ * admin session from `e2e/.auth/admin.json` by default.
+ *
+ * @param {string} method
+ * @param {string} apiPath
+ * @param {object} [options]
+ * @param {unknown} [options.body]
+ * @param {Record} [options.headers]
+ * @param {boolean} [options.csrf] Defaults to true on mutating methods; set explicitly for GET CSRF endpoints like `/backup/export`.
+ * @param {string} [options.cookieHeader]
+ * @param {boolean} [options.useAdminAuth]
+ */
+export async function apiFetch(method, apiPath, options = {}) {
+ const {
+ body,
+ headers = {},
+ csrf,
+ cookieHeader,
+ useAdminAuth = true,
+ } = options;
+
+ const upperMethod = String(method || "GET").toUpperCase();
+ const mergedHeaders = { ...headers };
+ const shouldSendCSRF =
+ csrf === true || (csrf !== false && MUTATING_METHODS.has(upperMethod));
+
+ if (shouldSendCSRF && !hasHeader(mergedHeaders, "x-who-csrf")) {
+ mergedHeaders["X-Who-CSRF"] = "1";
+ }
+
+ return await rawAppFetch(upperMethod, normalizeAdminApiPath(apiPath), {
+ body,
+ headers: mergedHeaders,
+ cookieHeader,
+ useAdminAuth,
+ });
+}
+
+/**
+ * Drive a full browser OIDC login from `/who/` through Authelia 4.39 + GLAuth
+ * and wait for the redirect back to `https://app.who.localhost:18443/who/...`.
+ *
+ * @param {import("@playwright/test").Page} page
+ * @param {{ username: string, password: string }} [creds]
+ */
+export async function loginViaAuthelia(page, creds = ADMIN_USER) {
+ await page.goto(`${APP_URL}/who/`);
+ const loginLink = page.locator('a[href="./auth/oidc/login"]');
+ await expect(loginLink).toBeVisible();
+ await expect(loginLink).toContainText(/Continue with OIDC/i);
+ await loginLink.click();
+
+ await page.waitForURL((url) => url.origin === AUTH_URL, { timeout: 20_000 });
+
+ const usernameField = page.locator("#username-textfield");
+ const passwordField = page.locator("#password-textfield");
+ const signInButton = page.locator("#sign-in-button");
+
+ await expect(usernameField).toBeVisible();
+ await usernameField.fill(creds.username);
+ await passwordField.fill(creds.password);
+ await signInButton.click();
+
+ await page.waitForURL(
+ (url) =>
+ url.origin === APP_URL &&
+ url.pathname.startsWith("/who/") &&
+ !url.pathname.startsWith("/who/auth/"),
+ { timeout: 20_000 },
+ );
+}
+
+/**
+ * Clear all captured requests on `mock-sink`.
+ *
+ * @returns {Promise<{ ok: boolean }>}
+ */
+export async function resetMockSink() {
+ const res = await fetch(`${SINK_URL}/_requests`, { method: "DELETE" });
+ if (!res.ok) {
+ throw new Error(`Failed to reset mock-sink: HTTP ${res.status}`);
+ }
+ return await res.json();
+}
+
+/**
+ * Fetch captured requests from `mock-sink`, optionally filtered by `"ddns"` or `"webhook"`.
+ *
+ * @param {"ddns" | "webhook"} [kind]
+ * @returns {Promise>>}
+ */
+export async function getSinkRequests(kind) {
+ const query = kind ? `?kind=${encodeURIComponent(kind)}` : "";
+ const res = await fetch(`${SINK_URL}/_requests${query}`);
+ if (!res.ok) {
+ throw new Error(`Failed to fetch mock-sink requests: HTTP ${res.status}`);
+ }
+ return await res.json();
+}
+
+/**
+ * Poll `mock-sink` until a captured request matches `predicate`, returning that entry.
+ *
+ * @param {(entry: Record) => boolean} predicate
+ * @param {number | { kind?: "ddns" | "webhook", timeoutMs?: number, intervalMs?: number }} [optionsOrTimeout]
+ * @returns {Promise>}
+ */
+export async function waitForSinkRequest(predicate, optionsOrTimeout = {}) {
+ const {
+ kind,
+ timeoutMs = 10_000,
+ intervalMs = 150,
+ } = typeof optionsOrTimeout === "number"
+ ? { timeoutMs: optionsOrTimeout }
+ : optionsOrTimeout;
+
+ let matched = null;
+ await expect
+ .poll(
+ async () => {
+ const entries = await getSinkRequests(kind);
+ matched = entries.find((entry) => predicate(entry)) ?? null;
+ return matched;
+ },
+ { timeout: timeoutMs, intervals: [intervalMs] },
+ )
+ .not.toBeNull();
+
+ return matched;
+}
+
+/**
+ * Read and parse a JSON touch file from `e2e/.generated/touch`.
+ * Returns `null` if the file does not exist yet or is mid-write (incomplete JSON),
+ * making it safe to poll directly inside Playwright `expect.poll(...)`.
+ *
+ * @param {string} filename
+ * @returns {Promise | null>}
+ */
+export async function readTouchFile(filename) {
+ const targetPath = path.resolve(TOUCH_HOST_DIR, filename);
+ const rel = path.relative(TOUCH_HOST_DIR, targetPath);
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) {
+ throw new Error(`Refusing to read touch file outside ${TOUCH_HOST_DIR}: ${filename}`);
+ }
+ try {
+ const content = await fs.promises.readFile(targetPath, "utf8");
+ return JSON.parse(content);
+ } catch (err) {
+ if (err?.code === "ENOENT" || err instanceof SyntaxError) {
+ return null;
+ }
+ throw err;
+ }
+}
diff --git a/e2e/tests/logs-and-settings.spec.mjs b/e2e/tests/logs-and-settings.spec.mjs
new file mode 100644
index 0000000..32242b7
--- /dev/null
+++ b/e2e/tests/logs-and-settings.spec.mjs
@@ -0,0 +1,467 @@
+import fs from "node:fs";
+import { expect, test } from "@playwright/test";
+import { ADMIN_USER, apiFetch, rawAppFetch } from "./helpers.mjs";
+
+const LOG_HOST = "e2e-log-host";
+const BACKUP_REC = "e2e-backup-rec";
+
+let originalSettings = {
+ accessLogRetentionDays: 30,
+ auditLogRetentionDays: 90,
+ ipHistoryRetentionDays: 0,
+};
+
+function attachErrorCollector(page) {
+ const pageErrors = [];
+ const consoleErrors = [];
+ page.on("pageerror", (err) => {
+ pageErrors.push(err?.message || String(err));
+ });
+ page.on("console", (msg) => {
+ if (msg.type() === "error") {
+ consoleErrors.push(msg.text());
+ }
+ });
+ return { pageErrors, consoleErrors };
+}
+
+function toLocalDatetimeInput(ms) {
+ const pad2 = (n) => String(n).padStart(2, "0");
+ const d = new Date(ms);
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
+}
+
+test.describe("Access Log, Audit Log & Settings", () => {
+ test.beforeAll(async () => {
+ for (const iam of [LOG_HOST, BACKUP_REC]) {
+ await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ }
+
+ const settingsRes = await apiFetch("GET", "/settings");
+ if (settingsRes.ok && settingsRes.data) {
+ originalSettings = {
+ accessLogRetentionDays: settingsRes.data.accessLogRetentionDays ?? 30,
+ auditLogRetentionDays: settingsRes.data.auditLogRetentionDays ?? 90,
+ ipHistoryRetentionDays: settingsRes.data.ipHistoryRetentionDays ?? 0,
+ };
+ }
+
+ const createRes = await apiFetch("POST", "/records", {
+ body: { iam: LOG_HOST, isAlias: false, ip: "198.51.100.90" },
+ });
+ expect(createRes.status).toBe(201);
+
+ const updateRes = await apiFetch("PUT", `/records/${LOG_HOST}`, {
+ body: { iam: LOG_HOST, isAlias: false, ip: "198.51.100.91" },
+ });
+ expect(updateRes.status).toBe(200);
+
+ const headers = { "User-Agent": "who-e2e-logs/1.0" };
+ for (let i = 0; i < 18; i++) {
+ const res = await rawAppFetch("GET", "/whoami", { headers });
+ expect(res.status).toBe(200);
+ }
+ for (let i = 0; i < 6; i++) {
+ const ip = `198.51.100.${92 + (i % 2)}`;
+ const res = await rawAppFetch("GET", `/iam/${LOG_HOST}/${ip}`, { headers });
+ expect(res.status).toBe(200);
+ }
+ for (let i = 0; i < 6; i++) {
+ const res = await rawAppFetch("GET", `/whois/${LOG_HOST}`, { headers });
+ expect(res.status).toBe(200);
+ }
+
+ await expect
+ .poll(
+ async () => {
+ const all = await apiFetch("GET", "/access-logs?range=1h&pageSize=1");
+ return all.data?.total ?? 0;
+ },
+ { timeout: 10_000, intervals: [150] },
+ )
+ .toBeGreaterThanOrEqual(30);
+
+ await expect
+ .poll(
+ async () => {
+ const iam = await apiFetch(
+ "GET",
+ `/access-logs?range=1h&endpoint=iam&iam=${LOG_HOST}&pageSize=1`,
+ );
+ return iam.data?.total ?? 0;
+ },
+ { timeout: 10_000, intervals: [150] },
+ )
+ .toBeGreaterThanOrEqual(6);
+ });
+
+ test.afterAll(async () => {
+ await apiFetch("PUT", "/settings", { body: originalSettings });
+ for (const iam of [LOG_HOST, BACKUP_REC]) {
+ const res = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ expect([200, 204, 404]).toContain(res.status);
+ }
+ });
+
+ test("Access Log: TimeRangePicker layout/presets/custom, FilterBar autocomplete, AccessDrawer, Top view, and Pagination", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/#/access");
+ await expect(page.locator("#main header h1")).toHaveText("Access Log");
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+
+ // Refresh sits to the left of TimeRangePicker
+ const refreshBtn = page.getByRole("button", { name: "Refresh" });
+ const timePickerBtn = page.getByRole("button", { name: /^Time range:/ });
+ const [refreshBox, pickerBox] = await Promise.all([
+ refreshBtn.boundingBox(),
+ timePickerBtn.boundingBox(),
+ ]);
+ expect(refreshBox).not.toBeNull();
+ expect(pickerBox).not.toBeNull();
+ expect(refreshBox.x).toBeLessThan(pickerBox.x);
+ expect(refreshBox.x + refreshBox.width).toBeLessThanOrEqual(pickerBox.x + 2);
+
+ // Presets 1h -> 24h -> custom range -> Reset
+ await timePickerBtn.click();
+ const pickerPopover = page.locator('[popover="auto"]:popover-open');
+ await expect(pickerPopover).toBeVisible();
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("range=1h") &&
+ res.status() === 200,
+ ),
+ pickerPopover.getByRole("button", { name: /Last 1 hour/ }).click(),
+ ]);
+ await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 1 hour/);
+
+ await timePickerBtn.click();
+ await expect(pickerPopover).toBeVisible();
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("range=24h") &&
+ res.status() === 200,
+ ),
+ pickerPopover.getByRole("button", { name: /Last 24 hours/ }).click(),
+ ]);
+ await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 24 hours/);
+
+ const nowMs = Date.now();
+ await timePickerBtn.click();
+ await expect(pickerPopover).toBeVisible();
+ await pickerPopover
+ .getByLabel("Start")
+ .fill(toLocalDatetimeInput(nowMs - 2 * 3_600_000));
+ await pickerPopover
+ .getByLabel("End")
+ .fill(toLocalDatetimeInput(nowMs + 3_600_000));
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("from=") &&
+ res.url().includes("to=") &&
+ res.status() === 200,
+ ),
+ pickerPopover.getByRole("button", { name: "Apply" }).click(),
+ ]);
+ await expect(timePickerBtn).not.toHaveAttribute("aria-label", /Last 24 hours/);
+
+ await timePickerBtn.click();
+ await expect(pickerPopover).toBeVisible();
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("range=24h") &&
+ res.status() === 200,
+ ),
+ pickerPopover.getByRole("button", { name: "Reset" }).click(),
+ ]);
+ await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 24 hours/);
+
+ // FilterBar autocomplete -> endpoint:iam -> AccessDrawer
+ const filterInput = page.locator("[data-search-input]");
+ await filterInput.click();
+ await filterInput.fill("endpoint:");
+ const suggestions = page.getByRole("listbox", { name: "endpoint suggestions" });
+ await expect(suggestions).toBeVisible();
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("endpoint=iam") &&
+ res.status() === 200,
+ ),
+ suggestions.getByRole("option", { name: /\/iam/ }).click(),
+ ]);
+ await expect(
+ page.getByRole("button", { name: "Remove endpoint:iam filter" }),
+ ).toBeVisible();
+
+ const firstRow = page.locator("tbody tr").first();
+ await expect(firstRow.locator('th[scope="row"]')).toContainText("/iam");
+ await firstRow.click();
+
+ const drawer = page.locator("#main dialog.who-drawer");
+ await expect(drawer).toBeVisible();
+ await expect(drawer).toContainText("Client & Resolution Metadata");
+ await expect(drawer).toContainText("Timestamps");
+ await drawer.getByRole("button", { name: "Close drawer" }).click();
+ await expect(drawer).toBeHidden();
+
+ // Toggle List | Top -> 5 TopBreakdown cards -> click Top item -> chip added -> List
+ const viewModeGroup = page.getByRole("group", { name: "View mode" });
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("view=top") &&
+ res.status() === 200,
+ ),
+ viewModeGroup.getByRole("button", { name: "Top" }).click(),
+ ]);
+
+ const topCards = page.locator("section", {
+ has: page.locator("h2", { hasText: /^Top / }),
+ });
+ await expect(topCards).toHaveCount(5);
+
+ const topIamsCard = page.locator("section", {
+ has: page.locator("h2", { hasText: "Top IAMs" }),
+ });
+ const firstTopIamBtn = topIamsCard.locator("ul button").first();
+ await expect(firstTopIamBtn).toBeVisible();
+ await firstTopIamBtn.click();
+ await expect(
+ page.locator('button[aria-label^="Remove iam:"][aria-label$=" filter"]'),
+ ).toBeVisible();
+
+ await viewModeGroup.getByRole("button", { name: "List" }).click();
+ await page.getByRole("button", { name: "Clear all filters" }).click();
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+
+ // Pagination page size change + Next page navigation
+ const rowsPerPage = page.getByLabel("Rows per page");
+ await expect(rowsPerPage).toBeVisible();
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("pageSize=25") &&
+ res.status() === 200,
+ ),
+ rowsPerPage.selectOption("25"),
+ ]);
+ await expect(page.locator("#main")).toContainText("Showing 1–25 of");
+
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/access-logs") &&
+ res.url().includes("page=2") &&
+ res.status() === 200,
+ ),
+ page.getByRole("button", { name: "Next page" }).click(),
+ ]);
+ await expect(page.locator("#main")).toContainText("Showing 26–");
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+
+ test("Audit Log: TimeRangePicker default All time reset, category:record filter, and Top drill-down", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/#/audit");
+ await expect(page.locator("#main header h1")).toHaveText("Audit Log");
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+
+ const refreshBtn = page.getByRole("button", { name: "Refresh" });
+ const timePickerBtn = page.getByRole("button", { name: /^Time range:/ });
+ const [refreshBox, pickerBox] = await Promise.all([
+ refreshBtn.boundingBox(),
+ timePickerBtn.boundingBox(),
+ ]);
+ expect(refreshBox).not.toBeNull();
+ expect(pickerBox).not.toBeNull();
+ expect(refreshBox.x).toBeLessThan(pickerBox.x);
+ expect(refreshBox.x + refreshBox.width).toBeLessThanOrEqual(pickerBox.x + 2);
+
+ await expect(timePickerBtn).toHaveAttribute("aria-label", /All time/);
+ await timePickerBtn.click();
+ const pickerPopover = page.locator('[popover="auto"]:popover-open');
+ await expect(pickerPopover).toBeVisible();
+ await pickerPopover.getByRole("button", { name: /Last 1 hour/ }).click();
+ await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 1 hour/);
+
+ await timePickerBtn.click();
+ await expect(pickerPopover).toBeVisible();
+ await pickerPopover.getByRole("button", { name: "Reset" }).click();
+ await expect(timePickerBtn).toHaveAttribute("aria-label", /All time/);
+
+ const filterInput = page.locator("[data-search-input]");
+ await filterInput.click();
+ await filterInput.fill("category:");
+ const suggestions = page.getByRole("listbox", { name: "category suggestions" });
+ await expect(suggestions).toBeVisible();
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/audit-logs") &&
+ res.url().includes("category=record") &&
+ res.status() === 200,
+ ),
+ suggestions.getByRole("option", { name: /^record\b/ }).click(),
+ ]);
+ await expect(
+ page.getByRole("button", { name: "Remove category:record filter" }),
+ ).toBeVisible();
+ await expect(
+ page.locator("tbody tr").first().locator('td[data-col="Action"]'),
+ ).toContainText("record");
+
+ const viewModeGroup = page.getByRole("group", { name: "View mode" });
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/audit-logs") &&
+ res.url().includes("view=top") &&
+ res.status() === 200,
+ ),
+ viewModeGroup.getByRole("button", { name: "Top" }).click(),
+ ]);
+
+ const topCards = page.locator("section", {
+ has: page.locator("h2", { hasText: /^Top / }),
+ });
+ await expect(topCards).toHaveCount(5);
+
+ const topActionsCard = page.locator("section", {
+ has: page.locator("h2", { hasText: "Top Actions" }),
+ });
+ const firstActionBtn = topActionsCard.locator("ul button").first();
+ await expect(firstActionBtn).toBeVisible();
+ await firstActionBtn.click();
+ await expect(
+ page.locator('button[aria-label^="Remove action:"][aria-label$=" filter"]'),
+ ).toBeVisible();
+
+ await viewModeGroup.getByRole("button", { name: "List" }).click();
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+
+ test("Settings: retention persistence, Backup export/merge import, and active session badge", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/#/settings");
+ await expect(page.locator("#main header h1")).toHaveText("Settings");
+
+ // 1. Retention persistence across reload
+ const retentionSection = page.locator("#settings-retention");
+ const accessDaysInput = page.getByLabel(/Access log retention \(days\)/i);
+ await expect(accessDaysInput).toHaveValue(
+ String(originalSettings.accessLogRetentionDays),
+ );
+
+ await accessDaysInput.fill("45");
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().endsWith("/who/api/v1/settings") &&
+ res.request().method() === "PUT" &&
+ res.status() === 200,
+ ),
+ retentionSection.getByRole("button", { name: "Save", exact: true }).click(),
+ ]);
+
+ await page.reload();
+ await expect(page.locator("#main header h1")).toHaveText("Settings");
+ await expect(page.getByLabel(/Access log retention \(days\)/i)).toHaveValue("45");
+
+ await page
+ .getByLabel(/Access log retention \(days\)/i)
+ .fill(String(originalSettings.accessLogRetentionDays));
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().endsWith("/who/api/v1/settings") &&
+ res.request().method() === "PUT" &&
+ res.status() === 200,
+ ),
+ page
+ .locator("#settings-retention")
+ .getByRole("button", { name: "Save", exact: true })
+ .click(),
+ ]);
+
+ // 2. Export Backup JSON via download event
+ const backupSection = page.locator("#settings-backup");
+ const [download] = await Promise.all([
+ page.waitForEvent("download"),
+ backupSection.getByRole("button", { name: "Export JSON" }).click(),
+ ]);
+ expect(download.suggestedFilename()).toBe("who-backup.json");
+ const downloadPath = await download.path();
+ expect(downloadPath).toBeTruthy();
+ const exported = JSON.parse(await fs.promises.readFile(downloadPath, "utf8"));
+ expect(exported).toMatchObject({
+ who: expect.any(Array),
+ secrets: expect.any(Array),
+ ddns: expect.any(Array),
+ webhooks: expect.any(Array),
+ touch: expect.any(Array),
+ });
+
+ // 3. Merge Backup JSON import + /whois verification + cleanup
+ const mergeBackup = {
+ who: [{ iam: BACKUP_REC, ip: "198.51.100.99" }],
+ };
+ await page.getByLabel("Backup JSON File").setInputFiles({
+ name: "e2e-merge-backup.json",
+ mimeType: "application/json",
+ buffer: Buffer.from(JSON.stringify(mergeBackup)),
+ });
+ await expect(backupSection).toContainText("e2e-merge-backup.json");
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes("/who/api/v1/backup/import") &&
+ res.request().method() === "POST" &&
+ res.status() === 200,
+ ),
+ backupSection.getByRole("button", { name: "Import JSON" }).click(),
+ ]);
+
+ const importedWhois = await rawAppFetch("GET", `/whois/${BACKUP_REC}`);
+ expect(importedWhois.status).toBe(200);
+ expect(importedWhois.text.trim()).toBe("198.51.100.99");
+
+ const cleanupBackupRec = await apiFetch("DELETE", `/records/${BACKUP_REC}`);
+ expect([200, 204, 404]).toContain(cleanupBackupRec.status);
+
+ // 4. Active Sign-In Sessions shows admin@who.localhost with Current badge
+ const sessionsList = page.getByRole("list", { name: "Active OIDC sessions" });
+ await expect(sessionsList).toBeVisible();
+ const currentSession = sessionsList
+ .locator("li", { hasText: ADMIN_USER.email })
+ .filter({ hasText: "Current" });
+ await expect(currentSession.first()).toBeVisible();
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+});
diff --git a/e2e/tests/mobile-layout.spec.mjs b/e2e/tests/mobile-layout.spec.mjs
new file mode 100644
index 0000000..587a212
--- /dev/null
+++ b/e2e/tests/mobile-layout.spec.mjs
@@ -0,0 +1,265 @@
+import { expect, test } from "@playwright/test";
+import { APP_URL, apiFetch, rawAppFetch } from "./helpers.mjs";
+
+const MOBILE_RECORDS = Array.from(
+ { length: 25 },
+ (_, idx) => `e2e-mob-${String(idx + 1).padStart(2, "0")}`,
+);
+
+const OVERFLOW_VIEWS = [
+ {
+ id: "overview",
+ heading: "Overview",
+ waitReady: async (page) => {
+ await expect(page.locator('section[aria-label="Key metrics"]')).toBeVisible();
+ await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0);
+ },
+ },
+ {
+ id: "records",
+ heading: "Records",
+ waitReady: async (page) => {
+ await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0);
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+ },
+ },
+ {
+ id: "access",
+ heading: "Access Log",
+ waitReady: async (page) => {
+ await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0);
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+ },
+ },
+ {
+ id: "audit",
+ heading: "Audit Log",
+ waitReady: async (page) => {
+ await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0);
+ await expect(page.locator("tbody tr").first()).toBeVisible();
+ },
+ },
+ {
+ id: "settings",
+ heading: "Settings",
+ waitReady: async (page) => {
+ await expect(page.locator("#settings-backup")).toBeVisible();
+ await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0);
+ },
+ },
+];
+
+function attachErrorCollector(page) {
+ const pageErrors = [];
+ const consoleErrors = [];
+ page.on("pageerror", (err) => {
+ pageErrors.push(err?.message || String(err));
+ });
+ page.on("console", (msg) => {
+ if (msg.type() === "error") {
+ consoleErrors.push(msg.text());
+ }
+ });
+ return { pageErrors, consoleErrors };
+}
+
+async function measureMainAndHeader(page, scrollTarget) {
+ return await page.evaluate(async (targetTop) => {
+ const main = document.getElementById("main");
+ const header = main?.querySelector("header");
+ if (!main || !header) {
+ return null;
+ }
+
+ if (typeof targetTop === "number") {
+ main.scrollTop = targetTop;
+ await new Promise((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve)),
+ );
+ }
+
+ const rect = header.getBoundingClientRect();
+ return {
+ scrollHeight: main.scrollHeight,
+ clientHeight: main.clientHeight,
+ scrollTop: main.scrollTop,
+ headerHeight: rect.height,
+ headerTop: rect.top,
+ docScrollWidth: document.documentElement.scrollWidth,
+ innerWidth: window.innerWidth,
+ };
+ }, scrollTarget);
+}
+
+test.describe("Mobile Viewport Layout, Sticky Header & Navigation Drawer (390x844)", () => {
+ test.beforeAll(async () => {
+ for (const iam of MOBILE_RECORDS) {
+ await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ }
+
+ const beforeAccessRes = await apiFetch("GET", "/access-logs?range=1h&pageSize=1");
+ expect(beforeAccessRes.status).toBe(200);
+ const beforeAccessTotal = beforeAccessRes.data?.total ?? 0;
+
+ for (let i = 0; i < MOBILE_RECORDS.length; i++) {
+ const iam = MOBILE_RECORDS[i];
+ const res = await apiFetch("POST", "/records", {
+ body: {
+ iam,
+ isAlias: false,
+ ip: `198.51.100.${101 + i}`,
+ },
+ });
+ expect(res.status).toBe(201);
+ }
+
+ const headers = { "User-Agent": "who-e2e-mobile/1.0" };
+ for (let i = 0; i < 10; i++) {
+ const res = await rawAppFetch("GET", "/whoami", { headers });
+ expect(res.status).toBe(200);
+ }
+ for (let i = 0; i < 10; i++) {
+ const iam = MOBILE_RECORDS[i];
+ const res = await rawAppFetch("GET", `/iam/${iam}/198.51.100.${201 + i}`, {
+ headers,
+ });
+ expect(res.status).toBe(200);
+ }
+ for (let i = 0; i < 10; i++) {
+ const iam = MOBILE_RECORDS[i];
+ const res = await rawAppFetch("GET", `/whois/${iam}`, { headers });
+ expect(res.status).toBe(200);
+ }
+
+ await expect
+ .poll(
+ async () => {
+ const all = await apiFetch("GET", "/access-logs?range=1h&pageSize=1");
+ return all.data?.total ?? 0;
+ },
+ { timeout: 10_000, intervals: [150] },
+ )
+ .toBeGreaterThanOrEqual(beforeAccessTotal + 30);
+
+ const auditCheck = await apiFetch("GET", "/audit-logs?pageSize=1");
+ expect(auditCheck.status).toBe(200);
+ expect(auditCheck.data?.total ?? 0).toBeGreaterThanOrEqual(25);
+ });
+
+ test.afterAll(async () => {
+ for (const iam of MOBILE_RECORDS) {
+ const res = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ expect([200, 204, 404]).toContain(res.status);
+ }
+ });
+
+ test("keeps 48px sticky header height before/after scroll and zero horizontal overflow across views", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ for (const view of OVERFLOW_VIEWS) {
+ await page.goto(`/who/#/${view.id}`);
+ await expect(page.locator("#main header h1")).toHaveText(view.heading);
+ await view.waitReady(page);
+ await page.waitForLoadState("networkidle");
+
+ const before = await measureMainAndHeader(page, 0);
+ expect(before, `Missing #main or on #/${view.id}`).not.toBeNull();
+ expect(
+ before.scrollHeight,
+ `Expected #main to overflow 844px viewport on #/${view.id}`,
+ ).toBeGreaterThan(before.clientHeight);
+ expect(
+ before.headerHeight,
+ `Initial header height on #/${view.id}`,
+ ).toBeGreaterThanOrEqual(47);
+ expect(
+ before.headerHeight,
+ `Initial header height on #/${view.id}`,
+ ).toBeLessThanOrEqual(49);
+ expect(
+ before.headerTop,
+ `Initial header top on #/${view.id}`,
+ ).toBeGreaterThanOrEqual(-1);
+ expect(
+ before.headerTop,
+ `Initial header top on #/${view.id}`,
+ ).toBeLessThanOrEqual(1);
+ expect(
+ before.docScrollWidth,
+ `Initial horizontal overflow on #/${view.id}`,
+ ).toBeLessThanOrEqual(before.innerWidth + 1);
+
+ const after = await measureMainAndHeader(page, 400);
+ expect(after, `Missing #main or after scroll on #/${view.id}`).not.toBeNull();
+ expect(
+ after.scrollTop,
+ `Expected #main to scroll on #/${view.id}`,
+ ).toBeGreaterThan(0);
+ expect(
+ after.headerHeight,
+ `Scrolled header height on #/${view.id}`,
+ ).toBeGreaterThanOrEqual(47);
+ expect(
+ after.headerHeight,
+ `Scrolled header height on #/${view.id}`,
+ ).toBeLessThanOrEqual(49);
+ expect(
+ after.headerTop,
+ `Sticky header top after scroll on #/${view.id}`,
+ ).toBeGreaterThanOrEqual(-1);
+ expect(
+ after.headerTop,
+ `Sticky header top after scroll on #/${view.id}`,
+ ).toBeLessThanOrEqual(1);
+ expect(
+ after.docScrollWidth,
+ `Horizontal overflow after scroll on #/${view.id}`,
+ ).toBeLessThanOrEqual(after.innerWidth + 1);
+
+ console.log(
+ `[mobile-layout] #/${view.id}: scrollHeight=${before.scrollHeight} clientHeight=${before.clientHeight} scrollTop=${after.scrollTop} header0=${before.headerHeight}px header400=${after.headerHeight}px top=${after.headerTop}px docWidth=${after.docScrollWidth}/${after.innerWidth}`,
+ );
+ }
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+
+ test("opens mobile navigation drawer via hamburger, navigates to Touch Files, and closes cleanly", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/#/overview");
+ await expect(page.locator("#main header h1")).toHaveText("Overview");
+ await expect(page.locator('aside[aria-label="Main navigation"]')).toBeHidden();
+
+ const menuButton = page.getByRole("button", { name: "Open navigation menu" });
+ await expect(menuButton).toBeVisible();
+ await menuButton.click();
+
+ const mobileDrawer = page.locator(
+ 'dialog.mobile-nav-dialog[aria-label="Main navigation"]',
+ );
+ await expect(mobileDrawer).toBeVisible();
+ await expect(mobileDrawer).toHaveAttribute("open", "");
+
+ await mobileDrawer.getByRole("link", { name: "Touch Files", exact: true }).click();
+
+ await expect(mobileDrawer).toBeHidden();
+ await expect(mobileDrawer).not.toHaveAttribute("open", "");
+ await expect(page).toHaveURL(`${APP_URL}/who/#/touch`);
+ await expect(page.locator("#main header h1")).toHaveText("Touch Files");
+
+ const touchMetrics = await measureMainAndHeader(page, 0);
+ expect(touchMetrics).not.toBeNull();
+ expect(touchMetrics.headerHeight).toBeGreaterThanOrEqual(47);
+ expect(touchMetrics.headerHeight).toBeLessThanOrEqual(49);
+ expect(touchMetrics.docScrollWidth).toBeLessThanOrEqual(touchMetrics.innerWidth + 1);
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+});
diff --git a/e2e/tests/navigation-and-overview.spec.mjs b/e2e/tests/navigation-and-overview.spec.mjs
new file mode 100644
index 0000000..f1805c0
--- /dev/null
+++ b/e2e/tests/navigation-and-overview.spec.mjs
@@ -0,0 +1,231 @@
+import { expect, test } from "@playwright/test";
+import { APP_URL } from "./helpers.mjs";
+
+const SECTIONS = [
+ { id: "overview", label: "Overview" },
+ { id: "records", label: "Records" },
+ { id: "ddns", label: "DDNS" },
+ { id: "webhooks", label: "Webhooks" },
+ { id: "touch", label: "Touch Files" },
+ { id: "access", label: "Access Log" },
+ { id: "audit", label: "Audit Log" },
+ { id: "settings", label: "Settings" },
+];
+
+function attachErrorCollector(page) {
+ const pageErrors = [];
+ const consoleErrors = [];
+ page.on("pageerror", (err) => {
+ pageErrors.push(err?.message || String(err));
+ });
+ page.on("console", (msg) => {
+ if (msg.type() === "error") {
+ consoleErrors.push(msg.text());
+ }
+ });
+ return { pageErrors, consoleErrors };
+}
+
+test.describe("Desktop Navigation, Overview, Shortcuts, Theme & Zero Idle Polling", () => {
+ test("loads Overview KPI cards and 24h traffic chart with zero console or page errors", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/");
+ await expect(page).toHaveURL(`${APP_URL}/who/#/overview`);
+ await expect(
+ page.locator("#main header h1"),
+ ).toHaveText("Overview");
+
+ const kpiSection = page.locator('section[aria-label="Key metrics"]');
+ await expect(kpiSection).toBeVisible();
+ await expect(kpiSection.getByText("Managed Records")).toBeVisible();
+ await expect(kpiSection.getByText("24h IP Changes")).toBeVisible();
+ await expect(kpiSection.getByText("DDNS Health")).toBeVisible();
+ await expect(kpiSection.getByText("24h Traffic")).toBeVisible();
+
+ const chartSection = page.locator('section[aria-label="24-hour request volume"]');
+ await expect(chartSection).toBeVisible();
+ await expect(
+ chartSection.getByRole("heading", { name: "24-Hour Request Strip", level: 2 }),
+ ).toBeVisible();
+ await expect(
+ chartSection.getByRole("group", { name: "Hourly request buckets" }),
+ ).toBeVisible();
+
+ await expect(
+ page.getByRole("heading", { name: "Recent IP Transitions", level: 2 }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("heading", { name: "Recent Delivery Failures", level: 2 }),
+ ).toBeVisible();
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+
+ test("navigates across all 8 sections via Sidebar and redirects legacy integrations routes", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/");
+ await expect(page.locator("#main header h1")).toHaveText("Overview");
+
+ const sidebar = page.locator('aside[aria-label="Main navigation"]');
+ for (const section of SECTIONS) {
+ await sidebar.getByRole("link", { name: section.label, exact: true }).click();
+ await expect(page).toHaveURL(`${APP_URL}/who/#/${section.id}`);
+ await expect(page.locator("#main header h1")).toHaveText(section.label);
+ }
+
+ // Legacy hashchange redirect: #/integrations -> #/ddns
+ await page.goto("/who/#/integrations");
+ await expect(page).toHaveURL(`${APP_URL}/who/#/ddns`);
+ await expect(page.locator("#main header h1")).toHaveText("DDNS");
+
+ // Cold load legacy redirect: #/integrations/webhooks -> #/webhooks
+ await page.goto("about:blank");
+ await page.goto("/who/#/integrations/webhooks");
+ await expect(page).toHaveURL(`${APP_URL}/who/#/webhooks`);
+ await expect(page.locator("#main header h1")).toHaveText("Webhooks");
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+
+ test("supports keyboard navigation chords (g r, g a), slash search focus, and Ctrl+B sidebar toggle", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/#/overview");
+ const mainHeading = page.locator("#main header h1");
+ await expect(mainHeading).toHaveText("Overview");
+
+ // Ensure focus is outside any form field before sending chord shortcuts.
+ await mainHeading.click();
+
+ await page.keyboard.press("g");
+ await page.keyboard.press("r");
+ await expect(page).toHaveURL(`${APP_URL}/who/#/records`);
+ await expect(mainHeading).toHaveText("Records");
+
+ await page.keyboard.press("g");
+ await page.keyboard.press("a");
+ await expect(page).toHaveURL(`${APP_URL}/who/#/audit`);
+ await expect(mainHeading).toHaveText("Audit Log");
+
+ await page.keyboard.press("/");
+ await expect(page.locator("[data-search-input]")).toBeFocused();
+
+ const sidebar = page.locator('aside[aria-label="Main navigation"]');
+ const sidebarWrapper = sidebar.locator("..");
+ await expect(sidebarWrapper).not.toHaveAttribute("inert", "");
+ await expect(
+ sidebar.getByRole("button", { name: "Collapse sidebar" }),
+ ).toBeVisible();
+
+ await page.keyboard.press("Control+b");
+ await expect(sidebarWrapper).toHaveAttribute("inert", "");
+ await expect(
+ page.getByRole("button", { name: "Expand sidebar" }),
+ ).toBeVisible();
+
+ await page.keyboard.press("Control+b");
+ await expect(sidebarWrapper).not.toHaveAttribute("inert", "");
+ await expect(
+ page.getByRole("button", { name: "Expand sidebar" }),
+ ).toHaveCount(0);
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+
+ test("persists light/dark theme toggle across page reload", async ({ page }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/#/overview");
+ await expect(page.locator("#main header h1")).toHaveText("Overview");
+
+ const html = page.locator("html");
+ const sidebar = page.locator('aside[aria-label="Main navigation"]');
+ const initiallyDark = await html.evaluate((el) => el.classList.contains("dark"));
+
+ const toggleName = initiallyDark ? "Switch to light theme" : "Switch to dark theme";
+ await sidebar.getByRole("button", { name: toggleName }).click();
+ await expect
+ .poll(() => html.evaluate((el) => el.classList.contains("dark")))
+ .toBe(!initiallyDark);
+
+ await page.reload();
+ await expect(page.locator("#main header h1")).toHaveText("Overview");
+ await expect
+ .poll(() => html.evaluate((el) => el.classList.contains("dark")))
+ .toBe(!initiallyDark);
+
+ // Restore original theme state so subsequent tests start cleanly.
+ const restoreName = !initiallyDark ? "Switch to light theme" : "Switch to dark theme";
+ await sidebar.getByRole("button", { name: restoreName }).click();
+ await expect
+ .poll(() => html.evaluate((el) => el.classList.contains("dark")))
+ .toBe(initiallyDark);
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+
+ test("triggers zero idle polling /api/v1/ requests on Overview, Records, DDNS, and Settings", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ const targets = [
+ {
+ id: "overview",
+ heading: "Overview",
+ readyLocator: () => page.locator('section[aria-label="Key metrics"]'),
+ },
+ {
+ id: "records",
+ heading: "Records",
+ readyLocator: () => page.locator("#main header h1"),
+ },
+ {
+ id: "ddns",
+ heading: "DDNS",
+ readyLocator: () => page.locator("#main header h1"),
+ },
+ {
+ id: "settings",
+ heading: "Settings",
+ readyLocator: () => page.locator("#settings-backup"),
+ },
+ ];
+
+ for (const target of targets) {
+ await page.goto(`/who/#/${target.id}`);
+ await expect(page.locator("#main header h1")).toHaveText(target.heading);
+ await expect(target.readyLocator()).toBeVisible();
+ await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0);
+ await page.waitForLoadState("networkidle");
+
+ const idleRequests = [];
+ const onRequest = (req) => {
+ if (req.url().includes("/who/api/v1/")) {
+ idleRequests.push(`${req.method()} ${req.url()}`);
+ }
+ };
+
+ page.on("request", onRequest);
+ await page.waitForTimeout(2500);
+ page.off("request", onRequest);
+
+ expect(idleRequests, `Unexpected idle API calls on #/${target.id}`).toEqual([]);
+ }
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+});
diff --git a/e2e/tests/public-endpoints.spec.mjs b/e2e/tests/public-endpoints.spec.mjs
new file mode 100644
index 0000000..12b71d6
--- /dev/null
+++ b/e2e/tests/public-endpoints.spec.mjs
@@ -0,0 +1,198 @@
+import net from "node:net";
+import { expect, test } from "@playwright/test";
+import { apiFetch, rawAppFetch } from "./helpers.mjs";
+
+const createdRecords = [];
+
+function parseHeaderLines(bodyText) {
+ return bodyText
+ .trim()
+ .split(/\r?\n/)
+ .filter(Boolean)
+ .map((line) => {
+ const sepIdx = line.indexOf(": ");
+ expect(sepIdx).toBeGreaterThan(0);
+ return {
+ name: line.slice(0, sepIdx),
+ value: line.slice(sepIdx + 2),
+ };
+ });
+}
+
+test.describe("Public Reflection, Alias, and Token Endpoints", () => {
+ test.afterAll(async () => {
+ for (const iam of [...createdRecords].reverse()) {
+ await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ }
+ createdRecords.length = 0;
+ });
+
+ test("GET /healthz returns 200 ok", async () => {
+ const res = await rawAppFetch("GET", "/healthz");
+ expect(res.status).toBe(200);
+ expect(res.text.trim()).toBe("ok");
+ });
+
+ test("GET /whoami and GET /whoami/headers reflect Traefik peer IP and sorted headers", async () => {
+ const whoamiRes = await rawAppFetch("GET", "/whoami");
+ expect(whoamiRes.status).toBe(200);
+ const detectedIP = whoamiRes.text.trim();
+ expect(net.isIP(detectedIP)).not.toBe(0);
+
+ // Default Traefik config ignores untrusted client X-Forwarded-For and overwrites with peer IP.
+ const spoofedRes = await rawAppFetch("GET", "/whoami", {
+ headers: { "X-Forwarded-For": "203.0.113.42" },
+ });
+ expect(spoofedRes.status).toBe(200);
+ expect(spoofedRes.text.trim()).toBe(detectedIP);
+
+ const headersRes = await rawAppFetch("GET", "/whoami/headers");
+ expect(headersRes.status).toBe(200);
+
+ const parsed = parseHeaderLines(headersRes.text);
+ expect(parsed.length).toBeGreaterThan(0);
+
+ for (let i = 1; i < parsed.length; i++) {
+ expect(parsed[i - 1].name <= parsed[i].name).toBe(true);
+ }
+
+ const headerMap = new Map(parsed.map((h) => [h.name, h.value]));
+ expect(headerMap.get("X-Forwarded-Proto")).toBe("https");
+ expect(headerMap.get("X-Forwarded-Host")).toBe("app.who.localhost:18443");
+
+ const xff = headerMap.get("X-Forwarded-For");
+ const realIP = headerMap.get("X-Real-Ip");
+ expect(xff || realIP).toBeTruthy();
+ if (xff) {
+ const lastHop = xff.split(",").pop().trim();
+ expect(lastHop).toBe(detectedIP);
+ }
+ if (realIP) {
+ expect(realIP).toBe(detectedIP);
+ }
+ });
+
+ test("GET /iam and GET /whois support IPv4, IPv6, invalid-IP fallback, and 404", async () => {
+ createdRecords.push("e2e-pub-v4", "e2e-pub-v6", "e2e-pub-fallback");
+
+ const whoamiRes = await rawAppFetch("GET", "/whoami");
+ expect(whoamiRes.status).toBe(200);
+ const detectedIP = whoamiRes.text.trim();
+
+ const iamV4 = await rawAppFetch("GET", "/iam/e2e-pub-v4/198.51.100.10");
+ expect(iamV4.status).toBe(200);
+ expect(iamV4.text.trim()).toBe("198.51.100.10");
+
+ const whoisV4 = await rawAppFetch("GET", "/whois/e2e-pub-v4");
+ expect(whoisV4.status).toBe(200);
+ expect(whoisV4.text.trim()).toBe("198.51.100.10");
+
+ const iamV6 = await rawAppFetch("GET", "/iam/e2e-pub-v6/2001:db8::10");
+ expect(iamV6.status).toBe(200);
+ expect(iamV6.text.trim()).toBe("2001:db8::10");
+
+ const whoisV6 = await rawAppFetch("GET", "/whois/e2e-pub-v6");
+ expect(whoisV6.status).toBe(200);
+ expect(whoisV6.text.trim()).toBe("2001:db8::10");
+
+ const iamFallback = await rawAppFetch("GET", "/iam/e2e-pub-fallback/not-an-ip");
+ expect(iamFallback.status).toBe(200);
+ expect(iamFallback.text.trim()).toBe(detectedIP);
+
+ const whoisFallback = await rawAppFetch("GET", "/whois/e2e-pub-fallback");
+ expect(whoisFallback.status).toBe(200);
+ expect(whoisFallback.text.trim()).toBe(detectedIP);
+
+ const missing = await rawAppFetch("GET", "/whois/e2e-does-not-exist");
+ expect(missing.status).toBe(404);
+ });
+
+ test("alias resolves member IPs newline-separated and rejects /iam updates with 400", async () => {
+ await rawAppFetch("GET", "/iam/e2e-pub-v4/198.51.100.10");
+ await rawAppFetch("GET", "/iam/e2e-pub-v6/2001:db8::10");
+ if (!createdRecords.includes("e2e-pub-v4")) createdRecords.push("e2e-pub-v4");
+ if (!createdRecords.includes("e2e-pub-v6")) createdRecords.push("e2e-pub-v6");
+
+ const createAlias = await apiFetch("POST", "/records", {
+ body: {
+ iam: "e2e-pub-alias",
+ isAlias: true,
+ alias: ["e2e-pub-v4", "e2e-pub-v6"],
+ },
+ });
+ expect(createAlias.status).toBe(201);
+ createdRecords.push("e2e-pub-alias");
+
+ const whoisAlias = await rawAppFetch("GET", "/whois/e2e-pub-alias");
+ expect(whoisAlias.status).toBe(200);
+ expect(whoisAlias.text.trim()).toBe("198.51.100.10\n2001:db8::10");
+
+ const iamAlias = await rawAppFetch("GET", "/iam/e2e-pub-alias");
+ expect(iamAlias.status).toBe(400);
+ });
+
+ test("per-record bearer token protects /iam and strips query token from access logs", async () => {
+ const createRec = await apiFetch("POST", "/records", {
+ body: { iam: "e2e-pub-tok", ip: "198.51.100.15" },
+ });
+ expect(createRec.status).toBe(201);
+ createdRecords.push("e2e-pub-tok");
+
+ const tokRes = await apiFetch("POST", "/records/e2e-pub-tok/token", {
+ body: { clear: false },
+ });
+ expect(tokRes.status).toBe(200);
+ expect(tokRes.data?.hasToken).toBe(true);
+ const token = tokRes.data?.token;
+ expect(typeof token).toBe("string");
+ expect(token.length).toBeGreaterThan(16);
+
+ const unauthUpdate = await rawAppFetch("GET", "/iam/e2e-pub-tok/198.51.100.20");
+ expect(unauthUpdate.status).toBe(401);
+
+ const bearerUpdate = await rawAppFetch("GET", "/iam/e2e-pub-tok/198.51.100.20", {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ expect(bearerUpdate.status).toBe(200);
+ expect(bearerUpdate.text.trim()).toBe("198.51.100.20");
+
+ const headerUpdate = await rawAppFetch("GET", "/iam/e2e-pub-tok/198.51.100.21", {
+ headers: { "X-Who-Token": token },
+ });
+ expect(headerUpdate.status).toBe(200);
+ expect(headerUpdate.text.trim()).toBe("198.51.100.21");
+
+ const queryUpdate = await rawAppFetch(
+ "GET",
+ `/iam/e2e-pub-tok/198.51.100.22?token=${encodeURIComponent(token)}`,
+ );
+ expect(queryUpdate.status).toBe(200);
+ expect(queryUpdate.text.trim()).toBe("198.51.100.22");
+
+ let logItems = [];
+ await expect
+ .poll(
+ async () => {
+ const logsRes = await apiFetch(
+ "GET",
+ "/access-logs?iam=e2e-pub-tok&pageSize=20",
+ );
+ expect(logsRes.status).toBe(200);
+ logItems = logsRes.data?.items ?? [];
+ return logItems.length;
+ },
+ { timeout: 5_000, intervals: [150] },
+ )
+ .toBeGreaterThanOrEqual(4);
+
+ for (const item of logItems) {
+ expect(item.iam).toBe("e2e-pub-tok");
+ expect(item.path).not.toContain("?");
+ expect(item.path).not.toContain("token=");
+ expect(item.path).not.toContain(token);
+ }
+
+ const loggedPaths = logItems.map((item) => item.path);
+ expect(loggedPaths).toContain("/iam/e2e-pub-tok/198.51.100.22");
+ });
+});
diff --git a/e2e/tests/records-and-drawer.spec.mjs b/e2e/tests/records-and-drawer.spec.mjs
new file mode 100644
index 0000000..e6dae11
--- /dev/null
+++ b/e2e/tests/records-and-drawer.spec.mjs
@@ -0,0 +1,321 @@
+import { expect, test } from "@playwright/test";
+import { apiFetch, rawAppFetch } from "./helpers.mjs";
+
+const MAIN_RECORD = "e2e-rec-main";
+const EPHEMERAL_RECORD = "e2e-rec-eph";
+const ALIAS_RECORD = "e2e-alias-group";
+
+function attachErrorCollector(page) {
+ const pageErrors = [];
+ const consoleErrors = [];
+ page.on("pageerror", (err) => {
+ pageErrors.push(err?.message || String(err));
+ });
+ page.on("console", (msg) => {
+ if (msg.type() === "error") {
+ consoleErrors.push(msg.text());
+ }
+ });
+ return { pageErrors, consoleErrors };
+}
+
+function recordRow(page, iam) {
+ return page.locator(`tr[aria-label="Inspect history for ${iam}"]`);
+}
+
+test.describe("Records CRUD, Ephemeral Persist, Alias Drawer & Bearer Token Lifecycle", () => {
+ test.beforeAll(async () => {
+ for (const iam of [ALIAS_RECORD, MAIN_RECORD, EPHEMERAL_RECORD]) {
+ await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ }
+ });
+
+ test.afterAll(async () => {
+ for (const iam of [ALIAS_RECORD, MAIN_RECORD, EPHEMERAL_RECORD]) {
+ const res = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`);
+ expect([200, 204, 404]).toContain(res.status);
+ }
+ });
+
+ test("exercises plain CRUD, ephemeral persist, alias drawer navigation, token auth, filter chips, and delete", async ({
+ page,
+ }) => {
+ const { pageErrors, consoleErrors } = attachErrorCollector(page);
+
+ await page.goto("/who/#/records");
+ await expect(page.locator("#main header h1")).toHaveText("Records");
+
+ // 1. Plain record add + /whois verification
+ await page.getByRole("button", { name: "New Record" }).click();
+ let dialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "Create Record or Alias", level: 1 }),
+ });
+ await expect(dialog).toBeVisible();
+ await dialog.locator("#record-iam-input").fill(MAIN_RECORD);
+ await dialog.locator("#record-ip-input").fill("198.51.100.51");
+ await dialog.getByRole("button", { name: "Create Record" }).click();
+ await expect(dialog).toBeHidden();
+
+ const mainRow = recordRow(page, MAIN_RECORD);
+ await expect(mainRow).toBeVisible();
+ await expect(mainRow.locator('td[data-col="State & Type"]')).toContainText("Persisted");
+ await expect(mainRow.locator('td[data-col="State & Type"]')).toContainText("IPv4");
+ await expect(mainRow.locator('td[data-col="Current IP(s)"]')).toContainText("198.51.100.51");
+
+ const whoisCreated = await rawAppFetch("GET", `/whois/${MAIN_RECORD}`);
+ expect(whoisCreated.status).toBe(200);
+ expect(whoisCreated.text.trim()).toBe("198.51.100.51");
+
+ // 2. Plain record edit + /whois verification
+ await mainRow.getByRole("button", { name: `Edit ${MAIN_RECORD}` }).click();
+ dialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: `Edit ${MAIN_RECORD}`, level: 1 }),
+ });
+ await expect(dialog).toBeVisible();
+ await dialog.locator("#record-ip-input").fill("198.51.100.52");
+ await dialog.getByRole("button", { name: "Save Changes" }).click();
+ await expect(dialog).toBeHidden();
+
+ await expect(mainRow.locator('td[data-col="Current IP(s)"]')).toContainText("198.51.100.52");
+ const whoisEdited = await rawAppFetch("GET", `/whois/${MAIN_RECORD}`);
+ expect(whoisEdited.status).toBe(200);
+ expect(whoisEdited.text.trim()).toBe("198.51.100.52");
+
+ // 3. Ephemeral record -> Persist flow
+ const ephRes = await rawAppFetch("GET", `/iam/${EPHEMERAL_RECORD}/198.51.100.61`);
+ expect(ephRes.status).toBe(200);
+ expect(ephRes.text.trim()).toBe("198.51.100.61");
+
+ await page.getByRole("button", { name: "Refresh" }).click();
+ const ephRow = recordRow(page, EPHEMERAL_RECORD);
+ await expect(ephRow).toBeVisible();
+ await expect(ephRow.locator('td[data-col="State & Type"]')).toContainText("Ephemeral");
+
+ const ephMenuTrigger = ephRow.getByRole("button", {
+ name: `More actions for ${EPHEMERAL_RECORD}`,
+ });
+ await ephMenuTrigger.click();
+ const openMenu = page.locator('[popover="auto"]:popover-open');
+ await expect(openMenu).toBeVisible();
+ await expect(page.locator("dialog.who-drawer[open]")).toHaveCount(0);
+
+ // Toggling the trigger closed must not bubble to row click / RecordDrawer.
+ await ephMenuTrigger.click();
+ await expect(openMenu).toHaveCount(0);
+ await expect(page.locator("dialog.who-drawer[open]")).toHaveCount(0);
+
+ await ephMenuTrigger.click();
+ await expect(openMenu).toBeVisible();
+ await openMenu.locator("button", { hasText: "Persist to SQLite" }).click();
+ await expect(openMenu).toHaveCount(0);
+ await expect(page.locator("dialog.who-drawer[open]")).toHaveCount(0);
+ await expect(ephRow.locator('td[data-col="State & Type"]')).toContainText("Persisted");
+
+ // 4. Alias create + IAM Name column verification + /whois verification
+ await page.getByRole("button", { name: "New Record" }).click();
+ dialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "Create Record or Alias", level: 1 }),
+ });
+ await expect(dialog).toBeVisible();
+ await dialog.getByRole("button", { name: "Alias Group" }).click();
+ await dialog.locator("#record-iam-input").fill(ALIAS_RECORD);
+
+ const memberInput = dialog.locator("#alias-member-input");
+ await memberInput.fill(MAIN_RECORD);
+ await memberInput.press("Enter");
+ await memberInput.fill(EPHEMERAL_RECORD);
+ await memberInput.press("Enter");
+ await dialog.getByRole("button", { name: "Create Alias" }).click();
+ await expect(dialog).toBeHidden();
+
+ const aliasRow = recordRow(page, ALIAS_RECORD);
+ await expect(aliasRow).toBeVisible();
+ await expect(aliasRow.locator('td[data-col="State & Type"]')).toContainText("Persisted");
+ await expect(aliasRow.locator('td[data-col="State & Type"]')).toContainText("Alias");
+
+ // IAM Name cell must show only the alias name (no "->" or member names).
+ const aliasNameCell = aliasRow.locator('th[scope="row"]');
+ await expect(aliasNameCell).toHaveText(ALIAS_RECORD);
+ await expect(aliasNameCell).not.toContainText("→");
+ await expect(aliasNameCell).not.toContainText(MAIN_RECORD);
+ await expect(aliasNameCell).not.toContainText(EPHEMERAL_RECORD);
+
+ const whoisAlias = await rawAppFetch("GET", `/whois/${ALIAS_RECORD}`);
+ expect(whoisAlias.status).toBe(200);
+ expect(whoisAlias.text.trim()).toBe("198.51.100.52\n198.51.100.61");
+
+ // 4b. Alias edit (remove member -> verify /whois -> restore member)
+ await aliasRow.getByRole("button", { name: `Edit ${ALIAS_RECORD}` }).click();
+ dialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: `Edit ${ALIAS_RECORD}`, level: 1 }),
+ });
+ await expect(dialog).toBeVisible();
+ await dialog.getByRole("button", { name: `Remove ${EPHEMERAL_RECORD}` }).click();
+ await dialog.getByRole("button", { name: "Save Changes" }).click();
+ await expect(dialog).toBeHidden();
+
+ const whoisAliasEdited = await rawAppFetch("GET", `/whois/${ALIAS_RECORD}`);
+ expect(whoisAliasEdited.status).toBe(200);
+ expect(whoisAliasEdited.text.trim()).toBe("198.51.100.52");
+
+ await aliasRow.getByRole("button", { name: `Edit ${ALIAS_RECORD}` }).click();
+ await expect(dialog).toBeVisible();
+ await dialog.locator("#alias-member-input").fill(EPHEMERAL_RECORD);
+ await dialog.locator("#alias-member-input").press("Enter");
+ await dialog.getByRole("button", { name: "Save Changes" }).click();
+ await expect(dialog).toBeHidden();
+
+ const whoisAliasRestored = await rawAppFetch("GET", `/whois/${ALIAS_RECORD}`);
+ expect(whoisAliasRestored.status).toBe(200);
+ expect(whoisAliasRestored.text.trim()).toBe("198.51.100.52\n198.51.100.61");
+
+ // 5. Alias RecordDrawer inspection + member IP update history + member chip jump
+ await aliasRow.click();
+ const drawer = page.locator("dialog.who-drawer[open]");
+ await expect(drawer).toBeVisible();
+ await expect(
+ drawer.getByRole("heading", { name: ALIAS_RECORD, level: 1 }),
+ ).toBeVisible();
+ await expect(
+ drawer.getByRole("button", { name: MAIN_RECORD, exact: true }),
+ ).toBeVisible();
+ await expect(
+ drawer.getByRole("button", { name: EPHEMERAL_RECORD, exact: true }),
+ ).toBeVisible();
+
+ const updateMainRes = await rawAppFetch("GET", `/iam/${MAIN_RECORD}/198.51.100.53`);
+ expect(updateMainRes.status).toBe(200);
+ expect(updateMainRes.text.trim()).toBe("198.51.100.53");
+
+ await drawer.getByRole("button", { name: "Refresh" }).click();
+ const latestHistoryItem = drawer.locator("ol > li").first();
+ const memberBadgeBtn = latestHistoryItem.getByRole("button", {
+ name: `Inspect member record ${MAIN_RECORD}`,
+ });
+ await expect(memberBadgeBtn).toBeVisible();
+ await expect(latestHistoryItem).toContainText("198.51.100.52");
+ await expect(latestHistoryItem).toContainText("198.51.100.53");
+
+ const oldIpEl = latestHistoryItem.getByText("198.51.100.52", { exact: true });
+ const newIpEl = latestHistoryItem.getByText("198.51.100.53", { exact: true });
+ const timeEl = latestHistoryItem.locator("div.text-right");
+ const [badgeBox, oldBox, newBox, timeBox] = await Promise.all([
+ memberBadgeBtn.boundingBox(),
+ oldIpEl.boundingBox(),
+ newIpEl.boundingBox(),
+ timeEl.boundingBox(),
+ ]);
+ expect(badgeBox).not.toBeNull();
+ expect(oldBox).not.toBeNull();
+ expect(newBox).not.toBeNull();
+ expect(timeBox).not.toBeNull();
+ expect(badgeBox.x + badgeBox.width).toBeLessThanOrEqual(timeBox.x);
+ expect(oldBox.x + oldBox.width).toBeLessThan(newBox.x);
+ expect(Math.abs(oldBox.y - newBox.y)).toBeLessThan(8);
+
+ // Click member chip to jump directly to e2e-rec-main's drawer.
+ await drawer.getByRole("button", { name: MAIN_RECORD, exact: true }).click();
+ await expect(
+ drawer.getByRole("heading", { name: MAIN_RECORD, level: 1 }),
+ ).toBeVisible();
+ await expect(drawer).toContainText("198.51.100.53");
+
+ await drawer.getByRole("button", { name: "Close drawer" }).click();
+ await expect(drawer).toHaveCount(0);
+ await expect(page.locator("dialog.who-drawer")).toBeHidden();
+
+ await page.locator("#main").getByRole("button", { name: "Refresh" }).click();
+ await expect(mainRow.locator('td[data-col="Current IP(s)"]')).toContainText("198.51.100.53");
+
+ // 6. Bearer token lifecycle via ActionMenu -> Reveal Dialog -> /iam check -> Clear Token
+ await mainRow
+ .getByRole("button", { name: `More actions for ${MAIN_RECORD}` })
+ .click();
+ await expect(openMenu).toBeVisible();
+ await openMenu.locator("button", { hasText: "Add Token" }).click();
+
+ const tokenDialog = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: "Bearer Token Generated", level: 1 }),
+ });
+ await expect(tokenDialog).toBeVisible();
+ const plaintextToken = (
+ await tokenDialog
+ .locator('div:has(> button[aria-label="Copy bearer token"]) code')
+ .textContent()
+ ).trim();
+ expect(plaintextToken.length).toBeGreaterThan(16);
+ await tokenDialog.getByRole("button", { name: "I've saved this token" }).click();
+ await expect(tokenDialog).toBeHidden();
+
+ await expect(mainRow.locator('td[data-col="/iam Auth"]')).toContainText("Token");
+
+ const unauthUpdate = await rawAppFetch("GET", `/iam/${MAIN_RECORD}/198.51.100.54`);
+ expect(unauthUpdate.status).toBe(401);
+
+ const authUpdate = await rawAppFetch("GET", `/iam/${MAIN_RECORD}/198.51.100.54`, {
+ headers: { Authorization: `Bearer ${plaintextToken}` },
+ });
+ expect(authUpdate.status).toBe(200);
+ expect(authUpdate.text.trim()).toBe("198.51.100.54");
+
+ await mainRow
+ .getByRole("button", { name: `More actions for ${MAIN_RECORD}` })
+ .click();
+ await expect(openMenu).toBeVisible();
+ await openMenu.locator("button", { hasText: "Clear Token" }).click();
+
+ const clearConfirm = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", {
+ name: `Clear bearer token for ${MAIN_RECORD}?`,
+ level: 1,
+ }),
+ });
+ await expect(clearConfirm).toBeVisible();
+ await clearConfirm.getByRole("button", { name: "Clear Token", exact: true }).click();
+ await expect(clearConfirm).toBeHidden();
+ await expect(mainRow.locator('td[data-col="/iam Auth"]')).toContainText("Open");
+
+ // 7. FilterBar structured chips + Pagination + Delete verification
+ const filterInput = page.locator("[data-search-input]");
+ await filterInput.click();
+ await filterInput.fill("state:persisted ");
+ await expect(
+ page.getByRole("button", { name: "Remove state:persisted filter" }),
+ ).toBeVisible();
+ await filterInput.fill("type:alias ");
+ await expect(
+ page.getByRole("button", { name: "Remove type:alias filter" }),
+ ).toBeVisible();
+
+ await expect(aliasRow).toBeVisible();
+ await expect(mainRow).toHaveCount(0);
+ await expect(ephRow).toHaveCount(0);
+
+ await page.getByRole("button", { name: "Clear all filters" }).click();
+ await page.keyboard.press("Escape");
+ await expect(page.locator("[data-search-input]")).toHaveAttribute("aria-expanded", "false");
+ await expect(mainRow).toBeVisible();
+ await expect(ephRow).toBeVisible();
+ await expect(aliasRow).toBeVisible();
+ await expect(page.getByLabel("Rows per page")).toBeVisible();
+ await expect(page.getByRole("navigation", { name: "Pagination" })).toBeVisible();
+
+ for (const iam of [ALIAS_RECORD, MAIN_RECORD, EPHEMERAL_RECORD]) {
+ const row = recordRow(page, iam);
+ await row.getByRole("button", { name: `Delete ${iam}` }).click();
+ const deleteConfirm = page.locator("dialog[open]").filter({
+ has: page.getByRole("heading", { name: `Delete ${iam}?`, level: 1 }),
+ });
+ await expect(deleteConfirm).toBeVisible();
+ await deleteConfirm.getByRole("button", { name: "Delete", exact: true }).click();
+ await expect(deleteConfirm).toBeHidden();
+ await expect(row).toHaveCount(0);
+ }
+
+ const whoisDeleted = await rawAppFetch("GET", `/whois/${MAIN_RECORD}`);
+ expect(whoisDeleted.status).toBe(404);
+
+ expect(pageErrors).toEqual([]);
+ expect(consoleErrors).toEqual([]);
+ });
+});
diff --git a/e2e/traefik/dynamic.yml b/e2e/traefik/dynamic.yml
new file mode 100644
index 0000000..a4f5027
--- /dev/null
+++ b/e2e/traefik/dynamic.yml
@@ -0,0 +1,33 @@
+tls:
+ certificates:
+ - certFile: /certs/server.crt
+ keyFile: /certs/server.key
+
+http:
+ routers:
+ who-app:
+ rule: "Host(`app.who.localhost`)"
+ entryPoints:
+ - websecure
+ tls: {}
+ service: who-svc
+
+ authelia-auth:
+ rule: "Host(`auth.who.localhost`)"
+ entryPoints:
+ - websecure
+ tls: {}
+ service: authelia-svc
+
+ services:
+ who-svc:
+ loadBalancer:
+ passHostHeader: true
+ servers:
+ - url: "http://who:80"
+
+ authelia-svc:
+ loadBalancer:
+ passHostHeader: true
+ servers:
+ - url: "http://authelia:9091"
diff --git a/e2e/traefik/traefik.yml b/e2e/traefik/traefik.yml
new file mode 100644
index 0000000..6587336
--- /dev/null
+++ b/e2e/traefik/traefik.yml
@@ -0,0 +1,11 @@
+log:
+ level: INFO
+
+entryPoints:
+ websecure:
+ address: ":18443"
+
+providers:
+ file:
+ filename: /etc/traefik/dynamic.yml
+ watch: true
diff --git a/internal/auth/oidc.go b/internal/auth/oidc.go
index 98b029f..4b07634 100644
--- a/internal/auth/oidc.go
+++ b/internal/auth/oidc.go
@@ -560,9 +560,53 @@ func (m *Manager) exchangeAndVerify(
if err := idToken.Claims(&claims); err != nil {
return nil, idTokenClaims{}, fmt.Errorf("decode id_token claims: %w", err)
}
+ if claims.Email == "" || claims.EmailVerified == nil || claims.Name == "" {
+ if hydrateErr := hydrateClaimsFromUserInfo(exchangeCtx, provider, token, idToken.Subject, &claims); hydrateErr != nil {
+ return nil, idTokenClaims{}, hydrateErr
+ }
+ }
return idToken, claims, nil
}
+func hydrateClaimsFromUserInfo(
+ ctx context.Context,
+ provider *oidc.Provider,
+ token *oauth2.Token,
+ expectedSub string,
+ claims *idTokenClaims,
+) error {
+ if provider.UserInfoEndpoint() == "" {
+ return nil
+ }
+ ui, err := provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
+ if err != nil {
+ if claims.Email != "" && claims.EmailVerified != nil {
+ log.Printf("AUTH: OIDC userinfo request failed; continuing with ID token claims: %v", err)
+ return nil
+ }
+ return fmt.Errorf("fetch userinfo: %w", err)
+ }
+ if subtle.ConstantTimeCompare([]byte(ui.Subject), []byte(expectedSub)) != 1 {
+ return errors.New("userinfo subject mismatch")
+ }
+
+ var uiClaims idTokenClaims
+ if claimErr := ui.Claims(&uiClaims); claimErr != nil {
+ return fmt.Errorf("decode userinfo claims: %w", claimErr)
+ }
+ if claims.Email == "" {
+ claims.Email = uiClaims.Email
+ }
+ if claims.EmailVerified == nil &&
+ (claims.Email == "" || uiClaims.Email == "" || strings.EqualFold(claims.Email, uiClaims.Email)) {
+ claims.EmailVerified = uiClaims.EmailVerified
+ }
+ if claims.Name == "" {
+ claims.Name = uiClaims.Name
+ }
+ return nil
+}
+
func (m *Manager) isAllowed(sub, email string, emailVerified *bool) bool {
return m.isIdentityAllowed(sub, email, emailVerified != nil && *emailVerified)
}
diff --git a/internal/auth/oidc_test.go b/internal/auth/oidc_test.go
index 25e092f..e51eeeb 100644
--- a/internal/auth/oidc_test.go
+++ b/internal/auth/oidc_test.go
@@ -45,6 +45,7 @@ type discoveryDoc struct {
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
JWKSURI string `json:"jwks_uri"`
+ UserInfoEndpoint string `json:"userinfo_endpoint,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported"`
SubjectTypesSupported []string `json:"subject_types_supported"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
@@ -71,14 +72,17 @@ type tokenEndpointResponse struct {
}
type mockOIDCIdP struct {
- server *httptest.Server
- privKey *rsa.PrivateKey
- kid string
- mu sync.Mutex
- codes map[string]authCodeRecord
- nextClaims idTokenClaimsSpec
- discoveryHits atomic.Int64
- tokenCalls atomic.Int64
+ server *httptest.Server
+ privKey *rsa.PrivateKey
+ kid string
+ mu sync.Mutex
+ codes map[string]authCodeRecord
+ nextClaims idTokenClaimsSpec
+ userInfoEnabled bool
+ userInfoHandler func(w http.ResponseWriter, r *http.Request)
+ discoveryHits atomic.Int64
+ tokenCalls atomic.Int64
+ userInfoCalls atomic.Int64
}
func newMockOIDCIdP(t *testing.T) *mockOIDCIdP {
@@ -105,6 +109,7 @@ func newMockOIDCIdP(t *testing.T) *mockOIDCIdP {
mux.HandleFunc("GET /jwks", idp.handleJWKS)
mux.HandleFunc("GET /authorize", idp.handleAuthorize)
mux.HandleFunc("POST /token", idp.handleToken)
+ mux.HandleFunc("GET /userinfo", idp.handleUserInfo)
idp.server = httptest.NewServer(mux)
t.Cleanup(idp.server.Close)
@@ -117,6 +122,13 @@ func (m *mockOIDCIdP) setNextClaims(spec idTokenClaimsSpec) {
m.nextClaims = spec
}
+func (m *mockOIDCIdP) setUserInfoHandler(fn func(w http.ResponseWriter, r *http.Request)) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.userInfoEnabled = true
+ m.userInfoHandler = fn
+}
+
func (m *mockOIDCIdP) issueCode(t *testing.T, authRedirectURL string) (code, state string) {
t.Helper()
@@ -160,7 +172,7 @@ func (m *mockOIDCIdP) issueCode(t *testing.T, authRedirectURL string) (code, sta
func (m *mockOIDCIdP) handleDiscovery(w http.ResponseWriter, _ *http.Request) {
m.discoveryHits.Add(1)
- writeTestJSON(w, discoveryDoc{
+ doc := discoveryDoc{
Issuer: m.server.URL,
AuthorizationEndpoint: m.server.URL + "/authorize",
TokenEndpoint: m.server.URL + "/token",
@@ -168,7 +180,25 @@ func (m *mockOIDCIdP) handleDiscovery(w http.ResponseWriter, _ *http.Request) {
ResponseTypesSupported: []string{"code"},
SubjectTypesSupported: []string{"public"},
IDTokenSigningAlgValuesSupported: []string{"RS256"},
- })
+ }
+ m.mu.Lock()
+ if m.userInfoEnabled {
+ doc.UserInfoEndpoint = m.server.URL + "/userinfo"
+ }
+ m.mu.Unlock()
+ writeTestJSON(w, doc)
+}
+
+func (m *mockOIDCIdP) handleUserInfo(w http.ResponseWriter, r *http.Request) {
+ m.userInfoCalls.Add(1)
+ m.mu.Lock()
+ fn := m.userInfoHandler
+ m.mu.Unlock()
+ if fn == nil {
+ http.Error(w, `{"error":"not_found"}`, http.StatusNotFound)
+ return
+ }
+ fn(w, r)
}
func (m *mockOIDCIdP) handleJWKS(w http.ResponseWriter, _ *http.Request) {
@@ -1172,3 +1202,331 @@ func verifyCrossSiteAndVerifiedSession(t *testing.T, idp *mockOIDCIdP, mux2 *htt
mux2.ServeHTTP(sameOriginRec, sameOriginReq)
mustStatus(t, sameOriginRec, http.StatusOK, "RequireAdmin same-origin")
}
+
+func TestOIDCCallbackHydratesClaimsFromUserInfo(t *testing.T) {
+ ctx := context.Background()
+ db := openAuthTestDB(t)
+ idp := newMockOIDCIdP(t)
+ idp.setNextClaims(idTokenClaimsSpec{Sub: "user-1"})
+ idp.setUserInfoHandler(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer mock-access-token" {
+ http.Error(w, `{"error":"invalid_token"}`, http.StatusUnauthorized)
+ return
+ }
+ writeTestJSON(w, map[string]any{
+ "sub": "user-1",
+ "email": "admin@example.com",
+ "email_verified": true,
+ "name": "Admin User",
+ })
+ })
+
+ mgr, err := auth.NewManager(auth.Config{
+ Issuer: idp.server.URL,
+ ClientID: "who-admin",
+ ClientSecret: "super-secret",
+ BasePath: "/who",
+ AllowedEmails: []string{"admin@example.com"},
+ HTTPClient: idp.server.Client(),
+ }, db, fixedClientIP)
+ mustNoErr(t, err, "NewManager")
+
+ mux := http.NewServeMux()
+ mgr.RegisterRoutes(mux)
+
+ cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, cbRec, "/who/", "OIDC callback with UserInfo hydration")
+ sessCookie := findCookie(cbRec.Result().Cookies(), "who_session")
+ if sessCookie == nil || sessCookie.Value == "" || !sessCookie.HttpOnly || !sessCookie.Secure ||
+ sessCookie.SameSite != http.SameSiteLaxMode || sessCookie.Path != "/who/" {
+ t.Fatalf("expected HttpOnly Secure Lax who_session cookie on Path=/who/, got %+v", sessCookie)
+ }
+ if got := idp.userInfoCalls.Load(); got != 1 {
+ t.Fatalf("expected 1 /userinfo call, got %d", got)
+ }
+
+ sessions, err := db.ListSessions(ctx)
+ mustNoErr(t, err, "ListSessions")
+ if len(sessions) != 1 {
+ t.Fatalf("expected 1 session in DB, got %d", len(sessions))
+ }
+ if sessions[0].Sub != "user-1" ||
+ sessions[0].Email != "admin@example.com" ||
+ !sessions[0].EmailVerified ||
+ sessions[0].Name != "Admin User" {
+ t.Fatalf("unexpected hydrated session in DB: %+v", sessions[0])
+ }
+}
+
+func TestOIDCCallbackRejectsUserInfoSubMismatch(t *testing.T) {
+ ctx := context.Background()
+ db := openAuthTestDB(t)
+ idp := newMockOIDCIdP(t)
+ idp.setNextClaims(idTokenClaimsSpec{Sub: "user-1"})
+ idp.setUserInfoHandler(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer mock-access-token" {
+ http.Error(w, `{"error":"invalid_token"}`, http.StatusUnauthorized)
+ return
+ }
+ writeTestJSON(w, map[string]any{
+ "sub": "attacker-sub",
+ "email": "admin@example.com",
+ "email_verified": true,
+ "name": "Attacker",
+ })
+ })
+
+ mgr, err := auth.NewManager(auth.Config{
+ Issuer: idp.server.URL,
+ ClientID: "who-admin",
+ ClientSecret: "super-secret",
+ BasePath: "/who",
+ AllowedEmails: []string{"admin@example.com"},
+ HTTPClient: idp.server.Client(),
+ }, db, fixedClientIP)
+ mustNoErr(t, err, "NewManager")
+
+ mux := http.NewServeMux()
+ mgr.RegisterRoutes(mux)
+
+ cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, cbRec, "/who/?auth_error=auth_failed", "OIDC callback with mismatched UserInfo sub")
+ if c := findCookie(cbRec.Result().Cookies(), "who_session"); c != nil && c.Value != "" {
+ t.Fatalf("expected no who_session cookie on UserInfo sub mismatch, got %+v", c)
+ }
+
+ sessions, err := db.ListSessions(ctx)
+ mustNoErr(t, err, "ListSessions")
+ if len(sessions) != 0 {
+ t.Fatalf("expected 0 sessions in DB on UserInfo sub mismatch, got %d", len(sessions))
+ }
+}
+
+func TestOIDCCallbackSkipsUserInfoWhenIDTokenComplete(t *testing.T) {
+ ctx := context.Background()
+ db := openAuthTestDB(t)
+ idp := newMockOIDCIdP(t)
+ verified := true
+ idp.setNextClaims(idTokenClaimsSpec{
+ Sub: "user-1",
+ Email: "admin@example.com",
+ EmailVerified: &verified,
+ Name: "Admin User",
+ })
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError)
+ })
+
+ mgr, err := auth.NewManager(auth.Config{
+ Issuer: idp.server.URL,
+ ClientID: "who-admin",
+ ClientSecret: "super-secret",
+ BasePath: "/who",
+ AllowedEmails: []string{"admin@example.com"},
+ HTTPClient: idp.server.Client(),
+ }, db, fixedClientIP)
+ mustNoErr(t, err, "NewManager")
+
+ mux := http.NewServeMux()
+ mgr.RegisterRoutes(mux)
+
+ cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, cbRec, "/who/", "OIDC callback with complete ID token")
+ if got := idp.userInfoCalls.Load(); got != 0 {
+ t.Fatalf("expected 0 /userinfo calls when ID token is complete, got %d", got)
+ }
+
+ sessions, err := db.ListSessions(ctx)
+ mustNoErr(t, err, "ListSessions")
+ if len(sessions) != 1 || sessions[0].Email != "admin@example.com" {
+ t.Fatalf("expected 1 session for admin@example.com, got %+v", sessions)
+ }
+}
+
+func TestOIDCCallbackUserInfoPreservesIDTokenClaimsAndHandlesNameFallback(t *testing.T) {
+ ctx := context.Background()
+ db := openAuthTestDB(t)
+ idp := newMockOIDCIdP(t)
+ verified := true
+
+ // 1. When ID token already has email + email_verified (only name missing), a 500 from /userinfo is non-fatal.
+ idp.setNextClaims(idTokenClaimsSpec{
+ Sub: "user-1",
+ Email: "admin@example.com",
+ EmailVerified: &verified,
+ })
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, `{"error":"unavailable"}`, http.StatusInternalServerError)
+ })
+
+ mgr, err := auth.NewManager(auth.Config{
+ Issuer: idp.server.URL,
+ ClientID: "who-admin",
+ ClientSecret: "super-secret",
+ BasePath: "/who",
+ AllowedEmails: []string{"admin@example.com"},
+ HTTPClient: idp.server.Client(),
+ }, db, fixedClientIP)
+ mustNoErr(t, err, "NewManager")
+
+ mux := http.NewServeMux()
+ mgr.RegisterRoutes(mux)
+
+ cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, cbRec, "/who/", "non-fatal /userinfo failure when only name missing")
+
+ // 2. UserInfo fills only missing fields without overwriting signed ID token claims.
+ idp.setNextClaims(idTokenClaimsSpec{
+ Sub: "user-2",
+ Email: "admin@example.com",
+ EmailVerified: &verified,
+ })
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ writeTestJSON(w, map[string]any{
+ "sub": "user-2",
+ "email": "other@example.com",
+ "email_verified": false,
+ "name": "Hydrated Name",
+ })
+ })
+
+ partialRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, partialRec, "/who/", "partial UserInfo hydration keeps signed ID token claims")
+
+ unverified := false
+ idp.setNextClaims(idTokenClaimsSpec{
+ Sub: "user-3",
+ Email: "signed@example.com",
+ EmailVerified: &unverified,
+ })
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ writeTestJSON(w, map[string]any{
+ "sub": "user-3",
+ "email": "admin@example.com",
+ "email_verified": true,
+ "name": "Denied Name",
+ })
+ })
+
+ deniedRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, deniedRec, "/who/?auth_error=access_denied", "signed ID token claims not overwritten by UserInfo")
+
+ sessions, err := db.ListSessions(ctx)
+ mustNoErr(t, err, "ListSessions")
+ if len(sessions) != 2 {
+ t.Fatalf("expected 2 sessions, got %+v", sessions)
+ }
+ bySub := map[string]storage.Session{}
+ for _, s := range sessions {
+ bySub[s.Sub] = s
+ }
+ if u2 := bySub["user-2"]; u2.Email != "admin@example.com" || !u2.EmailVerified || u2.Name != "Hydrated Name" {
+ t.Fatalf("expected user-2 to preserve signed email/email_verified and hydrate Name, got %+v", u2)
+ }
+
+ // 3. When ID token lacks email and advertised /userinfo returns 500, fail closed with auth_failed.
+ idp.setNextClaims(idTokenClaimsSpec{Sub: "user-4"})
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError)
+ })
+ errRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, errRec, "/who/?auth_error=auth_failed", "/userinfo 500 when ID token lacks email")
+}
+
+func TestOIDCCallbackDoesNotCrossBindUserInfoEmailVerified(t *testing.T) {
+ ctx := context.Background()
+ db := openAuthTestDB(t)
+ idp := newMockOIDCIdP(t)
+
+ mgr, err := auth.NewManager(auth.Config{
+ Issuer: idp.server.URL,
+ ClientID: "who-admin",
+ ClientSecret: "super-secret",
+ BasePath: "/who",
+ AllowedEmails: []string{"admin@example.com"},
+ HTTPClient: idp.server.Client(),
+ }, db, fixedClientIP)
+ mustNoErr(t, err, "NewManager")
+
+ mux := http.NewServeMux()
+ mgr.RegisterRoutes(mux)
+
+ // 1. UserInfo email_verified=true for a different email must NOT verify ID token email.
+ idp.setNextClaims(idTokenClaimsSpec{
+ Sub: "user-cross",
+ Email: "admin@example.com",
+ })
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ writeTestJSON(w, map[string]any{
+ "sub": "user-cross",
+ "email": "other@example.com",
+ "email_verified": true,
+ "name": "Other Email User",
+ })
+ })
+
+ deniedRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, deniedRec, "/who/?auth_error=access_denied", "cross-email email_verified must not be adopted")
+ if c := findCookie(deniedRec.Result().Cookies(), "who_session"); c != nil && c.Value != "" {
+ t.Fatalf("expected no who_session cookie on cross-bound UserInfo email_verified, got %+v", c)
+ }
+
+ sessions, err := db.ListSessions(ctx)
+ mustNoErr(t, err, "ListSessions after cross-bind attempt")
+ if len(sessions) != 0 {
+ t.Fatalf("expected 0 sessions after cross-bind attempt, got %+v", sessions)
+ }
+
+ audits, _, err := db.QueryAuditLogs(ctx, storage.AuditLogFilter{Category: "auth", Limit: 10})
+ mustNoErr(t, err, "QueryAuditLogs")
+ if len(audits) != 1 || audits[0].Action != "login_denied" {
+ t.Fatalf("expected 1 login_denied audit log, got %+v", audits)
+ }
+
+ // 2. Case-insensitive matching email in UserInfo adopts email_verified=true.
+ idp.setNextClaims(idTokenClaimsSpec{
+ Sub: "user-case",
+ Email: "Admin@Example.COM",
+ Name: "Admin User",
+ })
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ writeTestJSON(w, map[string]any{
+ "sub": "user-case",
+ "email": "admin@example.com",
+ "email_verified": true,
+ })
+ })
+ caseRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, caseRec, "/who/", "case-insensitive matching UserInfo email")
+
+ // 3. Omitted email in UserInfo still adopts email_verified=true for the ID token email.
+ idp.setNextClaims(idTokenClaimsSpec{
+ Sub: "user-omitted-ui-email",
+ Email: "admin@example.com",
+ })
+ idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) {
+ writeTestJSON(w, map[string]any{
+ "sub": "user-omitted-ui-email",
+ "email_verified": true,
+ "name": "Omitted Email User",
+ })
+ })
+ omittedRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true)
+ mustRedirect(t, omittedRec, "/who/", "omitted UserInfo email adopts email_verified")
+
+ sessions, err = db.ListSessions(ctx)
+ mustNoErr(t, err, "ListSessions")
+ if len(sessions) != 2 {
+ t.Fatalf("expected 2 sessions, got %+v", sessions)
+ }
+ bySub := map[string]storage.Session{}
+ for _, s := range sessions {
+ bySub[s.Sub] = s
+ }
+ if u := bySub["user-case"]; !u.EmailVerified || u.Email != "Admin@Example.COM" {
+ t.Fatalf("unexpected user-case session: %+v", u)
+ }
+ if u := bySub["user-omitted-ui-email"]; !u.EmailVerified || u.Email != "admin@example.com" || u.Name != "Omitted Email User" {
+ t.Fatalf("unexpected user-omitted-ui-email session: %+v", u)
+ }
+}
diff --git a/main.go b/main.go
index 9ee0565..bd6da11 100644
--- a/main.go
+++ b/main.go
@@ -37,6 +37,7 @@ type RuntimeOptions struct {
ConfigPath string
DataDir string
BasePath string
+ DDNSEndpoint string
OIDCIssuer string
OIDCClientID string
OIDCClientSecret string
@@ -99,6 +100,7 @@ func parseRuntimeOptions(args []string, getenv func(string) string) (RuntimeOpti
}
opts.BasePath = normalizedBase
+ opts.DDNSEndpoint = strings.TrimSpace(opts.DDNSEndpoint)
opts.OIDCIssuer = strings.TrimSpace(opts.OIDCIssuer)
opts.OIDCClientID = strings.TrimSpace(opts.OIDCClientID)
opts.OIDCRedirectURL = strings.TrimSpace(opts.OIDCRedirectURL)
@@ -122,6 +124,7 @@ func newRuntimeFlagSet(
fset.StringVar(&opts.ConfigPath, "config", strings.TrimSpace(getenv("WHO_CONFIG")), "Optional seed config.json file path (env: WHO_CONFIG)")
fset.StringVar(&opts.DataDir, "data-dir", envOrDefault(getenv, "WHO_DATA_DIR", defaultDataDir), "Directory holding who.db SQLite database (env: WHO_DATA_DIR)")
fset.StringVar(rawBasePath, "base-path", strings.TrimSpace(getenv("WHO_BASE_PATH")), "URL prefix for admin UI, /auth/*, and /api/v1/* (env: WHO_BASE_PATH)")
+ fset.StringVar(&opts.DDNSEndpoint, "ddns-endpoint", strings.TrimSpace(getenv("WHO_DDNS_ENDPOINT")), "Optional DDNS provider endpoint override (env: WHO_DDNS_ENDPOINT)")
fset.StringVar(&opts.OIDCIssuer, "oidc-issuer", strings.TrimSpace(getenv("WHO_OIDC_ISSUER")), "OIDC issuer URL (env: WHO_OIDC_ISSUER)")
fset.StringVar(&opts.OIDCClientID, "oidc-client-id", strings.TrimSpace(getenv("WHO_OIDC_CLIENT_ID")), "OIDC client ID (env: WHO_OIDC_CLIENT_ID)")
fset.StringVar(&opts.OIDCClientSecret, "oidc-client-secret", getenv("WHO_OIDC_CLIENT_SECRET"), "OIDC client secret (env: WHO_OIDC_CLIENT_SECRET)")
@@ -266,11 +269,12 @@ func initServer(ctx context.Context, opts *RuntimeOptions, db *storage.DB, acces
}
server := &Server{
- db: db,
- store: NewStore(),
- accessLog: accessLogger,
- auth: authMgr,
- verbose: opts.Verbose,
+ db: db,
+ store: NewStore(),
+ accessLog: accessLogger,
+ auth: authMgr,
+ ddnsEndpoint: opts.DDNSEndpoint,
+ verbose: opts.Verbose,
}
if err := server.ReloadFromDB(ctx); err != nil {
return nil, fmt.Errorf("reload runtime configuration: %w", err)
diff --git a/main_test.go b/main_test.go
index 45b3484..9db0e20 100644
--- a/main_test.go
+++ b/main_test.go
@@ -720,6 +720,51 @@ func assertRuntimeOptionVerboseAndValidation(t *testing.T) {
}
}
+func TestParseRuntimeOptionsDDNSEndpoint(t *testing.T) {
+ defaults, err := parseRuntimeOptions(nil, func(string) string { return "" })
+ if err != nil {
+ t.Fatalf("parseRuntimeOptions defaults error: %v", err)
+ }
+ if defaults.DDNSEndpoint != "" {
+ t.Fatalf("default DDNSEndpoint = %q, want empty string", defaults.DDNSEndpoint)
+ }
+
+ getenv := func(k string) string {
+ if k == "WHO_DDNS_ENDPOINT" {
+ return " http://mock-sink:9999 "
+ }
+ return ""
+ }
+ fromEnv, err := parseRuntimeOptions(nil, getenv)
+ if err != nil {
+ t.Fatalf("parseRuntimeOptions env error: %v", err)
+ }
+ if fromEnv.DDNSEndpoint != "http://mock-sink:9999" {
+ t.Fatalf("env DDNSEndpoint = %q, want %q", fromEnv.DDNSEndpoint, "http://mock-sink:9999")
+ }
+
+ overridden, err := parseRuntimeOptions([]string{"--ddns-endpoint", " http://override:8080 "}, getenv)
+ if err != nil {
+ t.Fatalf("parseRuntimeOptions CLI override error: %v", err)
+ }
+ if overridden.DDNSEndpoint != "http://override:8080" {
+ t.Fatalf("CLI override DDNSEndpoint = %q, want %q", overridden.DDNSEndpoint, "http://override:8080")
+ }
+
+ db, _ := openAccessLogTestDB(t)
+ logger := NewAccessLogger(db)
+ t.Cleanup(func() {
+ _ = logger.Close(context.Background())
+ })
+ srv, initErr := initServer(context.Background(), &fromEnv, db, logger)
+ if initErr != nil {
+ t.Fatalf("initServer: %v", initErr)
+ }
+ if srv.ddnsEndpoint != "http://mock-sink:9999" {
+ t.Fatalf("srv.ddnsEndpoint = %q, want %q", srv.ddnsEndpoint, "http://mock-sink:9999")
+ }
+}
+
func TestRetentionPassPrunesLogsAndExpiredSessions(t *testing.T) {
ctx := context.Background()
db, _ := openAccessLogTestDB(t)
diff --git a/ui/src/components/ActionMenu.svelte b/ui/src/components/ActionMenu.svelte
index 2597d82..3ce2c27 100644
--- a/ui/src/components/ActionMenu.svelte
+++ b/ui/src/components/ActionMenu.svelte
@@ -62,13 +62,6 @@ $effect(() => {
return () => focusgroupEl.removeEventListener("keydown", handleMenuKeydown);
});
-$effect(() => {
- if (!menuEl) return;
- const stopClick = (e) => e.stopPropagation();
- menuEl.addEventListener("click", stopClick);
- return () => menuEl.removeEventListener("click", stopClick);
-});
-
// Reposition fallback fixed coordinates on resize/scroll and close if focus leaves menu system
$effect(() => {
if (!open || typeof window === "undefined") return;
@@ -269,11 +262,13 @@ function handleItemClick(e, item) {
+