[web] The web UI: hosts, add/edit with apply progress, undo, history and restore, share links, engine switch, certificates and device installs, signing by hand, settings and tokens; smoke test counts every §4 flow's clicks

This commit is contained in:
2026-11-07 23:44:27 +01:00
parent aed5fbfcff
commit 3e326e85a0
47 changed files with 7868 additions and 3 deletions
+202
View File
@@ -0,0 +1,202 @@
// 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 smoke test of every ROADMAP §4 flow with its clicks counted (handoff §4, §15): the real
// app against a stand-in for control's API. Typing, focus and waiting are not clicks.
import { cleanup, render, screen, waitFor, within } from "@testing-library/svelte";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import App from "../src/App.svelte";
import { app } from "../src/lib/app.svelte";
import { installMock, type Mock } from "./mockApi";
let mock: Mock;
let clicks = 0;
let user: ReturnType<typeof userEvent.setup>;
async function click(el: Element) {
clicks++;
await user.click(el);
}
function start(path = "/") {
history.replaceState({}, "", path);
app.path = path;
app.panel = null;
app.overview = null;
app.etag = null;
app.signedOut = false;
app.switchResult = null;
app.renewedUntil = null;
app.dismissed = [];
mock = installMock();
clicks = 0;
user = userEvent.setup();
render(App);
}
const called = (method: string, path: string) => mock.calls.some((c) => c.method === method && c.path.startsWith(path));
const T = { timeout: 5000 };
beforeEach(() => {
try {
sessionStorage.clear();
} catch {
/* none */
}
});
afterEach(() => cleanup());
describe("ROADMAP §4 flows, clicks counted", () => {
it("Add host: + Host → fill → Apply = 2 clicks, auto-kept", async () => {
start();
await click(await screen.findByRole("button", { name: "Add a host" }));
await user.type(await screen.findByLabelText("Hostname"), "recipes.home.test");
await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
await click(screen.getByRole("button", { name: "Apply" }));
// Kept: the panel closes by itself and the new host is in the list.
await waitFor(() => expect(called("GET", "/applies/ch_new")).toBe(true), T);
await waitFor(() => expect(document.querySelector("dialog.ia-panel")).toBeNull(), T);
await screen.findByRole("button", { name: "More for recipes.home.test" }, T);
expect(called("POST", "/hosts")).toBe(true);
const sent = mock.calls.find((c) => c.method === "POST" && c.path === "/hosts")?.body as { host: Record<string, unknown> };
// Every field is sent explicitly, with the design's defaults.
expect(sent.host).toMatchObject({ hostname: "recipes.home.test", tls: "domi", auth: "forward-auth", websockets: true });
expect(clicks).toBe(2);
});
it("Undo last change = 1 click", async () => {
start();
await click(await screen.findByRole("button", { name: /^Undo: Added recipes\.home\.test/ }));
await waitFor(() => expect(called("POST", "/undo")).toBe(true));
const body = mock.calls.find((c) => c.path === "/undo" && c.method === "POST")?.body as Record<string, string>;
expect(body.target_change_id).toBe("ch_1");
expect(clicks).toBe(1);
});
it("Restore: History → pick → Restore = 3 clicks", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
await click(within(nav).getByRole("link", { name: "History" }));
await click(await screen.findByRole("button", { name: /Changed wiki\.home\.test/ }));
await screen.findByText(/sends traffic to changes from/);
await click(await screen.findByRole("button", { name: "Restore this version" }));
await waitFor(() => expect(called("POST", "/restore")).toBe(true));
expect(clicks).toBe(3);
});
it("Share link: ⋯ → Share link → Copy = 3 clicks (default expiry 7 days)", async () => {
start();
await click(await screen.findByRole("button", { name: "More for wiki.home.test" }));
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
const copy = await screen.findByRole("button", { name: "Copy link" });
await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
await click(copy);
await screen.findByText("Copied");
const mint = mock.calls.find((c) => c.method === "POST" && c.path.endsWith("/share-links"))?.body as Record<string, unknown>;
expect(mint.expires_in_s).toBe(604800);
expect(await navigator.clipboard.readText()).toContain("?share=ish1.");
expect(clicks).toBe(3);
});
it("Share link on a host with links off: 4 clicks (open question Q1 not decided)", async () => {
start();
await click(await screen.findByRole("button", { name: "More for photos.home.test" }));
await click(await screen.findByRole("menuitem", { name: /Share link/ }));
await click(await screen.findByRole("button", { name: "Turn on share links" }));
const copy = await screen.findByRole("button", { name: "Copy link" }, T);
await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull());
await click(copy);
await screen.findByText("Copied");
expect(called("PATCH", "/hosts/photos.home.test")).toBe(true);
expect(clicks).toBe(4);
});
it("Switch engine: engine chip → Switch to Caddy = 2 clicks", async () => {
start();
await click(await screen.findByRole("button", { name: /^Engine: Pingora/ }));
await click(await screen.findByRole("button", { name: "Switch to Caddy" }));
await waitFor(() => expect(called("POST", "/engine")).toBe(true));
const body = mock.calls.find((c) => c.method === "POST" && c.path === "/engine")?.body as Record<string, string>;
expect(body.target).toBe("caddy");
await screen.findByText("Now serving with Caddy.", {}, T);
expect(clicks).toBe(2);
});
it("Device certificate: Certificates → + Device → Issue = 3 clicks; install is the accepted 4th", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
await click(within(nav).getByRole("link", { name: "Certificates" }));
await click(await screen.findByRole("button", { name: "Add a device certificate" }));
await user.type(await screen.findByLabelText("Device name"), "Mark's phone");
await click(screen.getByRole("button", { name: "Issue" }));
await screen.findByLabelText("Match code 47 19 83");
expect(clicks).toBe(3);
// Approved on the server (the stand-in approves on the first poll).
await click(await screen.findByRole("button", { name: "Show QR code" }, T));
await screen.findByText("ABCD-EFGH-JKLM-NPQR");
expect(clicks).toBe(4);
});
it("Renew intermediate: banner Renew = 1 click", async () => {
start();
await click(await screen.findByRole("button", { name: "Renew" }));
await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true));
await screen.findByLabelText("Match code 47 19 83");
expect(clicks).toBe(1);
});
it("API token: ⚙ → API → New token = 3 clicks; Copy token is the accepted 4th", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
const nav = screen.getAllByRole("navigation", { name: "Main" })[0];
await click(within(nav).getByRole("link", { name: "Settings" }));
await click(await screen.findByRole("tab", { name: "API" }));
await click(await screen.findByRole("button", { name: "New token" }));
const box = (await screen.findByLabelText("New API token")) as HTMLInputElement;
expect(box.value).toBe("ian_tk1_secretvalue");
expect(clicks).toBe(3);
await click(screen.getByRole("button", { name: "Copy token" }));
expect(await navigator.clipboard.readText()).toBe("ian_tk1_secretvalue");
expect(clicks).toBe(4);
// The token is never stored by the page.
expect(JSON.stringify({ ...sessionStorage })).not.toContain("ian_tk1");
expect(JSON.stringify({ ...localStorage })).not.toContain("ian_tk1");
});
});
describe("sign-in and contact", () => {
it("a 401 without Ianitor's envelope shows the signed-out dialog", async () => {
start();
await screen.findByRole("button", { name: "Add a host" });
globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch;
app.etag = null;
await click(screen.getByRole("button", { name: "Add a host" }));
await user.type(await screen.findByLabelText("Hostname"), "x.home.test");
await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080");
await click(screen.getByRole("button", { name: "Apply" }));
await screen.findByRole("alertdialog", { name: "Your sign-in has ended" });
// What was typed is still there.
expect((screen.getByLabelText("Hostname") as HTMLInputElement).value).toBe("x.home.test");
});
it("every request carries the UI header and no token", async () => {
const seen: Headers[] = [];
start();
const inner = globalThis.fetch;
globalThis.fetch = (async (i: RequestInfo | URL, init?: RequestInit) => {
seen.push(new Headers(init?.headers));
return inner(i, init);
}) as typeof fetch;
await click(await screen.findByRole("button", { name: /^Undo:/ }));
await waitFor(() => expect(seen.length).toBeGreaterThan(0));
for (const h of seen) {
expect(h.get("X-Ianitor-UI")).toBe("1");
expect(h.get("Authorization")).toBeNull();
}
});
});
+174
View File
@@ -0,0 +1,174 @@
// 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/.
// 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.
type Json = Record<string, unknown>;
export interface Mock {
calls: { method: string; path: string; body: unknown }[];
state: {
engine: "pingora" | "caddy";
switching: number;
intermediate: "ok" | "due";
renewal: boolean;
requestPolls: number;
hostsAdded: string[];
};
}
const now = () => new Date().toISOString();
const later = (s: number) => new Date(Date.now() + s * 1000).toISOString();
function host(hostname: string, share: boolean) {
return {
hostname,
upstreams: ["http://10.0.0.2:3000"],
tls: "domi",
auth: "forward-auth",
websockets: true,
share_links: share,
device_certs: false,
added_at: null,
health: { state: "healthy", last_check_at: now(), latency_ms: 12, since: now(), failure: null, upstreams: [] },
certificate: { state: "ok", not_after: later(86400 * 80), error_code: null },
};
}
function apply(id: string, state: string, summary: string, hosts: string[]) {
return {
id,
change_id: id,
kind: "add",
summary,
hosts,
state,
created_at: now(),
finished_at: state === "kept" ? now() : null,
steps: ["validate", "compile", "write", "reload", "watch", "push"].map((key) => ({ key, state: state === "kept" ? "done" : "pending" })),
queue: null,
watch: null,
reason: state === "kept" ? { code: "apply.kept", message: `${hosts[0]} is live. Health checks passed for 60 s.` } : null,
errors: [],
commit_short: "4f1c2ab",
push: null,
attempted_host: null,
};
}
export function installMock(): Mock {
const m: Mock = {
calls: [],
state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] },
};
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))],
engine: {
running: m.state.engine,
state: m.state.switching > 0 ? "switching" : "running",
since: now(),
target: null,
switchable: true,
fallback_ready: { built_at: now(), current: true },
last_error: null,
notes: [],
},
last_apply: apply("ch_1", "kept", "Added recipes.home.test", ["recipes.home.test"]),
undo: {
available: true,
target: { change_id: "ch_1", summary: "Added recipes.home.test", kept_at: now(), commit_short: "4f1c2ab" },
effect: "Removes recipes.home.test",
blocked: null,
},
active_apply: null,
repo: { name: "ianitor-routes", last_push_at: now(), unpushed: 0, push_error_code: null },
intermediate:
m.state.intermediate === "due"
? {
state: "due",
subject: "Ianitor Domi Intermediate 2025-12",
not_after: later(86400 * 23),
days_left: 23,
renewal: m.state.renewal
? { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(3600), approved_at: null, device_id: null, name: null, csr_pem: "-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n", not_after: null, message_code: "pki.renew.manual", message: "Sign this request…", approve_command: "ianitor-control ca sign …", problem: null }
: null,
banner: m.state.renewal ? null : { code: "pki.renew_due", message: "The Domi intermediate certificate expires in 23 days, on 30 November 2026." },
}
: { state: "ok", subject: "x", not_after: later(86400 * 300), days_left: 300, renewal: null, banner: null },
site: { forward_auth_configured: true, acme_configured: true, secrets: ["api_key"], watch_seconds: 60, share_links_available: true },
paused: null,
paused_reason: null,
health_error: null,
rev: "rev1",
viewer: { name: "mark", via: "authelia" },
server_time: now(),
});
const routes: [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]][] = [
["GET", /^\/overview$/, () => [200, overview()]],
["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]],
["POST", /^\/hosts$/, (_, b) => {
const h = (b.host as Json).hostname as string;
m.state.hostsAdded.push(h);
return [202, { apply: apply("ch_new", "queued", `Added ${h}`, [h]) }];
}],
["GET", /^\/applies\/ch_new$/, () => [200, apply("ch_new", "kept", `Added ${m.state.hostsAdded.at(-1)}`, [m.state.hostsAdded.at(-1) ?? ""])]],
["GET", /^\/applies\/(.+)$/, (mm) => [200, apply(mm[1], "kept", "Done", ["x.home.test"])]],
["POST", /^\/undo$/, () => [202, { apply: apply("ch_undo", "queued", "Undid: Added recipes.home.test", ["recipes.home.test"]) }]],
["GET", /^\/history(\?.*)?$/, () => [200, { entries: [{ change_id: "ch_old", summary: "Changed wiki.home.test", kind: "edit", state: "kept", at: now(), commit_short: "9b20e7d", hosts: ["wiki.home.test"], reason_short: null }], next_before: null }]],
["GET", /^\/history\/ch_old\/restore-preview$/, () => [200, { restorable: true, same_as_current: false, changes: [{ hostname: "wiki.home.test", effect: "changed", fields: [{ field: "upstreams", from: "http://10.0.0.2:3000", to: "http://10.0.0.9:3000" }] }], blocked: null }]],
["POST", /^\/restore$/, () => [202, { apply: apply("ch_restore", "queued", "Restored the version of 5 November 2026", ["wiki.home.test"]) }]],
["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_1", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.abc`, expires_at: later(7 * 86400), path_prefix: "/", has_password: false, warning: null }]],
["PATCH", /^\/hosts\/([^/]+)$/, (mm) => [202, { apply: apply("ch_share", "queued", `Turned share links on for ${decodeURIComponent(mm[1])}`, [decodeURIComponent(mm[1])]) }]],
["DELETE", /^\/share-links\/.+$/, () => [204, null]],
["GET", /^\/engine$/, () => {
if (m.state.switching > 0) {
m.state.switching--;
if (m.state.switching === 0) m.state.engine = "caddy";
}
return [200, { running: m.state.engine, state: m.state.switching > 0 ? "switching" : "running", target: null, since: now(), switchable: true, last_error: null, notes: [] }];
}],
["POST", /^\/engine$/, () => {
m.state.switching = 1;
return [202, { running: m.state.engine, state: "switching", target: "caddy", since: now(), switchable: true, last_error: null, notes: [] }];
}],
["GET", /^\/certs$/, () => [200, { intermediate: overview().intermediate, root: { offline: true, subject: "Domi PKI Root", not_after: later(86400 * 3000), sha256: "ab" }, devices: [], device_lifetime_days: 365, server_lifetime_days: 90, approval: "manual", requests: [] }]],
["POST", /^\/certs\/devices$/, (_, b) => [202, { request_id: "pr_dev", kind: "device", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: null, device_id: null, name: b.name, csr_pem: null, not_after: null, message_code: "pki.waiting.manual", message: "Approve it on the server…", approve_command: "ianitor-control pki approve 47 19 83", problem: null }]],
["GET", /^\/pki-requests\/pr_dev$/, () => {
m.state.requestPolls++;
return [200, { request_id: "pr_dev", kind: "device", state: "approved", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: now(), device_id: "dv_1", name: "Mark's phone", csr_pem: null, not_after: null, message_code: "pki.issued", message: "Mark's phone has a certificate.", approve_command: null, problem: null }];
}],
["POST", /^\/certs\/devices\/dv_1\/bundle$/, () => [200, { download_url: "https://ui.home.test/api/v1/device-bundles/abc", one_time_password: "ABCD-EFGH-JKLM-NPQR", expires_at: later(600), filename: "domi-device.p12", qr_svg: "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>" }]],
["POST", /^\/certs\/intermediate\/renewal$/, () => {
m.state.renewal = true;
return [202, { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83" }];
}],
["GET", /^\/settings$/, () => [200, { repo: { name: "ianitor-routes", last_push_at: now() }, watch_seconds: 60 }]],
["GET", /^\/tokens$/, () => [200, { items: [] }]],
["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 }]],
];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url;
const path = url.replace(/^.*\/api\/v1/, "");
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" } });
}) as typeof fetch;
return m;
}
+39
View File
@@ -0,0 +1,39 @@
// 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/.
// jsdom lacks a few browser features the UI uses.
if (typeof HTMLDialogElement !== "undefined") {
const p = HTMLDialogElement.prototype as HTMLDialogElement & Record<string, unknown>;
if (!p.showModal) {
p.showModal = function (this: HTMLDialogElement) {
this.setAttribute("open", "");
};
p.show = function (this: HTMLDialogElement) {
this.setAttribute("open", "");
};
p.close = function (this: HTMLDialogElement) {
this.removeAttribute("open");
};
}
}
const clipboard = { text: "", writeText: async (t: string) => void (clipboard.text = t) };
Object.defineProperty(globalThis.navigator, "clipboard", { value: clipboard, configurable: true });
(globalThis as unknown as { __clipboard: typeof clipboard }).__clipboard = clipboard;
if (!("BroadcastChannel" in globalThis)) {
(globalThis as unknown as { BroadcastChannel: unknown }).BroadcastChannel = class {
onmessage: unknown = null;
postMessage() {}
close() {}
};
}
if (!("randomUUID" in crypto)) {
Object.defineProperty(crypto, "randomUUID", { value: () => Math.random().toString(36).slice(2) });
}
window.open = () => null;
HTMLAnchorElement.prototype.click = function () {};