192 lines
11 KiB
TypeScript
192 lines
11 KiB
TypeScript
// 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. Its builders and routes are also the
|
|
// base of the screenshots' demo control plane (demo.ts, docs/release.md).
|
|
|
|
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();
|
|
|
|
export 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 },
|
|
};
|
|
}
|
|
|
|
export 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,
|
|
};
|
|
}
|
|
|
|
/** 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))],
|
|
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, compared: 3, matched: 3, 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: 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(),
|
|
});
|
|
|
|
return [
|
|
["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 }]],
|
|
];
|
|
}
|
|
|
|
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;
|
|
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 });
|
|
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;
|
|
}
|