diff --git a/apps/web/tests/demo.test.ts b/apps/web/tests/demo.test.ts new file mode 100644 index 0000000..2abed14 --- /dev/null +++ b/apps/web/tests/demo.test.ts @@ -0,0 +1,97 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The release's screenshots (docs/release.md): every shot's screen is drawn from the demo control +// plane alone (each click and wait selector found, no call unanswered), and nothing the demo +// serves or the page shows names a real host, address or person. + +import { cleanup, render, waitFor } from "@testing-library/svelte"; +import { afterEach, describe, expect, it } from "vitest"; +import App from "../src/App.svelte"; +import { app } from "../src/lib/app.svelte"; +import { SHOTS, demoApi } from "./demo"; + +const ALLOWED_TLDS = new Set(["test", "example", "invalid"]); +const DOC_NETS = ["192.0.2.", "198.51.100.", "203.0.113."]; +const FORBIDDEN = ["mark", "marek", "novak", "flowers", "esp32", "hyperv"]; + +/** What in a text could be real: addresses outside the documentation ranges, names outside .test. */ +function realLooking(text: string): string[] { + const found: string[] = []; + for (const m of text.matchAll(/(? m[0].startsWith(n))) found.push(m[0]); + } + for (const m of text.matchAll(/(? { + const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url; + const path = url.replace(/^.*\/api\/v1/, ""); + const a = api(init?.method ?? "GET", path, init?.body ? JSON.parse(String(init.body)) : {}); + served.push({ status: a.status, path, text: a.text }); + return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } }); + }) as typeof fetch; + render(App); +} + +function pageText(): string[] { + const out: string[] = []; + const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + for (let n = walk.nextNode(); n; n = walk.nextNode()) if (n.textContent?.trim()) out.push(n.textContent); + document.querySelectorAll("input, textarea").forEach((i) => out.push(i.value)); + document.querySelectorAll("[href]").forEach((a) => out.push(a.getAttribute("href") ?? "")); + return out; +} + +afterEach(() => cleanup()); + +describe("realLooking", () => { + it("passes invented names and refuses real-looking ones", () => { + expect(realLooking("wiki.home.test http://192.0.2.10:3000 on 127.0.0.1 for ada")).toEqual([]); + expect(realLooking("http://10.0.0.2:3000")).toEqual(["10.0.0.2"]); + expect(realLooking("gitea.example.cz and Mark's phone")).toEqual(["gitea.example.cz", "mark"]); + expect(realLooking("flowers.stage")).toEqual(["flowers.stage", "flowers"]); + }); +}); + +describe("the release's screenshots from the demo control plane", () => { + for (const shot of SHOTS) { + it(`${shot.name}: drawn from invented data only`, async () => { + start(shot.path); + for (const sel of shot.click ?? []) { + const el = await waitFor(() => { + const e = document.querySelector(sel); + expect(e, `click ${sel}`).not.toBeNull(); + return e as HTMLElement; + }, { timeout: 5000 }); + el.click(); + } + await waitFor(() => expect(document.querySelector(shot.wait), `wait ${shot.wait}`).not.toBeNull(), { timeout: 5000 }); + + expect(served.filter((s) => s.status === 404).map((s) => s.path)).toEqual([]); + // Control's codes (apply.kept, pki.renew_due) are dotted words, not names. + const json = served.map((s) => (s.text ?? "").replace(/"(?:code|message_code|error_code)":"[^"]*"/g, "")); + const seen = [...json, ...pageText()]; + expect(seen.flatMap(realLooking)).toEqual([]); + }); + } +}); diff --git a/apps/web/tests/demo.ts b/apps/web/tests/demo.ts new file mode 100644 index 0000000..2dfe3cb --- /dev/null +++ b/apps/web/tests/demo.ts @@ -0,0 +1,236 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The demo control plane for the release's screenshots (docs/release.md): control's answers +// (docs/api.md) for a small invented home server, built on the click smoke test's stand-in +// (mockApi.ts), whose routes answer every call the demo does not replace. Everything here is +// invented: hostnames under .test, addresses in the documentation ranges (RFC 5737), people ada +// and felix, made-up commits and fingerprints. demo.test.ts renders every shot from it and fails +// on any other name or address. + +import { apply, host, mockRoutes, newMock, respond, type Route } from "./mockApi"; + +/** One screenshot: the page, the selectors clicked in order, and the selector that means "drawn". */ +export interface Shot { + name: string; + title: string; + path: string; + click?: string[]; + wait: string; +} + +/** The viewport in CSS pixels; the PNGs are this size. */ +export const SIZE = { width: 1440, height: 900 } as const; + +export const SHOTS: Shot[] = [ + { name: "hosts", title: "Every host, its health and where it sends traffic", path: "/", wait: "[aria-label=Hosts] .ia-row:nth-child(8) .ia-host" }, + { name: "host", title: "Editing a host", path: "/hosts/wiki.home.test/edit", wait: "#host-form input[readonly]" }, + { name: "engine", title: "Pingora serving, Caddy ready as the fallback", path: "/", click: ["[data-engine-chip]"], wait: "dialog.ia-popover[open] .ia-card" }, + { name: "history", title: "History: going back to a kept version", path: "/history/ch_0006", wait: "section.detail ul li:nth-child(2)" }, + { name: "certificates", title: "The Domi CA and the device certificates", path: "/certificates", wait: "ul.devices li:nth-child(5)" }, +]; + +type Json = Record; + +const DAY = 86_400; +const at = (s: number) => new Date(Date.now() + s * 1000).toISOString(); + +interface Health { + state: string; + latency?: number | null; + upstreams?: Json[]; + failure?: Json | null; +} + +function demoHost(hostname: string, upstreams: string[], h: Health, over: Json = {}): Json { + const base = host(hostname, false); + return { + ...base, + upstreams, + health: { + state: h.state, + last_check_at: h.state === "unknown" ? null : at(-4), + latency_ms: h.latency ?? null, + since: at(-6 * DAY), + failure: h.failure ?? null, + upstreams: h.upstreams ?? [], + }, + ...over, + }; +} + +const MUSIC = ["http://192.0.2.20:4533", "http://192.0.2.21:4533"]; + +function hosts(): Json[] { + return [ + demoHost("wiki.home.test", ["http://192.0.2.10:3000"], { state: "healthy", latency: 9 }, { share_links: true }), + demoHost("photos.home.test", ["http://192.0.2.11:2342"], { state: "healthy", latency: 23 }), + demoHost("recipes.home.test", ["http://192.0.2.12:9000"], { state: "healthy", latency: 14 }, { added_at: at(-2 * 3600) }), + demoHost("music.home.test", MUSIC, { + state: "degraded", + latency: 18, + failure: { kind: "refused", upstream: MUSIC[1], count: 3, of: 3 }, + upstreams: [ + { url: MUSIC[0], state: "healthy", last_check_at: at(-4), latency_ms: 18, failure_kind: null }, + { url: MUSIC[1], state: "down", last_check_at: at(-4), latency_ms: null, failure_kind: "refused" }, + ], + }), + demoHost("cameras.home.test", ["https://192.0.2.30:7443"], { state: "healthy", latency: 31 }, { device_certs: true }), + demoHost("status.home.test", ["http://192.0.2.40:3001"], { state: "healthy", latency: 6 }, { tls: "letsencrypt", auth: "none" }), + demoHost("printer.home.test", ["http://192.0.2.50:631"], { state: "unknown" }, { websockets: false }), + ]; +} + +function lastApply(): Json { + return { + ...apply("ch_0008", "kept", "Added recipes.home.test", ["recipes.home.test"]), + created_at: at(-2 * 3600 - 70), + finished_at: at(-2 * 3600), + reason: { code: "apply.kept", message: "recipes.home.test is live. Health checks passed for 60 s." }, + commit_short: "c41d7e2", + push: { state: "pushed", at: at(-2 * 3600), error_code: null, next_try_at: null }, + }; +} + +function intermediate(): Json { + return { state: "ok", subject: "Demo Intermediate CA", not_after: at(212 * DAY), days_left: 212, renewal: null, banner: null }; +} + +function overview(): Json { + const list = hosts(); + const count = (s: string) => list.filter((h) => (h.health as Json).state === s).length; + return { + counts: { hosts: list.length, healthy: count("healthy"), degraded: count("degraded"), down: count("down"), unknown: count("unknown") }, + hosts: list, + engine: { + running: "pingora", + state: "running", + since: at(-6 * DAY), + target: null, + switchable: true, + fallback_ready: { + built_at: at(-2 * 3600), + current: true, + compared: list.length, + matched: list.length, + differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."], + }, + last_error: null, + notes: [], + }, + last_apply: lastApply(), + undo: { + available: true, + target: { change_id: "ch_0008", summary: "Added recipes.home.test", kept_at: at(-2 * 3600), commit_short: "c41d7e2" }, + effect: "Removes recipes.home.test", + blocked: null, + }, + active_apply: null, + repo: { name: "home-routes", last_push_at: at(-2 * 3600), unpushed: 0, push_error_code: null }, + intermediate: intermediate(), + site: { forward_auth_configured: true, acme_configured: true, secrets: ["photos_api_key"], watch_seconds: 60, share_links_available: true, auth_logout_url: "https://auth.home.test/logout" }, + paused: null, + paused_reason: null, + health_error: null, + rev: "rev-demo-8", + viewer: { name: "ada", via: "authelia" }, + }; +} + +function spec(hostname: string): Json | null { + const row = hosts().find((h) => h.hostname === hostname); + if (!row) return null; + const wiki = hostname === "wiki.home.test"; + return { + hostname, + upstreams: row.upstreams, + tls: row.tls, + auth: row.auth, + websockets: row.websockets, + share_links: row.share_links, + device_certs: row.device_certs, + access_log: wiki ? "truncated" : "off", + health_check: (row.health as Json).state === "unknown" ? null : { path: wiki ? "/healthz" : "/", interval_secs: 30 }, + request_headers: [], + response_headers: wiki ? [{ action: "set", name: "X-Frame-Options", value: "SAMEORIGIN" }] : [], + }; +} + +const HISTORY = [ + { change_id: "ch_0008", summary: "Added recipes.home.test", kind: "add", state: "kept", ago: 2 * 3600, commit_short: "c41d7e2", hosts: ["recipes.home.test"], reason_short: null }, + { change_id: "ch_0007", summary: "Changed music.home.test", kind: "edit", state: "kept", ago: 1 * DAY, commit_short: "8e03b5a", hosts: ["music.home.test"], reason_short: null }, + { change_id: "ch_0006", summary: "Turned share links on for wiki.home.test", kind: "share_links", state: "kept", ago: 2 * DAY, commit_short: "5a9f210", hosts: ["wiki.home.test"], reason_short: null }, + { change_id: "ch_0005", summary: "Changed photos.home.test", kind: "edit", state: "reverted", ago: 3 * DAY, commit_short: null, hosts: ["photos.home.test"], reason_short: "photos.home.test answered 502 during the watch" }, + { change_id: "ch_0004", summary: "Added cameras.home.test", kind: "add", state: "kept", ago: 5 * DAY, commit_short: "0b7c4e9", hosts: ["cameras.home.test"], reason_short: null }, + { change_id: "ch_0003", summary: "Added printer.home.test", kind: "add", state: "kept", ago: 9 * DAY, commit_short: "e2d81f6", hosts: ["printer.home.test"], reason_short: null }, + { change_id: "ch_0002", summary: "Added status.home.test", kind: "add", state: "kept", ago: 12 * DAY, commit_short: "73a6c05", hosts: ["status.home.test"], reason_short: null }, + { change_id: "ch_0001", summary: "Added wiki.home.test", kind: "add", state: "kept", ago: 20 * DAY, commit_short: "1f4b9a3", hosts: ["wiki.home.test"], reason_short: null }, +]; + +function history(): Json { + return { entries: HISTORY.map(({ ago, ...e }) => ({ ...e, at: at(-ago) })), next_before: null }; +} + +function restorePreview(id: string): Json { + if (id === "ch_0008") return { restorable: false, same_as_current: true, changes: [], blocked: { code: "restore.same", message: "This version is the same as the current one." } }; + return { + restorable: true, + same_as_current: false, + changes: [ + { hostname: "recipes.home.test", effect: "removed", fields: [] }, + { hostname: "music.home.test", effect: "changed", fields: [{ field: "upstreams", from: MUSIC.join(", "), to: MUSIC[0] }] }, + ], + blocked: null, + }; +} + +function certs(): Json { + const device = (id: string, name: string, kind: string, made: number, until: number, revoked: number | null = null) => ({ + id, + name, + kind, + created_at: at(-made * DAY), + not_after: at(until * DAY), + state: revoked === null ? "valid" : "revoked", + revoked_at: revoked === null ? null : at(-revoked * DAY), + }); + return { + intermediate: intermediate(), + root: { offline: true, subject: "Demo Root CA", not_after: at(3000 * DAY), sha256: "5c0f9e2a71d84b36a8e1f40c2d9b7e6315a2c8d04f9b1e7a6c3d5f8e0b2a4c61" }, + devices: [ + device("dv_1", "ada's phone", "phone", 40, 325), + device("dv_2", "felix's laptop", "computer", 61, 304), + device("dv_3", "Kitchen tablet", "phone", 345, 20), + device("dv_4", "Notes app on the desk PC", "app", 12, 353), + device("dv_5", "Old phone", "phone", 200, 165, 30), + ], + device_lifetime_days: 365, + device_valid_until: null, + server_lifetime_days: 90, + approval: "manual", + requests: [], + }; +} + +/** The demo's own answers, first; the smoke test's stand-in answers the rest. */ +export function demoRoutes(): Route[] { + return [ + ["GET", /^\/overview$/, () => [200, overview()]], + ["GET", /^\/hosts\/([^/?]+)$/, (mm) => { + const s = spec(decodeURIComponent(mm[1])); + return s ? [200, { host: s, rev: "rev-demo-8" }] : [404, { error: { code: "host.not_found", message: "There is no such host.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "demo" }]; + }], + ["GET", /^\/history(\?.*)?$/, () => [200, history()]], + ["GET", /^\/history\/([^/]+)\/restore-preview$/, (mm) => [200, restorePreview(decodeURIComponent(mm[1]))]], + ["GET", /^\/certs$/, () => [200, certs()]], + ["GET", /^\/settings$/, () => [200, { repo: { name: "home-routes", last_push_at: at(-2 * 3600) }, watch_seconds: 60 }]], + ...mockRoutes(newMock()), + ]; +} + +/** Control's API for the demo: `path` is what follows /api/v1 (with its query). */ +export function demoApi(): (method: string, path: string, body: Json) => { status: number; text: string | null } { + const routes = demoRoutes(); + return (method, path, body) => respond(routes, method.toUpperCase(), path, body); +} diff --git a/apps/web/tests/mockApi.ts b/apps/web/tests/mockApi.ts index 1c1228e..d849ccc 100644 --- a/apps/web/tests/mockApi.ts +++ b/apps/web/tests/mockApi.ts @@ -3,7 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. // A stateful stand-in for control's API, shaped like the real answers (docs/api.md), so the -// smoke tests can walk every §4 flow and count its clicks. +// smoke tests can walk every §4 flow and count its clicks. Its builders and routes are also the +// base of the screenshots' demo control plane (demo.ts, docs/release.md). type Json = Record; @@ -22,7 +23,7 @@ export interface Mock { const now = () => new Date().toISOString(); const later = (s: number) => new Date(Date.now() + s * 1000).toISOString(); -function host(hostname: string, share: boolean) { +export function host(hostname: string, share: boolean) { return { hostname, upstreams: ["http://10.0.0.2:3000"], @@ -37,7 +38,7 @@ function host(hostname: string, share: boolean) { }; } -function apply(id: string, state: string, summary: string, hosts: string[]) { +export function apply(id: string, state: string, summary: string, hosts: string[]) { return { id, change_id: id, @@ -58,12 +59,30 @@ function apply(id: string, state: string, summary: string, hosts: string[]) { }; } -export function installMock(): Mock { - const m: Mock = { +/** One API call: method, the path after /api/v1, and its answer as [status, body]. */ +export type Route = [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]]; + +export function newMock(): Mock { + return { calls: [], state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] }, }; +} +/** The first route that matches answers, with server_time added as control does; else control's 404. */ +export function respond(routes: Route[], method: string, path: string, body: Json): { status: number; text: string | null } { + for (const [mm, re, f] of routes) { + const match = path.match(re); + if (mm === method && match) { + const [status, data] = f(match, body); + const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data; + return { status, text: status === 204 ? null : JSON.stringify(withTime) }; + } + } + return { status: 404, text: JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }) }; +} + +export function mockRoutes(m: Mock): Route[] { const overview = (): Json => ({ counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 }, hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))], @@ -108,7 +127,7 @@ export function installMock(): Mock { server_time: now(), }); - const routes: [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]][] = [ + return [ ["GET", /^\/overview$/, () => [200, overview()]], ["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]], ["POST", /^\/hosts$/, (_, b) => { @@ -152,6 +171,11 @@ export function installMock(): Mock { ["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]], ["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]], ]; +} + +export function installMock(): Mock { + const m = newMock(); + const routes = mockRoutes(m); globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url; @@ -159,15 +183,8 @@ export function installMock(): Mock { const method = (init?.method ?? "GET").toUpperCase(); const body = init?.body ? JSON.parse(String(init.body)) : {}; m.calls.push({ method, path, body }); - for (const [mm, re, f] of routes) { - const match = path.match(re); - if (mm === method && match) { - const [status, data] = f(match, body); - const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data; - return new Response(status === 204 ? null : JSON.stringify(withTime), { status, headers: { "Content-Type": "application/json" } }); - } - } - return new Response(JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }), { status: 404, headers: { "Content-Type": "application/json" } }); + const a = respond(routes, method, path, body); + return new Response(a.text, { status: a.status, headers: { "Content-Type": "application/json" } }); }) as typeof fetch; return m;