[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:
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<!-- 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/. -->
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<title>Hosts — Ianitor Domi</title>
|
||||
</head>
|
||||
<body class="ia">
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
+22
-3
@@ -1,10 +1,29 @@
|
||||
{
|
||||
"name": "web",
|
||||
"version": "0.0.0",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"license": "MPL-2.0",
|
||||
"description": "Ianitor Domi web UI (Svelte 5). Placeholder until phase 3.",
|
||||
"description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node -e \"console.log('web: placeholder, the UI arrives in phase 3; nothing is listening')\""
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ianitor/ui": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
||||
"@testing-library/svelte": "^5.2.6",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@tsconfig/svelte": "^5.0.4",
|
||||
"jsdom": "^26.0.0",
|
||||
"svelte": "^5.20.0",
|
||||
"svelte-check": "^4.1.4",
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^6.1.0",
|
||||
"vitest": "^3.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// The shell (handoff §2.16): sidebar on desktop, top and bottom bars on phone, the routes,
|
||||
// the banners every screen starts with, toasts and the signed-out dialog (§10).
|
||||
import { onMount } from "svelte";
|
||||
import { Button, Dialog, Icon } from "@ianitor/ui";
|
||||
import type { IconName } from "@ianitor/ui";
|
||||
import TopBanners from "./components/TopBanners.svelte";
|
||||
import { app, navigate, refresh, startPolling } from "./lib/app.svelte";
|
||||
import { remembered } from "./lib/applies";
|
||||
import Certificates from "./views/Certificates.svelte";
|
||||
import History from "./views/History.svelte";
|
||||
import Hosts from "./views/Hosts.svelte";
|
||||
import RenewByHand from "./views/RenewByHand.svelte";
|
||||
import Settings from "./views/Settings.svelte";
|
||||
import SignedIn from "./views/SignedIn.svelte";
|
||||
|
||||
const route = $derived.by(() => {
|
||||
const u = new URL(app.path, "http://x");
|
||||
const p = u.pathname.replace(/\/+$/, "") || "/";
|
||||
const seg = p.split("/").filter(Boolean).map(decodeURIComponent);
|
||||
if (p === "/signed-in") return { view: "signed-in" as const };
|
||||
if (seg[0] === "history") return { view: "history" as const, host: u.searchParams.get("host") ?? undefined, pick: seg[1] };
|
||||
if (seg[0] === "certificates") return { view: seg[1] === "renew-by-hand" ? ("renew" as const) : ("certs" as const), newDevice: seg[1] === "new" };
|
||||
if (seg[0] === "settings") return { view: "settings" as const, tab: seg[1] ?? "general" };
|
||||
return { view: "hosts" as const, newHost: seg[0] === "hosts" && seg[1] === "new", edit: seg[0] === "hosts" && seg[2] === "edit" ? seg[1] : undefined };
|
||||
});
|
||||
|
||||
const NAV: { href: string; label: string; icon: IconName; views: string[] }[] = [
|
||||
{ href: "/", label: "Hosts", icon: "building", views: ["hosts"] },
|
||||
{ href: "/history", label: "History", icon: "history", views: ["history"] },
|
||||
{ href: "/certificates", label: "Certificates", icon: "shield", views: ["certs", "renew"] },
|
||||
{ href: "/settings/general", label: "Settings", icon: "gear", views: ["settings"] },
|
||||
];
|
||||
const TITLES: Record<string, string> = { hosts: "Hosts", history: "History", certs: "Certificates", renew: "Certificates", settings: "Settings", "signed-in": "Signed in" };
|
||||
|
||||
$effect(() => {
|
||||
document.title = `${TITLES[route.view] ?? "Hosts"} — Ianitor Domi`;
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
if (route.view === "signed-in") return;
|
||||
const stop = startPolling();
|
||||
// Resume an apply this tab was watching before a reload or a sign-in (§3).
|
||||
const id = remembered();
|
||||
if (id && route.view === "hosts") app.panel = { kind: "host", resume: id };
|
||||
let ch: BroadcastChannel | undefined;
|
||||
try {
|
||||
ch = new BroadcastChannel("ianitor-auth");
|
||||
ch.onmessage = (m) => {
|
||||
if (m.data === "signed-in") {
|
||||
app.signedOut = false;
|
||||
void refresh();
|
||||
}
|
||||
};
|
||||
} catch {
|
||||
/* no BroadcastChannel: "I have signed in" still works */
|
||||
}
|
||||
return () => {
|
||||
stop();
|
||||
ch?.close();
|
||||
};
|
||||
});
|
||||
|
||||
function go(e: MouseEvent, href: string) {
|
||||
if (e.metaKey || e.ctrlKey || e.shiftKey) return;
|
||||
e.preventDefault();
|
||||
navigate(href);
|
||||
}
|
||||
|
||||
function signIn() {
|
||||
const w = window.open("/signed-in", "ianitor-sign-in");
|
||||
if (!w) location.href = `/signed-in?back=${encodeURIComponent(app.path)}`;
|
||||
}
|
||||
|
||||
async function signedInAgain() {
|
||||
app.signedOut = false;
|
||||
await refresh();
|
||||
}
|
||||
|
||||
const viewer = $derived(app.overview?.viewer ?? null);
|
||||
</script>
|
||||
|
||||
{#if route.view === "signed-in"}
|
||||
<SignedIn />
|
||||
{:else}
|
||||
<a class="skip domi-btn" href="#main">Skip to content</a>
|
||||
<div class="shell">
|
||||
<nav class="sidebar" aria-label="Main">
|
||||
<div class="ia-wordmark brand">IANITOR DOMI</div>
|
||||
{#each NAV as n (n.href)}
|
||||
<a href={n.href} class="nav" aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} />{n.label}</a>
|
||||
{/each}
|
||||
<div class="foot ia-muted">
|
||||
<p>{viewer?.via === "authelia" ? `Signed in as ${viewer.name} through Authelia` : viewer ? `Using the API token "${viewer.name}"` : "Signed in through Authelia"}</p>
|
||||
<p>Control on 127.0.0.1 only</p>
|
||||
</div>
|
||||
</nav>
|
||||
<header class="topbar"><span class="ia-wordmark">IANITOR DOMI</span></header>
|
||||
<main id="main" tabindex="-1">
|
||||
<TopBanners />
|
||||
{#if route.view === "hosts"}
|
||||
<Hosts route={{ newHost: route.newHost, edit: route.edit }} />
|
||||
{:else if route.view === "history"}
|
||||
{#key route.host}<History host={route.host} pick={route.pick} />{/key}
|
||||
{:else if route.view === "certs"}
|
||||
<Certificates newDevice={route.newDevice} />
|
||||
{:else if route.view === "renew"}
|
||||
<RenewByHand />
|
||||
{:else if route.view === "settings"}
|
||||
<Settings tab={route.tab} />
|
||||
{/if}
|
||||
</main>
|
||||
<nav class="bottombar" aria-label="Main">
|
||||
{#each NAV as n (n.href)}
|
||||
<a href={n.href} aria-current={n.views.includes(route.view) ? "page" : undefined} onclick={(e) => go(e, n.href)}><Icon name={n.icon} /><span>{n.label}</span></a>
|
||||
{/each}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="ia-toasts" role="status" aria-live="polite">
|
||||
{#each app.toasts as t (t.id)}<div class="ia-toast"><Icon name="check" />{t.text}</div>{/each}
|
||||
</div>
|
||||
|
||||
{#if app.signedOut}
|
||||
<Dialog title="Your sign-in has ended" role="alertdialog" escape={false} closable={false} onclose={() => {}}>
|
||||
<p>Sign in again; this page keeps what you typed.</p>
|
||||
{#snippet footer()}
|
||||
<Button onclick={signedInAgain}>I have signed in</Button>
|
||||
<Button variant="primary" onclick={signIn} data-autofocus>Sign in</Button>
|
||||
{/snippet}
|
||||
</Dialog>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.shell { display: grid; grid-template-columns: var(--sidebar-w) minmax(0, 1fr); min-height: 100dvh; }
|
||||
.sidebar { background: var(--colonnade); border-right: 1px solid var(--hairline); padding: 22px 14px; display: flex; flex-direction: column; gap: 4px; position: sticky; top: 0; height: 100dvh; }
|
||||
.brand { padding: 4px 10px 18px; }
|
||||
.nav { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-nav); text-decoration: none; border: 1px solid transparent; }
|
||||
.nav:hover { background: var(--surface); color: var(--text); }
|
||||
.nav[aria-current="page"] { background: var(--surface-2); color: var(--text); box-shadow: var(--inset-lit); border-color: color-mix(in srgb, var(--accent) 30%, transparent); }
|
||||
.nav[aria-current="page"] :global(svg) { color: var(--accent); }
|
||||
.foot { margin-top: auto; font-size: 0.82rem; display: flex; flex-direction: column; gap: 4px; padding: 0 10px; }
|
||||
main { padding: var(--main-pad); display: flex; flex-direction: column; gap: 18px; min-width: 0; outline: none; }
|
||||
.topbar, .bottombar { display: none; }
|
||||
@media (max-width: 719.98px) {
|
||||
.shell { grid-template-columns: minmax(0, 1fr); }
|
||||
.sidebar { display: none; }
|
||||
.topbar { display: flex; align-items: center; justify-content: space-between; background: var(--colonnade); border-bottom: 1px solid var(--hairline); padding: 10px 16px; }
|
||||
.topbar .ia-wordmark { font-size: 12px; letter-spacing: 0.26em; }
|
||||
main { padding: 18px 16px calc(90px + env(safe-area-inset-bottom)); gap: 14px; }
|
||||
.bottombar { display: grid; grid-template-columns: repeat(4, 1fr); position: fixed; left: 0; right: 0; bottom: 0; background: var(--colonnade); border-top: 1px solid var(--hairline); padding: 6px 8px calc(10px + env(safe-area-inset-bottom)); z-index: 40; }
|
||||
.bottombar a { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: var(--phone-bar-h); border-radius: var(--radius-sm); color: var(--text-2); font-weight: 600; font-size: var(--fs-tab-phone); text-decoration: none; }
|
||||
.bottombar a[aria-current="page"] { background: var(--surface-2); color: var(--text); }
|
||||
.bottombar a[aria-current="page"] :global(svg) { color: var(--accent); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,80 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §7.1: the apply checklist, its countdown and the queued state.
|
||||
import { Button, Icon, Progress } from "@ianitor/ui";
|
||||
import type { ApplyView } from "../lib/types";
|
||||
import { app, secondsLeft } from "../lib/app.svelte";
|
||||
|
||||
let { apply, oncancel }: { apply: ApplyView; oncancel?: () => void } = $props();
|
||||
|
||||
const engine = $derived(app.overview?.engine.running === "caddy" ? "Caddy" : "Pingora");
|
||||
const watchSeconds = $derived(app.overview?.site?.watch_seconds ?? 60);
|
||||
const left = $derived(apply.watch ? secondsLeft(apply.watch.ends_at) : watchSeconds);
|
||||
const st = (k: string) => apply.steps.find((s) => s.key === k)?.state ?? "pending";
|
||||
const merged = (a: string, b: string) => {
|
||||
const x = st(a);
|
||||
const y = st(b);
|
||||
if (x === "failed" || y === "failed") return "failed";
|
||||
if (x === "running" || y === "running") return "running";
|
||||
if (x === "done" && (y === "done" || y === "skipped")) return "done";
|
||||
return x;
|
||||
};
|
||||
const noWatch = $derived(apply.reason?.code === "apply.kept.no_watch");
|
||||
const rows = $derived([
|
||||
{ s: st("validate"), t: { pending: "Check the host file", running: "Checking the host file", done: "Checked the host file", failed: "The host file did not pass the check", skipped: "Check the host file" } },
|
||||
{ s: merged("compile", "write"), t: { pending: "Build the Pingora and Caddy settings", running: "Building the Pingora and Caddy settings", done: "Built the Pingora and Caddy settings", failed: "Could not build the settings", skipped: "Build the Pingora and Caddy settings" } },
|
||||
{ s: st("reload"), t: { pending: `Reload ${engine}`, running: `Reloading ${engine}`, done: `Reloaded ${engine}, no connections dropped`, failed: `${engine} did not take the new settings`, skipped: `Reload ${engine}` } },
|
||||
{
|
||||
s: st("watch"),
|
||||
t: noWatch
|
||||
? { pending: "Check that it answers", running: `Checking that it answers: ${left} s left`, done: "It answers", failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." }
|
||||
: { pending: `Watch health checks for ${watchSeconds} s`, running: `Watching health checks: ${left} s left`, done: `Health checks passed for ${watchSeconds} s`, failed: "Health checks failed", skipped: "Nothing to watch: the host is removed." },
|
||||
},
|
||||
]);
|
||||
const prefix: Record<string, string> = { done: "Done:", running: "Now:", pending: "Next:", failed: "Failed:", skipped: "Skipped:" };
|
||||
const final = $derived(["kept", "reverted", "failed", "needs_attention"].includes(apply.state));
|
||||
</script>
|
||||
|
||||
{#if apply.state === "queued"}
|
||||
<p class="ia-status" data-s="running">
|
||||
<Icon name="clock" />
|
||||
<span>
|
||||
Waiting for "{apply.queue?.waiting_for?.summary ?? "another change"}" to finish{apply.queue?.waiting_for?.seconds_left != null
|
||||
? `, about ${apply.queue.waiting_for.seconds_left} s`
|
||||
: ""}.
|
||||
{#if (apply.queue?.position ?? 1) > 1}{(apply.queue?.position ?? 1) - 1} other changes are ahead of this one.{/if}
|
||||
</span>
|
||||
</p>
|
||||
{#if oncancel}<div><Button onclick={oncancel}>Cancel</Button></div>{/if}
|
||||
{:else}
|
||||
<ol class="steps">
|
||||
{#each rows as r, i (i)}
|
||||
<li class={r.s}>
|
||||
{#if r.s === "done"}<Icon name="check" />{:else if r.s === "running"}<Icon name="clock" />{:else if r.s === "failed"}<Icon name="ring" />{:else}<span class="hollow" aria-hidden="true"></span>{/if}
|
||||
<span><span class="sr-only">{prefix[r.s]}</span>{r.t[r.s as keyof typeof r.t]}</span>
|
||||
</li>
|
||||
{/each}
|
||||
{#if st("watch") === "failed" && !final}
|
||||
<li class="running"><Icon name="clock" /><span><span class="sr-only">Now:</span>Undoing the change</span></li>
|
||||
{/if}
|
||||
</ol>
|
||||
{#if apply.state === "watching"}
|
||||
<Progress label="Health watch" max={watchSeconds} now={watchSeconds - left} text="{left} seconds left" />
|
||||
<p class="ia-hint">You can leave this screen. Other changes wait their turn; only one apply runs at a time.</p>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.steps li { display: flex; gap: 10px; align-items: center; }
|
||||
.steps li.pending { color: var(--muted); }
|
||||
.steps li.running { color: var(--text); }
|
||||
.steps li.running :global(svg) { color: var(--accent); }
|
||||
.steps li.done { color: var(--text-2); }
|
||||
.steps li.done :global(svg) { color: var(--kept); }
|
||||
.steps li.failed :global(svg) { color: var(--down); }
|
||||
.steps li.skipped { color: var(--muted); }
|
||||
.hollow { width: 14px; height: 14px; border-radius: 50%; border: 2px solid var(--muted); margin: 2px; }
|
||||
</style>
|
||||
@@ -0,0 +1,140 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §7.4 and §7.5: the last-change bar with Undo (1 click), and the reverted / not
|
||||
// applied banner that stands in for its first line.
|
||||
import { Banner, Button, Icon, Progress } from "@ianitor/ui";
|
||||
import { ApiError, call, del, newKey, post, sentence } from "../lib/api";
|
||||
import { app, refresh, secondsLeft, toast } from "../lib/app.svelte";
|
||||
import { firstSentence, when } from "../lib/format";
|
||||
import type { ApplyView } from "../lib/types";
|
||||
|
||||
let { onshowsteps, onedit }: { onshowsteps: (id: string) => void; onedit: (a: ApplyView, field?: string) => void } = $props();
|
||||
|
||||
const o = $derived(app.overview);
|
||||
const last = $derived(o?.last_apply ?? null);
|
||||
const active = $derived(o?.active_apply ?? null);
|
||||
const undo = $derived(o?.undo ?? null);
|
||||
let moved = $state<string | null>(null);
|
||||
let undoing = $state(false);
|
||||
let pushing = $state(false);
|
||||
const dismissKey = $derived(last ? `apply:${last.id}` : "");
|
||||
|
||||
function runningHeading(summary: string, a: ApplyView | null): string {
|
||||
if (!a) return summary;
|
||||
const h = a.hosts[0] ?? "";
|
||||
switch (a.kind) {
|
||||
case "add": return `Adding ${h}`;
|
||||
case "remove": return `Removing ${h}`;
|
||||
case "edit": return `Changing ${h}`;
|
||||
case "share_links": return `Turning on share links for ${h}`;
|
||||
default: return summary;
|
||||
}
|
||||
}
|
||||
|
||||
async function doUndo() {
|
||||
if (!undo?.target) return;
|
||||
undoing = true;
|
||||
moved = null;
|
||||
try {
|
||||
await post("/undo", { target_change_id: undo.target.change_id });
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.code === "undo.target_moved") {
|
||||
moved = e.body.message;
|
||||
await refresh();
|
||||
} else {
|
||||
moved = sentence(e);
|
||||
}
|
||||
} finally {
|
||||
undoing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pushNow() {
|
||||
pushing = true;
|
||||
try {
|
||||
await call("POST", "/repo/push", {}, { idem: newKey() });
|
||||
} catch {
|
||||
/* the bar shows the push state on the next poll */
|
||||
} finally {
|
||||
pushing = false;
|
||||
await refresh();
|
||||
}
|
||||
}
|
||||
|
||||
async function cancel(id: string) {
|
||||
try {
|
||||
await del(`/applies/${encodeURIComponent(id)}`);
|
||||
toast("Cancelled before it started. Nothing changed.");
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
moved = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
const keptLine = $derived.by(() => {
|
||||
if (!last || last.state !== "kept") return "";
|
||||
const t = when(last.finished_at ?? last.created_at, app.now);
|
||||
const code = last.reason?.code ?? "";
|
||||
if (code === "apply.kept.no_watch") return `${last.hosts[0] ?? ""} has no health check, so Ianitor only checked that it answers.`;
|
||||
const what = code === "apply.kept.removed" ? "removed" : code === "apply.kept.no_edge" ? "saved, nothing checked (development mode)" : `health checks passed for ${o?.site?.watch_seconds ?? 60} s`;
|
||||
const push = last.push?.state === "pushed" ? `pushed to Gitea as ${last.commit_short}` : last.push?.state === "pending" ? "sending to Gitea" : last.commit_short ? `saved as commit ${last.commit_short}` : "";
|
||||
return [t, what, push].filter(Boolean).join(" · ");
|
||||
});
|
||||
const pushFailed = $derived(last?.state === "kept" && last.push?.state === "failed");
|
||||
const undoReason = $derived(undo?.blocked && undo.blocked.code !== "undo.nothing" ? undo.blocked.message : null);
|
||||
const watchLeft = $derived(last?.watch ? secondsLeft(last.watch.ends_at) : null);
|
||||
</script>
|
||||
|
||||
{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)}
|
||||
{@const parts = firstSentence(last.reason?.message ?? "")}
|
||||
<Banner tone="notice" ondismiss={() => (app.dismissed = [...app.dismissed, dismissKey])}>
|
||||
{#snippet title()}<span class="ia-status" data-s="reverted"><Icon name="undo" /><span class="word">{last.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
|
||||
{#if parts[1]}Reason: {parts[1]}{/if}
|
||||
{#snippet actions()}
|
||||
{#if last.attempted_host}<Button variant="outline" onclick={() => onedit(last, last.reason?.field ?? undefined)}>Edit and try again</Button>{/if}
|
||||
{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
|
||||
{#if last || active}
|
||||
<section class="ia-bar" aria-label="Last change">
|
||||
{#if active}
|
||||
<div class="grow">
|
||||
<div class="ia-status" data-s="running"><Icon name="clock" /><span class="word">{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"}</span>
|
||||
<span>{runningHeading(active.summary, last && last.id === active.id ? last : null)}</span></div>
|
||||
<div class="ia-sub">{active.state === "queued" ? "Waiting for another change to finish" : `${watchLeft ?? active.seconds_left ?? 0} s left`}</div>
|
||||
{#if active.state === "watching" && watchLeft != null}
|
||||
{@const total = o?.site?.watch_seconds ?? 60}
|
||||
<Progress label="Health watch" max={total} now={total - watchLeft} text="{watchLeft} seconds left" />
|
||||
{/if}
|
||||
</div>
|
||||
{#if active.state === "queued"}<Button onclick={() => cancel(active.id)}>Cancel</Button>{:else}<button type="button" class="domi-btn link" onclick={() => onshowsteps(active.id)}>Show steps</button>{/if}
|
||||
{:else if last}
|
||||
<div class="grow">
|
||||
{#if last.state === "kept"}
|
||||
<div><span class="ia-status" data-s="kept"><Icon name="check" /><span class="word">kept</span></span> {last.summary}</div>
|
||||
<div class="ia-sub" class:warn={pushFailed}>{pushFailed ? "Kept, but not yet saved to Gitea. Ianitor tries again by itself." : keptLine}</div>
|
||||
{:else if undo?.target}
|
||||
<div>Undo: {undo.target.summary}</div>
|
||||
{/if}
|
||||
{#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}<div class="ia-sub">{undo.effect}</div>{/if}
|
||||
{#if moved}<div class="ia-sub" role="status">{moved}</div>{/if}
|
||||
{#if undoReason}<div class="ia-sub" id="undo-reason">{undoReason}</div>{/if}
|
||||
{#if !undo?.target}<div class="ia-sub">Nothing to undo yet.</div>{/if}
|
||||
</div>
|
||||
{#if pushFailed}<Button onclick={pushNow} pending={pushing}>Try now</Button>{/if}
|
||||
{#if undo?.target}
|
||||
<Button icon="undo" onclick={doUndo} pending={undoing} disabled={!!undoReason || !undo.available}
|
||||
describedby={undoReason ? "undo-reason" : undefined}
|
||||
label="Undo: {undo.target.summary}.{undo.effect ? ' ' + undo.effect + '.' : ''}">Undo</Button>
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.warn { color: var(--degraded); }
|
||||
</style>
|
||||
@@ -0,0 +1,107 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §9: the engine popover. Click 1 is the chip, click 2 "Switch to Caddy" (the popover
|
||||
// is the confirmation). The switch runs in control; this polls GET /engine until it ends.
|
||||
import { onDestroy } from "svelte";
|
||||
import { Banner, Button, Dialog, Icon, Progress } from "@ianitor/ui";
|
||||
import { call, get, newKey, sentence } from "../lib/api";
|
||||
import { app, refresh } from "../lib/app.svelte";
|
||||
import { when } from "../lib/format";
|
||||
import type { EngineView } from "../lib/types";
|
||||
|
||||
let { onclose }: { onclose: () => void } = $props();
|
||||
|
||||
const e = $derived(app.overview?.engine ?? null);
|
||||
const running = $derived(e?.running ?? "pingora");
|
||||
const name = $derived(running === "caddy" ? "Caddy" : "Pingora");
|
||||
const other = $derived(running === "caddy" ? "Pingora" : "Caddy");
|
||||
const target = $derived(running === "caddy" ? "pingora" : "caddy");
|
||||
let switching = $state(false);
|
||||
let problem = $state<string | null>(null);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
onDestroy(() => clearTimeout(timer));
|
||||
|
||||
const activeLinks = $derived(app.overview?.hosts.filter((h) => h.share_links).length ?? 0);
|
||||
const notReady = $derived(running === "pingora" && !e?.fallback_ready?.built_at);
|
||||
const disabledReason = $derived(!e?.switchable ? "This server does not let Ianitor switch engines." : notReady ? "Caddy is not ready: its settings have not been built yet." : null);
|
||||
|
||||
async function doSwitch() {
|
||||
problem = null;
|
||||
switching = true;
|
||||
const from = name;
|
||||
const to = other;
|
||||
try {
|
||||
await call("POST", "/engine", { target }, { idem: newKey() });
|
||||
const poll = async () => {
|
||||
try {
|
||||
const v = await get<EngineView>("/engine", { quiet: true });
|
||||
if (v.state === "switching") {
|
||||
timer = setTimeout(poll, 1000);
|
||||
return;
|
||||
}
|
||||
switching = false;
|
||||
await refresh();
|
||||
if (v.last_error) {
|
||||
app.switchResult = { ok: false, title: `${to} did not start, so ${from} is serving again.`, text: "Visitors had a short break and nothing else changed.", detail: v.last_error.detail ?? null };
|
||||
} else {
|
||||
app.switchResult = { ok: true, title: `Now serving with ${to}.`, text: "Switch back from the engine chip at any time; it is the same 2 clicks." };
|
||||
}
|
||||
onclose();
|
||||
} catch {
|
||||
// Contact may drop for a few seconds while the engines change (§9.2).
|
||||
timer = setTimeout(poll, 1000);
|
||||
}
|
||||
};
|
||||
timer = setTimeout(poll, 500);
|
||||
} catch (err) {
|
||||
switching = false;
|
||||
problem = sentence(err);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Dialog title="Serving with {name}" kind="popover" modal={false} {onclose}>
|
||||
<p class="ia-label">Engine</p>
|
||||
{#if e?.state === "stopped"}
|
||||
<p><strong>{name} is not answering.</strong> Visitors may not reach any host. Switching to {other} is the quickest way back.</p>
|
||||
{:else}
|
||||
<p class="ia-text2">
|
||||
{#if e?.since}Since {when(e.since, app.now)}. {/if}
|
||||
{#if running === "pingora"}
|
||||
{#if notReady}Caddy is not ready: its settings have not been built yet.{:else}Caddy is ready with the same routes: built {when(e?.fallback_ready?.built_at, app.now)}{e?.fallback_ready?.current ? "" : " (it is rebuilt from the current routes when you switch)"}.{/if}
|
||||
{:else}Pingora is ready with the same routes.{/if}
|
||||
</p>
|
||||
{/if}
|
||||
<div class="ia-card">
|
||||
<p><strong>What happens</strong></p>
|
||||
<ul>
|
||||
<li>{name} stops and {other} starts. New visits reach {other} in about 2 seconds.</li>
|
||||
<li>Open connections close; videos and uploads in progress restart.</li>
|
||||
<li>Hosts and certificates stay the same.</li>
|
||||
{#if running === "pingora"}
|
||||
<li>Share links stop working while Caddy serves: visitors with a link get the normal sign-in. They work again when you switch back.{#if activeLinks} Hosts with share links: {activeLinks}.{/if}</li>
|
||||
<li>Changes wait while Caddy serves; switch back to make them.</li>
|
||||
{:else}
|
||||
<li>Share links work again, and changes can be made again.</li>
|
||||
{/if}
|
||||
<li>This page may lose contact for a few seconds.</li>
|
||||
</ul>
|
||||
</div>
|
||||
{#if switching}
|
||||
<p class="ia-status" data-s="running" role="status"><Icon name="clock" /><strong>Switching to {other}</strong></p>
|
||||
<Progress label="Switching engine" max={1} now={0} text="{name} stopping, starting {other}" />
|
||||
{/if}
|
||||
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||
{#if disabledReason}<p class="ia-hint" id="switch-reason">{disabledReason}</p>{/if}
|
||||
{#snippet footer()}
|
||||
<Button onclick={onclose}>Cancel</Button>
|
||||
<Button variant={e?.state === "stopped" ? "primary" : "outline"} icon="swap" onclick={doSwitch} pending={switching}
|
||||
disabled={!!disabledReason} describedby={disabledReason ? "switch-reason" : undefined}>Switch to {other}</Button>
|
||||
{/snippet}
|
||||
</Dialog>
|
||||
|
||||
<style>
|
||||
ul { margin: 6px 0 0; padding-left: 1.1rem; color: var(--text-2); }
|
||||
</style>
|
||||
@@ -0,0 +1,142 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §2.5 and §5.1: the host list, sorted down, degraded, pending, unknown, healthy.
|
||||
import { Status } from "@ianitor/ui";
|
||||
import type { StatusKind } from "@ianitor/ui";
|
||||
import HostMenu from "./HostMenu.svelte";
|
||||
import { app, changesBlocked } from "../lib/app.svelte";
|
||||
import { ago, duration } from "../lib/format";
|
||||
import type { HostRow } from "../lib/types";
|
||||
|
||||
let {
|
||||
hosts,
|
||||
onedit,
|
||||
onremove,
|
||||
onshare,
|
||||
onhistory,
|
||||
onretry,
|
||||
}: {
|
||||
hosts: HostRow[];
|
||||
onedit: (h: string) => void;
|
||||
onremove: (h: string) => void;
|
||||
onshare: (h: string) => void;
|
||||
onhistory: (h: string) => void;
|
||||
onretry: (h: string) => void;
|
||||
} = $props();
|
||||
|
||||
const ORDER: Record<string, number> = { down: 0, degraded: 1, pending: 2, unknown: 3, healthy: 4 };
|
||||
const sorted = $derived([...hosts].sort((a, b) => (ORDER[a.health.state] ?? 5) - (ORDER[b.health.state] ?? 5) || a.hostname.localeCompare(b.hostname)));
|
||||
const running = $derived(app.overview?.active_apply ? (app.overview.last_apply?.hosts ?? []) : []);
|
||||
const underCaddy = $derived(app.overview?.engine.running === "caddy");
|
||||
|
||||
function kind(h: HostRow): [StatusKind, string] {
|
||||
switch (h.health.state) {
|
||||
case "healthy": return ["healthy", "healthy"];
|
||||
case "degraded": return ["degraded", "degraded"];
|
||||
case "down": return ["down", "down"];
|
||||
case "pending": return ["unknown", "waiting"];
|
||||
default: return ["unknown", "not checked"];
|
||||
}
|
||||
}
|
||||
|
||||
function since(h: HostRow): string {
|
||||
return h.health.since ? duration((app.now - Date.parse(h.health.since)) / 1000) : "a while";
|
||||
}
|
||||
|
||||
function sub(h: HostRow): { text: string; problem: boolean } {
|
||||
const f = h.health.failure;
|
||||
const visitors = 'Visitors get an error page.';
|
||||
switch (h.health.state) {
|
||||
case "healthy": {
|
||||
const added = h.added_at && app.now - Date.parse(h.added_at) < 86_400_000 ? "Added today · c" : "C";
|
||||
const lat = h.health.latency_ms != null && !underCaddy ? ` · ${h.health.latency_ms} ms` : "";
|
||||
return { text: `${added}hecked ${ago(h.health.last_check_at, app.now)}${lat}`, problem: false };
|
||||
}
|
||||
case "degraded": {
|
||||
const ok = h.health.upstreams.filter((u) => u.state === "healthy").length;
|
||||
const m = h.health.upstreams.length;
|
||||
if (m > 1) return { text: `${ok} of ${m} addresses answer. Visitors are sent to the ones that do.`, problem: true };
|
||||
return { text: `Answering only some checks.`, problem: true };
|
||||
}
|
||||
case "down":
|
||||
if (f?.kind === "refused") return { text: `Connection refused for ${since(h)}. ${visitors}`, problem: true };
|
||||
if (f?.kind === "timeout") return { text: `Not answering for ${since(h)}. ${visitors}`, problem: true };
|
||||
if (f?.kind === "name") return { text: `The name ${f.upstream ?? ""} cannot be found. ${visitors}`, problem: true };
|
||||
if (f?.kind === "tls") return { text: `The certificate of ${f.upstream ?? ""} cannot be checked.`, problem: true };
|
||||
return { text: `Answering with an error page for ${since(h)}.`, problem: true };
|
||||
case "pending": return { text: "Waiting for the first check.", problem: false };
|
||||
default: return { text: "No health check set for this host.", problem: false };
|
||||
}
|
||||
}
|
||||
|
||||
function phoneDetail(h: HostRow): string {
|
||||
if (h.health.state === "healthy" && h.health.latency_ms != null) return `${h.health.latency_ms} ms`;
|
||||
if (h.health.state === "down" && h.health.failure?.kind === "refused") return `refused for ${since(h)}`;
|
||||
if (h.health.state === "unknown") return "no health check";
|
||||
if (h.added_at && app.now - Date.parse(h.added_at) < 86_400_000) return "added today";
|
||||
return h.share_links ? "share links on" : "";
|
||||
}
|
||||
|
||||
function chips(h: HostRow): string[] {
|
||||
const c = [h.tls === "domi" ? "Domi certificate" : "Let's Encrypt"];
|
||||
c.push(h.auth === "forward-auth" ? "Sign-in first" : "Open to anyone");
|
||||
if (h.share_links) c.push("Share links on");
|
||||
if (h.device_certs) c.push("Device certificate needed");
|
||||
if (!h.websockets) c.push("No websockets");
|
||||
return c;
|
||||
}
|
||||
|
||||
const blocked = $derived(changesBlocked());
|
||||
const shareReason = $derived(!app.overview?.site?.share_links_available ? (underCaddy ? "Share links are paused while Caddy serves." : "Share links are not set up on this server.") : null);
|
||||
</script>
|
||||
|
||||
<div class="ia-list" role="table" aria-label="Hosts">
|
||||
<div class="ia-row head" role="row">
|
||||
<span class="ia-label col-status" role="columnheader">Status</span>
|
||||
<span class="ia-label" role="columnheader">Host</span>
|
||||
<span class="ia-label desktop" role="columnheader">Sends traffic to</span>
|
||||
<span role="columnheader"><span class="sr-only">More</span></span>
|
||||
</div>
|
||||
{#each sorted as h (h.hostname)}
|
||||
{@const [k, w] = kind(h)}
|
||||
{@const s = sub(h)}
|
||||
<div class="ia-row" role="row">
|
||||
<span class="col-status" role="cell"><Status kind={k} word={w} /></span>
|
||||
<span role="cell">
|
||||
<span class="phone-dot"><Status kind={k} word="" /></span>
|
||||
<span class="ia-host">{h.hostname}</span>
|
||||
<span class="ia-chips desktop">{#each chips(h) as c (c)}<span class="ia-chip">{c}</span>{/each}</span>
|
||||
<span class="ia-sub phone">{w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""}</span>
|
||||
</span>
|
||||
<span role="cell" class="desktop">
|
||||
<span>{h.upstreams[0] ?? ""}</span>{#if h.upstreams.length > 1} <span class="ia-muted">+{h.upstreams.length - 1} more</span>{/if}
|
||||
<span class="ia-sub" class:problem={s.problem} style="display:block">{running.includes(h.hostname) ? "Changing now · " : ""}{s.text}</span>
|
||||
{#if h.certificate.state === "pending"}<span class="ia-sub" style="display:block">Waiting for Let's Encrypt to issue the certificate.</span>{/if}
|
||||
{#if h.certificate.state === "failed"}
|
||||
<span class="ia-sub" style="display:block;color:var(--down)">Let's Encrypt could not confirm <strong>{h.hostname}</strong>. The name must point to this server, and port 80 must be open from the internet.
|
||||
<button type="button" class="domi-btn link" onclick={() => onretry(h.hostname)}>Try again</button></span>
|
||||
{/if}
|
||||
</span>
|
||||
<span role="cell">
|
||||
<HostMenu hostname={h.hostname} items={[
|
||||
{ label: "Share link", icon: "link", reason: shareReason, run: () => onshare(h.hostname) },
|
||||
{ label: "Edit host", icon: "pencil", reason: blocked, run: () => onedit(h.hostname) },
|
||||
{ label: "Show in history", icon: "history", run: () => onhistory(h.hostname) },
|
||||
{ label: "Remove host", icon: "trash", danger: true, divider: true, reason: blocked, run: () => onremove(h.hostname) },
|
||||
]} />
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.phone, .phone-dot { display: none; }
|
||||
.problem { color: var(--text-2) !important; }
|
||||
@media (max-width: 719.98px) {
|
||||
.desktop { display: none !important; }
|
||||
.phone { display: block; padding-left: 22px; }
|
||||
.phone-dot { display: inline; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,86 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts" module>
|
||||
import type { IconName } from "@ianitor/ui";
|
||||
export interface Item {
|
||||
label: string;
|
||||
icon: IconName;
|
||||
danger?: boolean;
|
||||
reason?: string | null;
|
||||
divider?: boolean;
|
||||
run: () => void;
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
// Handoff §2.6: the row's ⋯ menu (WAI-ARIA menu button).
|
||||
import { tick } from "svelte";
|
||||
import { Icon } from "@ianitor/ui";
|
||||
|
||||
let { hostname, items }: { hostname: string; items: Item[] } = $props();
|
||||
|
||||
let open = $state(false);
|
||||
let btn: HTMLButtonElement | undefined = $state();
|
||||
let list: HTMLUListElement | undefined = $state();
|
||||
const id = "menu-" + Math.random().toString(36).slice(2, 9);
|
||||
|
||||
const nodes = () => Array.from(list?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? []);
|
||||
|
||||
async function show(focus: "first" | "last" = "first") {
|
||||
open = true;
|
||||
await tick();
|
||||
const n = nodes();
|
||||
(focus === "first" ? n[0] : n[n.length - 1])?.focus();
|
||||
}
|
||||
|
||||
function close(back = true) {
|
||||
open = false;
|
||||
if (back) btn?.focus();
|
||||
}
|
||||
|
||||
function key(e: KeyboardEvent) {
|
||||
const n = nodes();
|
||||
const i = n.indexOf(document.activeElement as HTMLElement);
|
||||
if (e.key === "ArrowDown") { e.preventDefault(); n[(i + 1) % n.length]?.focus(); }
|
||||
else if (e.key === "ArrowUp") { e.preventDefault(); n[(i - 1 + n.length) % n.length]?.focus(); }
|
||||
else if (e.key === "Home") { e.preventDefault(); n[0]?.focus(); }
|
||||
else if (e.key === "End") { e.preventDefault(); n[n.length - 1]?.focus(); }
|
||||
else if (e.key === "Escape") { e.preventDefault(); close(); }
|
||||
else if (e.key === "Tab") close(false);
|
||||
}
|
||||
|
||||
function pick(it: Item) {
|
||||
if (it.reason) return;
|
||||
close(false);
|
||||
it.run();
|
||||
}
|
||||
|
||||
function outside(e: MouseEvent) {
|
||||
if (open && !(e.target instanceof Node && (list?.contains(e.target) || btn?.contains(e.target)))) close(false);
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onclick={outside} />
|
||||
|
||||
<div class="ia-menu-wrap">
|
||||
<button bind:this={btn} type="button" class="ia-icon-btn" aria-label="More for {hostname}" aria-haspopup="menu"
|
||||
aria-expanded={open} aria-controls={id}
|
||||
onclick={() => (open ? close() : show())}
|
||||
onkeydown={(e) => { if (e.key === "ArrowDown") { e.preventDefault(); show("first"); } else if (e.key === "ArrowUp") { e.preventDefault(); show("last"); } }}>
|
||||
<Icon name="dots" />
|
||||
</button>
|
||||
{#if open}
|
||||
<ul bind:this={list} class="ia-menu" role="menu" id={id} aria-label={hostname} tabindex="-1" onkeydown={key}>
|
||||
{#each items as it (it.label)}
|
||||
{#if it.divider}<li role="separator"><hr /></li>{/if}
|
||||
<li role="none">
|
||||
<button type="button" role="menuitem" tabindex="-1" class:danger={it.danger} aria-disabled={it.reason ? "true" : undefined} onclick={() => pick(it)}>
|
||||
<Icon name={it.icon} />{it.label}
|
||||
{#if it.reason}<span class="reason">{it.reason}</span>{/if}
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,499 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §6 and §7: the add/edit panel, its validation on blur, Apply, and the progress and
|
||||
// outcome of the apply it starts. Every decision comes from control; the form only carries it.
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
|
||||
import ApplyProgress from "./ApplyProgress.svelte";
|
||||
import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
|
||||
import { app, changesBlocked, refresh, toast } from "../lib/app.svelte";
|
||||
import { FINAL, follow } from "../lib/applies";
|
||||
import { firstSentence } from "../lib/format";
|
||||
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
|
||||
|
||||
let {
|
||||
hostname,
|
||||
resume,
|
||||
prefill,
|
||||
focusField,
|
||||
onclose,
|
||||
}: {
|
||||
hostname?: string;
|
||||
resume?: string;
|
||||
prefill?: HostSpec | null;
|
||||
focusField?: string;
|
||||
onclose: () => void;
|
||||
} = $props();
|
||||
|
||||
const site = $derived(app.overview?.site ?? null);
|
||||
const signinOk = $derived(site?.forward_auth_configured ?? false);
|
||||
|
||||
// ---- the form
|
||||
type Rule = { action: "set" | "remove"; name: string; kind: "value" | "secret"; value: string; secret: string };
|
||||
let host = $state({
|
||||
hostname: "",
|
||||
upstreams: [""],
|
||||
tls: "domi" as "domi" | "letsencrypt",
|
||||
auth: "forward-auth" as "forward-auth" | "none",
|
||||
websockets: true,
|
||||
share_links: false,
|
||||
device_certs: false,
|
||||
access_log: "off" as "off" | "truncated",
|
||||
hc: false,
|
||||
hcPath: "/",
|
||||
hcEvery: 30,
|
||||
req: [] as Rule[],
|
||||
resp: [] as Rule[],
|
||||
});
|
||||
let rev = $state<string | null>(null);
|
||||
let more = $state(false);
|
||||
let loading = $state(true);
|
||||
let notFound = $state<string | null>(null);
|
||||
let errors = $state<Record<string, ErrorBody>>({});
|
||||
let touched = $state<Record<string, boolean>>({});
|
||||
let summary = $state("");
|
||||
let underFooter = $state("");
|
||||
let conflict = $state<ErrorBody | null>(null);
|
||||
let topError = $state<ApiError | null>(null);
|
||||
let idem = newKey();
|
||||
let lastBody = "";
|
||||
|
||||
// ---- the apply
|
||||
let apply = $state<ApplyView | null>(null);
|
||||
let phase = $state<"form" | "progress">("form");
|
||||
let stop: (() => void) | undefined;
|
||||
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
function fromSpec(s: HostSpec) {
|
||||
host.hostname = s.hostname;
|
||||
host.upstreams = s.upstreams.length ? [...s.upstreams] : [""];
|
||||
host.tls = s.tls;
|
||||
host.auth = s.auth;
|
||||
host.websockets = s.websockets;
|
||||
host.share_links = s.share_links;
|
||||
host.device_certs = !!s.device_certs;
|
||||
host.access_log = s.access_log;
|
||||
host.hc = !!s.health_check;
|
||||
host.hcPath = s.health_check?.path ?? "/";
|
||||
host.hcEvery = s.health_check?.interval_secs ?? 30;
|
||||
const rule = (r: HeaderRule): Rule => ({ action: r.action, name: r.name, kind: r.secret ? "secret" : "value", value: r.value ?? "", secret: r.secret ?? "" });
|
||||
host.req = (s.request_headers ?? []).map(rule);
|
||||
host.resp = (s.response_headers ?? []).map(rule);
|
||||
if (host.hc || host.req.length || host.resp.length || !host.websockets || host.share_links || host.access_log !== "off" || host.device_certs) more = true;
|
||||
}
|
||||
|
||||
function spec(): HostSpec {
|
||||
const rules = (rs: Rule[]): HeaderRule[] =>
|
||||
rs.map((r) =>
|
||||
r.action === "remove"
|
||||
? { action: "remove", name: r.name }
|
||||
: r.kind === "secret"
|
||||
? { action: "set", name: r.name, secret: r.secret }
|
||||
: { action: "set", name: r.name, value: r.value },
|
||||
);
|
||||
// The UI always sends every field explicitly (the schema's own defaults differ).
|
||||
return {
|
||||
hostname: host.hostname.trim(),
|
||||
upstreams: host.upstreams.map((u) => u.trim()).filter((u, i) => u !== "" || i === 0),
|
||||
tls: host.tls,
|
||||
auth: host.auth,
|
||||
websockets: host.websockets,
|
||||
share_links: host.share_links,
|
||||
device_certs: host.device_certs,
|
||||
access_log: host.access_log,
|
||||
health_check: host.hc ? { path: host.hcPath, interval_secs: Number(host.hcEvery) } : null,
|
||||
request_headers: rules(host.req),
|
||||
response_headers: rules(host.resp),
|
||||
};
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
if (resume) {
|
||||
phase = "progress";
|
||||
stop = follow(resume, onApply);
|
||||
}
|
||||
if (prefill) {
|
||||
fromSpec(prefill);
|
||||
} else if (hostname) {
|
||||
try {
|
||||
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
|
||||
fromSpec(d.host);
|
||||
rev = d.rev;
|
||||
} catch (e) {
|
||||
notFound = sentence(e);
|
||||
}
|
||||
} else {
|
||||
rev = app.overview?.rev ?? null;
|
||||
if (!signinOk) host.auth = "none";
|
||||
}
|
||||
loading = false;
|
||||
if (focusField) {
|
||||
if (focusField.startsWith("health_check")) more = true;
|
||||
setTimeout(() => document.getElementById(fieldId(focusField))?.focus(), 0);
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
stop?.();
|
||||
clearTimeout(closeTimer);
|
||||
});
|
||||
|
||||
function fieldId(f: string): string {
|
||||
return "f-" + f.replace(/[^a-z0-9]+/gi, "-");
|
||||
}
|
||||
const errAt = (f: string) => errors[f];
|
||||
|
||||
function setErrors(list: ErrorBody[], only?: string) {
|
||||
const next: Record<string, ErrorBody> = only ? { ...errors } : {};
|
||||
if (only) {
|
||||
for (const k of Object.keys(next)) if (k === only || k.startsWith(only + "[")) delete next[k];
|
||||
}
|
||||
for (const e of list) {
|
||||
const f = e.field ?? "";
|
||||
if (!f) continue;
|
||||
if (only && !(f === only || f.startsWith(only + "["))) continue;
|
||||
next[f] = e;
|
||||
}
|
||||
errors = next;
|
||||
}
|
||||
|
||||
// Validation on blur (§2.10): only the field that lost focus, debounced.
|
||||
let blurTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
function blur(field: string) {
|
||||
touched[field] = true;
|
||||
clearTimeout(blurTimer);
|
||||
blurTimer = setTimeout(async () => {
|
||||
try {
|
||||
await call("POST", `/hosts/validate?mode=${hostname ? "edit" : "create"}`, spec());
|
||||
setErrors([], field);
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError) setErrors(e.errors.length ? e.errors : [e.body], field);
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
|
||||
async function submit(e?: Event) {
|
||||
e?.preventDefault();
|
||||
if (changesBlocked()) return;
|
||||
const body = spec();
|
||||
const text = JSON.stringify(body);
|
||||
if (text !== lastBody) {
|
||||
idem = newKey();
|
||||
lastBody = text;
|
||||
}
|
||||
underFooter = "";
|
||||
conflict = null;
|
||||
topError = null;
|
||||
try {
|
||||
const path = hostname ? `/hosts/${encodeURIComponent(hostname)}` : "/hosts";
|
||||
const a = await call<{ apply: ApplyView }>(hostname ? "PUT" : "POST", path, { host: body, base_rev: rev }, { idem });
|
||||
const ap = a.data?.apply;
|
||||
if (!ap) return;
|
||||
apply = ap;
|
||||
phase = "progress";
|
||||
stop?.();
|
||||
stop = follow(ap.id, onApply);
|
||||
} catch (err) {
|
||||
if (!(err instanceof ApiError)) {
|
||||
topError = null;
|
||||
underFooter = sentence(err);
|
||||
return;
|
||||
}
|
||||
if (err.code === "change.conflict") {
|
||||
conflict = err.body;
|
||||
return;
|
||||
}
|
||||
if (err.code === "change.unchanged") {
|
||||
underFooter = "This is the same as what is live now, so nothing changed.";
|
||||
return;
|
||||
}
|
||||
const list = err.errors.length ? err.errors : err.body.field ? [err.body] : [];
|
||||
if (list.length) {
|
||||
setErrors(list);
|
||||
for (const x of list) if (x.field) touched[x.field] = true;
|
||||
summary = `${list.length} ${list.length === 1 ? "thing" : "things"} to fix before Apply.`;
|
||||
const first = list.find((x) => x.field)?.field;
|
||||
if (first?.startsWith("health_check") || first?.includes("headers")) more = true;
|
||||
if (first) setTimeout(() => document.getElementById(fieldId(first))?.focus(), 0);
|
||||
} else {
|
||||
topError = err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onApply(a: ApplyView) {
|
||||
apply = a;
|
||||
if (a.state === "kept") {
|
||||
closeTimer = setTimeout(() => onclose(), 1500);
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelQueued() {
|
||||
if (!apply) return;
|
||||
try {
|
||||
await del(`/applies/${encodeURIComponent(apply.id)}`);
|
||||
toast("Cancelled before it started. Nothing changed.");
|
||||
stop?.();
|
||||
phase = "form";
|
||||
apply = null;
|
||||
} catch (e) {
|
||||
underFooter = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
function editAgain(field?: string) {
|
||||
stop?.();
|
||||
phase = "form";
|
||||
apply = null;
|
||||
idem = newKey();
|
||||
const f = field ?? "upstreams[0]";
|
||||
if (f.startsWith("health_check")) {
|
||||
more = true;
|
||||
host.hc = true;
|
||||
}
|
||||
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
|
||||
}
|
||||
|
||||
async function keepMine() {
|
||||
if (!hostname) {
|
||||
rev = app.overview?.rev ?? rev;
|
||||
} else {
|
||||
try {
|
||||
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
|
||||
rev = d.rev;
|
||||
} catch {
|
||||
/* keep the old rev */
|
||||
}
|
||||
}
|
||||
await refresh();
|
||||
if (!hostname) rev = app.overview?.rev ?? rev;
|
||||
conflict = null;
|
||||
}
|
||||
|
||||
async function useTheirs() {
|
||||
if (!hostname) return;
|
||||
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
|
||||
fromSpec(d.host);
|
||||
rev = d.rev;
|
||||
conflict = null;
|
||||
}
|
||||
|
||||
const name = $derived(host.hostname.trim() || hostname || "the host");
|
||||
const heading = $derived.by(() => {
|
||||
if (phase !== "progress" || !apply) return hostname ? `Edit ${hostname}` : "New host";
|
||||
const h = apply.hosts[0] ?? name;
|
||||
switch (apply.kind) {
|
||||
case "add":
|
||||
return `Adding ${h}`;
|
||||
case "remove":
|
||||
return `Removing ${h}`;
|
||||
case "share_links":
|
||||
return `Turning on share links for ${h}`;
|
||||
default:
|
||||
return `Changing ${h}`;
|
||||
}
|
||||
});
|
||||
const reasonOffer = $derived.by(() => {
|
||||
const c = apply?.reason?.code ?? "";
|
||||
if (/apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
|
||||
if (/apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: "" };
|
||||
if (c.startsWith("apply.reverted") || c === "apply.failed.validation" || c.startsWith("pki.")) return { label: "Edit and try again", field: apply?.reason?.field ?? undefined };
|
||||
return null;
|
||||
});
|
||||
const blocked = $derived(changesBlocked());
|
||||
const shareWarning = $derived(host.auth === "none" && host.share_links);
|
||||
</script>
|
||||
|
||||
<Dialog title={heading} kind="panel" {onclose}>
|
||||
{#if loading}
|
||||
<p class="ia-muted">Loading…</p>
|
||||
{:else if notFound}
|
||||
<Banner tone="notice" live="status">{#snippet title()}{notFound}{/snippet}
|
||||
{#snippet actions()}<Button onclick={onclose}>Back to hosts</Button>{/snippet}
|
||||
</Banner>
|
||||
{:else if phase === "progress" && apply}
|
||||
<div aria-live="polite" class="sr-only">
|
||||
{#if apply.state === "queued"}Waiting for another change to finish.{:else if apply.state === "watching"}Watching health checks.{:else if apply.state === "kept"}Kept. {apply.reason?.message}{:else if apply.state === "reverted"}Reverted. {apply.reason?.message}{:else if apply.state === "failed"}Not applied. {apply.reason?.message}{/if}
|
||||
</div>
|
||||
<ApplyProgress {apply} oncancel={cancelQueued} />
|
||||
{#if apply.state === "kept"}
|
||||
<Banner tone="kept">
|
||||
{#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet}
|
||||
{apply.reason?.message ?? ""}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
|
||||
</Banner>
|
||||
{:else if apply.state === "reverted" || apply.state === "failed"}
|
||||
{@const parts = firstSentence(apply.reason?.message ?? "")}
|
||||
<Banner tone="notice" live="status">
|
||||
{#snippet title()}<span class="ia-status" data-s="reverted"><span class="word">{apply?.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
|
||||
{#if parts[1]}Reason: {parts[1]}{/if}
|
||||
{#snippet actions()}
|
||||
{#if reasonOffer}
|
||||
<Button variant="outline" onclick={() => (reasonOffer?.field === "" ? (editAgain(), submit()) : editAgain(reasonOffer?.field))}>{reasonOffer.label}</Button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Banner>
|
||||
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if}
|
||||
<p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p>
|
||||
{:else if apply.state === "needs_attention"}
|
||||
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}</Banner>
|
||||
{/if}
|
||||
{:else}
|
||||
<form id="host-form" onsubmit={submit} novalidate>
|
||||
{#if summary}<p class="sr-only" role="alert">{summary}</p>{/if}
|
||||
{#if conflict}
|
||||
<Banner tone="notice" live="status">
|
||||
{#snippet title()}{conflict?.message}{/snippet}
|
||||
{#snippet actions()}<Button onclick={keepMine}>Keep my edits</Button>{#if hostname}<Button onclick={useTheirs}>Use the new version</Button>{/if}{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
{#if topError}
|
||||
<Banner tone="notice" live="status">{#snippet title()}{sentence(topError)}{/snippet}</Banner>
|
||||
{#if topError.body.detail}<Details detail={topError.body.detail} reference={topError.requestId} />{/if}
|
||||
{/if}
|
||||
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for={fieldId("hostname")}>Hostname</label>
|
||||
<input id={fieldId("hostname")} class="domi-input" bind:value={host.hostname} readonly={!!hostname}
|
||||
autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
|
||||
aria-invalid={errAt("hostname") && touched["hostname"] ? "true" : undefined}
|
||||
aria-describedby="{fieldId('hostname')}-e {fieldId('hostname')}-h" onblur={() => blur("hostname")} />
|
||||
{#if errAt("hostname") && touched["hostname"]}
|
||||
<p class="domi-error" id="{fieldId('hostname')}-e"><Icon name="ring" />{errAt("hostname").message}
|
||||
{#if errAt("hostname").params?.suggestion}
|
||||
<button type="button" class="domi-btn link" onclick={() => { host.hostname = errAt("hostname").params.suggestion; blur("hostname"); }}>Use {errAt("hostname").params.suggestion}</button>
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
{#if hostname}<p class="ia-hint" id="{fieldId('hostname')}-h">To use another address, add a new host and remove this one.</p>{/if}
|
||||
</div>
|
||||
|
||||
{#each host.upstreams as _, i (i)}
|
||||
{@const f = `upstreams[${i}]`}
|
||||
{@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)}
|
||||
<div class="domi-field">
|
||||
{#if i === 0}<label class="domi-field-label" for={fieldId(f)}>Send traffic to</label>{/if}
|
||||
<div class="row">
|
||||
<input id={fieldId(f)} class="domi-input" bind:value={host.upstreams[i]} autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
|
||||
aria-label={i === 0 ? undefined : `Also send traffic to, address ${i + 1}`}
|
||||
aria-invalid={err && (touched[f] || touched["upstreams"]) ? "true" : undefined}
|
||||
aria-describedby="{fieldId(f)}-e" onblur={() => blur(f)} />
|
||||
{#if i > 0}<button type="button" class="ia-icon-btn" aria-label="Remove this address" onclick={() => host.upstreams.splice(i, 1)}><Icon name="trash" /></button>{/if}
|
||||
</div>
|
||||
{#if err && (touched[f] || touched["upstreams"])}
|
||||
<p class="domi-error" id="{fieldId(f)}-e"><Icon name="ring" />{err.message}
|
||||
{#if err.params?.suggestion}<button type="button" class="domi-btn link" onclick={() => { host.upstreams[i] = err.params.suggestion; blur(f); }}>Use {err.params.suggestion}</button>{/if}
|
||||
</p>
|
||||
{/if}
|
||||
{#if i === 0 && host.upstreams.length === 1}<p class="ia-hint">Add another address later for a second server.</p>{/if}
|
||||
</div>
|
||||
{/each}
|
||||
<div><button type="button" class="domi-btn link" onclick={() => host.upstreams.push("")}>Add another address</button></div>
|
||||
|
||||
<Segmented legend="Certificate" name="tls" bind:value={host.tls}
|
||||
options={[{ value: "domi", label: "Domi certificate" }, { value: "letsencrypt", label: "Let's Encrypt" }]} />
|
||||
<p class="ia-hint">Domi for home devices only; Let's Encrypt for a public site.</p>
|
||||
|
||||
<Segmented legend="Who can open it" name="auth" bind:value={host.auth} disabled={signinOk ? [] : ["forward-auth"]}
|
||||
options={[{ value: "forward-auth", label: "Sign in first" }, { value: "none", label: "Anyone" }]} />
|
||||
{#if !signinOk}<p class="ia-hint">Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository.</p>{/if}
|
||||
{#if errAt("auth")}<p class="domi-error"><Icon name="ring" />{errAt("auth").message}</p>{/if}
|
||||
|
||||
<div>
|
||||
<button type="button" class="domi-btn link" aria-expanded={more} aria-controls="more-options" onclick={() => (more = !more)}>
|
||||
More options: headers, websockets, health check, share links, visit log
|
||||
</button>
|
||||
</div>
|
||||
{#if more}
|
||||
<div id="more-options" class="more">
|
||||
<div class="domi-field">
|
||||
<span class="domi-field-label">Health check</span>
|
||||
<label class="ia-check"><input type="checkbox" bind:checked={host.hc} /> Check that it answers</label>
|
||||
<p class="ia-hint">Ianitor asks this address regularly and shows the result on the main screen.</p>
|
||||
</div>
|
||||
{#if host.hc}
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for={fieldId("health_check.path")}>Health check address</label>
|
||||
<input id={fieldId("health_check.path")} class="domi-input" bind:value={host.hcPath} aria-invalid={errAt("health_check.path") ? "true" : undefined} onblur={() => blur("health_check.path")} />
|
||||
{#if errAt("health_check.path")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.path").message}</p>{/if}
|
||||
<p class="ia-hint">Use an address that answers without signing in, like /health.</p>
|
||||
</div>
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for={fieldId("health_check.interval_secs")}>Checks every</label>
|
||||
<div class="row"><input id={fieldId("health_check.interval_secs")} class="domi-input narrow" type="number" min="1" max="3600" bind:value={host.hcEvery} onblur={() => blur("health_check.interval_secs")} /> <span class="ia-text2">seconds</span></div>
|
||||
{#if errAt("health_check.interval_secs")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.interval_secs").message}</p>{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="domi-field">
|
||||
<span class="domi-field-label">Websockets</span>
|
||||
<label class="ia-check"><input type="checkbox" bind:checked={host.websockets} /> Allow websockets</label>
|
||||
<p class="ia-hint">Live updates for apps like Home Assistant. Leave on unless you know the app does not need them.</p>
|
||||
</div>
|
||||
<div class="domi-field">
|
||||
<span class="domi-field-label">Share links</span>
|
||||
<label class="ia-check"><input type="checkbox" bind:checked={host.share_links} /> Allow share links</label>
|
||||
<p class="ia-hint">Lets you make links that open this host without signing in, until they expire.</p>
|
||||
{#if shareWarning}<p class="ia-hint">Anyone can already open {name}, so a share link changes nothing.</p>{/if}
|
||||
</div>
|
||||
<div class="domi-field">
|
||||
<span class="domi-field-label">Device certificates</span>
|
||||
<label class="ia-check"><input type="checkbox" bind:checked={host.device_certs} /> Only devices with a Domi device certificate</label>
|
||||
<p class="ia-hint">Phones, computers and apps need a certificate from Certificates before they can open it.</p>
|
||||
</div>
|
||||
<Segmented legend="Visit log" name="access_log" bind:value={host.access_log} options={[{ value: "off", label: "Off" }, { value: "truncated", label: "On" }]} />
|
||||
<p class="ia-hint">On keeps a log on this server, with visitor addresses shortened.</p>
|
||||
{#each [{ list: "request_headers", rules: host.req, title: "Header rules sent to your service", secrets: true }, { list: "response_headers", rules: host.resp, title: "Header rules sent back to visitors", secrets: false }] as group (group.list)}
|
||||
<div class="domi-field">
|
||||
<span class="domi-field-label">{group.title}</span>
|
||||
{#each group.rules as r, i (i)}
|
||||
{@const p = `${group.list}[${i}]`}
|
||||
<div class="rule ia-card">
|
||||
<Segmented legend="Rule {i + 1}" name="{p}-action" bind:value={r.action} options={[{ value: "set", label: "Set" }, { value: "remove", label: "Remove" }]} />
|
||||
<label class="domi-field-label" for={fieldId(p + ".name")}>Header name</label>
|
||||
<input id={fieldId(p + ".name")} class="domi-input" bind:value={r.name} onblur={() => blur(p + ".name")} />
|
||||
{#if r.action === "set"}
|
||||
{#if group.secrets}
|
||||
<Segmented legend="Value" name="{p}-kind" bind:value={r.kind} disabled={(site?.secrets.length ?? 0) === 0 ? ["secret"] : []} options={[{ value: "value", label: "Fixed value" }, { value: "secret", label: "Secret" }]} />
|
||||
{/if}
|
||||
{#if r.kind === "secret" && group.secrets}
|
||||
<select class="domi-input" bind:value={r.secret} aria-label="Secret">
|
||||
{#each site?.secrets ?? [] as s (s)}<option value={s}>{s}</option>{/each}
|
||||
</select>
|
||||
{:else}
|
||||
<input class="domi-input" bind:value={r.value} aria-label="Value" onblur={() => blur(p + ".value")} />
|
||||
{/if}
|
||||
{/if}
|
||||
{#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}<p class="domi-error"><Icon name="ring" />{e.message}</p>{/each}
|
||||
<button type="button" class="ia-icon-btn" aria-label="Remove this rule" onclick={() => group.rules.splice(i, 1)}><Icon name="trash" /></button>
|
||||
</div>
|
||||
{/each}
|
||||
<div><button type="button" class="domi-btn link" onclick={() => group.rules.push({ action: "set", name: "", kind: "value", value: "", secret: site?.secrets[0] ?? "" })}>Add a rule</button></div>
|
||||
{#if group.secrets && (site?.secrets.length ?? 0) === 0}<p class="ia-hint">No secrets are listed in ianitor.toml.</p>{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</form>
|
||||
{/if}
|
||||
|
||||
{#snippet footer()}
|
||||
{#if phase === "form" && !loading && !notFound}
|
||||
{#if underFooter}<p class="ia-hint full" role="status">{underFooter}</p>{/if}
|
||||
{#if blocked}<p class="ia-hint full" id="apply-blocked">{blocked}</p>{/if}
|
||||
<Button onclick={onclose}>Cancel</Button>
|
||||
<Button variant="primary" type="submit" form="host-form" disabled={!!blocked} describedby={blocked ? "apply-blocked" : undefined}>Apply</Button>
|
||||
{:else if phase === "progress" && apply && FINAL.includes(apply.state)}
|
||||
<Button onclick={onclose}>Close</Button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Dialog>
|
||||
|
||||
<style>
|
||||
form { display: flex; flex-direction: column; gap: 16px; }
|
||||
.row { display: flex; gap: 8px; align-items: center; }
|
||||
.more { display: flex; flex-direction: column; gap: 16px; }
|
||||
.rule { display: flex; flex-direction: column; gap: 8px; }
|
||||
.narrow { max-width: 8rem; }
|
||||
.full { flex-basis: 100%; }
|
||||
</style>
|
||||
@@ -0,0 +1,69 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §13.5: the intermediate banner. Renew is 1 click; the banner then shows the match
|
||||
// code. Until Custos can sign (docs/custos-ticket.md) the request is signed by hand offline,
|
||||
// so the waiting banner links to that page.
|
||||
import { Banner, Button } from "@ianitor/ui";
|
||||
import { del, post, sentence } from "../lib/api";
|
||||
import { app, navigate, refresh, secondsLeft } from "../lib/app.svelte";
|
||||
import { duration, longDate } from "../lib/format";
|
||||
import type { PkiRequest } from "../lib/types";
|
||||
|
||||
const i = $derived(app.overview?.intermediate ?? null);
|
||||
let pending = $state(false);
|
||||
let problem = $state<string | null>(null);
|
||||
|
||||
async function renew() {
|
||||
pending = true;
|
||||
problem = null;
|
||||
try {
|
||||
await post<PkiRequest>("/certs/intermediate/renewal");
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
} finally {
|
||||
pending = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function cancel(id: string) {
|
||||
try {
|
||||
await del(`/pki-requests/${encodeURIComponent(id)}`);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if app.renewedUntil}
|
||||
<Banner tone="kept" live="status" ondismiss={() => (app.renewedUntil = null)}>
|
||||
{#snippet title()}Renewed. The Domi intermediate certificate is now valid until {longDate(app.renewedUntil, false)}.{/snippet}
|
||||
</Banner>
|
||||
{:else if i?.renewal}
|
||||
{@const r = i.renewal}
|
||||
<Banner tone="notice" label="Domi intermediate certificate">
|
||||
{#snippet title()}
|
||||
<span tabindex="-1">Sign the renewal on the offline computer. Check that it shows the same code:</span>
|
||||
<span class="code" aria-label="Match code {r.match_code}">{r.match_code}</span>
|
||||
{/snippet}
|
||||
The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if}
|
||||
{#snippet actions()}
|
||||
<Button variant="outline" onclick={() => navigate("/certificates/renew-by-hand")}>Sign it by hand</Button>
|
||||
<Button onclick={() => cancel(r.request_id)}>Cancel request</Button>
|
||||
{/snippet}
|
||||
</Banner>
|
||||
{:else if i?.banner}
|
||||
<Banner tone={i.state === "due" ? "notice" : "down"} label="Domi intermediate certificate">
|
||||
{#snippet title()}<strong>{i.banner?.message}</strong>{/snippet}
|
||||
{i.state === "missing" ? "Setting it up makes a request that the Domi root signs on the offline computer." : "Renewing makes a request that the Domi root signs; check the match code on both screens."}
|
||||
{#if problem} {problem}{/if}
|
||||
{#snippet actions()}<Button variant="outline" onclick={renew} {pending}>{i.state === "missing" ? "Set up" : "Renew"}</Button>{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.code { font-family: var(--font-inscription); font-size: 1.4rem; letter-spacing: 0.16em; color: var(--accent-strong); margin-left: 8px; }
|
||||
</style>
|
||||
@@ -0,0 +1,163 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §8.2: mint on open (click 2), Copy link (click 3). Changing an option re-mints with
|
||||
// `replaces`, so one link from this dialog is valid at a time; closing without copying stops it.
|
||||
// Links off: "Turn on share links" applies the change, then Copy link (4 clicks: open
|
||||
// question Q1 is not decided, so this is the fallback path the design allows).
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { Banner, Button, Dialog, Icon, Segmented } from "@ianitor/ui";
|
||||
import ApplyProgress from "./ApplyProgress.svelte";
|
||||
import { ApiError, call, del, newKey, patch, sentence } from "../lib/api";
|
||||
import { app } from "../lib/app.svelte";
|
||||
import { follow } from "../lib/applies";
|
||||
import { longDate } from "../lib/format";
|
||||
import type { ApplyView, MintedLink } from "../lib/types";
|
||||
|
||||
let { hostname, onclose }: { hostname: string; onclose: () => void } = $props();
|
||||
|
||||
const row = $derived(app.overview?.hosts.find((h) => h.hostname === hostname));
|
||||
let on = $state(false);
|
||||
let link = $state<MintedLink | null>(null);
|
||||
let minting = $state(false);
|
||||
let copied = $state(false);
|
||||
let copiedBefore = $state(false);
|
||||
let refused = $state(false);
|
||||
let problem = $state<string | null>(null);
|
||||
let fieldErr = $state<{ field: string; message: string } | null>(null);
|
||||
let days = $state<"1" | "7" | "30">("7");
|
||||
let prefix = $state("/");
|
||||
let showPassword = $state(false);
|
||||
let password = $state("");
|
||||
let usingPassword = $state(false);
|
||||
let turning = $state<ApplyView | null>(null);
|
||||
let stopFollow: (() => void) | undefined;
|
||||
let secretBox: HTMLInputElement | undefined = $state();
|
||||
|
||||
onMount(() => {
|
||||
on = !!row?.share_links;
|
||||
if (on) void mint();
|
||||
});
|
||||
onDestroy(() => stopFollow?.());
|
||||
|
||||
async function mint() {
|
||||
minting = true;
|
||||
problem = null;
|
||||
fieldErr = null;
|
||||
try {
|
||||
const body: Record<string, unknown> = { path_prefix: prefix || "/", expires_in_s: Number(days) * 86400 };
|
||||
if (usingPassword && password) body.password = password;
|
||||
if (link) body.replaces = link.id;
|
||||
const a = await call<MintedLink>("POST", `/hosts/${encodeURIComponent(hostname)}/share-links`, body, { idem: newKey() });
|
||||
if (link && copied) copiedBefore = true;
|
||||
link = a.data;
|
||||
copied = false;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.body.field) {
|
||||
fieldErr = { field: e.body.field, message: e.body.message };
|
||||
if (e.body.field === "password") usingPassword = false;
|
||||
}
|
||||
else problem = sentence(e);
|
||||
} finally {
|
||||
minting = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
if (!link) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(link.url);
|
||||
copied = true;
|
||||
refused = false;
|
||||
} catch {
|
||||
refused = true;
|
||||
secretBox?.select();
|
||||
}
|
||||
}
|
||||
|
||||
async function turnOn() {
|
||||
try {
|
||||
const a = await patch<{ apply: ApplyView }>(`/hosts/${encodeURIComponent(hostname)}`, { share_links: true, base_rev: app.overview?.rev ?? null });
|
||||
turning = a.apply;
|
||||
stopFollow = follow(a.apply.id, async (x) => {
|
||||
turning = x;
|
||||
if (x.state === "kept") {
|
||||
on = true;
|
||||
await mint();
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
function close() {
|
||||
// A link nobody copied does not stay valid.
|
||||
if (link && !copied) void del(`/share-links/${encodeURIComponent(link.id)}`, { keepalive: true }).catch(() => {});
|
||||
onclose();
|
||||
}
|
||||
|
||||
const underCaddy = $derived(app.overview?.engine.running === "caddy");
|
||||
</script>
|
||||
|
||||
<Dialog title="Share {hostname}" onclose={close}>
|
||||
{#if !on}
|
||||
{#if turning}
|
||||
<ApplyProgress apply={turning} />
|
||||
{#if turning.state === "reverted" || turning.state === "failed"}
|
||||
<Banner tone="notice" live="status">{#snippet title()}Share links were not turned on. {turning?.reason?.message}{/snippet}</Banner>
|
||||
{/if}
|
||||
{:else}
|
||||
<p><strong>Share links are off for {hostname}.</strong></p>
|
||||
<p class="ia-text2">Turning them on is a change to the host, checked like any other.</p>
|
||||
{#if problem}<p class="domi-error" role="alert"><Icon name="ring" />{problem}</p>{/if}
|
||||
<div><Button variant="outline" onclick={turnOn} disabled={!!app.overview?.paused}>Turn on share links</Button></div>
|
||||
{/if}
|
||||
{:else}
|
||||
<p class="ia-text2">Anyone with this link can open the site without signing in, until it expires.</p>
|
||||
{#if underCaddy}
|
||||
<Banner tone="notice">{#snippet title()}Caddy is serving right now, so share links do not work: visitors with this link get the normal sign-in. The link works after switching back to Pingora, until it expires.{/snippet}</Banner>
|
||||
{/if}
|
||||
{#if link?.warning}<p class="ia-hint">{link.warning.message}</p>{/if}
|
||||
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||
{#if link}
|
||||
<input bind:this={secretBox} class="ia-secret" readonly value={link.url} aria-label="Share link" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
|
||||
{:else if minting}
|
||||
<p class="ia-muted">Making the link…</p>
|
||||
{/if}
|
||||
{#if copied}
|
||||
<p class="ia-status" data-s="kept" role="status"><Icon name="check" /><span>Copied</span></p>
|
||||
<p class="ia-hint">Expires on {longDate(link?.expires_at)}. To stop it sooner: Settings, Share links, Stop this link.</p>
|
||||
{:else}
|
||||
<Button variant="primary" full icon="copy" onclick={copy} disabled={!link || minting} data-autofocus>Copy link</Button>
|
||||
{/if}
|
||||
{#if refused}<p class="ia-hint" role="alert">Your browser did not allow copying. Press Ctrl+C to copy the selected link.</p>{/if}
|
||||
{#if copiedBefore && !copied}<p class="ia-hint">The link you copied before is stopped. Copy this one.</p>{/if}
|
||||
|
||||
<Segmented legend="Expires after" name="expiry" bind:value={days} onchange={() => mint()}
|
||||
options={[{ value: "1", label: "1 day" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} />
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for="share-prefix">Only addresses starting with</label>
|
||||
<input id="share-prefix" class="domi-input" bind:value={prefix} onblur={() => mint()} onkeydown={(e) => { if (e.key === "Enter") { e.preventDefault(); void mint(); } }}
|
||||
aria-invalid={fieldErr?.field === "path_prefix" ? "true" : undefined} />
|
||||
{#if fieldErr?.field === "path_prefix"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
|
||||
<p class="ia-hint">/ shares the whole site. Try /share/summer-2026 for one album.</p>
|
||||
</div>
|
||||
{#if usingPassword}
|
||||
<p class="ia-hint">This link asks for the password.</p>
|
||||
<div><button type="button" class="domi-btn link" onclick={() => { usingPassword = false; password = ""; void mint(); }}>Remove the password</button></div>
|
||||
{:else if showPassword}
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for="share-password">Password</label>
|
||||
<input id="share-password" class="domi-input" type="password" autocomplete="new-password" bind:value={password}
|
||||
aria-invalid={fieldErr?.field === "password" ? "true" : undefined} />
|
||||
{#if fieldErr?.field === "password"}<p class="domi-error"><Icon name="ring" />{fieldErr.message}</p>{/if}
|
||||
<p class="ia-hint">At least 8 characters. Send it to them separately.</p>
|
||||
<div><Button onclick={() => { usingPassword = true; void mint(); }}>Use this password</Button></div>
|
||||
</div>
|
||||
{:else}
|
||||
<div><button type="button" class="domi-btn link" onclick={() => (showPassword = true)}>Add a password</button></div>
|
||||
{/if}
|
||||
{/if}
|
||||
</Dialog>
|
||||
@@ -0,0 +1,73 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §2.8 order: paused / needs attention, lost contact, health unavailable, the Caddy
|
||||
// notice, then (on Hosts) the intermediate banner. First on every screen.
|
||||
import { Banner, Button, Details } from "@ianitor/ui";
|
||||
import { post, sentence } from "../lib/api";
|
||||
import { app, refresh } from "../lib/app.svelte";
|
||||
import { when } from "../lib/format";
|
||||
import type { ApplyView } from "../lib/types";
|
||||
|
||||
const o = $derived(app.overview);
|
||||
let restoring = $state(false);
|
||||
let problem = $state<string | null>(null);
|
||||
|
||||
const restorable = $derived(
|
||||
!!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target,
|
||||
);
|
||||
|
||||
async function restoreLastKept() {
|
||||
if (!o?.undo?.target) return;
|
||||
restoring = true;
|
||||
try {
|
||||
const a = await post<{ apply: ApplyView }>("/restore", { change_id: o.undo.target.change_id, base_rev: o.rev });
|
||||
app.panel = { kind: "host", resume: a.apply.id };
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
} finally {
|
||||
restoring = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function retry() {
|
||||
await refresh();
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if o?.paused}
|
||||
<Banner tone="down" live="alert">
|
||||
{#snippet title()}<span class="ia-status" data-s="down"><span class="word">{restorable ? "needs attention" : "paused"}</span></span> <strong>{o.paused?.message}</strong>{/snippet}
|
||||
{#if restorable && o.undo?.target}Goes back to "{o.undo.target.summary}" from {when(o.undo.target.kept_at, app.now)}. It is checked like any change.{/if}
|
||||
{#if problem} {problem}{/if}
|
||||
{#snippet actions()}
|
||||
{#if restorable}<Button variant="primary" onclick={restoreLastKept} pending={restoring}>Restore the last kept version</Button>{/if}
|
||||
{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
|
||||
{#if app.lostContact}
|
||||
<Banner tone="down" live="alert">
|
||||
{#snippet title()}<strong>{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}</strong>{/snippet}
|
||||
Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {when(new Date(app.lastUpdated).toISOString(), app.now)}.{/if}
|
||||
{#snippet actions()}<Button onclick={retry}>Try again now</Button>{/snippet}
|
||||
</Banner>
|
||||
{/if}
|
||||
|
||||
{#if o?.health_error}
|
||||
<Banner tone="notice">{#snippet title()}{o.health_error?.message}{/snippet}</Banner>
|
||||
{/if}
|
||||
|
||||
{#if app.switchResult}
|
||||
{@const r = app.switchResult}
|
||||
<Banner tone={r.ok ? "kept" : "down"} live="status" ondismiss={() => (app.switchResult = null)}>
|
||||
{#snippet title()}<strong>{r.title}</strong>{/snippet}
|
||||
{r.text}
|
||||
{#if r.detail}<Details detail={r.detail} />{/if}
|
||||
</Banner>
|
||||
{/if}
|
||||
|
||||
{#if o?.engine.running === "caddy" && (o.hosts.some((h) => h.share_links) ?? false)}
|
||||
<Banner tone="notice">{#snippet title()}Caddy is serving (the fallback), so share links do not work until you switch back.{/snippet}</Banner>
|
||||
{/if}
|
||||
@@ -0,0 +1,184 @@
|
||||
// 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 one typed API client (handoff §0, §10, §11). It owns the base path, the UI header (CSRF),
|
||||
// redirect: "manual" (sign-out detection), Idempotency-Keys, the error envelope, the server
|
||||
// clock offset, rate-limit and in-progress retries, and lost-contact detection. It decides
|
||||
// nothing about the data.
|
||||
|
||||
import type { ErrorBody, ErrorEnvelope } from "./types";
|
||||
|
||||
export const BASE = "/api/v1";
|
||||
|
||||
/** A refusal from control, with its envelope. */
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public body: ErrorBody,
|
||||
public errors: ErrorBody[],
|
||||
public requestId: string,
|
||||
) {
|
||||
super(body.message);
|
||||
}
|
||||
get code(): string {
|
||||
return this.body.code;
|
||||
}
|
||||
}
|
||||
|
||||
/** Authelia's portal redirect, or a 401 without Ianitor's envelope. */
|
||||
export class SignedOut extends Error {}
|
||||
|
||||
/** No answer (network, or a proxy error without an envelope). */
|
||||
export class LostContact extends Error {}
|
||||
|
||||
type Listener = () => void;
|
||||
|
||||
export interface ClientEvents {
|
||||
onSignedOut?: Listener;
|
||||
onContact?: (ok: boolean) => void;
|
||||
onServerTime?: (offsetMs: number) => void;
|
||||
}
|
||||
|
||||
let events: ClientEvents = {};
|
||||
export function setClientEvents(e: ClientEvents): void {
|
||||
events = e;
|
||||
}
|
||||
|
||||
/** A key for one click; reused by every retry of that click (§11.3). */
|
||||
export function newKey(): string {
|
||||
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
|
||||
return Math.random().toString(36).slice(2) + Date.now().toString(36);
|
||||
}
|
||||
|
||||
export interface CallOptions {
|
||||
idem?: string;
|
||||
etag?: string;
|
||||
/** Do not count a failure as lost contact (engine switch, §9.2). */
|
||||
quiet?: boolean;
|
||||
keepalive?: boolean;
|
||||
}
|
||||
|
||||
export interface Answer<T> {
|
||||
status: number;
|
||||
data: T | null;
|
||||
etag: string | null;
|
||||
}
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
function envelope(v: unknown): v is ErrorEnvelope {
|
||||
return typeof v === "object" && v !== null && "error" in v && typeof (v as ErrorEnvelope).error === "object";
|
||||
}
|
||||
|
||||
export async function call<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
opts: CallOptions = {},
|
||||
): Promise<Answer<T>> {
|
||||
let rateRetried = false;
|
||||
for (let attempt = 0; attempt < 12; attempt++) {
|
||||
const headers: Record<string, string> = { "X-Ianitor-UI": "1", Accept: "application/json" };
|
||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||
if (opts.idem) headers["Idempotency-Key"] = opts.idem;
|
||||
if (opts.etag) headers["If-None-Match"] = opts.etag;
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(BASE + path, {
|
||||
method,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
redirect: "manual",
|
||||
credentials: "same-origin",
|
||||
keepalive: opts.keepalive,
|
||||
});
|
||||
} catch {
|
||||
if (!opts.quiet) events.onContact?.(false);
|
||||
throw new LostContact("no answer");
|
||||
}
|
||||
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400 && res.status !== 304)) {
|
||||
events.onSignedOut?.();
|
||||
throw new SignedOut("signed out");
|
||||
}
|
||||
if (res.status === 304) {
|
||||
events.onContact?.(true);
|
||||
return { status: 304, data: null, etag: opts.etag ?? null };
|
||||
}
|
||||
let json: unknown = null;
|
||||
const text = await res.text();
|
||||
try {
|
||||
json = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
json = null;
|
||||
}
|
||||
if (json && typeof json === "object" && "server_time" in json) {
|
||||
const t = Date.parse(String((json as { server_time: string }).server_time));
|
||||
if (!Number.isNaN(t)) events.onServerTime?.(t - Date.now());
|
||||
}
|
||||
if (!envelope(json)) {
|
||||
if (res.status === 401) {
|
||||
events.onSignedOut?.();
|
||||
throw new SignedOut("signed out");
|
||||
}
|
||||
if (res.status >= 502 && res.status <= 504) {
|
||||
if (!opts.quiet) events.onContact?.(false);
|
||||
throw new LostContact(`proxy answered ${res.status}`);
|
||||
}
|
||||
events.onContact?.(true);
|
||||
return { status: res.status, data: json as T, etag: res.headers.get("ETag") };
|
||||
}
|
||||
events.onContact?.(true);
|
||||
const env = json;
|
||||
if (env.error.code === "request.in_progress") {
|
||||
await sleep(1000);
|
||||
continue;
|
||||
}
|
||||
if (env.error.code === "rate.limited" && !rateRetried) {
|
||||
rateRetried = true;
|
||||
await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000);
|
||||
continue;
|
||||
}
|
||||
if (res.status === 401 && env.error.code.startsWith("token.")) {
|
||||
// The UI holds no token: a token refusal means the sign-in did not reach control.
|
||||
events.onSignedOut?.();
|
||||
throw new SignedOut(env.error.message);
|
||||
}
|
||||
throw new ApiError(res.status, env.error, env.errors ?? [], env.request_id ?? "");
|
||||
}
|
||||
throw new ApiError(
|
||||
409,
|
||||
{
|
||||
code: "request.in_progress",
|
||||
message: "The first request with this Idempotency-Key is still being handled. Try again in a moment.",
|
||||
field: null,
|
||||
params: {},
|
||||
retry_after_s: 1,
|
||||
detail: null,
|
||||
},
|
||||
[],
|
||||
"",
|
||||
);
|
||||
}
|
||||
|
||||
export const get = <T>(path: string, opts?: CallOptions) => call<T>("GET", path, undefined, opts).then((a) => a.data as T);
|
||||
export const post = <T>(path: string, body: unknown = {}, opts?: CallOptions) =>
|
||||
call<T>("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
||||
export const put = <T>(path: string, body: unknown, opts?: CallOptions) =>
|
||||
call<T>("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
||||
export const patch = <T>(path: string, body: unknown, opts?: CallOptions) =>
|
||||
call<T>("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
||||
export const del = (path: string, opts?: CallOptions) => call<unknown>("DELETE", path, undefined, opts).then(() => undefined);
|
||||
|
||||
/** A UI sentence for request.* codes (handoff §12.4): bugs or a stale page, not user mistakes. */
|
||||
export function sentence(e: unknown): string {
|
||||
if (e instanceof ApiError) {
|
||||
if (e.code.startsWith("request.") && e.code !== "request.in_progress") {
|
||||
return "Ianitor refused this request from the page. Reload the page and try again.";
|
||||
}
|
||||
return e.body.message;
|
||||
}
|
||||
if (e instanceof LostContact) return "Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back.";
|
||||
if (e instanceof SignedOut) return "Your sign-in has ended. Sign in again; this page keeps what you typed.";
|
||||
return "Something went wrong.";
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// 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/.
|
||||
|
||||
// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state,
|
||||
// the server clock offset and toasts. No business logic: everything shown comes from control.
|
||||
|
||||
import { call, setClientEvents } from "./api";
|
||||
import type { Overview } from "./types";
|
||||
|
||||
export interface Toast {
|
||||
id: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export const app = $state({
|
||||
overview: null as Overview | null,
|
||||
etag: null as string | null,
|
||||
loadError: false,
|
||||
lostContact: false,
|
||||
lostSince: 0,
|
||||
lastUpdated: 0,
|
||||
signedOut: false,
|
||||
offset: 0,
|
||||
now: Date.now(),
|
||||
path: typeof location === "undefined" ? "/" : location.pathname + location.search,
|
||||
toasts: [] as Toast[],
|
||||
/** Dismissed banner keys (reverted outcome, renewed, switched). */
|
||||
dismissed: [] as string[],
|
||||
/** The outcome of the last engine switch, until dismissed (handoff §9.2). */
|
||||
switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null },
|
||||
/** A renewal just installed (handoff §13.5). */
|
||||
renewedUntil: null as null | string,
|
||||
/** Panels the main screen opens (add/edit host, share, engine). */
|
||||
panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" },
|
||||
});
|
||||
|
||||
let failures = 0;
|
||||
let firstFailure = 0;
|
||||
|
||||
setClientEvents({
|
||||
onSignedOut: () => {
|
||||
app.signedOut = true;
|
||||
},
|
||||
onContact: (ok) => {
|
||||
if (ok) {
|
||||
failures = 0;
|
||||
app.lostContact = false;
|
||||
return;
|
||||
}
|
||||
if (failures === 0) firstFailure = Date.now();
|
||||
failures++;
|
||||
// Retry quietly for 10 s (a reload takes about 2 s), then say so (§11.1).
|
||||
if (Date.now() - firstFailure >= 10_000) {
|
||||
if (!app.lostContact) app.lostSince = Date.now();
|
||||
app.lostContact = true;
|
||||
}
|
||||
},
|
||||
onServerTime: (o) => {
|
||||
app.offset = o;
|
||||
},
|
||||
});
|
||||
|
||||
/** Server time now, in ms (all countdowns use it, §7.2). */
|
||||
export function serverNow(): number {
|
||||
return app.now + app.offset;
|
||||
}
|
||||
|
||||
/** Seconds left until an ISO time, on the server's clock. */
|
||||
export function secondsLeft(iso: string | null | undefined): number {
|
||||
if (!iso) return 0;
|
||||
return Math.max(0, Math.ceil((Date.parse(iso) - serverNow()) / 1000));
|
||||
}
|
||||
|
||||
export async function refresh(): Promise<void> {
|
||||
if (app.signedOut) return;
|
||||
try {
|
||||
const a = await call<Overview>("GET", "/overview", undefined, { etag: app.etag ?? undefined });
|
||||
if (a.status === 200 && a.data) {
|
||||
app.overview = a.data;
|
||||
app.etag = a.etag;
|
||||
}
|
||||
app.loadError = false;
|
||||
app.lastUpdated = Date.now();
|
||||
} catch {
|
||||
if (!app.overview) app.loadError = true;
|
||||
}
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let hiddenSince = 0;
|
||||
|
||||
/** Poll every 5 s while visible, 30 s when hidden, stop after 15 min hidden (Q9). */
|
||||
export function startPolling(): () => void {
|
||||
let stopped = false;
|
||||
const tick = async () => {
|
||||
if (stopped) return;
|
||||
const hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
|
||||
if (hidden && !hiddenSince) hiddenSince = Date.now();
|
||||
if (!hidden) hiddenSince = 0;
|
||||
if (!(hidden && Date.now() - hiddenSince > 15 * 60_000)) await refresh();
|
||||
const every = app.lostContact ? 5000 : hidden ? 30_000 : 5000;
|
||||
timer = setTimeout(tick, every);
|
||||
};
|
||||
const vis = () => {
|
||||
if (document.visibilityState === "visible" && hiddenSince) {
|
||||
hiddenSince = 0;
|
||||
clearTimeout(timer);
|
||||
void tick();
|
||||
}
|
||||
};
|
||||
document.addEventListener("visibilitychange", vis);
|
||||
const clock = setInterval(() => (app.now = Date.now()), 1000);
|
||||
void tick();
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
clearInterval(clock);
|
||||
document.removeEventListener("visibilitychange", vis);
|
||||
};
|
||||
}
|
||||
|
||||
let toastId = 0;
|
||||
export function toast(text: string): void {
|
||||
const id = ++toastId;
|
||||
app.toasts = [...app.toasts.slice(-2), { id, text }];
|
||||
setTimeout(() => {
|
||||
app.toasts = app.toasts.filter((t) => t.id !== id);
|
||||
}, 6000);
|
||||
}
|
||||
|
||||
export function navigate(path: string): void {
|
||||
if (path === app.path) return;
|
||||
history.pushState({}, "", path);
|
||||
app.path = path;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("popstate", () => {
|
||||
app.path = location.pathname + location.search;
|
||||
});
|
||||
}
|
||||
|
||||
/** Is a change allowed now? (Paused, or no contact.) */
|
||||
export function changesBlocked(): string | null {
|
||||
const o = app.overview;
|
||||
if (app.lostContact) return "Ianitor's control service is not answering.";
|
||||
if (o?.paused) return "Changes are paused.";
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// 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/.
|
||||
|
||||
// Following an apply (handoff §2.2 of ui-api, §3 here): GET /applies/{id} every second while it
|
||||
// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
|
||||
|
||||
import { get } from "./api";
|
||||
import { refresh } from "./app.svelte";
|
||||
import type { ApplyView } from "./types";
|
||||
|
||||
export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
|
||||
const KEY = "ianitor.activeApply";
|
||||
|
||||
export function remember(id: string | null): void {
|
||||
try {
|
||||
if (id) sessionStorage.setItem(KEY, id);
|
||||
else sessionStorage.removeItem(KEY);
|
||||
} catch {
|
||||
/* storage may be off; the bar still shows the running apply */
|
||||
}
|
||||
}
|
||||
|
||||
export function remembered(): string | null {
|
||||
try {
|
||||
return sessionStorage.getItem(KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Poll until the apply ends. Returns a stop function. */
|
||||
export function follow(id: string, onupdate: (a: ApplyView) => void, every = 1000): () => void {
|
||||
let stopped = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
remember(id);
|
||||
const tick = async () => {
|
||||
if (stopped) return;
|
||||
try {
|
||||
const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`);
|
||||
if (stopped) return;
|
||||
onupdate(a);
|
||||
if (FINAL.includes(a.state)) {
|
||||
remember(null);
|
||||
void refresh();
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* lost contact or a reload in progress: keep trying (the banner says so after 10 s) */
|
||||
}
|
||||
timer = setTimeout(tick, every);
|
||||
};
|
||||
void tick();
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// 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/.
|
||||
|
||||
// Formatting only (handoff §3): times in the browser's zone, 24-hour clock, counts sentences.
|
||||
|
||||
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
const LONG = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||
|
||||
const two = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
/** "Today 14:02", "Yesterday 21:14", "5 Nov 21:14", "5 Nov 2025". */
|
||||
export function when(iso: string | null | undefined, now = Date.now()): string {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return "";
|
||||
const n = new Date(now);
|
||||
const hm = `${two(d.getHours())}:${two(d.getMinutes())}`;
|
||||
const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
|
||||
if (sameDay(d, n)) return `Today ${hm}`;
|
||||
const y = new Date(n);
|
||||
y.setDate(n.getDate() - 1);
|
||||
if (sameDay(d, y)) return `Yesterday ${hm}`;
|
||||
if (d.getFullYear() !== n.getFullYear()) return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
|
||||
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`;
|
||||
}
|
||||
|
||||
/** "14 November 2026 at 14:20". */
|
||||
export function longDate(iso: string | null | undefined, withTime = true): string {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return "";
|
||||
const s = `${d.getDate()} ${LONG[d.getMonth()]} ${d.getFullYear()}`;
|
||||
return withTime ? `${s} at ${two(d.getHours())}:${two(d.getMinutes())}` : s;
|
||||
}
|
||||
|
||||
/** "2 Mar 2027". */
|
||||
export function shortDate(iso: string | null | undefined): string {
|
||||
if (!iso) return "";
|
||||
const d = new Date(iso);
|
||||
return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`;
|
||||
}
|
||||
|
||||
/** "8 s", "6 minutes", "2 hours", "3 days". */
|
||||
export function duration(secs: number): string {
|
||||
if (secs < 60) return `${Math.max(0, Math.round(secs))} s`;
|
||||
const m = Math.round(secs / 60);
|
||||
if (m < 60) return m === 1 ? "1 minute" : `${m} minutes`;
|
||||
const h = Math.round(secs / 3600);
|
||||
if (h < 48) return h === 1 ? "1 hour" : `${h} hours`;
|
||||
const days = Math.round(secs / 86400);
|
||||
return `${days} days`;
|
||||
}
|
||||
|
||||
export function ago(iso: string | null | undefined, now: number): string {
|
||||
if (!iso) return "";
|
||||
return duration((now - Date.parse(iso)) / 1000) + " ago";
|
||||
}
|
||||
|
||||
/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1). */
|
||||
export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }): string {
|
||||
const parts = [`${c.healthy} healthy`];
|
||||
if (c.degraded) parts.push(`${c.degraded} degraded`);
|
||||
if (c.down) parts.push(`${c.down} down`);
|
||||
if (c.unknown) parts.push(`${c.unknown} not checked`);
|
||||
return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`;
|
||||
}
|
||||
|
||||
/** Split a server message on its first sentence (handoff §7.5). */
|
||||
export function firstSentence(m: string): [string, string] {
|
||||
const i = m.indexOf(". ");
|
||||
return i < 0 ? [m, ""] : [m.slice(0, i + 1), m.slice(i + 2)];
|
||||
}
|
||||
|
||||
/** Field labels in sentences (handoff §6.5). */
|
||||
export const FIELD_LABEL: Record<string, string> = {
|
||||
hostname: "address",
|
||||
upstreams: "sends traffic to",
|
||||
tls: "certificate",
|
||||
auth: "who can open it",
|
||||
"health_check.path": "health check address",
|
||||
"health_check.interval_secs": "checks every",
|
||||
share_links: "share links",
|
||||
device_certs: "device certificates",
|
||||
access_log: "visit log",
|
||||
websockets: "websockets",
|
||||
headers: "header rules",
|
||||
};
|
||||
|
||||
export function fieldValue(field: string, v: string): string {
|
||||
if (v === "") return "none";
|
||||
if (field === "tls") return v === "domi" ? "Domi certificate" : "Let's Encrypt";
|
||||
if (field === "auth") return v === "forward-auth" ? "sign in first" : "anyone";
|
||||
if (field === "access_log") return v === "truncated" ? "on" : "off";
|
||||
if (v === "true") return "on";
|
||||
if (v === "false") return "off";
|
||||
if (field === "health_check.interval_secs") return `${v} s`;
|
||||
return v;
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// 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 shapes the UI reads from control (docs/api.md, docs/ui-api.md, GET /api/v1/openapi.json).
|
||||
// Only the fields the UI uses are typed.
|
||||
|
||||
export interface ErrorBody {
|
||||
code: string;
|
||||
message: string;
|
||||
field: string | null;
|
||||
params: Record<string, string>;
|
||||
retry_after_s: number | null;
|
||||
detail: string | null;
|
||||
}
|
||||
|
||||
export interface ErrorEnvelope {
|
||||
error: ErrorBody;
|
||||
errors: ErrorBody[];
|
||||
request_id: string;
|
||||
}
|
||||
|
||||
export interface Blocked {
|
||||
code: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface Reason {
|
||||
code: string;
|
||||
message: string;
|
||||
hostname?: string | null;
|
||||
upstream?: string | null;
|
||||
field?: string | null;
|
||||
detail?: string | null;
|
||||
params?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface Step {
|
||||
key: "validate" | "compile" | "write" | "reload" | "watch" | "push";
|
||||
state: "pending" | "running" | "done" | "failed" | "skipped";
|
||||
}
|
||||
|
||||
export interface ApplyView {
|
||||
id: string;
|
||||
change_id: string;
|
||||
kind: "add" | "edit" | "remove" | "undo" | "restore" | "share_links";
|
||||
summary: string;
|
||||
hosts: string[];
|
||||
state: "queued" | "validating" | "applying" | "watching" | "kept" | "reverted" | "failed" | "needs_attention";
|
||||
created_at: string;
|
||||
finished_at: string | null;
|
||||
steps: Step[];
|
||||
queue: { position: number; waiting_for: { apply_id: string; summary: string; seconds_left: number | null } | null } | null;
|
||||
watch: { ends_at: string; seconds_left: number; hosts: { hostname: string; passed: number; failed: number; total: number }[] } | null;
|
||||
reason: Reason | null;
|
||||
errors: ErrorBody[];
|
||||
commit_short: string | null;
|
||||
push: { state: "pushed" | "pending" | "failed"; at: string | null; error_code: string | null; next_try_at: string | null } | null;
|
||||
attempted_host?: HostSpec | null;
|
||||
}
|
||||
|
||||
export interface HeaderRule {
|
||||
action: "set" | "remove";
|
||||
name: string;
|
||||
value?: string;
|
||||
secret?: string;
|
||||
}
|
||||
|
||||
export interface HostSpec {
|
||||
hostname: string;
|
||||
upstreams: string[];
|
||||
tls: "domi" | "letsencrypt";
|
||||
auth: "none" | "forward-auth";
|
||||
websockets: boolean;
|
||||
share_links: boolean;
|
||||
device_certs?: boolean;
|
||||
access_log: "off" | "truncated";
|
||||
health_check?: { path: string; interval_secs: number } | null;
|
||||
request_headers?: HeaderRule[];
|
||||
response_headers?: HeaderRule[];
|
||||
}
|
||||
|
||||
export interface HealthView {
|
||||
state: "healthy" | "degraded" | "down" | "unknown" | "pending";
|
||||
last_check_at: string | null;
|
||||
latency_ms: number | null;
|
||||
since: string | null;
|
||||
failure: { kind: string; upstream: string | null; count: number; of: number } | null;
|
||||
upstreams: { url: string; state: string; last_check_at: string | null; latency_ms: number | null; failure_kind: string | null }[];
|
||||
}
|
||||
|
||||
export interface HostRow {
|
||||
hostname: string;
|
||||
upstreams: string[];
|
||||
tls: string;
|
||||
auth: string;
|
||||
websockets: boolean;
|
||||
share_links: boolean;
|
||||
device_certs: boolean;
|
||||
added_at: string | null;
|
||||
health: HealthView;
|
||||
certificate: { state: "ok" | "pending" | "failed"; not_after: string | null; error_code: string | null };
|
||||
}
|
||||
|
||||
export interface PkiRequest {
|
||||
request_id: string;
|
||||
kind: "device" | "intermediate";
|
||||
state: "waiting" | "approved" | "denied" | "expired" | "cancelled" | "failed";
|
||||
match_code: string;
|
||||
created_at: string;
|
||||
expires_at: string;
|
||||
approved_at: string | null;
|
||||
device_id: string | null;
|
||||
name: string | null;
|
||||
csr_pem: string | null;
|
||||
not_after: string | null;
|
||||
message_code: string;
|
||||
message: string;
|
||||
approve_command: string | null;
|
||||
problem: string | null;
|
||||
}
|
||||
|
||||
export interface IntermediateView {
|
||||
state: "ok" | "due" | "urgent" | "expired" | "missing";
|
||||
subject: string | null;
|
||||
not_after: string | null;
|
||||
days_left: number | null;
|
||||
renewal: PkiRequest | null;
|
||||
banner: Blocked | null;
|
||||
}
|
||||
|
||||
export interface EngineView {
|
||||
running: "pingora" | "caddy";
|
||||
state: "running" | "switching" | "stopped";
|
||||
since: string | null;
|
||||
target: string | null;
|
||||
switchable: boolean;
|
||||
fallback_ready: { built_at: string | null; current: boolean } | null;
|
||||
last_error: Reason | null;
|
||||
notes: Blocked[];
|
||||
}
|
||||
|
||||
export interface UndoView {
|
||||
available: boolean;
|
||||
target: { change_id: string; summary: string; kept_at: string | null; commit_short: string | null } | null;
|
||||
effect: string | null;
|
||||
blocked: Blocked | null;
|
||||
}
|
||||
|
||||
export interface Overview {
|
||||
counts: { hosts: number; healthy: number; degraded: number; down: number; unknown: number };
|
||||
hosts: HostRow[];
|
||||
engine: EngineView;
|
||||
last_apply: ApplyView | null;
|
||||
undo: UndoView;
|
||||
active_apply: { id: string; state: string; summary: string; seconds_left: number | null; queued: number } | null;
|
||||
repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null;
|
||||
intermediate: IntermediateView | null;
|
||||
site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean } | null;
|
||||
paused: Blocked | null;
|
||||
paused_reason: string | null;
|
||||
health_error: Blocked | null;
|
||||
rev: string | null;
|
||||
viewer?: { name: string; via: string } | null;
|
||||
server_time: string;
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
change_id: string;
|
||||
summary: string;
|
||||
kind: string;
|
||||
state: string;
|
||||
at: string;
|
||||
commit_short: string | null;
|
||||
hosts: string[];
|
||||
reason_short: string | null;
|
||||
}
|
||||
|
||||
export interface RestorePreview {
|
||||
restorable: boolean;
|
||||
same_as_current: boolean;
|
||||
changes: { hostname: string; effect: "added" | "removed" | "changed"; fields: { field: string; from: string; to: string }[] }[];
|
||||
blocked: Blocked | null;
|
||||
}
|
||||
|
||||
export interface ShareLink {
|
||||
id: string;
|
||||
hostname: string;
|
||||
path_prefix: string;
|
||||
created_at: string;
|
||||
expires_at: string;
|
||||
has_password: boolean;
|
||||
state: "active" | "expired" | "stopped";
|
||||
}
|
||||
|
||||
export interface MintedLink {
|
||||
id: string;
|
||||
url: string;
|
||||
expires_at: string;
|
||||
path_prefix: string;
|
||||
has_password: boolean;
|
||||
warning: Blocked | null;
|
||||
}
|
||||
|
||||
export interface TokenRow {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
last_used_at: string | null;
|
||||
expires_at: string | null;
|
||||
revoked_at?: string | null;
|
||||
}
|
||||
|
||||
export interface CreatedToken {
|
||||
id: string;
|
||||
name: string;
|
||||
token: string;
|
||||
expires_at: string | null;
|
||||
}
|
||||
|
||||
export interface DeviceRow {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: "phone" | "computer" | "app";
|
||||
created_at: string;
|
||||
not_after: string;
|
||||
state: "valid" | "revoked" | "expired";
|
||||
revoked_at: string | null;
|
||||
}
|
||||
|
||||
export interface CertsView {
|
||||
intermediate: IntermediateView | null;
|
||||
root: { offline: boolean; subject: string; not_after: string; sha256: string };
|
||||
devices: DeviceRow[];
|
||||
device_lifetime_days: number;
|
||||
server_lifetime_days: number;
|
||||
approval: string;
|
||||
requests: PkiRequest[];
|
||||
}
|
||||
|
||||
export interface Bundle {
|
||||
download_url: string;
|
||||
one_time_password: string;
|
||||
expires_at: string;
|
||||
filename: string;
|
||||
qr_svg: string | null;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// 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/.
|
||||
|
||||
import "@ianitor/ui/tokens.css";
|
||||
import "@ianitor/ui/components.css";
|
||||
import { mount } from "svelte";
|
||||
import App from "./App.svelte";
|
||||
|
||||
const target = document.getElementById("app");
|
||||
if (target) mount(App, { target });
|
||||
@@ -0,0 +1,245 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §13: Certificates → + Device → Issue (3 clicks), approval with the match code, then
|
||||
// the install (the accepted 4th click). Until Custos can approve, approval is the server
|
||||
// command control names (docs/pki.md).
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { Banner, Button, Dialog, Icon, Segmented, Status } from "@ianitor/ui";
|
||||
import HostMenu from "../components/HostMenu.svelte";
|
||||
import IntermediateBanner from "../components/IntermediateBanner.svelte";
|
||||
import { ApiError, del, get, post, sentence } from "../lib/api";
|
||||
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
|
||||
import { shortDate, when } from "../lib/format";
|
||||
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
|
||||
|
||||
let { newDevice }: { newDevice: boolean } = $props();
|
||||
|
||||
let certs = $state<CertsView | null>(null);
|
||||
let problem = $state<string | null>(null);
|
||||
let name = $state("");
|
||||
let kind = $state<"phone" | "computer" | "app">("phone");
|
||||
let nameErr = $state<string | null>(null);
|
||||
let issuing = $state(false);
|
||||
let request = $state<PkiRequest | null>(null);
|
||||
let bundle = $state<{ device: DeviceRow | { id: string; name: string; kind: string }; b: Bundle; format: string } | null>(null);
|
||||
let confirmRevoke = $state<string | null>(null);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
certs = await get<CertsView>("/certs");
|
||||
problem = null;
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
onMount(load);
|
||||
onDestroy(() => clearTimeout(timer));
|
||||
|
||||
async function issue(e?: Event) {
|
||||
e?.preventDefault();
|
||||
issuing = true;
|
||||
nameErr = null;
|
||||
try {
|
||||
request = await post<PkiRequest>("/certs/devices", { name, kind });
|
||||
poll();
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.body.field === "name") nameErr = err.body.message;
|
||||
else problem = sentence(err);
|
||||
} finally {
|
||||
issuing = false;
|
||||
}
|
||||
}
|
||||
|
||||
function poll() {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(async () => {
|
||||
if (!request) return;
|
||||
try {
|
||||
request = await get<PkiRequest>(`/pki-requests/${encodeURIComponent(request.request_id)}`);
|
||||
} catch {
|
||||
/* keep waiting */
|
||||
}
|
||||
if (request?.state === "waiting") poll();
|
||||
else void load();
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
async function cancelRequest() {
|
||||
if (!request) return;
|
||||
await del(`/pki-requests/${encodeURIComponent(request.request_id)}`).catch(() => {});
|
||||
request = null;
|
||||
closeForm();
|
||||
}
|
||||
|
||||
async function install(d: { id: string; name: string; kind: string }, format: "qr" | "p12") {
|
||||
try {
|
||||
const b = await post<Bundle>(`/certs/devices/${encodeURIComponent(d.id)}/bundle`, { format });
|
||||
bundle = { device: d, b, format };
|
||||
if (format === "p12") {
|
||||
const a = document.createElement("a");
|
||||
a.href = b.download_url;
|
||||
a.download = `${d.name}.p12`;
|
||||
a.rel = "noreferrer";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function revoke(d: DeviceRow) {
|
||||
try {
|
||||
await del(`/certs/devices/${encodeURIComponent(d.id)}`);
|
||||
toast(`Revoked. ${d.name} can no longer get in.`);
|
||||
confirmRevoke = null;
|
||||
await load();
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
function closeForm() {
|
||||
clearTimeout(timer);
|
||||
name = "";
|
||||
nameErr = null;
|
||||
if (request?.state !== "approved") request = null;
|
||||
navigate("/certificates");
|
||||
}
|
||||
|
||||
const lifetime = $derived(certs?.device_lifetime_days ?? 365);
|
||||
const until = $derived(shortDate(new Date(Date.now() + lifetime * 86_400_000).toISOString()));
|
||||
const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
|
||||
switch (certs?.intermediate?.state) {
|
||||
case "ok": return ["healthy", "valid"];
|
||||
case "due": return ["degraded", "renew soon"];
|
||||
case "urgent": return ["down", "renew now"];
|
||||
case "expired": return ["down", "expired"];
|
||||
default: return ["unknown", "not set up"];
|
||||
}
|
||||
});
|
||||
const kindIcon = (k: string) => (k === "phone" ? "phone" : k === "computer" ? "laptop" : "app") as "phone" | "laptop" | "app";
|
||||
const issuedDevice = $derived(request?.state === "approved" && request.device_id ? { id: request.device_id, name: request.name ?? name, kind } : null);
|
||||
</script>
|
||||
|
||||
<div class="head">
|
||||
<h1 class="ia-display">Certificates</h1>
|
||||
<Button variant="outline" icon="plus" label="Add a device certificate" onclick={() => navigate("/certificates/new")}>Device</Button>
|
||||
</div>
|
||||
|
||||
<IntermediateBanner />
|
||||
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||
|
||||
{#if certs}
|
||||
<section class="ia-card">
|
||||
<p class="ia-label">Domi intermediate</p>
|
||||
<p><Status kind={intState[0]} word={intState[1]} /> {#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}</p>
|
||||
<p class="ia-sub">Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).</p>
|
||||
</section>
|
||||
|
||||
<p class="ia-label">Devices</p>
|
||||
{#if certs.devices.length === 0}
|
||||
<div class="ia-frame"><h2 class="ia-h3">No device certificates yet</h2><p class="ia-text2">A device certificate lets a phone, computer or Domi app into hosts that ask for one.</p></div>
|
||||
{:else}
|
||||
<ul class="devices">
|
||||
{#each certs.devices as d (d.id)}
|
||||
<li>
|
||||
<Icon name={kindIcon(d.kind)} />
|
||||
<span class="dname">{d.name}</span>
|
||||
<span class="ia-muted">until {shortDate(d.not_after)}</span>
|
||||
{#if d.state === "revoked"}<Status kind="unknown" word="revoked {d.revoked_at ? shortDate(d.revoked_at) : ''}" />{:else if d.state === "expired"}<Status kind="down" word="expired" />{/if}
|
||||
{#if confirmRevoke === d.id}
|
||||
<span class="confirm">Revoke the certificate of "{d.name}"? It can no longer get in.
|
||||
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
|
||||
<Button small variant="danger" onclick={() => revoke(d)}>Revoke</Button></span>
|
||||
{:else if d.state === "valid"}
|
||||
<HostMenu hostname={d.name} items={[
|
||||
{ label: "Install on the device", icon: "key", run: () => install(d, d.kind === "computer" ? "p12" : "qr") },
|
||||
{ label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) },
|
||||
]} />
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if newDevice}
|
||||
<Dialog title="New device certificate" kind="panel" onclose={closeForm}>
|
||||
{#if !request}
|
||||
<form id="device-form" onsubmit={issue} class="form">
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for="device-name">Device name</label>
|
||||
<input id="device-name" class="domi-input" bind:value={name} autocomplete="off" aria-invalid={nameErr ? "true" : undefined} aria-describedby="device-name-h" />
|
||||
{#if nameErr}<p class="domi-error"><Icon name="ring" />{nameErr}</p>{/if}
|
||||
<p class="ia-hint" id="device-name-h">Shown in this list and inside the certificate.</p>
|
||||
</div>
|
||||
<Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} />
|
||||
<p class="ia-hint">Valid for {lifetime} days, until {until}. It lets this device into hosts that ask for a Domi device certificate.</p>
|
||||
</form>
|
||||
{:else if request.state === "waiting"}
|
||||
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
|
||||
<p>Approve it on the server, and only if it shows the same code:</p>
|
||||
<p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p>
|
||||
{#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if}
|
||||
<p class="ia-muted">The request stays open for {Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")}. Nothing is issued until it is approved.</p>
|
||||
<div><Button onclick={cancelRequest}>Cancel request</Button></div>
|
||||
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
|
||||
{:else if issuedDevice}
|
||||
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved at {when(request?.approved_at, app.now)}.{/snippet}</Banner>
|
||||
<div class="buttons">
|
||||
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
|
||||
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
|
||||
</div>
|
||||
<p class="ia-hint">The file is protected with a one-time password shown next to the QR code.</p>
|
||||
{:else}
|
||||
<Banner tone="notice" live="status">{#snippet title()}{request?.message}{/snippet}
|
||||
{#snippet actions()}<Button variant="outline" onclick={() => { request = null; void issue(); }}>Try again</Button>{/snippet}</Banner>
|
||||
{/if}
|
||||
{#snippet footer()}
|
||||
{#if !request}
|
||||
<Button onclick={closeForm}>Cancel</Button>
|
||||
<Button variant="primary" type="submit" form="device-form" pending={issuing}>Issue</Button>
|
||||
{:else if request.state !== "waiting"}
|
||||
<Button onclick={() => { request = null; closeForm(); void load(); }}>Close</Button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Dialog>
|
||||
{/if}
|
||||
|
||||
{#if bundle}
|
||||
<Dialog title="Install on {bundle.device.name}" onclose={() => { bundle = null; void refresh(); }}>
|
||||
<div class="install">
|
||||
{#if bundle.b.qr_svg}
|
||||
<div class="ia-qr" role="img" aria-label="QR code for downloading the certificate">{@html bundle.b.qr_svg}</div>
|
||||
{/if}
|
||||
<div>
|
||||
<p class="ia-label">Password for the file</p>
|
||||
<p class="otp">{bundle.b.one_time_password}</p>
|
||||
<p class="ia-hint">Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).</p>
|
||||
</div>
|
||||
</div>
|
||||
<p class="ia-text2">
|
||||
{#if bundle.device.kind === "computer"}Open the downloaded file and enter the password when it asks.
|
||||
{:else if bundle.device.kind === "app"}In the app, choose Import certificate, pick the file, and enter the password.
|
||||
{:else}Scan the code with the device's camera, open the link, and enter the password when it asks. Then allow the certificate in the device's settings.{/if}
|
||||
</p>
|
||||
</Dialog>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.head { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; flex-wrap: wrap; }
|
||||
.devices { list-style: none; margin: 0; padding: 0; border: 1px solid var(--hairline); border-radius: var(--radius-lg); }
|
||||
.devices li { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; min-height: 56px; padding: 6px 10px 6px 16px; border-top: 1px solid var(--hairline); }
|
||||
.devices li:first-child { border-top: 0; }
|
||||
.dname { font-weight: 600; flex: 1 1 140px; }
|
||||
.confirm { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; flex-basis: 100%; }
|
||||
.form { display: flex; flex-direction: column; gap: 16px; }
|
||||
.buttons { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.install { display: flex; gap: 20px; flex-wrap: wrap; align-items: flex-start; }
|
||||
.otp { font-weight: 700; font-size: 1.4rem; letter-spacing: 0.08em; }
|
||||
</style>
|
||||
@@ -0,0 +1,179 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §8.1: History → pick → Restore this version (3 clicks with the nav click).
|
||||
import { onMount } from "svelte";
|
||||
import { Banner, Button, Status } from "@ianitor/ui";
|
||||
import type { StatusKind } from "@ianitor/ui";
|
||||
import HostPanel from "../components/HostPanel.svelte";
|
||||
import { get, post, sentence } from "../lib/api";
|
||||
import { app, changesBlocked, navigate } from "../lib/app.svelte";
|
||||
import { FIELD_LABEL, fieldValue, longDate, when } from "../lib/format";
|
||||
import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types";
|
||||
|
||||
let { host, pick }: { host?: string; pick?: string } = $props();
|
||||
|
||||
let entries = $state<HistoryEntry[]>([]);
|
||||
let next = $state<string | null>(null);
|
||||
let loaded = $state(false);
|
||||
let problem = $state<string | null>(null);
|
||||
let chosen = $state<string | null>(null);
|
||||
let preview = $state<RestorePreview | null>(null);
|
||||
let attempt = $state<ApplyView | null>(null);
|
||||
let restoring = $state(false);
|
||||
let resume = $state<string | null>(null);
|
||||
let editFrom = $state<HostSpec | null>(null);
|
||||
|
||||
async function load(before?: string) {
|
||||
try {
|
||||
const q = new URLSearchParams({ limit: "50" });
|
||||
if (host) q.set("host", host);
|
||||
if (before) q.set("before", before);
|
||||
const r = await get<{ entries: HistoryEntry[]; next_before: string | null }>(`/history?${q}`);
|
||||
entries = before ? [...entries, ...r.entries] : r.entries;
|
||||
next = r.next_before;
|
||||
problem = null;
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
} finally {
|
||||
loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function choose(id: string) {
|
||||
chosen = id;
|
||||
preview = null;
|
||||
attempt = null;
|
||||
try {
|
||||
preview = await get<RestorePreview>(`/history/${encodeURIComponent(id)}/restore-preview`);
|
||||
if (preview.blocked?.code === "restore.not_kept") attempt = await get<ApplyView>(`/history/${encodeURIComponent(id)}`);
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
if (!chosen) return;
|
||||
restoring = true;
|
||||
try {
|
||||
const a = await post<{ apply: ApplyView }>("/restore", { change_id: chosen, base_rev: app.overview?.rev ?? null });
|
||||
resume = a.apply.id;
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
} finally {
|
||||
restoring = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void load().then(() => {
|
||||
if (pick) void choose(pick);
|
||||
});
|
||||
const focus = () => void load();
|
||||
window.addEventListener("focus", focus);
|
||||
return () => window.removeEventListener("focus", focus);
|
||||
});
|
||||
|
||||
function stateOf(e: HistoryEntry): [StatusKind, string] {
|
||||
switch (e.state) {
|
||||
case "kept": return ["kept", "kept"];
|
||||
case "reverted": return ["reverted", "reverted"];
|
||||
case "failed": return ["reverted", "not applied"];
|
||||
case "queued": return ["running", "waiting"];
|
||||
default: return ["running", "applying"];
|
||||
}
|
||||
}
|
||||
|
||||
const entry = $derived(entries.find((e) => e.change_id === chosen));
|
||||
const n = $derived(preview?.changes.length ?? 0);
|
||||
const paused = $derived(app.overview?.paused ? !["apply.needs_attention", "control.files_unwritten"].includes(app.overview.paused_reason ?? "") : false);
|
||||
const blocked = $derived(paused ? "Changes are paused." : changesBlocked() && !app.overview?.paused ? changesBlocked() : null);
|
||||
|
||||
function key(e: KeyboardEvent, i: number) {
|
||||
const btns = Array.from(document.querySelectorAll<HTMLButtonElement>(".entries button"));
|
||||
if (e.key === "ArrowDown") { e.preventDefault(); btns[Math.min(btns.length - 1, i + 1)]?.focus(); }
|
||||
if (e.key === "ArrowUp") { e.preventDefault(); btns[Math.max(0, i - 1)]?.focus(); }
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1 class="ia-display">{host ? `History of ${host}` : "History"}</h1>
|
||||
{#if host}<div><button type="button" class="domi-btn link" onclick={() => navigate("/history")}>Show all changes</button></div>{/if}
|
||||
{#if problem}<Banner tone="notice" live="status">{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||
|
||||
<div class="cols">
|
||||
<div class="list">
|
||||
{#if loaded && entries.length === 0}
|
||||
<div class="ia-frame"><h2 class="ia-h3">No changes yet</h2><p class="ia-text2">Every change you apply is listed here, newest first.</p></div>
|
||||
{/if}
|
||||
<ul class="entries">
|
||||
{#each entries as e, i (e.change_id)}
|
||||
{@const [k, w] = stateOf(e)}
|
||||
<li>
|
||||
<button type="button" class="entry" aria-current={chosen === e.change_id ? "true" : undefined} onclick={() => choose(e.change_id)} onkeydown={(ev) => key(ev, i)}>
|
||||
<span class="sum">{e.summary}</span><Status kind={k} word={w} />
|
||||
<span class="ia-sub">{when(e.at, app.now)} · {e.state === "kept" ? (e.commit_short ?? "") : (e.reason_short ?? "")}</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{#if next}<Button onclick={() => load(next ?? undefined)}>Show older changes</Button>{/if}
|
||||
</div>
|
||||
|
||||
{#if chosen && preview}
|
||||
<section class="detail" aria-label="Version">
|
||||
<p class="ia-label">Version of {when(entry?.at, app.now)}</p>
|
||||
{#if preview.blocked?.code === "restore.not_kept"}
|
||||
<h2 class="ia-h3">This change did not stay</h2>
|
||||
{#if attempt?.reason}<p>{attempt.reason.message}</p>{/if}
|
||||
<p class="ia-text2">This change was undone at the time, so there is nothing to go back to.</p>
|
||||
{#if attempt?.attempted_host}<div><Button variant="outline" onclick={() => (editFrom = attempt?.attempted_host ?? null)}>Edit and try again</Button></div>{/if}
|
||||
{:else if preview.blocked?.code === "restore.same"}
|
||||
<h2 class="ia-h3">Go back to this version?</h2>
|
||||
<p class="ia-text2">This version is the same as the current one. Nothing to restore.</p>
|
||||
<div class="buttons"><Button onclick={() => (chosen = null)}>Close</Button></div>
|
||||
{:else}
|
||||
<h2 class="ia-h3">Go back to this version?</h2>
|
||||
<p>{n === 1 ? "Restoring puts 1 host back to how it was then:" : `Restoring puts ${n} hosts back to how they were then:`}</p>
|
||||
<ul>
|
||||
{#each preview.changes as c (c.hostname)}
|
||||
{#if c.effect === "added"}<li><strong>{c.hostname}</strong> is added back</li>
|
||||
{:else if c.effect === "removed"}<li><strong>{c.hostname}</strong> is removed</li>
|
||||
{:else}
|
||||
{#each c.fields as f (f.field)}
|
||||
<li><strong>{c.hostname}</strong>: {#if f.field === "headers"}header rules change{:else}{FIELD_LABEL[f.field] ?? f.field} changes from {fieldValue(f.field, f.from)} to {fieldValue(f.field, f.to)}{/if}</li>
|
||||
{/each}
|
||||
{/if}
|
||||
{/each}
|
||||
</ul>
|
||||
<p class="ia-hint">Applied as a new commit with the same {app.overview?.site?.watch_seconds ?? 60}-second watch. If health checks fail, it is undone.</p>
|
||||
{#if blocked}<p class="ia-hint" id="restore-blocked">{blocked}</p>{/if}
|
||||
<div class="buttons">
|
||||
<Button onclick={() => (chosen = null)}>Close</Button>
|
||||
<Button variant="primary" onclick={restore} pending={restoring} disabled={!!blocked} describedby={blocked ? "restore-blocked" : undefined}>Restore this version</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if resume}
|
||||
<HostPanel resume={resume} onclose={() => { resume = null; void load(); }} />
|
||||
{/if}
|
||||
{#if editFrom}
|
||||
<HostPanel prefill={editFrom} hostname={undefined} onclose={() => { editFrom = null; void load(); }} />
|
||||
{/if}
|
||||
<span class="sr-only">{longDate(entry?.at)}</span>
|
||||
|
||||
<style>
|
||||
.cols { display: flex; gap: 24px; flex-wrap: wrap; align-items: flex-start; }
|
||||
.list { flex: 1 1 360px; max-width: 520px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.entries { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
|
||||
.entry { display: grid; grid-template-columns: 1fr auto; gap: 2px 12px; width: 100%; min-height: 44px; padding: 10px 12px; border-radius: var(--radius-sm); border: 1px solid transparent; background: none; color: var(--text); text-align: left; cursor: pointer; }
|
||||
.entry:hover { background: var(--surface); }
|
||||
.entry[aria-current="true"] { background: var(--surface-2); border-color: color-mix(in srgb, var(--accent) 55%, transparent); }
|
||||
.sum { font-weight: 600; }
|
||||
.detail { flex: 2 1 360px; background: var(--colonnade); border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.detail ul { margin: 0; padding-left: 1.1rem; }
|
||||
.buttons { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; }
|
||||
</style>
|
||||
@@ -0,0 +1,141 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §5: the main screen.
|
||||
import { Banner, Button, Icon } from "@ianitor/ui";
|
||||
import ChangeBar from "../components/ChangeBar.svelte";
|
||||
import EnginePopover from "../components/EnginePopover.svelte";
|
||||
import HostList from "../components/HostList.svelte";
|
||||
import HostPanel from "../components/HostPanel.svelte";
|
||||
import IntermediateBanner from "../components/IntermediateBanner.svelte";
|
||||
import ShareDialog from "../components/ShareDialog.svelte";
|
||||
import { call, newKey, post, sentence } from "../lib/api";
|
||||
import { app, changesBlocked, navigate, refresh, toast } from "../lib/app.svelte";
|
||||
import { countsSentence, when } from "../lib/format";
|
||||
import type { ApplyView, HostSpec } from "../lib/types";
|
||||
|
||||
let { route }: { route: { newHost: boolean; edit?: string } } = $props();
|
||||
|
||||
const o = $derived(app.overview);
|
||||
let prefill = $state<HostSpec | null>(null);
|
||||
let focusField = $state<string | undefined>(undefined);
|
||||
let problem = $state<string | null>(null);
|
||||
|
||||
const panelOpen = $derived(route.newHost || !!route.edit || app.panel?.kind === "host");
|
||||
const blocked = $derived(changesBlocked());
|
||||
|
||||
function closePanel() {
|
||||
prefill = null;
|
||||
focusField = undefined;
|
||||
if (app.panel?.kind === "host") app.panel = null;
|
||||
if (route.newHost || route.edit) navigate("/");
|
||||
void refresh();
|
||||
}
|
||||
|
||||
async function remove(h: string) {
|
||||
problem = null;
|
||||
try {
|
||||
await call("DELETE", `/hosts/${encodeURIComponent(h)}?base_rev=${encodeURIComponent(o?.rev ?? "")}`, undefined, { idem: newKey() });
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function retry(h: string) {
|
||||
try {
|
||||
await post(`/hosts/${encodeURIComponent(h)}/certificate/retry`);
|
||||
toast("Trying Let's Encrypt again.");
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
function editAgain(a: ApplyView, field?: string) {
|
||||
prefill = a.attempted_host ?? null;
|
||||
focusField = field;
|
||||
if (a.kind === "add" || !a.hosts[0]) {
|
||||
navigate("/hosts/new");
|
||||
} else {
|
||||
navigate(`/hosts/${encodeURIComponent(a.hosts[0])}/edit`);
|
||||
}
|
||||
}
|
||||
|
||||
const engineName = $derived(o?.engine.running === "caddy" ? "Caddy" : "Pingora");
|
||||
const engineLabel = $derived(
|
||||
o?.engine.state === "switching" ? "Engine: switching" : `Engine: ${engineName}${o?.engine.state === "stopped" ? ", not answering" : ""}. Change engine`,
|
||||
);
|
||||
</script>
|
||||
|
||||
<div class="head">
|
||||
<div>
|
||||
<h1 class="ia-display">Hosts</h1>
|
||||
{#if o}<p class="ia-text2">{countsSentence(o.counts)}</p>{/if}
|
||||
</div>
|
||||
<div class="actions">
|
||||
{#if o}
|
||||
<button type="button" class="ia-engine" aria-haspopup="dialog" aria-expanded={app.panel?.kind === "engine"} aria-label={engineLabel}
|
||||
onclick={() => (app.panel = app.panel?.kind === "engine" ? null : { kind: "engine" })}>
|
||||
{#if o.engine.state === "switching"}<Icon name="clock" /> Engine Switching…{:else}
|
||||
<span class="ia-status" data-s={o.engine.state === "stopped" ? "down" : "healthy"}><span class="ia-dot"></span></span>
|
||||
<small class="desktop">Engine</small> {engineName}{#if o.engine.running === "caddy"} <small>(fallback)</small>{/if}{/if}
|
||||
<Icon name="chevron" />
|
||||
</button>
|
||||
{/if}
|
||||
<Button variant="primary" icon="plus" label="Add a host" disabled={!!blocked} describedby={blocked ? "add-blocked" : undefined} onclick={() => navigate("/hosts/new")}>Host</Button>
|
||||
{#if blocked}<span class="sr-only" id="add-blocked">{blocked}</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<IntermediateBanner />
|
||||
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||
|
||||
<ChangeBar onshowsteps={(id) => (app.panel = { kind: "host", resume: id })} onedit={editAgain} />
|
||||
|
||||
{#if !o && !app.loadError}
|
||||
<div class="ia-list" aria-busy="true"><span class="sr-only">Loading hosts…</span>
|
||||
{#each [0, 1, 2] as i (i)}<div class="ia-row"><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span class="ia-placeholder"></span><span></span></div>{/each}
|
||||
</div>
|
||||
{:else if app.loadError && !o}
|
||||
<Banner tone="down" live="alert">{#snippet title()}This page could not load. Ianitor's control service may be restarting.{/snippet}
|
||||
{#snippet actions()}<Button onclick={() => refresh()}>Try again now</Button>{/snippet}</Banner>
|
||||
{:else if o && o.hosts.length === 0}
|
||||
<div class="ia-frame"><h2 class="ia-h3">No hosts yet</h2><p class="ia-text2">Add the first one: the name people type, and where Ianitor should send them.</p></div>
|
||||
{:else if o}
|
||||
<HostList hosts={o.hosts}
|
||||
onedit={(h) => navigate(`/hosts/${encodeURIComponent(h)}/edit`)}
|
||||
onremove={remove}
|
||||
onshare={(h) => (app.panel = { kind: "share", hostname: h })}
|
||||
onhistory={(h) => navigate(`/history?host=${encodeURIComponent(h)}`)}
|
||||
onretry={retry} />
|
||||
{/if}
|
||||
|
||||
{#if o?.repo}
|
||||
<hr class="ia-ornament" />
|
||||
<p class="ia-muted footer">
|
||||
Routes live in the {o.repo.name} repository, one file per host.
|
||||
{#if o.repo.last_push_at}Last pushed to Gitea at {when(o.repo.last_push_at, app.now)}.{/if}
|
||||
{#if o.repo.unpushed}{o.repo.unpushed} changes not yet pushed.{/if}
|
||||
<button type="button" class="domi-btn link" onclick={() => navigate("/history")}>See history</button>
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if panelOpen}
|
||||
{#key route.edit ?? (app.panel?.kind === "host" ? app.panel.resume : "new")}
|
||||
<HostPanel hostname={route.edit} resume={app.panel?.kind === "host" ? app.panel.resume : undefined} {prefill} {focusField} onclose={closePanel} />
|
||||
{/key}
|
||||
{/if}
|
||||
{#if app.panel?.kind === "share"}
|
||||
<ShareDialog hostname={app.panel.hostname} onclose={() => { app.panel = null; void refresh(); }} />
|
||||
{/if}
|
||||
{#if app.panel?.kind === "engine"}
|
||||
<EnginePopover onclose={() => (app.panel = null)} />
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 16px; }
|
||||
.actions { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
|
||||
.footer { text-align: center; }
|
||||
@media (max-width: 719.98px) { .desktop { display: none; } }
|
||||
</style>
|
||||
@@ -0,0 +1,110 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §13.6: signing the intermediate by hand on the offline computer (the temporary step
|
||||
// until Custos can sign, docs/pki.md). The root key never comes to this server.
|
||||
import { Banner, Button, Icon } from "@ianitor/ui";
|
||||
import { ApiError, post, put, sentence } from "../lib/api";
|
||||
import { app, navigate, refresh } from "../lib/app.svelte";
|
||||
import type { PkiRequest } from "../lib/types";
|
||||
|
||||
const r = $derived(app.overview?.intermediate?.renewal ?? null);
|
||||
let pem = $state("");
|
||||
let paste = $state(false);
|
||||
let err = $state<string | null>(null);
|
||||
let pending = $state(false);
|
||||
let starting = $state(false);
|
||||
const day = new Date().toISOString().slice(0, 10);
|
||||
|
||||
function download() {
|
||||
if (!r?.csr_pem) return;
|
||||
const url = URL.createObjectURL(new Blob([r.csr_pem], { type: "application/pkcs10" }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `domi-intermediate-${day}.csr`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
async function file(e: Event) {
|
||||
const f = (e.currentTarget as HTMLInputElement).files?.[0];
|
||||
if (f) pem = await f.text();
|
||||
}
|
||||
|
||||
async function use() {
|
||||
if (!r) return;
|
||||
pending = true;
|
||||
err = null;
|
||||
try {
|
||||
const done = await put<PkiRequest>(`/pki-requests/${encodeURIComponent(r.request_id)}/certificate`, { certificate_pem: pem });
|
||||
app.renewedUntil = done.not_after;
|
||||
await refresh();
|
||||
navigate("/certificates");
|
||||
} catch (e) {
|
||||
err = e instanceof ApiError ? e.body.message : sentence(e);
|
||||
} finally {
|
||||
pending = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
starting = true;
|
||||
try {
|
||||
await post("/certs/intermediate/renewal");
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
err = sentence(e);
|
||||
} finally {
|
||||
starting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1 class="ia-display">Sign the intermediate by hand</h1>
|
||||
<p class="ia-text2">Custos cannot sign certificates yet, so the Domi root signs on the offline computer. The root key never comes to this server.</p>
|
||||
|
||||
{#if !r}
|
||||
<Banner tone="notice">{#snippet title()}There is no open renewal request.{/snippet}
|
||||
{#snippet actions()}<Button variant="outline" onclick={start} pending={starting}>Start a renewal</Button>{/snippet}</Banner>
|
||||
{:else}
|
||||
<section class="step">
|
||||
<p class="ia-label">Step 1</p>
|
||||
<h2 class="ia-h3">Download the request</h2>
|
||||
<p class="ia-text2">This file asks the Domi root to sign a new intermediate certificate. It holds no secret.</p>
|
||||
<p>Check that the offline computer shows the same code: <span class="ia-code small" aria-label="Match code {r.match_code}">{r.match_code}</span></p>
|
||||
<div><Button icon="copy" onclick={download}>Download the request (.csr)</Button></div>
|
||||
</section>
|
||||
<section class="step">
|
||||
<p class="ia-label">Step 2</p>
|
||||
<h2 class="ia-h3">Sign it on the offline computer</h2>
|
||||
<p class="ia-text2">Copy the file to the offline computer that holds the Domi root, then run:</p>
|
||||
<pre class="ia-secret ia-cmd">ianitor-control ca sign --root <root folder> --csr domi-intermediate-{day}.csr --out domi-intermediate-{day}.crt</pre>
|
||||
<p class="ia-muted">It asks for the root's passphrase and shows the code; sign only if it is the code above.</p>
|
||||
</section>
|
||||
<section class="step">
|
||||
<p class="ia-label">Step 3</p>
|
||||
<h2 class="ia-h3">Upload the signed certificate</h2>
|
||||
{#if paste}
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for="cert-paste">Signed certificate</label>
|
||||
<textarea id="cert-paste" class="domi-input" rows="8" bind:value={pem} aria-invalid={err ? "true" : undefined}></textarea>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for="cert-file">Signed certificate (.crt)</label>
|
||||
<input id="cert-file" class="domi-input" type="file" accept=".crt,.pem" onchange={file} aria-invalid={err ? "true" : undefined} />
|
||||
<div><button type="button" class="domi-btn link" onclick={() => (paste = true)}>Paste it instead</button></div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if err}<p class="domi-error" role="alert"><Icon name="ring" />{err}</p>{/if}
|
||||
<div><Button variant="primary" onclick={use} {pending} disabled={!pem.includes("BEGIN CERTIFICATE")}>Use this certificate</Button></div>
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.step { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 20px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.small { font-size: 1.4rem; }
|
||||
</style>
|
||||
@@ -0,0 +1,279 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §8.3: Settings with General, API (⚙ → API → New token = 3 clicks, Copy token the
|
||||
// accepted 4th), Share links and About.
|
||||
import { onMount } from "svelte";
|
||||
import { Banner, Button, Dialog, Segmented } from "@ianitor/ui";
|
||||
import { ApiError, call, del, get, newKey, patch, post, sentence } from "../lib/api";
|
||||
import { app, navigate, toast } from "../lib/app.svelte";
|
||||
import { shortDate, when } from "../lib/format";
|
||||
import type { CreatedToken, ShareLink, TokenRow } from "../lib/types";
|
||||
|
||||
let { tab }: { tab: string } = $props();
|
||||
const TABS = [
|
||||
{ id: "general", label: "General" },
|
||||
{ id: "api", label: "API" },
|
||||
{ id: "share-links", label: "Share links" },
|
||||
{ id: "about", label: "About" },
|
||||
];
|
||||
|
||||
let settings = $state<{ repo: { name: string; last_push_at: string | null } | null; watch_seconds: number } | null>(null);
|
||||
let tokens = $state<TokenRow[]>([]);
|
||||
let revoked = $state<Record<string, string>>({});
|
||||
let links = $state<ShareLink[]>([]);
|
||||
let problem = $state<string | null>(null);
|
||||
let expiry = $state<"year" | "never">("year");
|
||||
let made = $state<CreatedToken | null>(null);
|
||||
let tokenName = $state("");
|
||||
let tokenCopied = $state(false);
|
||||
let askClose = $state(false);
|
||||
let nameErr = $state<string | null>(null);
|
||||
let confirmRevoke = $state<string | null>(null);
|
||||
let confirmStopAll = $state(false);
|
||||
let creating = $state(false);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
if (tab === "general") settings = await get("/settings");
|
||||
if (tab === "api") tokens = (await get<{ items: TokenRow[] }>("/tokens")).items;
|
||||
if (tab === "share-links") links = (await get<{ items: ShareLink[] }>("/share-links")).items;
|
||||
problem = null;
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
$effect(() => {
|
||||
void tab;
|
||||
void load();
|
||||
});
|
||||
onMount(() => {
|
||||
const f = () => void load();
|
||||
window.addEventListener("focus", f);
|
||||
return () => window.removeEventListener("focus", f);
|
||||
});
|
||||
|
||||
function tabKey(e: KeyboardEvent, i: number) {
|
||||
let j = i;
|
||||
if (e.key === "ArrowRight") j = (i + 1) % TABS.length;
|
||||
else if (e.key === "ArrowLeft") j = (i - 1 + TABS.length) % TABS.length;
|
||||
else if (e.key === "Home") j = 0;
|
||||
else if (e.key === "End") j = TABS.length - 1;
|
||||
else return;
|
||||
e.preventDefault();
|
||||
navigate(`/settings/${TABS[j].id}`);
|
||||
setTimeout(() => document.getElementById(`tab-${TABS[j].id}`)?.focus(), 0);
|
||||
}
|
||||
|
||||
async function newToken() {
|
||||
creating = true;
|
||||
try {
|
||||
const name = `Token made ${shortDate(new Date().toISOString())}`;
|
||||
const body = expiry === "never" ? { name, never_expires: true } : { name, expires_in_days: 365 };
|
||||
made = await post<CreatedToken>("/tokens", body);
|
||||
tokenName = made.name;
|
||||
tokenCopied = false;
|
||||
askClose = false;
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
} finally {
|
||||
creating = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copyToken() {
|
||||
if (!made) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(made.token);
|
||||
tokenCopied = true;
|
||||
} catch {
|
||||
problem = "Your browser did not allow copying. Select the token and press Ctrl+C.";
|
||||
}
|
||||
}
|
||||
|
||||
async function closeToken(force = false) {
|
||||
if (!made) return;
|
||||
if (!tokenCopied && !force) {
|
||||
askClose = true;
|
||||
return;
|
||||
}
|
||||
if (tokenName.trim() && tokenName !== made.name) {
|
||||
try {
|
||||
await patch(`/tokens/${encodeURIComponent(made.id)}`, { name: tokenName.trim() });
|
||||
toast("Renamed.");
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.code === "token.name") {
|
||||
nameErr = e.body.message;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The token leaves memory with the dialog.
|
||||
made = null;
|
||||
tokenName = "";
|
||||
void load();
|
||||
}
|
||||
|
||||
async function revoke(t: TokenRow) {
|
||||
try {
|
||||
await del(`/tokens/${encodeURIComponent(t.id)}`);
|
||||
revoked = { ...revoked, [t.id]: new Date().toISOString() };
|
||||
confirmRevoke = null;
|
||||
toast(`Revoked. Anything using "${t.name}" stops working now.`);
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function stop(l: ShareLink) {
|
||||
try {
|
||||
await del(`/share-links/${encodeURIComponent(l.id)}`);
|
||||
toast("Stopped. The link stops working within a few seconds.");
|
||||
void load();
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAll() {
|
||||
try {
|
||||
await call("POST", "/share-links/stop-all", {}, { idem: newKey() });
|
||||
toast("All share links are stopped. New ones work as usual.");
|
||||
confirmStopAll = false;
|
||||
void load();
|
||||
} catch (e) {
|
||||
problem = sentence(e);
|
||||
}
|
||||
}
|
||||
|
||||
const active = $derived(links.filter((l) => l.state === "active"));
|
||||
const ended = $derived(links.filter((l) => l.state !== "active"));
|
||||
const viewer = $derived(app.overview?.viewer ?? null);
|
||||
</script>
|
||||
|
||||
<h1 class="ia-display">Settings</h1>
|
||||
<div class="tabs" role="tablist" aria-label="Settings">
|
||||
{#each TABS as t, i (t.id)}
|
||||
<button type="button" role="tab" id="tab-{t.id}" aria-selected={tab === t.id} aria-controls="panel-{t.id}" tabindex={tab === t.id ? 0 : -1}
|
||||
onclick={() => navigate(`/settings/${t.id}`)} onkeydown={(e) => tabKey(e, i)}>{t.label}</button>
|
||||
{/each}
|
||||
</div>
|
||||
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
|
||||
|
||||
<div role="tabpanel" id="panel-{tab}" aria-labelledby="tab-{tab}" class="panel">
|
||||
{#if tab === "general"}
|
||||
<p class="ia-label">Routes repository</p>
|
||||
<p>{settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + when(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}</p>
|
||||
<p class="ia-label">Health watch after apply</p>
|
||||
<p>{settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds</p>
|
||||
<p class="ia-label">Signed in</p>
|
||||
<p>{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}</p>
|
||||
{:else if tab === "api"}
|
||||
<div class="row">
|
||||
<h2 class="ia-h3">API tokens</h2>
|
||||
<Button variant="outline" icon="plus" onclick={newToken} pending={creating}>New token</Button>
|
||||
<Segmented legend="New tokens expire after" name="token-expiry" bind:value={expiry} options={[{ value: "year", label: "1 year" }, { value: "never", label: "Never" }]} />
|
||||
</div>
|
||||
<p class="ia-hint">The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.</p>
|
||||
{#if tokens.length === 0}
|
||||
<div class="ia-frame"><h2 class="ia-h3">No API tokens</h2><p class="ia-text2">Scripts and other Domi apps use a token to talk to Ianitor.</p></div>
|
||||
{:else}
|
||||
<ul class="rows">
|
||||
{#each tokens as t (t.id)}
|
||||
<li>
|
||||
<div class="grow">
|
||||
<span class="tname" class:struck={!!revoked[t.id] || !!t.revoked_at}>{t.name}</span>
|
||||
<span class="ia-sub" style="display:block">
|
||||
{#if revoked[t.id]}Revoked {when(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${when(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if}
|
||||
</span>
|
||||
</div>
|
||||
{#if !revoked[t.id] && !t.revoked_at}
|
||||
{#if confirmRevoke === t.id}
|
||||
<span>Revoke "{t.name}"? Anything using it stops working now.</span>
|
||||
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
|
||||
<Button small variant="danger" onclick={() => revoke(t)}>Revoke</Button>
|
||||
{:else}
|
||||
<Button small variant="danger" onclick={() => (confirmRevoke = t.id)}>Revoke</Button>
|
||||
{/if}
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
{:else if tab === "share-links"}
|
||||
<div class="row">
|
||||
<h2 class="ia-h3">Share links</h2>
|
||||
{#if active.length}<Button variant="danger" onclick={() => (confirmStopAll = true)}>Stop all share links</Button>{/if}
|
||||
</div>
|
||||
{#if app.overview?.engine.running === "caddy"}
|
||||
<Banner tone="notice">{#snippet title()}Caddy is serving, so these links do not work right now. They work again after switching back to Pingora.{/snippet}</Banner>
|
||||
{/if}
|
||||
{#if confirmStopAll}
|
||||
<p>Stop all {active.length} active links? Every link made so far stops working. New ones work as usual.
|
||||
<Button small onclick={() => (confirmStopAll = false)}>Cancel</Button> <Button small variant="danger" onclick={stopAll}>Stop all</Button></p>
|
||||
{/if}
|
||||
{#if links.length === 0}
|
||||
<div class="ia-frame"><h2 class="ia-h3">No share links</h2><p class="ia-text2">Make one from a host's menu (⋯), Share link.</p></div>
|
||||
{:else}
|
||||
<ul class="rows">
|
||||
{#each active as l (l.id)}
|
||||
<li>
|
||||
<div class="grow"><strong>{l.hostname}</strong>{l.path_prefix !== "/" ? l.path_prefix : ""}
|
||||
<span class="ia-sub" style="display:block">Made {when(l.created_at, app.now)} · expires {when(l.expires_at, app.now)}{l.has_password ? " · password" : ""}</span></div>
|
||||
<Button small onclick={() => stop(l)}>Stop this link</Button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{#if ended.length}
|
||||
<details><summary>Ended ({ended.length})</summary>
|
||||
<ul class="rows">{#each ended as l (l.id)}<li><span class="grow">{l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""}</span><span class="ia-sub">{l.state} {shortDate(l.expires_at)}</span></li>{/each}</ul>
|
||||
</details>
|
||||
{/if}
|
||||
{/if}
|
||||
{:else}
|
||||
<p>Ianitor Domi 0.1.0</p>
|
||||
<p>MPL-2.0</p>
|
||||
<p>Built, tested and signed by Fabrica Domi</p>
|
||||
<p><a class="domi-btn link" href="https://gitea.marek-novak.cz/mnovak/Ianitor" rel="noreferrer">Source on Gitea</a></p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if made}
|
||||
<Dialog title="Your new token" escape={false} onclose={() => closeToken()}>
|
||||
<p><strong>Copy it now and save it in Custos.</strong></p>
|
||||
<p class="ia-text2">Ianitor cannot show it again; if it is lost, make a new one and revoke this one.</p>
|
||||
<input class="ia-secret" readonly value={made.token} aria-label="New API token" onfocus={(e) => (e.currentTarget as HTMLInputElement).select()} />
|
||||
<div class="grid">
|
||||
<div class="domi-field">
|
||||
<label class="domi-field-label" for="token-name">Name</label>
|
||||
<input id="token-name" class="domi-input" bind:value={tokenName} aria-invalid={nameErr ? "true" : undefined} />
|
||||
{#if nameErr}<p class="domi-error">{nameErr}</p>{/if}
|
||||
<p class="ia-hint">Rename it now or later, so you know what uses it.</p>
|
||||
</div>
|
||||
<Button variant={tokenCopied ? "quiet" : "primary"} icon="copy" onclick={copyToken} data-autofocus>{tokenCopied ? "Copy again" : "Copy token"}</Button>
|
||||
</div>
|
||||
{#if tokenCopied}<p role="status">Copied. Paste it into Custos now. Ianitor cannot show it again.</p>{/if}
|
||||
<p class="ia-muted">{made.expires_at ? `Expires on ${shortDate(made.expires_at)}.` : "Never expires."}</p>
|
||||
{#if askClose}
|
||||
<p role="alert">Close without copying? The token cannot be shown again.
|
||||
<Button small onclick={() => (askClose = false)}>Go back</Button> <Button small variant="danger" onclick={() => closeToken(true)}>Close anyway</Button></p>
|
||||
{/if}
|
||||
{#snippet footer()}<Button onclick={() => closeToken()}>I have saved it</Button>{/snippet}
|
||||
</Dialog>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.tabs { display: flex; gap: 4px; overflow-x: auto; }
|
||||
.tabs [role="tab"] { min-height: 44px; padding: 0 1rem; border-radius: var(--radius-sm); border: 0; background: none; color: var(--text-2); font-weight: 600; cursor: pointer; }
|
||||
.tabs [role="tab"][aria-selected="true"] { background: var(--surface-2); color: var(--text); }
|
||||
.panel { display: flex; flex-direction: column; gap: 10px; }
|
||||
.row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; }
|
||||
.rows { list-style: none; margin: 0; padding: 0; }
|
||||
.rows li { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; min-height: 44px; padding: 8px 0; border-top: 1px solid var(--hairline); }
|
||||
.grow { flex: 1 1 200px; min-width: 0; }
|
||||
.tname { font-weight: 600; }
|
||||
.struck { text-decoration: line-through; color: var(--muted); }
|
||||
.grid { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: end; }
|
||||
@media (max-width: 719.98px) { .grid { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
@@ -0,0 +1,33 @@
|
||||
<!-- 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/. -->
|
||||
<script lang="ts">
|
||||
// Handoff §10.2: Authelia sends the sign-in tab back here; it tells the first tab and closes.
|
||||
import { onMount } from "svelte";
|
||||
|
||||
onMount(() => {
|
||||
const back = new URL(location.href).searchParams.get("back");
|
||||
try {
|
||||
const ch = new BroadcastChannel("ianitor-auth");
|
||||
ch.postMessage("signed-in");
|
||||
ch.close();
|
||||
} catch {
|
||||
/* the first tab rechecks with "I have signed in" */
|
||||
}
|
||||
if (back && back.startsWith("/") && !back.startsWith("//")) {
|
||||
location.replace(back);
|
||||
return;
|
||||
}
|
||||
setTimeout(() => window.close(), 300);
|
||||
});
|
||||
</script>
|
||||
|
||||
<main class="signed-in">
|
||||
<p class="ia-wordmark">IANITOR DOMI</p>
|
||||
<h1 class="ia-h3">You are signed in again.</h1>
|
||||
<p class="ia-text2">You can close this tab and go back to Ianitor.</p>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.signed-in { max-width: 420px; margin: 20vh auto; padding: 0 16px; display: flex; flex-direction: column; gap: 12px; }
|
||||
</style>
|
||||
@@ -0,0 +1,7 @@
|
||||
// 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/.
|
||||
|
||||
import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
|
||||
|
||||
export default { preprocess: vitePreprocess() };
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 () {};
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "@tsconfig/svelte/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noImplicitReturns": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"isolatedModules": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["vite/client"],
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.svelte", "tests/**/*.ts", "../../packages/ui/src/**/*.ts", "../../packages/ui/src/**/*.svelte"]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// 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/.
|
||||
|
||||
import { svelte } from "@sveltejs/vite-plugin-svelte";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
// Dev server: 127.0.0.1 only (CLAUDE.md), never --host 0.0.0.0. /api goes to control's --dev on
|
||||
// 127.0.0.1:7878. In production edge sends Authelia's identity and the per-boot proof; in dev
|
||||
// there is no Authelia, so the dev proxy (never the browser) adds the dev API token from
|
||||
// $IANITOR_DEV_TOKEN, which `ianitor-control --dev` prints.
|
||||
const control = process.env.IANITOR_CONTROL ?? "http://127.0.0.1:7878";
|
||||
const token = process.env.IANITOR_DEV_TOKEN;
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [svelte()],
|
||||
server: {
|
||||
host: "127.0.0.1",
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: control,
|
||||
changeOrigin: true,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
||||
},
|
||||
},
|
||||
},
|
||||
preview: { host: "127.0.0.1" },
|
||||
build: { outDir: "dist", sourcemap: false, assetsInlineLimit: 0 },
|
||||
resolve: process.env.VITEST ? { conditions: ["browser"] } : undefined,
|
||||
test: {
|
||||
environment: "jsdom",
|
||||
setupFiles: ["./tests/setup.ts"],
|
||||
include: ["tests/**/*.test.ts"],
|
||||
testTimeout: 20000,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user