Files
ianitor/apps/web/tests/demo.ts
T

295 lines
14 KiB
TypeScript

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
// 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, nowMs, respond, type Route } from "./mockApi";
import { CREDIT } from "../src/lib/credit";
/** 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<string, unknown>;
const DAY = 86_400;
const at = (s: number) => new Date(nowMs() + 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(added: Json[] = []): Json {
const list = [...hosts(), ...added];
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. A host added in the
* demo (the e2e suite's Add host flow) is listed from then on, healthy, with the upstream it was
* given; a device certificate request carries the name it was asked with. */
export function demoRoutes(): Route[] {
const m = newMock();
const added: Json[] = [];
let device = "";
const request = (state: "waiting" | "approved"): Json => ({
request_id: "pr_dev",
kind: "device",
state,
match_code: "47 19 83",
created_at: at(-5),
expires_at: at(600),
approved_at: state === "approved" ? at(0) : null,
device_id: state === "approved" ? "dv_1" : null,
name: device,
csr_pem: null,
not_after: state === "approved" ? at(365 * DAY) : null,
message_code: state === "approved" ? "pki.issued" : "pki.waiting.manual",
message: state === "approved" ? `${device} has a certificate.` : "Approve it on the server with the match code.",
approve_command: state === "approved" ? null : "ianitor-control pki approve 47 19 83",
problem: null,
});
return [
["GET", /^\/overview$/, () => [200, overview(added)]],
["POST", /^\/hosts$/, (_, b) => {
const h = b.host as Json;
const name = String(h.hostname);
m.state.hostsAdded.push(name);
const ups = Array.isArray(h.upstreams) ? h.upstreams.map(String) : [];
added.push(demoHost(name, ups, { state: "healthy", latency: 11 }, { added_at: at(0) }));
return [202, { apply: apply("ch_new", "queued", `Added ${name}`, [name]) }];
}],
["POST", /^\/certs\/devices$/, (_, b) => {
device = String(b.name ?? "");
return [202, request("waiting")];
}],
["GET", /^\/pki-requests\/pr_dev$/, () => [200, request("approved")]],
// A share link whose token cannot be read as a name (the stand-in's `ish1.abc` would be).
["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_demo", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.4f9c2a7e1b0d`, expires_at: at(7 * DAY), path_prefix: "/", has_password: false, warning: null }]],
["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(m),
];
}
/** 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);
}
// What the demo may show (demo.test.ts, and the e2e suite on every page it visits).
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. The licence's
* credit (src/lib/credit.ts, LICENSE Exhibit B) is real on purpose and is the only text left out. */
export function realLooking(shown: string): string[] {
const found: string[] = [];
const text = [CREDIT.url, CREDIT.notice].reduce((t, c) => t.split(c).join(" "), shown);
for (const m of text.matchAll(/(?<![\w.])\d{1,3}(?:\.\d{1,3}){3}(?![\w.])/g)) {
if (m[0] !== "127.0.0.1" && !DOC_NETS.some((n) => m[0].startsWith(n))) found.push(m[0]);
}
for (const m of text.matchAll(/(?<![\w.-])(?:[a-z0-9-]+\.)+([a-z][a-z0-9-]*)(?![\w-])/gi)) {
if (!ALLOWED_TLDS.has(m[1].toLowerCase())) found.push(m[0]);
}
for (const w of FORBIDDEN) if (new RegExp(`\\b${w}\\b`, "i").test(text)) found.push(w);
return found;
}