[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
+245
View File
@@ -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>
+179
View File
@@ -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>
+141
View File
@@ -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>
+110
View File
@@ -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 &lt;root folder&gt; --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>
+279
View File
@@ -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>
+33
View File
@@ -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>