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

This commit is contained in:
2026-11-07 23:44:27 +01:00
parent aed5fbfcff
commit 3e326e85a0
47 changed files with 7868 additions and 3 deletions
@@ -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>
+140
View File
@@ -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>
+142
View File
@@ -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>
+86
View File
@@ -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>
+499
View File
@@ -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>
+163
View File
@@ -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>
+73
View File
@@ -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}