From 503916492d6a8980514e5003706360cc9400ee04 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sun, 8 Nov 2026 11:21:44 +0100 Subject: [PATCH] [web] Design review: last row's menu not clipped, Hostname focused after loading, popover closes on Esc and outside click, phone engine chip in the top bar, paused and needs-attention copy with Restore in the panel, change bar offers and countdown, focus after share and kept, fingerprint check when signing by hand, draft kept through sign-in --- apps/web/src/App.svelte | 18 ++++++- apps/web/src/components/ChangeBar.svelte | 43 +++++++++++---- apps/web/src/components/EngineChip.svelte | 29 ++++++++++ apps/web/src/components/EnginePopover.svelte | 36 +++++++++---- apps/web/src/components/HostList.svelte | 2 +- apps/web/src/components/HostMenu.svelte | 4 +- apps/web/src/components/HostPanel.svelte | 53 ++++++++++++++++--- .../src/components/IntermediateBanner.svelte | 8 +-- apps/web/src/components/ShareDialog.svelte | 10 ++-- apps/web/src/components/TopBanners.svelte | 50 +++++++++-------- apps/web/src/lib/app.svelte.ts | 32 ++++++++++- apps/web/src/lib/applies.ts | 7 ++- apps/web/src/lib/format.ts | 20 ++++++- apps/web/src/lib/types.ts | 6 ++- apps/web/src/views/Certificates.svelte | 16 +++--- apps/web/src/views/History.svelte | 3 +- apps/web/src/views/Hosts.svelte | 39 ++++++-------- apps/web/src/views/RenewByHand.svelte | 28 ++++++++-- apps/web/src/views/Settings.svelte | 10 ++-- apps/web/tests/flows.test.ts | 26 ++++++++- apps/web/tests/mockApi.ts | 2 +- packages/ui/src/Dialog.svelte | 23 ++++++-- packages/ui/src/components.css | 17 +++++- packages/ui/src/icons.ts | 1 + 24 files changed, 364 insertions(+), 119 deletions(-) create mode 100644 apps/web/src/components/EngineChip.svelte diff --git a/apps/web/src/App.svelte b/apps/web/src/App.svelte index 674e7a6..f073ddc 100644 --- a/apps/web/src/App.svelte +++ b/apps/web/src/App.svelte @@ -7,6 +7,8 @@ import { onMount } from "svelte"; import { Button, Dialog, Icon } from "@ianitor/ui"; import type { IconName } from "@ianitor/ui"; + import EngineChip from "./components/EngineChip.svelte"; + import EnginePopover from "./components/EnginePopover.svelte"; import TopBanners from "./components/TopBanners.svelte"; import { app, navigate, refresh, startPolling } from "./lib/app.svelte"; import { remembered } from "./lib/applies"; @@ -72,7 +74,12 @@ function signIn() { const w = window.open("/signed-in", "ianitor-sign-in"); - if (!w) location.href = `/signed-in?back=${encodeURIComponent(app.path)}`; + if (!w) { + // The new tab was blocked: this tab goes to the sign-in, so an open form is saved first + // (sessionStorage, this tab only) and comes back after it (§10). + window.dispatchEvent(new Event("ianitor:save-draft")); + location.href = `/signed-in?back=${encodeURIComponent(app.path)}`; + } } async function signedInAgain() { @@ -99,7 +106,7 @@ {#if app.overview?.site?.auth_logout_url}Sign out{/if} -
IANITOR DOMI
+
IANITOR DOMI{#if app.phone}{/if}
{#if route.view === "hosts"} @@ -121,6 +128,13 @@ + {#if app.panel?.kind === "engine"} + { + app.panel = null; + document.querySelector("[data-engine-chip]")?.focus(); + }} /> + {/if} +
{#each app.toasts as t (t.id)}
{t.text}
{/each}
diff --git a/apps/web/src/components/ChangeBar.svelte b/apps/web/src/components/ChangeBar.svelte index 50b7352..c7c2dcc 100644 --- a/apps/web/src/components/ChangeBar.svelte +++ b/apps/web/src/components/ChangeBar.svelte @@ -4,10 +4,10 @@ {#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)} @@ -93,8 +117,9 @@ (app.dismissed = [...app.dismissed, dismissKey])}> {#snippet title()}{last.state === "failed" ? "not applied" : "reverted"} {parts[0]}{/snippet} {#if parts[1]}Reason: {parts[1]}{/if} + {#if last.reason?.detail && last.reason.code.startsWith("apply.failed.")}
{/if} {#snippet actions()} - {#if last.attempted_host}{/if} + {#if offer}{/if} {/snippet} {/if} @@ -104,8 +129,8 @@ {#if active}
{active.state === "queued" ? "waiting" : active.state === "watching" ? "watching" : "applying"} - {runningHeading(active.summary, last && last.id === active.id ? last : null)}
-
{active.state === "queued" ? "Waiting for another change to finish" : `${watchLeft ?? active.seconds_left ?? 0} s left`}
+ {runningHeading(active.summary, active.kind ? active : null)}
+
{active.state === "queued" ? "Waiting for another change to finish" : active.state === "watching" ? `${watchLeft ?? 0} s left` : "Checking and loading the change"}
{#if active.state === "watching" && watchLeft != null} {@const total = o?.site?.watch_seconds ?? 60} @@ -116,7 +141,7 @@
{#if last.state === "kept"}
kept {last.summary}
-
{pushFailed ? "Kept, but not yet saved to Gitea. Ianitor tries again by itself." : keptLine}
+
{pushFailed ? pushLine : keptLine}
{:else if undo?.target}
Undo: {undo.target.summary}
{/if} @@ -125,7 +150,7 @@ {#if undoReason}
{undoReason}
{/if} {#if !undo?.target}
Nothing to undo yet.
{/if}
- {#if pushFailed}{/if} + {#if canPushNow}{/if} {#if undo?.target} +{/if} + + diff --git a/apps/web/src/components/EnginePopover.svelte b/apps/web/src/components/EnginePopover.svelte index cd7f368..57f59f7 100644 --- a/apps/web/src/components/EnginePopover.svelte +++ b/apps/web/src/components/EnginePopover.svelte @@ -4,11 +4,11 @@ - +

Engine

{#if e?.state === "stopped"} -

{name} is not answering. Visitors may not reach any host. Switching to {other} is the quickest way back.

+

Visitors may not reach any host. Switching to {other} is the quickest way back.

{:else}

- {#if e?.since}Since {when(e.since, app.now)}. {/if} + {#if e?.since}Since {whenInline(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} + {#if notReady}Caddy is not ready: its settings have not been built yet.{:else if differs > 0}Caddy is built with the same routes {whenInline(fr?.built_at, app.now)}, but {differs} of {fr?.compared} hosts behave differently on it.{:else}Caddy is ready with the same routes: built {whenInline(fr?.built_at, app.now)}{fr?.compared ? `, and all ${fr.compared} hosts behave the same` : ""}.{/if} + {#if !notReady && !fr?.current} It is rebuilt from the current routes when you switch.{/if} {:else}Pingora is ready with the same routes.{/if}

+ {#if running === "pingora" && !notReady && fr?.differences.length} +
+ {/if} {/if}

What happens

@@ -81,10 +95,10 @@
  • Open connections close; videos and uploads in progress restart.
  • Hosts and certificates stay the same.
  • {#if running === "pingora"} -
  • 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}
  • -
  • Changes wait while Caddy serves; switch back to make them.
  • +
  • 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}{" "}{activeLinks === 1 ? "1 share link is" : `${activeLinks} share links are`} active.{/if}
  • +
  • Changes keep working: Ianitor tries each one on Caddy and undoes it if a host stops answering.
  • {:else} -
  • Share links work again, and changes can be made again.
  • +
  • Share links work again.
  • {/if}
  • This page may lose contact for a few seconds.
  • diff --git a/apps/web/src/components/HostList.svelte b/apps/web/src/components/HostList.svelte index a51cd60..70e0ea0 100644 --- a/apps/web/src/components/HostList.svelte +++ b/apps/web/src/components/HostList.svelte @@ -111,7 +111,7 @@ {w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""} - {h.upstreams[0] ?? ""}{#if h.upstreams.length > 1} +{h.upstreams.length - 1} more{/if} + {h.upstreams[0] ?? ""}{#if h.upstreams.length > 1}{" "}+{h.upstreams.length - 1} more{/if} {running.includes(h.hostname) ? "Changing now · " : ""}{s.text} {#if h.certificate.state === "pending"}Waiting for Let's Encrypt to issue the certificate.{/if} {#if h.certificate.state === "failed"} diff --git a/apps/web/src/components/HostMenu.svelte b/apps/web/src/components/HostMenu.svelte index 95be1ee..9fcad4a 100644 --- a/apps/web/src/components/HostMenu.svelte +++ b/apps/web/src/components/HostMenu.svelte @@ -52,7 +52,9 @@ function pick(it: Item) { if (it.reason) return; - close(false); + // Focus back on More first: a dialog the item opens returns focus there when it closes + // (§2.9), not to a menu item that no longer exists. + close(true); it.run(); } diff --git a/apps/web/src/components/HostPanel.svelte b/apps/web/src/components/HostPanel.svelte index 23001bc..961825d 100644 --- a/apps/web/src/components/HostPanel.svelte +++ b/apps/web/src/components/HostPanel.svelte @@ -8,7 +8,7 @@ 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 { app, changesBlocked, refresh, restoreLastKept, 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"; @@ -62,6 +62,8 @@ // ---- the apply let apply = $state(null); + let restoring = $state(false); + let restoreProblem = $state(null); let phase = $state<"form" | "progress">("form"); let stop: (() => void) | undefined; let closeTimer: ReturnType | undefined; @@ -128,16 +130,43 @@ 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); + // A form saved before this tab went to sign in comes back (App.svelte, signIn). + try { + const raw = sessionStorage.getItem(DRAFT); + const d = raw ? (JSON.parse(raw) as { hostname: string; host: typeof host }) : null; + if (d && d.hostname === (hostname ?? "") && !resume) { + Object.assign(host, d.host); + more = more || d.host.hc || d.host.req.length > 0 || d.host.resp.length > 0; + } + sessionStorage.removeItem(DRAFT); + } catch { + /* no storage: nothing to bring back */ } + loading = false; + if (phase === "form") { + // The Dialog focused its heading while this said "Loading…": now the first field + // (Hostname; Send traffic to when editing), so typing right after opening works. + const f = focusField ?? (hostname ? "upstreams[0]" : "hostname"); + if (f.startsWith("health_check")) more = true; + setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0); + } + window.addEventListener("ianitor:save-draft", saveDraft); }); + const DRAFT = "ianitor-draft"; + function saveDraft() { + if (phase !== "form") return; + try { + sessionStorage.setItem(DRAFT, JSON.stringify({ hostname: hostname ?? "", host: $state.snapshot(host) })); + } catch { + /* no storage */ + } + } + onDestroy(() => { stop?.(); clearTimeout(closeTimer); + if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft); }); function fieldId(f: string): string { @@ -226,6 +255,7 @@ function onApply(a: ApplyView) { apply = a; if (a.state === "kept") { + if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null; closeTimer = setTimeout(() => onclose(), 1500); } } @@ -291,6 +321,10 @@ return `Removing ${h}`; case "share_links": return `Turning on share links for ${h}`; + case "undo": + return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`; + case "restore": + return apply.summary.replace(/^Restored /, "Restoring "); default: return `Changing ${h}`; } @@ -321,7 +355,7 @@ {#if apply.state === "kept"} {#snippet title()}kept {apply?.hosts[0] ?? name} {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} + {(apply.reason?.message ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if} {:else if apply.state === "reverted" || apply.state === "failed"} {@const parts = firstSentence(apply.reason?.message ?? "")} @@ -337,7 +371,12 @@ {#if apply.reason?.detail}
    {/if}

    Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.

    {:else if apply.state === "needs_attention"} - {#snippet title()}Ianitor could not undo a failed change.{/snippet}{apply.reason?.message} + {#snippet title()}Ianitor could not undo a failed change.{/snippet}{apply.reason?.message} + {#if restoreProblem}

    {restoreProblem}

    {/if} + {#snippet actions()} + {#if app.overview?.undo?.target}{/if} + {/snippet} +
    {/if} {:else}
    diff --git a/apps/web/src/components/IntermediateBanner.svelte b/apps/web/src/components/IntermediateBanner.svelte index 5a5ea9b..6ea48a7 100644 --- a/apps/web/src/components/IntermediateBanner.svelte +++ b/apps/web/src/components/IntermediateBanner.svelte @@ -46,8 +46,7 @@ {@const r = i.renewal} {#snippet title()} - Sign the renewal on the offline computer. Check that it shows the same code: - {r.match_code} + Sign the renewal on the offline computer. Sign it by hand shows the files, the command and the fingerprint to check. {/snippet} The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if} {#snippet actions()} @@ -58,12 +57,9 @@ {:else if i?.banner} {#snippet title()}{i.banner?.message}{/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."} + {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 on the offline computer."} {#if problem} {problem}{/if} {#snippet actions()}{/snippet} {/if} - diff --git a/apps/web/src/components/ShareDialog.svelte b/apps/web/src/components/ShareDialog.svelte index 5a6a6df..365baa3 100644 --- a/apps/web/src/components/ShareDialog.svelte +++ b/apps/web/src/components/ShareDialog.svelte @@ -17,8 +17,9 @@ let { hostname, onclose }: { hostname: string; onclose: () => void } = $props(); - const row = $derived(app.overview?.hosts.find((h) => h.hostname === hostname)); - let on = $state(false); + // Known before the Dialog mounts, so its focus lands on Copy link (§2.9), not the title. + // svelte-ignore state_referenced_locally + let on = $state(!!app.overview?.hosts.find((h) => h.hostname === hostname)?.share_links); let link = $state(null); let minting = $state(false); let copied = $state(false); @@ -33,10 +34,9 @@ let usingPassword = $state(false); let turning = $state(null); let stopFollow: (() => void) | undefined; - let secretBox: HTMLInputElement | undefined = $state(); + let secretBox: HTMLTextAreaElement | undefined = $state(); onMount(() => { - on = !!row?.share_links; if (on) void mint(); }); onDestroy(() => stopFollow?.()); @@ -122,7 +122,7 @@ {#if link?.warning}

    {link.warning.message}

    {/if} {#if problem}{#snippet title()}{problem}{/snippet}{/if} {#if link} - (e.currentTarget as HTMLInputElement).select()} /> + {:else if minting}

    Making the link…

    {/if} diff --git a/apps/web/src/components/TopBanners.svelte b/apps/web/src/components/TopBanners.svelte index c625b6c..5594692 100644 --- a/apps/web/src/components/TopBanners.svelte +++ b/apps/web/src/components/TopBanners.svelte @@ -5,32 +5,36 @@ // 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"; + import { app, refresh, restorable as canRestore, restoreLastKept } from "../lib/app.svelte"; + import { atTime, whenInline } from "../lib/format"; const o = $derived(app.overview); let restoring = $state(false); let problem = $state(null); - const restorable = $derived( - !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target, - ); + const restorable = $derived(canRestore()); - async function restoreLastKept() { - if (!o?.undo?.target) return; + async function restore() { 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; - } + problem = await restoreLastKept(); + restoring = false; } + // §7.6: the bold line and line 2 by the pause's underlying code. + const pause = $derived.by(() => { + const code = o?.paused_reason ?? ""; + const message = o?.paused?.message ?? ""; + if (code === "apply.needs_attention") + return { bold: "Ianitor could not undo a failed change.", line2: "Visitors are served the last good settings, but the routes repository still has the change. Restore the last kept version to make them match again.", extra: "" }; + if (code === "control.files_unwritten") + return { bold: "The change is live, but Ianitor could not save the proxy settings to disk.", line2: "Changes are paused until Ianitor restarts and saves them. Restoring the last kept version also clears this.", extra: "On the server: sudo systemctl restart ianitor-control" }; + // control.paused wraps the reason: "Changes are paused: "; show the reason itself. + const own = message.replace(/^Changes are paused: /, ""); + if (/^(repo|file|site)\./.test(code)) + return { bold: own, line2: `Fix the file in the ${o?.repo?.name ?? "routes"} repository; Ianitor picks it up by itself.`, extra: "" }; + return { bold: own, line2: "", extra: "" }; + }); + async function retry() { await refresh(); } @@ -38,11 +42,13 @@ {#if o?.paused} - {#snippet title()}{restorable ? "needs attention" : "paused"} {o.paused?.message}{/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 title()}{o.paused_reason === "apply.needs_attention" ? "needs attention" : "paused"} {pause.bold}{/snippet} + {#if pause.line2}{pause.line2}{/if} + {#if restorable && o.undo?.target}

    Goes back to "{o.undo.target.summary}" from {whenInline(o.undo.target.kept_at, app.now)}. It is checked like any change.

    {/if} + {#if problem}

    {problem}

    {/if} + {#if pause.extra}
    {/if} {#snippet actions()} - {#if restorable}{/if} + {#if restorable}{/if} {/snippet} {/if} @@ -50,7 +56,7 @@ {#if app.lostContact} {#snippet title()}{typeof navigator !== "undefined" && navigator.onLine === false ? "This device is offline. Ianitor keeps running." : "Ianitor's control service is not answering."}{/snippet} - Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {when(new Date(app.lastUpdated).toISOString(), app.now)}.{/if} + Traffic keeps flowing; changes wait until it is back.{#if app.lastUpdated} Last updated {atTime(new Date(app.lastUpdated).toISOString(), app.now)}.{/if} {#snippet actions()}{/snippet} {/if} diff --git a/apps/web/src/lib/app.svelte.ts b/apps/web/src/lib/app.svelte.ts index ee5c6bd..be2af13 100644 --- a/apps/web/src/lib/app.svelte.ts +++ b/apps/web/src/lib/app.svelte.ts @@ -5,7 +5,7 @@ // Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state, // the server clock offset and toasts. No business logic: everything shown comes from control. -import { call, setClientEvents } from "./api"; +import { call, newKey, sentence, setClientEvents } from "./api"; import type { Overview } from "./types"; export interface Toast { @@ -31,6 +31,10 @@ export const app = $state({ switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null }, /** A renewal just installed (handoff §13.5). */ renewedUntil: null as null | string, + /** After a kept add or edit: the row whose More button gets focus (§7.5). */ + focusHost: null as string | null, + /** Narrower than 720 px (the phone layout, handoff §5.2). */ + phone: false, /** Panels the main screen opens (add/edit host, share, engine). */ panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" }, }); @@ -135,6 +139,12 @@ export function navigate(path: string): void { app.path = path; } +if (typeof window !== "undefined" && typeof window.matchMedia === "function") { + const mq = window.matchMedia("(max-width: 719.98px)"); + app.phone = mq.matches; + mq.addEventListener?.("change", (e) => (app.phone = e.matches)); +} + if (typeof window !== "undefined") { window.addEventListener("popstate", () => { app.path = location.pathname + location.search; @@ -148,3 +158,23 @@ export function changesBlocked(): string | null { if (o?.paused) return "Changes are paused."; return null; } + +/** "Restore the last kept version" (handoff §7.6): start it and show its progress in a panel. + * Returns the sentence to show when it could not start. */ +export async function restoreLastKept(): Promise { + const o = app.overview; + if (!o?.undo?.target) return null; + try { + const a = await call<{ apply: { id: string } }>("POST", "/restore", { change_id: o.undo.target.change_id, base_rev: o.rev }, { idem: newKey() }); + if (a.data) app.panel = { kind: "host", resume: a.data.apply.id }; + return null; + } catch (e) { + return sentence(e); + } +} + +/** Whether the pause can be cleared by restoring the last kept version. */ +export function restorable(): boolean { + const o = app.overview; + return !!o?.paused && ["apply.needs_attention", "control.files_unwritten"].includes(o.paused_reason ?? "") && !!o.undo?.target; +} diff --git a/apps/web/src/lib/applies.ts b/apps/web/src/lib/applies.ts index 59691a2..d724450 100644 --- a/apps/web/src/lib/applies.ts +++ b/apps/web/src/lib/applies.ts @@ -6,7 +6,7 @@ // runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it. import { get } from "./api"; -import { refresh } from "./app.svelte"; +import { app, refresh } from "./app.svelte"; import type { ApplyView } from "./types"; export const FINAL = ["kept", "reverted", "failed", "needs_attention"]; @@ -36,6 +36,11 @@ export function follow(id: string, onupdate: (a: ApplyView) => void, every = 100 remember(id); const tick = async () => { if (stopped) return; + if (app.signedOut) { + // No requests while signed out (the overview poll stops too); look again shortly. + timer = setTimeout(tick, every); + return; + } try { const a = await get(`/applies/${encodeURIComponent(id)}`); if (stopped) return; diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts index 61b1c70..9e7dfbb 100644 --- a/apps/web/src/lib/format.ts +++ b/apps/web/src/lib/format.ts @@ -25,6 +25,21 @@ export function when(iso: string | null | undefined, now = Date.now()): string { return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`; } +/** Inside a sentence: "today 14:02", "yesterday 21:14", "5 Nov 21:14". */ +export function whenInline(iso: string | null | undefined, now = Date.now()): string { + return when(iso, now).replace(/^(Today|Yesterday)/, (s) => s.toLowerCase()); +} + +/** After "at" / "on": "at 14:03", "yesterday at 21:14", "on 5 Nov at 21:14", "on 5 Nov 2025". */ +export function atTime(iso: string | null | undefined, now = Date.now()): string { + const w = when(iso, now); + if (!w) return ""; + if (w.startsWith("Today ")) return `at ${w.slice(6)}`; + if (w.startsWith("Yesterday ")) return `yesterday at ${w.slice(10)}`; + const m = /^(\d+ \w+) (\d\d:\d\d)$/.exec(w); + return m ? `on ${m[1]} at ${m[2]}` : `on ${w}`; +} + /** "14 November 2026 at 14:20". */ export function longDate(iso: string | null | undefined, withTime = true): string { if (!iso) return ""; @@ -57,12 +72,13 @@ export function ago(iso: string | null | undefined, now: number): string { return duration((now - Date.parse(iso)) / 1000) + " ago"; } -/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1). */ -export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }): string { +/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1); short (phone, §5.2): "5 healthy, 1 degraded, 1 down". */ +export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }, short = false): string { const parts = [`${c.healthy} healthy`]; if (c.degraded) parts.push(`${c.degraded} degraded`); if (c.down) parts.push(`${c.down} down`); if (c.unknown) parts.push(`${c.unknown} not checked`); + if (short) return parts.join(", "); return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`; } diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 3f093d9..009a2d6 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -113,6 +113,7 @@ export interface PkiRequest { device_id: string | null; name: string | null; csr_pem: string | null; + csr_sha256?: string | null; not_after: string | null; message_code: string; message: string; @@ -136,7 +137,7 @@ export interface EngineView { since: string | null; target: string | null; switchable: boolean; - fallback_ready: { built_at: string | null; current: boolean } | null; + fallback_ready: { built_at: string | null; current: boolean; compared: number; matched: number; differences: string[] } | null; last_error: Reason | null; notes: Blocked[]; } @@ -154,7 +155,7 @@ export interface Overview { engine: EngineView; last_apply: ApplyView | null; undo: UndoView; - active_apply: { id: string; state: string; summary: string; seconds_left: number | null; queued: number } | null; + active_apply: { id: string; state: string; summary: string; seconds_left: number | null; kind: string; hosts: string[]; watch_ends_at: string | null; queued: number } | null; repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null; intermediate: IntermediateView | null; site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean; auth_logout_url?: string | null } | null; @@ -234,6 +235,7 @@ export interface CertsView { root: { offline: boolean; subject: string; not_after: string; sha256: string }; devices: DeviceRow[]; device_lifetime_days: number; + device_valid_until: string | null; server_lifetime_days: number; approval: string; requests: PkiRequest[]; diff --git a/apps/web/src/views/Certificates.svelte b/apps/web/src/views/Certificates.svelte index ca3eb1e..cea22c1 100644 --- a/apps/web/src/views/Certificates.svelte +++ b/apps/web/src/views/Certificates.svelte @@ -11,7 +11,7 @@ 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 { atTime, shortDate } from "../lib/format"; import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types"; let { newDevice }: { newDevice: boolean } = $props(); @@ -120,7 +120,11 @@ } const lifetime = $derived(certs?.device_lifetime_days ?? 365); - const until = $derived(shortDate(new Date(Date.now() + lifetime * 86_400_000).toISOString())); + // The server caps it at the intermediate's end (Q7); without one it cannot issue anyway. + const until = $derived(shortDate(certs?.device_valid_until ?? new Date(Date.now() + lifetime * 86_400_000).toISOString())); + const capped = $derived( + !!certs?.device_valid_until && Date.parse(certs.device_valid_until) < Date.now() + (lifetime - 1) * 86_400_000, + ); const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => { switch (certs?.intermediate?.state) { case "ok": return ["healthy", "valid"]; @@ -187,18 +191,18 @@

    Shown in this list and inside the certificate.

    -

    Valid for {lifetime} days, until {until}. It lets this device into hosts that ask for a Domi device certificate.

    +

    {#if capped}Valid until {until}, when the Domi intermediate certificate ends (renew it to issue for a full year).{:else}Valid for {lifetime} days, until {until}.{/if} It lets this device into hosts that ask for a Domi device certificate.

    {:else if request.state === "waiting"}

    Waiting for approval

    -

    Approve it on the server, and only if it shows the same code:

    +

    Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:

    {request.match_code}

    {#if request.approve_command}

    Run on the server:

    {request.approve_command}
    {/if} -

    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.

    +

    The request stays open for 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). Nothing is issued until it is approved.

    Waiting for approval. Code {request.match_code}. {:else if issuedDevice} - {#snippet title()}{issuedDevice.name} has a certificate. Approved at {when(request?.approved_at, app.now)}.{/snippet} + {#snippet title()}{issuedDevice.name} has a certificate. Approved {atTime(request?.approved_at, app.now)}.{/snippet}
    diff --git a/apps/web/src/views/History.svelte b/apps/web/src/views/History.svelte index 70d9be3..5431572 100644 --- a/apps/web/src/views/History.svelte +++ b/apps/web/src/views/History.svelte @@ -9,7 +9,7 @@ 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 { FIELD_LABEL, fieldValue, when } from "../lib/format"; import type { ApplyView, HistoryEntry, HostSpec, RestorePreview } from "../lib/types"; let { host, pick }: { host?: string; pick?: string } = $props(); @@ -163,7 +163,6 @@ {#if editFrom} { editFrom = null; void load(); }} /> {/if} -{longDate(entry?.at)} diff --git a/apps/web/src/views/RenewByHand.svelte b/apps/web/src/views/RenewByHand.svelte index 8372488..4e88263 100644 --- a/apps/web/src/views/RenewByHand.svelte +++ b/apps/web/src/views/RenewByHand.svelte @@ -16,6 +16,20 @@ let pending = $state(false); let starting = $state(false); const base = $derived(r?.file_base ?? `domi-intermediate-${new Date().toISOString().slice(0, 10)}`); + const signCmd = $derived(r?.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`); + const checkCmd = $derived(`openssl req -in ${base}.csr -outform DER | openssl dgst -sha256`); + let copied = $state(false); + // Groups of 8, easier to compare by eye; openssl prints it without spaces. + const group = (h: string) => h.match(/.{1,8}/g)?.join(" ") ?? h; + async function copy(text: string) { + try { + await navigator.clipboard.writeText(text); + copied = true; + setTimeout(() => (copied = false), 3000); + } catch { + err = "Your browser did not allow copying. Select the command and copy it."; + } + } function save(text: string, name: string, type: string) { const url = URL.createObjectURL(new Blob([text], { type })); @@ -88,15 +102,19 @@

    Step 1

    Download the request

    This file asks the Domi root to sign a new intermediate certificate. It holds no secret.

    -

    Check that the offline computer shows the same code: {r.match_code}

    -
    +

    Step 2

    Sign it on the offline computer

    Copy both files to the offline computer that holds the Domi root, then run:

    -
    {r.approve_command ?? `openssl x509 -req -in ${base}.csr -CA domi-root.crt -CAkey domi-root.key -days 365 -sha256 -extfile ${base}.ext -out ${base}.crt`}
    -

    Before signing, check that the request is the one this page shows: openssl req -in {base}.csr -noout -subject. (On a computer with Ianitor installed, ianitor-control ca sign does the same and shows the match code.)

    +

    First check that the request is the one this server made. This prints its fingerprint:

    +
    {checkCmd}
    + {#if r.csr_sha256}

    openssl must print the same fingerprint as this page: {group(r.csr_sha256)}

    {/if} +

    Then sign it:

    +
    {signCmd}
    +
    {#if copied}Copied{/if}
    +

    On a computer with Ianitor installed, ianitor-control ca sign signs it instead and shows the match code {r.match_code}.

    Step 3

    @@ -121,5 +139,5 @@ diff --git a/apps/web/src/views/Settings.svelte b/apps/web/src/views/Settings.svelte index 43acad5..2cd2f0f 100644 --- a/apps/web/src/views/Settings.svelte +++ b/apps/web/src/views/Settings.svelte @@ -8,7 +8,7 @@ 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 { longDate, shortDate, whenInline } from "../lib/format"; import type { CreatedToken, ShareLink, TokenRow } from "../lib/types"; let { tab }: { tab: string } = $props(); @@ -164,7 +164,7 @@
    {#if tab === "general"}

    Routes repository

    -

    {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."}

    +

    {settings?.repo ? `${settings.repo.name} on Gitea · ${settings.repo.last_push_at ? "pushed " + whenInline(settings.repo.last_push_at, app.now) : "not pushed yet"}` : "No place to push to is set up."}

    Health watch after apply

    {settings?.watch_seconds ?? app.overview?.site?.watch_seconds ?? 60} seconds

    Signed in

    @@ -186,7 +186,7 @@
    {t.name} - {#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} + {#if revoked[t.id]}Revoked {whenInline(revoked[t.id], app.now)}{:else}Made {shortDate(t.created_at)} · {t.last_used_at ? `last used ${whenInline(t.last_used_at, app.now)}` : "never used"} · {t.expires_at ? `expires ${shortDate(t.expires_at)}` : "never expires"}{/if}
    {#if !revoked[t.id] && !t.revoked_at} @@ -221,7 +221,7 @@ {#each active as l (l.id)}
  • {l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""} - Made {when(l.created_at, app.now)} · expires {when(l.expires_at, app.now)}{l.has_password ? " · password" : ""}
    + Made {whenInline(l.created_at, app.now)} · expires {whenInline(l.expires_at, app.now)}{l.has_password ? " · password" : ""}
  • {/each} @@ -255,7 +255,7 @@
    {#if tokenCopied}

    Copied. Paste it into Custos now. Ianitor cannot show it again.

    {/if} -

    {made.expires_at ? `Expires on ${shortDate(made.expires_at)}.` : "Never expires."}

    +

    {made.expires_at ? `Expires on ${longDate(made.expires_at, false)}.` : "Never expires."}

    {#if askClose}

    Close without copying? The token cannot be shown again.

    diff --git a/apps/web/tests/flows.test.ts b/apps/web/tests/flows.test.ts index 55f8ecf..b666f8b 100644 --- a/apps/web/tests/flows.test.ts +++ b/apps/web/tests/flows.test.ts @@ -146,7 +146,8 @@ describe("ROADMAP §4 flows, clicks counted", () => { start(); await click(await screen.findByRole("button", { name: "Renew" })); await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true)); - await screen.findByLabelText("Match code 47 19 83"); + // The renewal is waiting: the banner says where to sign it (no code to compare with openssl). + await screen.findByRole("button", { name: "Sign it by hand" }); expect(clicks).toBe(1); }); @@ -176,6 +177,29 @@ describe("focus", () => { await user.keyboard("recipes.home.test"); expect((await screen.findByLabelText("Hostname") as HTMLInputElement).value).toBe("recipes.home.test"); }); + + it("the share dialog opens on Copy link and gives focus back to the row's More button", async () => { + start(); + const more = await screen.findByRole("button", { name: "More for wiki.home.test" }); + await click(more); + await click(await screen.findByRole("menuitem", { name: /Share link/ })); + const copy = await screen.findByRole("button", { name: "Copy link" }); + await waitFor(() => expect(document.activeElement).toBe(copy)); + // jsdom fires no cancel event on Esc for a modal dialog: close it with its button. + await click(screen.getByRole("button", { name: "Close" })); + await waitFor(() => expect(screen.queryByRole("button", { name: "Copy link" })).toBeNull()); + await waitFor(() => expect(document.activeElement).toBe(more)); + }); + + it("the engine popover closes with Esc and focus goes back to the chip", async () => { + start(); + const chip = await screen.findByRole("button", { name: /^Engine: Pingora/ }); + await click(chip); + await screen.findByRole("button", { name: "Switch to Caddy" }); + await user.keyboard("{Escape}"); + await waitFor(() => expect(screen.queryByRole("button", { name: "Switch to Caddy" })).toBeNull()); + expect(document.activeElement).toBe(screen.getByRole("button", { name: /^Engine: Pingora/ })); + }); }); describe("sign-in and contact", () => { diff --git a/apps/web/tests/mockApi.ts b/apps/web/tests/mockApi.ts index 58967a4..1c1228e 100644 --- a/apps/web/tests/mockApi.ts +++ b/apps/web/tests/mockApi.ts @@ -73,7 +73,7 @@ export function installMock(): Mock { since: now(), target: null, switchable: true, - fallback_ready: { built_at: now(), current: true }, + fallback_ready: { built_at: now(), current: true, compared: 3, matched: 3, differences: ["Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none."] }, last_error: null, notes: [], }, diff --git a/packages/ui/src/Dialog.svelte b/packages/ui/src/Dialog.svelte index 718004a..e4dad8f 100644 --- a/packages/ui/src/Dialog.svelte +++ b/packages/ui/src/Dialog.svelte @@ -39,12 +39,29 @@ if (modal && typeof el.showModal === "function") el.showModal(); else if (typeof el.show === "function") el.show(); else el.setAttribute("open", ""); - const first = el.querySelector( - "[data-autofocus], input:not([type=hidden]):not([readonly]):not([type=radio]), textarea, select", - ); + const first = + el.querySelector("[data-autofocus]") ?? + el.querySelector("input:not([type=hidden]):not([readonly]):not([type=radio]), textarea:not([readonly]), select"); (first ?? el.querySelector(".ia-dialog-title"))?.focus(); } + // A dialog opened with show() (the popover) gets no cancel event: Esc and a click outside + // close it here, like the modal ones. + const key = (e: KeyboardEvent) => { + if (!modal && e.key === "Escape" && escape) { + e.preventDefault(); + onclose(); + } + }; + const down = (e: PointerEvent) => { + if (!modal && escape && el && e.target instanceof Node && !el.contains(e.target)) onclose(); + }; + document.addEventListener("keydown", key); + // On the next turn, so the click that opened the popover does not close it. + const t = setTimeout(() => document.addEventListener("pointerdown", down), 0); return () => { + clearTimeout(t); + document.removeEventListener("keydown", key); + document.removeEventListener("pointerdown", down); if (opener instanceof HTMLElement && document.contains(opener)) opener.focus(); }; }); diff --git a/packages/ui/src/components.css b/packages/ui/src/components.css index 1561a9e..23bd0d7 100644 --- a/packages/ui/src/components.css +++ b/packages/ui/src/components.css @@ -12,6 +12,15 @@ @import "@fontsource/manrope/latin-400.css"; @import "@fontsource/manrope/latin-600.css"; @import "@fontsource/manrope/latin-700.css"; +/* latin-ext: Czech names and places (č, ř, ů) in host names, device names and messages. */ +@import "@fontsource/cinzel/latin-ext-500.css"; +@import "@fontsource/cormorant-garamond/latin-ext-500.css"; +@import "@fontsource/cormorant-garamond/latin-ext-600.css"; +@import "@fontsource/manrope/latin-ext-400.css"; +@import "@fontsource/manrope/latin-ext-600.css"; +@import "@fontsource/manrope/latin-ext-700.css"; + +html, body { margin: 0; } .ia .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; @@ -98,7 +107,10 @@ .ia .ia-engine small { color: var(--muted); font-weight: 400; font-size: 0.86rem; } /* ── Lists and rows (§2.5) ──────────────────────────────────────────────── */ -.ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); overflow: hidden; } +.ia .ia-list { border: 1px solid var(--hairline); border-radius: var(--radius-lg); } +/* No overflow clipping on the list: a row's menu must reach past it. The end rows carry the corners. */ +.ia .ia-list > :first-child { border-top-left-radius: calc(var(--radius-lg) - 1px); border-top-right-radius: calc(var(--radius-lg) - 1px); } +.ia .ia-list > :last-child { border-bottom-left-radius: calc(var(--radius-lg) - 1px); border-bottom-right-radius: calc(var(--radius-lg) - 1px); } .ia .ia-row { display: grid; grid-template-columns: 128px minmax(0, 1.4fr) minmax(0, 1.6fr) 44px; gap: 16px; padding: 12px 10px 12px 18px; align-items: start; border-top: 1px solid var(--hairline); } .ia .ia-row:first-child { border-top: 0; } .ia .ia-row.head { background: var(--colonnade); padding-top: 10px; padding-bottom: 10px; align-items: center; } @@ -121,6 +133,7 @@ background: none; color: var(--text-2); font-weight: 600; font-size: 0.92rem; text-align: left; cursor: pointer; } .ia .ia-menu [role="menuitem"]:hover, .ia .ia-menu [role="menuitem"]:focus { background: var(--surface-2); color: var(--text); outline: none; } +.ia .ia-menu [role="menuitem"]:focus-visible { outline: var(--focus-ring); outline-offset: -2px; } .ia .ia-menu [role="menuitem"].danger { color: var(--danger); } .ia .ia-menu [role="menuitem"][aria-disabled="true"] { color: var(--disabled); cursor: not-allowed; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; } .ia .ia-menu .reason { flex-basis: 100%; padding-left: 28px; font-weight: 400; font-size: var(--fs-sub); color: var(--muted); } @@ -185,7 +198,7 @@ @media (max-width: 719.98px) { .ia .ia-toasts { right: 16px; left: 16px; bottom: calc(80px + env(safe-area-inset-bottom)); } } .ia .ia-progress { height: 6px; border-radius: 3px; background: var(--surface-2); overflow: hidden; } .ia .ia-progress > span { display: block; height: 100%; background: var(--accent); transition: width var(--dur-tick) linear; } -.ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; color: var(--text); font: inherit; } +.ia .ia-secret { display: block; width: 100%; background: var(--surface); border: 1px solid var(--control-edge); border-radius: var(--radius-sm); box-shadow: var(--carved); padding: 12px 14px; font: inherit; font-weight: 600; letter-spacing: 0.02em; word-break: break-all; overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text); resize: none; } .ia .ia-details pre { background: var(--surface); border-radius: var(--radius-sm); color: var(--muted); font-size: var(--fs-sub); white-space: pre-wrap; padding: 10px 12px; margin: 6px 0; } .ia .ia-frame { border: 1px solid var(--hairline); border-radius: var(--radius-lg); padding: 32px; text-align: center; } .ia .ia-card { background: var(--surface); border: 1px solid var(--hairline); border-radius: var(--radius); padding: 12px 14px; } diff --git a/packages/ui/src/icons.ts b/packages/ui/src/icons.ts index 7ca9b9d..d5d99de 100644 --- a/packages/ui/src/icons.ts +++ b/packages/ui/src/icons.ts @@ -17,6 +17,7 @@ export const ICONS = { building: "M4 21V5l8-3 8 3v16M9 21v-5h6v5M8 8h2M14 8h2M8 12h2M14 12h2", swap: "M7 7h13l-4-4M17 17H4l4 4", copy: "M9 9h11v11H9zM5 15H4V4h11v1", + download: "M12 4v11M7 10l5 5 5-5M5 20h14", chevron: "M6 9l6 6 6-6", dots: "M5 12h.01M12 12h.01M19 12h.01", close: "M6 6l12 12M18 6 6 18",