diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..d0f2f85 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,17 @@ + + + + + + + + + Hosts — Ianitor Domi + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json index 591d4d1..77afe14 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,10 +1,29 @@ { "name": "web", - "version": "0.0.0", + "version": "0.1.0", "private": true, "license": "MPL-2.0", - "description": "Ianitor Domi web UI (Svelte 5). Placeholder until phase 3.", + "description": "Ianitor Domi web UI (Svelte 5, runes, TypeScript strict). A pure client of the control API.", + "type": "module", "scripts": { - "dev": "node -e \"console.log('web: placeholder, the UI arrives in phase 3; nothing is listening')\"" + "dev": "vite", + "build": "vite build", + "check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings", + "test": "vitest run" + }, + "dependencies": { + "@ianitor/ui": "workspace:*" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.0.3", + "@testing-library/svelte": "^5.2.6", + "@testing-library/user-event": "^14.6.1", + "@tsconfig/svelte": "^5.0.4", + "jsdom": "^26.0.0", + "svelte": "^5.20.0", + "svelte-check": "^4.1.4", + "typescript": "^5.7.3", + "vite": "^6.1.0", + "vitest": "^3.0.5" } } diff --git a/apps/web/src/App.svelte b/apps/web/src/App.svelte new file mode 100644 index 0000000..5507c99 --- /dev/null +++ b/apps/web/src/App.svelte @@ -0,0 +1,160 @@ + + + +{#if route.view === "signed-in"} + +{:else} + +
+ +
IANITOR DOMI
+
+ + {#if route.view === "hosts"} + + {:else if route.view === "history"} + {#key route.host}{/key} + {:else if route.view === "certs"} + + {:else if route.view === "renew"} + + {:else if route.view === "settings"} + + {/if} +
+ +
+ +
+ {#each app.toasts as t (t.id)}
{t.text}
{/each} +
+ + {#if app.signedOut} + {}}> +

Sign in again; this page keeps what you typed.

+ {#snippet footer()} + + + {/snippet} +
+ {/if} +{/if} + + diff --git a/apps/web/src/components/ApplyProgress.svelte b/apps/web/src/components/ApplyProgress.svelte new file mode 100644 index 0000000..0659c19 --- /dev/null +++ b/apps/web/src/components/ApplyProgress.svelte @@ -0,0 +1,80 @@ + + + +{#if apply.state === "queued"} +

+ + + 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} + +

+ {#if oncancel}
{/if} +{:else} +
    + {#each rows as r, i (i)} +
  1. + {#if r.s === "done"}{:else if r.s === "running"}{:else if r.s === "failed"}{:else}{/if} + {prefix[r.s]}{r.t[r.s as keyof typeof r.t]} +
  2. + {/each} + {#if st("watch") === "failed" && !final} +
  3. Now:Undoing the change
  4. + {/if} +
+ {#if apply.state === "watching"} + +

You can leave this screen. Other changes wait their turn; only one apply runs at a time.

+ {/if} +{/if} + + diff --git a/apps/web/src/components/ChangeBar.svelte b/apps/web/src/components/ChangeBar.svelte new file mode 100644 index 0000000..50b7352 --- /dev/null +++ b/apps/web/src/components/ChangeBar.svelte @@ -0,0 +1,140 @@ + + + +{#if last && (last.state === "reverted" || last.state === "failed") && !app.dismissed.includes(dismissKey)} + {@const parts = firstSentence(last.reason?.message ?? "")} + (app.dismissed = [...app.dismissed, dismissKey])}> + {#snippet title()}{last.state === "failed" ? "not applied" : "reverted"} {parts[0]}{/snippet} + {#if parts[1]}Reason: {parts[1]}{/if} + {#snippet actions()} + {#if last.attempted_host}{/if} + {/snippet} + +{/if} + +{#if last || active} +
+ {#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`}
+ {#if active.state === "watching" && watchLeft != null} + {@const total = o?.site?.watch_seconds ?? 60} + + {/if} +
+ {#if active.state === "queued"}{:else}{/if} + {:else if last} +
+ {#if last.state === "kept"} +
kept {last.summary}
+
{pushFailed ? "Kept, but not yet saved to Gitea. Ianitor tries again by itself." : keptLine}
+ {:else if undo?.target} +
Undo: {undo.target.summary}
+ {/if} + {#if undo?.effect && (last.state !== "kept" || undo?.target?.change_id !== last.change_id)}
{undo.effect}
{/if} + {#if moved}
{moved}
{/if} + {#if undoReason}
{undoReason}
{/if} + {#if !undo?.target}
Nothing to undo yet.
{/if} +
+ {#if pushFailed}{/if} + {#if undo?.target} + + {/if} + {/if} +
+{/if} + + diff --git a/apps/web/src/components/EnginePopover.svelte b/apps/web/src/components/EnginePopover.svelte new file mode 100644 index 0000000..cd7f368 --- /dev/null +++ b/apps/web/src/components/EnginePopover.svelte @@ -0,0 +1,107 @@ + + + + +

Engine

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

{name} is not answering. 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 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} +

+ {/if} +
+

What happens

+
    +
  • {name} stops and {other} starts. New visits reach {other} in about 2 seconds.
  • +
  • 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.
  • + {:else} +
  • Share links work again, and changes can be made again.
  • + {/if} +
  • This page may lose contact for a few seconds.
  • +
+
+ {#if switching} +

Switching to {other}

+ + {/if} + {#if problem}{#snippet title()}{problem}{/snippet}{/if} + {#if disabledReason}

{disabledReason}

{/if} + {#snippet footer()} + + + {/snippet} +
+ + diff --git a/apps/web/src/components/HostList.svelte b/apps/web/src/components/HostList.svelte new file mode 100644 index 0000000..a51cd60 --- /dev/null +++ b/apps/web/src/components/HostList.svelte @@ -0,0 +1,142 @@ + + + +
+
+ Status + Host + Sends traffic to + More +
+ {#each sorted as h (h.hostname)} + {@const [k, w] = kind(h)} + {@const s = sub(h)} +
+ + + + {h.hostname} + {#each chips(h) as c (c)}{c}{/each} + {w}{phoneDetail(h) ? ` · ${phoneDetail(h)}` : ""} + + + {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"} + Let's Encrypt could not confirm {h.hostname}. The name must point to this server, and port 80 must be open from the internet. + + {/if} + + + 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) }, + ]} /> + +
+ {/each} +
+ + diff --git a/apps/web/src/components/HostMenu.svelte b/apps/web/src/components/HostMenu.svelte new file mode 100644 index 0000000..95be1ee --- /dev/null +++ b/apps/web/src/components/HostMenu.svelte @@ -0,0 +1,86 @@ + + + + + + + +
+ + {#if open} + + {/if} +
diff --git a/apps/web/src/components/HostPanel.svelte b/apps/web/src/components/HostPanel.svelte new file mode 100644 index 0000000..23001bc --- /dev/null +++ b/apps/web/src/components/HostPanel.svelte @@ -0,0 +1,499 @@ + + + + + {#if loading} +

Loading…

+ {:else if notFound} + {#snippet title()}{notFound}{/snippet} + {#snippet actions()}{/snippet} + + {:else if phase === "progress" && apply} +
+ {#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} +
+ + {#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} + + {:else if apply.state === "reverted" || apply.state === "failed"} + {@const parts = firstSentence(apply.reason?.message ?? "")} + + {#snippet title()}{apply?.state === "failed" ? "not applied" : "reverted"} {parts[0]}{/snippet} + {#if parts[1]}Reason: {parts[1]}{/if} + {#snippet actions()} + {#if reasonOffer} + + {/if} + {/snippet} + + {#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} + {/if} + {:else} +
+ {#if summary}{/if} + {#if conflict} + + {#snippet title()}{conflict?.message}{/snippet} + {#snippet actions()}{#if hostname}{/if}{/snippet} + + {/if} + {#if topError} + {#snippet title()}{sentence(topError)}{/snippet} + {#if topError.body.detail}
{/if} + {/if} + +
+ + blur("hostname")} /> + {#if errAt("hostname") && touched["hostname"]} +

{errAt("hostname").message} + {#if errAt("hostname").params?.suggestion} + + {/if} +

+ {/if} + {#if hostname}

To use another address, add a new host and remove this one.

{/if} +
+ + {#each host.upstreams as _, i (i)} + {@const f = `upstreams[${i}]`} + {@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)} +
+ {#if i === 0}{/if} +
+ blur(f)} /> + {#if i > 0}{/if} +
+ {#if err && (touched[f] || touched["upstreams"])} +

{err.message} + {#if err.params?.suggestion}{/if} +

+ {/if} + {#if i === 0 && host.upstreams.length === 1}

Add another address later for a second server.

{/if} +
+ {/each} +
+ + +

Domi for home devices only; Let's Encrypt for a public site.

+ + + {#if !signinOk}

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.

{/if} + {#if errAt("auth")}

{errAt("auth").message}

{/if} + +
+ +
+ {#if more} +
+
+ Health check + +

Ianitor asks this address regularly and shows the result on the main screen.

+
+ {#if host.hc} +
+ + blur("health_check.path")} /> + {#if errAt("health_check.path")}

{errAt("health_check.path").message}

{/if} +

Use an address that answers without signing in, like /health.

+
+
+ +
blur("health_check.interval_secs")} /> seconds
+ {#if errAt("health_check.interval_secs")}

{errAt("health_check.interval_secs").message}

{/if} +
+ {/if} +
+ Websockets + +

Live updates for apps like Home Assistant. Leave on unless you know the app does not need them.

+
+
+ Share links + +

Lets you make links that open this host without signing in, until they expire.

+ {#if shareWarning}

Anyone can already open {name}, so a share link changes nothing.

{/if} +
+
+ Device certificates + +

Phones, computers and apps need a certificate from Certificates before they can open it.

+
+ +

On keeps a log on this server, with visitor addresses shortened.

+ {#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)} +
+ {group.title} + {#each group.rules as r, i (i)} + {@const p = `${group.list}[${i}]`} +
+ + + blur(p + ".name")} /> + {#if r.action === "set"} + {#if group.secrets} + + {/if} + {#if r.kind === "secret" && group.secrets} + + {:else} + blur(p + ".value")} /> + {/if} + {/if} + {#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}

{e.message}

{/each} + +
+ {/each} +
+ {#if group.secrets && (site?.secrets.length ?? 0) === 0}

No secrets are listed in ianitor.toml.

{/if} +
+ {/each} +
+ {/if} + + {/if} + + {#snippet footer()} + {#if phase === "form" && !loading && !notFound} + {#if underFooter}

{underFooter}

{/if} + {#if blocked}

{blocked}

{/if} + + + {:else if phase === "progress" && apply && FINAL.includes(apply.state)} + + {/if} + {/snippet} +
+ + diff --git a/apps/web/src/components/IntermediateBanner.svelte b/apps/web/src/components/IntermediateBanner.svelte new file mode 100644 index 0000000..5a5ea9b --- /dev/null +++ b/apps/web/src/components/IntermediateBanner.svelte @@ -0,0 +1,69 @@ + + + +{#if app.renewedUntil} + (app.renewedUntil = null)}> + {#snippet title()}Renewed. The Domi intermediate certificate is now valid until {longDate(app.renewedUntil, false)}.{/snippet} + +{:else if i?.renewal} + {@const r = i.renewal} + + {#snippet title()} + Sign the renewal on the offline computer. Check that it shows the same code: + {r.match_code} + {/snippet} + The request stays open for {duration(secondsLeft(r.expires_at))}. {#if problem}{problem}{/if} + {#snippet actions()} + + + {/snippet} + +{: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."} + {#if problem} {problem}{/if} + {#snippet actions()}{/snippet} + +{/if} + + diff --git a/apps/web/src/components/ShareDialog.svelte b/apps/web/src/components/ShareDialog.svelte new file mode 100644 index 0000000..5a6a6df --- /dev/null +++ b/apps/web/src/components/ShareDialog.svelte @@ -0,0 +1,163 @@ + + + + + {#if !on} + {#if turning} + + {#if turning.state === "reverted" || turning.state === "failed"} + {#snippet title()}Share links were not turned on. {turning?.reason?.message}{/snippet} + {/if} + {:else} +

Share links are off for {hostname}.

+

Turning them on is a change to the host, checked like any other.

+ {#if problem}{/if} +
+ {/if} + {:else} +

Anyone with this link can open the site without signing in, until it expires.

+ {#if underCaddy} + {#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} + {/if} + {#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} + {#if copied} +

Copied

+

Expires on {longDate(link?.expires_at)}. To stop it sooner: Settings, Share links, Stop this link.

+ {:else} + + {/if} + {#if refused}{/if} + {#if copiedBefore && !copied}

The link you copied before is stopped. Copy this one.

{/if} + + mint()} + options={[{ value: "1", label: "1 day" }, { value: "7", label: "7 days" }, { value: "30", label: "30 days" }]} /> +
+ + mint()} onkeydown={(e) => { if (e.key === "Enter") { e.preventDefault(); void mint(); } }} + aria-invalid={fieldErr?.field === "path_prefix" ? "true" : undefined} /> + {#if fieldErr?.field === "path_prefix"}

{fieldErr.message}

{/if} +

/ shares the whole site. Try /share/summer-2026 for one album.

+
+ {#if usingPassword} +

This link asks for the password.

+
+ {:else if showPassword} +
+ + + {#if fieldErr?.field === "password"}

{fieldErr.message}

{/if} +

At least 8 characters. Send it to them separately.

+
+
+ {:else} +
+ {/if} + {/if} +
diff --git a/apps/web/src/components/TopBanners.svelte b/apps/web/src/components/TopBanners.svelte new file mode 100644 index 0000000..c625b6c --- /dev/null +++ b/apps/web/src/components/TopBanners.svelte @@ -0,0 +1,73 @@ + + + +{#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 actions()} + {#if restorable}{/if} + {/snippet} + +{/if} + +{#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} + {#snippet actions()}{/snippet} + +{/if} + +{#if o?.health_error} + {#snippet title()}{o.health_error?.message}{/snippet} +{/if} + +{#if app.switchResult} + {@const r = app.switchResult} + (app.switchResult = null)}> + {#snippet title()}{r.title}{/snippet} + {r.text} + {#if r.detail}
{/if} + +{/if} + +{#if o?.engine.running === "caddy" && (o.hosts.some((h) => h.share_links) ?? false)} + {#snippet title()}Caddy is serving (the fallback), so share links do not work until you switch back.{/snippet} +{/if} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts new file mode 100644 index 0000000..5eedc8f --- /dev/null +++ b/apps/web/src/lib/api.ts @@ -0,0 +1,184 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The one typed API client (handoff §0, §10, §11). It owns the base path, the UI header (CSRF), +// redirect: "manual" (sign-out detection), Idempotency-Keys, the error envelope, the server +// clock offset, rate-limit and in-progress retries, and lost-contact detection. It decides +// nothing about the data. + +import type { ErrorBody, ErrorEnvelope } from "./types"; + +export const BASE = "/api/v1"; + +/** A refusal from control, with its envelope. */ +export class ApiError extends Error { + constructor( + public status: number, + public body: ErrorBody, + public errors: ErrorBody[], + public requestId: string, + ) { + super(body.message); + } + get code(): string { + return this.body.code; + } +} + +/** Authelia's portal redirect, or a 401 without Ianitor's envelope. */ +export class SignedOut extends Error {} + +/** No answer (network, or a proxy error without an envelope). */ +export class LostContact extends Error {} + +type Listener = () => void; + +export interface ClientEvents { + onSignedOut?: Listener; + onContact?: (ok: boolean) => void; + onServerTime?: (offsetMs: number) => void; +} + +let events: ClientEvents = {}; +export function setClientEvents(e: ClientEvents): void { + events = e; +} + +/** A key for one click; reused by every retry of that click (§11.3). */ +export function newKey(): string { + if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID(); + return Math.random().toString(36).slice(2) + Date.now().toString(36); +} + +export interface CallOptions { + idem?: string; + etag?: string; + /** Do not count a failure as lost contact (engine switch, §9.2). */ + quiet?: boolean; + keepalive?: boolean; +} + +export interface Answer { + status: number; + data: T | null; + etag: string | null; +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +function envelope(v: unknown): v is ErrorEnvelope { + return typeof v === "object" && v !== null && "error" in v && typeof (v as ErrorEnvelope).error === "object"; +} + +export async function call( + method: string, + path: string, + body?: unknown, + opts: CallOptions = {}, +): Promise> { + let rateRetried = false; + for (let attempt = 0; attempt < 12; attempt++) { + const headers: Record = { "X-Ianitor-UI": "1", Accept: "application/json" }; + if (body !== undefined) headers["Content-Type"] = "application/json"; + if (opts.idem) headers["Idempotency-Key"] = opts.idem; + if (opts.etag) headers["If-None-Match"] = opts.etag; + let res: Response; + try { + res = await fetch(BASE + path, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + redirect: "manual", + credentials: "same-origin", + keepalive: opts.keepalive, + }); + } catch { + if (!opts.quiet) events.onContact?.(false); + throw new LostContact("no answer"); + } + if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400 && res.status !== 304)) { + events.onSignedOut?.(); + throw new SignedOut("signed out"); + } + if (res.status === 304) { + events.onContact?.(true); + return { status: 304, data: null, etag: opts.etag ?? null }; + } + let json: unknown = null; + const text = await res.text(); + try { + json = text ? JSON.parse(text) : null; + } catch { + json = null; + } + if (json && typeof json === "object" && "server_time" in json) { + const t = Date.parse(String((json as { server_time: string }).server_time)); + if (!Number.isNaN(t)) events.onServerTime?.(t - Date.now()); + } + if (!envelope(json)) { + if (res.status === 401) { + events.onSignedOut?.(); + throw new SignedOut("signed out"); + } + if (res.status >= 502 && res.status <= 504) { + if (!opts.quiet) events.onContact?.(false); + throw new LostContact(`proxy answered ${res.status}`); + } + events.onContact?.(true); + return { status: res.status, data: json as T, etag: res.headers.get("ETag") }; + } + events.onContact?.(true); + const env = json; + if (env.error.code === "request.in_progress") { + await sleep(1000); + continue; + } + if (env.error.code === "rate.limited" && !rateRetried) { + rateRetried = true; + await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000); + continue; + } + if (res.status === 401 && env.error.code.startsWith("token.")) { + // The UI holds no token: a token refusal means the sign-in did not reach control. + events.onSignedOut?.(); + throw new SignedOut(env.error.message); + } + throw new ApiError(res.status, env.error, env.errors ?? [], env.request_id ?? ""); + } + throw new ApiError( + 409, + { + code: "request.in_progress", + message: "The first request with this Idempotency-Key is still being handled. Try again in a moment.", + field: null, + params: {}, + retry_after_s: 1, + detail: null, + }, + [], + "", + ); +} + +export const get = (path: string, opts?: CallOptions) => call("GET", path, undefined, opts).then((a) => a.data as T); +export const post = (path: string, body: unknown = {}, opts?: CallOptions) => + call("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T); +export const put = (path: string, body: unknown, opts?: CallOptions) => + call("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T); +export const patch = (path: string, body: unknown, opts?: CallOptions) => + call("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T); +export const del = (path: string, opts?: CallOptions) => call("DELETE", path, undefined, opts).then(() => undefined); + +/** A UI sentence for request.* codes (handoff §12.4): bugs or a stale page, not user mistakes. */ +export function sentence(e: unknown): string { + if (e instanceof ApiError) { + if (e.code.startsWith("request.") && e.code !== "request.in_progress") { + return "Ianitor refused this request from the page. Reload the page and try again."; + } + return e.body.message; + } + if (e instanceof LostContact) return "Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back."; + if (e instanceof SignedOut) return "Your sign-in has ended. Sign in again; this page keeps what you typed."; + return "Something went wrong."; +} diff --git a/apps/web/src/lib/app.svelte.ts b/apps/web/src/lib/app.svelte.ts new file mode 100644 index 0000000..ee5c6bd --- /dev/null +++ b/apps/web/src/lib/app.svelte.ts @@ -0,0 +1,150 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Shared UI state: the overview (polled, handoff §3), the route, contact and sign-in state, +// the server clock offset and toasts. No business logic: everything shown comes from control. + +import { call, setClientEvents } from "./api"; +import type { Overview } from "./types"; + +export interface Toast { + id: number; + text: string; +} + +export const app = $state({ + overview: null as Overview | null, + etag: null as string | null, + loadError: false, + lostContact: false, + lostSince: 0, + lastUpdated: 0, + signedOut: false, + offset: 0, + now: Date.now(), + path: typeof location === "undefined" ? "/" : location.pathname + location.search, + toasts: [] as Toast[], + /** Dismissed banner keys (reverted outcome, renewed, switched). */ + dismissed: [] as string[], + /** The outcome of the last engine switch, until dismissed (handoff §9.2). */ + switchResult: null as null | { ok: boolean; title: string; text: string; detail?: string | null }, + /** A renewal just installed (handoff §13.5). */ + renewedUntil: null as null | string, + /** Panels the main screen opens (add/edit host, share, engine). */ + panel: null as null | { kind: "host"; hostname?: string; resume?: string } | { kind: "share"; hostname: string } | { kind: "engine" }, +}); + +let failures = 0; +let firstFailure = 0; + +setClientEvents({ + onSignedOut: () => { + app.signedOut = true; + }, + onContact: (ok) => { + if (ok) { + failures = 0; + app.lostContact = false; + return; + } + if (failures === 0) firstFailure = Date.now(); + failures++; + // Retry quietly for 10 s (a reload takes about 2 s), then say so (§11.1). + if (Date.now() - firstFailure >= 10_000) { + if (!app.lostContact) app.lostSince = Date.now(); + app.lostContact = true; + } + }, + onServerTime: (o) => { + app.offset = o; + }, +}); + +/** Server time now, in ms (all countdowns use it, §7.2). */ +export function serverNow(): number { + return app.now + app.offset; +} + +/** Seconds left until an ISO time, on the server's clock. */ +export function secondsLeft(iso: string | null | undefined): number { + if (!iso) return 0; + return Math.max(0, Math.ceil((Date.parse(iso) - serverNow()) / 1000)); +} + +export async function refresh(): Promise { + if (app.signedOut) return; + try { + const a = await call("GET", "/overview", undefined, { etag: app.etag ?? undefined }); + if (a.status === 200 && a.data) { + app.overview = a.data; + app.etag = a.etag; + } + app.loadError = false; + app.lastUpdated = Date.now(); + } catch { + if (!app.overview) app.loadError = true; + } +} + +let timer: ReturnType | undefined; +let hiddenSince = 0; + +/** Poll every 5 s while visible, 30 s when hidden, stop after 15 min hidden (Q9). */ +export function startPolling(): () => void { + let stopped = false; + const tick = async () => { + if (stopped) return; + const hidden = typeof document !== "undefined" && document.visibilityState === "hidden"; + if (hidden && !hiddenSince) hiddenSince = Date.now(); + if (!hidden) hiddenSince = 0; + if (!(hidden && Date.now() - hiddenSince > 15 * 60_000)) await refresh(); + const every = app.lostContact ? 5000 : hidden ? 30_000 : 5000; + timer = setTimeout(tick, every); + }; + const vis = () => { + if (document.visibilityState === "visible" && hiddenSince) { + hiddenSince = 0; + clearTimeout(timer); + void tick(); + } + }; + document.addEventListener("visibilitychange", vis); + const clock = setInterval(() => (app.now = Date.now()), 1000); + void tick(); + return () => { + stopped = true; + clearTimeout(timer); + clearInterval(clock); + document.removeEventListener("visibilitychange", vis); + }; +} + +let toastId = 0; +export function toast(text: string): void { + const id = ++toastId; + app.toasts = [...app.toasts.slice(-2), { id, text }]; + setTimeout(() => { + app.toasts = app.toasts.filter((t) => t.id !== id); + }, 6000); +} + +export function navigate(path: string): void { + if (path === app.path) return; + history.pushState({}, "", path); + app.path = path; +} + +if (typeof window !== "undefined") { + window.addEventListener("popstate", () => { + app.path = location.pathname + location.search; + }); +} + +/** Is a change allowed now? (Paused, or no contact.) */ +export function changesBlocked(): string | null { + const o = app.overview; + if (app.lostContact) return "Ianitor's control service is not answering."; + if (o?.paused) return "Changes are paused."; + return null; +} diff --git a/apps/web/src/lib/applies.ts b/apps/web/src/lib/applies.ts new file mode 100644 index 0000000..59691a2 --- /dev/null +++ b/apps/web/src/lib/applies.ts @@ -0,0 +1,58 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Following an apply (handoff §2.2 of ui-api, §3 here): GET /applies/{id} every second while it +// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it. + +import { get } from "./api"; +import { refresh } from "./app.svelte"; +import type { ApplyView } from "./types"; + +export const FINAL = ["kept", "reverted", "failed", "needs_attention"]; +const KEY = "ianitor.activeApply"; + +export function remember(id: string | null): void { + try { + if (id) sessionStorage.setItem(KEY, id); + else sessionStorage.removeItem(KEY); + } catch { + /* storage may be off; the bar still shows the running apply */ + } +} + +export function remembered(): string | null { + try { + return sessionStorage.getItem(KEY); + } catch { + return null; + } +} + +/** Poll until the apply ends. Returns a stop function. */ +export function follow(id: string, onupdate: (a: ApplyView) => void, every = 1000): () => void { + let stopped = false; + let timer: ReturnType | undefined; + remember(id); + const tick = async () => { + if (stopped) return; + try { + const a = await get(`/applies/${encodeURIComponent(id)}`); + if (stopped) return; + onupdate(a); + if (FINAL.includes(a.state)) { + remember(null); + void refresh(); + return; + } + } catch { + /* lost contact or a reload in progress: keep trying (the banner says so after 10 s) */ + } + timer = setTimeout(tick, every); + }; + void tick(); + return () => { + stopped = true; + clearTimeout(timer); + }; +} diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts new file mode 100644 index 0000000..61b1c70 --- /dev/null +++ b/apps/web/src/lib/format.ts @@ -0,0 +1,99 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Formatting only (handoff §3): times in the browser's zone, 24-hour clock, counts sentences. + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const LONG = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +const two = (n: number) => String(n).padStart(2, "0"); + +/** "Today 14:02", "Yesterday 21:14", "5 Nov 21:14", "5 Nov 2025". */ +export function when(iso: string | null | undefined, now = Date.now()): string { + if (!iso) return ""; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ""; + const n = new Date(now); + const hm = `${two(d.getHours())}:${two(d.getMinutes())}`; + const sameDay = (a: Date, b: Date) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); + if (sameDay(d, n)) return `Today ${hm}`; + const y = new Date(n); + y.setDate(n.getDate() - 1); + if (sameDay(d, y)) return `Yesterday ${hm}`; + if (d.getFullYear() !== n.getFullYear()) return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`; + return `${d.getDate()} ${MONTHS[d.getMonth()]} ${hm}`; +} + +/** "14 November 2026 at 14:20". */ +export function longDate(iso: string | null | undefined, withTime = true): string { + if (!iso) return ""; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ""; + const s = `${d.getDate()} ${LONG[d.getMonth()]} ${d.getFullYear()}`; + return withTime ? `${s} at ${two(d.getHours())}:${two(d.getMinutes())}` : s; +} + +/** "2 Mar 2027". */ +export function shortDate(iso: string | null | undefined): string { + if (!iso) return ""; + const d = new Date(iso); + return `${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`; +} + +/** "8 s", "6 minutes", "2 hours", "3 days". */ +export function duration(secs: number): string { + if (secs < 60) return `${Math.max(0, Math.round(secs))} s`; + const m = Math.round(secs / 60); + if (m < 60) return m === 1 ? "1 minute" : `${m} minutes`; + const h = Math.round(secs / 3600); + if (h < 48) return h === 1 ? "1 hour" : `${h} hours`; + const days = Math.round(secs / 86400); + return `${days} days`; +} + +export function ago(iso: string | null | undefined, now: number): string { + if (!iso) return ""; + return duration((now - Date.parse(iso)) / 1000) + " ago"; +} + +/** "7 hosts · 5 healthy, 1 degraded, 1 down" (handoff §5.1). */ +export function countsSentence(c: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }): string { + const parts = [`${c.healthy} healthy`]; + if (c.degraded) parts.push(`${c.degraded} degraded`); + if (c.down) parts.push(`${c.down} down`); + if (c.unknown) parts.push(`${c.unknown} not checked`); + return `${c.hosts} ${c.hosts === 1 ? "host" : "hosts"} · ${parts.join(", ")}`; +} + +/** Split a server message on its first sentence (handoff §7.5). */ +export function firstSentence(m: string): [string, string] { + const i = m.indexOf(". "); + return i < 0 ? [m, ""] : [m.slice(0, i + 1), m.slice(i + 2)]; +} + +/** Field labels in sentences (handoff §6.5). */ +export const FIELD_LABEL: Record = { + hostname: "address", + upstreams: "sends traffic to", + tls: "certificate", + auth: "who can open it", + "health_check.path": "health check address", + "health_check.interval_secs": "checks every", + share_links: "share links", + device_certs: "device certificates", + access_log: "visit log", + websockets: "websockets", + headers: "header rules", +}; + +export function fieldValue(field: string, v: string): string { + if (v === "") return "none"; + if (field === "tls") return v === "domi" ? "Domi certificate" : "Let's Encrypt"; + if (field === "auth") return v === "forward-auth" ? "sign in first" : "anyone"; + if (field === "access_log") return v === "truncated" ? "on" : "off"; + if (v === "true") return "on"; + if (v === "false") return "off"; + if (field === "health_check.interval_secs") return `${v} s`; + return v; +} diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts new file mode 100644 index 0000000..407bd31 --- /dev/null +++ b/apps/web/src/lib/types.ts @@ -0,0 +1,247 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The shapes the UI reads from control (docs/api.md, docs/ui-api.md, GET /api/v1/openapi.json). +// Only the fields the UI uses are typed. + +export interface ErrorBody { + code: string; + message: string; + field: string | null; + params: Record; + retry_after_s: number | null; + detail: string | null; +} + +export interface ErrorEnvelope { + error: ErrorBody; + errors: ErrorBody[]; + request_id: string; +} + +export interface Blocked { + code: string; + message: string; +} + +export interface Reason { + code: string; + message: string; + hostname?: string | null; + upstream?: string | null; + field?: string | null; + detail?: string | null; + params?: Record; +} + +export interface Step { + key: "validate" | "compile" | "write" | "reload" | "watch" | "push"; + state: "pending" | "running" | "done" | "failed" | "skipped"; +} + +export interface ApplyView { + id: string; + change_id: string; + kind: "add" | "edit" | "remove" | "undo" | "restore" | "share_links"; + summary: string; + hosts: string[]; + state: "queued" | "validating" | "applying" | "watching" | "kept" | "reverted" | "failed" | "needs_attention"; + created_at: string; + finished_at: string | null; + steps: Step[]; + queue: { position: number; waiting_for: { apply_id: string; summary: string; seconds_left: number | null } | null } | null; + watch: { ends_at: string; seconds_left: number; hosts: { hostname: string; passed: number; failed: number; total: number }[] } | null; + reason: Reason | null; + errors: ErrorBody[]; + commit_short: string | null; + push: { state: "pushed" | "pending" | "failed"; at: string | null; error_code: string | null; next_try_at: string | null } | null; + attempted_host?: HostSpec | null; +} + +export interface HeaderRule { + action: "set" | "remove"; + name: string; + value?: string; + secret?: string; +} + +export interface HostSpec { + hostname: string; + upstreams: string[]; + tls: "domi" | "letsencrypt"; + auth: "none" | "forward-auth"; + websockets: boolean; + share_links: boolean; + device_certs?: boolean; + access_log: "off" | "truncated"; + health_check?: { path: string; interval_secs: number } | null; + request_headers?: HeaderRule[]; + response_headers?: HeaderRule[]; +} + +export interface HealthView { + state: "healthy" | "degraded" | "down" | "unknown" | "pending"; + last_check_at: string | null; + latency_ms: number | null; + since: string | null; + failure: { kind: string; upstream: string | null; count: number; of: number } | null; + upstreams: { url: string; state: string; last_check_at: string | null; latency_ms: number | null; failure_kind: string | null }[]; +} + +export interface HostRow { + hostname: string; + upstreams: string[]; + tls: string; + auth: string; + websockets: boolean; + share_links: boolean; + device_certs: boolean; + added_at: string | null; + health: HealthView; + certificate: { state: "ok" | "pending" | "failed"; not_after: string | null; error_code: string | null }; +} + +export interface PkiRequest { + request_id: string; + kind: "device" | "intermediate"; + state: "waiting" | "approved" | "denied" | "expired" | "cancelled" | "failed"; + match_code: string; + created_at: string; + expires_at: string; + approved_at: string | null; + device_id: string | null; + name: string | null; + csr_pem: string | null; + not_after: string | null; + message_code: string; + message: string; + approve_command: string | null; + problem: string | null; +} + +export interface IntermediateView { + state: "ok" | "due" | "urgent" | "expired" | "missing"; + subject: string | null; + not_after: string | null; + days_left: number | null; + renewal: PkiRequest | null; + banner: Blocked | null; +} + +export interface EngineView { + running: "pingora" | "caddy"; + state: "running" | "switching" | "stopped"; + since: string | null; + target: string | null; + switchable: boolean; + fallback_ready: { built_at: string | null; current: boolean } | null; + last_error: Reason | null; + notes: Blocked[]; +} + +export interface UndoView { + available: boolean; + target: { change_id: string; summary: string; kept_at: string | null; commit_short: string | null } | null; + effect: string | null; + blocked: Blocked | null; +} + +export interface Overview { + counts: { hosts: number; healthy: number; degraded: number; down: number; unknown: number }; + hosts: HostRow[]; + engine: EngineView; + last_apply: ApplyView | null; + undo: UndoView; + active_apply: { id: string; state: string; summary: string; seconds_left: number | null; queued: number } | null; + repo: { name: string; last_push_at: string | null; unpushed: number; push_error_code: string | null } | null; + intermediate: IntermediateView | null; + site: { forward_auth_configured: boolean; acme_configured: boolean; secrets: string[]; watch_seconds: number; share_links_available: boolean } | null; + paused: Blocked | null; + paused_reason: string | null; + health_error: Blocked | null; + rev: string | null; + viewer?: { name: string; via: string } | null; + server_time: string; +} + +export interface HistoryEntry { + change_id: string; + summary: string; + kind: string; + state: string; + at: string; + commit_short: string | null; + hosts: string[]; + reason_short: string | null; +} + +export interface RestorePreview { + restorable: boolean; + same_as_current: boolean; + changes: { hostname: string; effect: "added" | "removed" | "changed"; fields: { field: string; from: string; to: string }[] }[]; + blocked: Blocked | null; +} + +export interface ShareLink { + id: string; + hostname: string; + path_prefix: string; + created_at: string; + expires_at: string; + has_password: boolean; + state: "active" | "expired" | "stopped"; +} + +export interface MintedLink { + id: string; + url: string; + expires_at: string; + path_prefix: string; + has_password: boolean; + warning: Blocked | null; +} + +export interface TokenRow { + id: string; + name: string; + created_at: string; + last_used_at: string | null; + expires_at: string | null; + revoked_at?: string | null; +} + +export interface CreatedToken { + id: string; + name: string; + token: string; + expires_at: string | null; +} + +export interface DeviceRow { + id: string; + name: string; + kind: "phone" | "computer" | "app"; + created_at: string; + not_after: string; + state: "valid" | "revoked" | "expired"; + revoked_at: string | null; +} + +export interface CertsView { + intermediate: IntermediateView | null; + root: { offline: boolean; subject: string; not_after: string; sha256: string }; + devices: DeviceRow[]; + device_lifetime_days: number; + server_lifetime_days: number; + approval: string; + requests: PkiRequest[]; +} + +export interface Bundle { + download_url: string; + one_time_password: string; + expires_at: string; + filename: string; + qr_svg: string | null; +} diff --git a/apps/web/src/main.ts b/apps/web/src/main.ts new file mode 100644 index 0000000..fcd4afc --- /dev/null +++ b/apps/web/src/main.ts @@ -0,0 +1,11 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +import "@ianitor/ui/tokens.css"; +import "@ianitor/ui/components.css"; +import { mount } from "svelte"; +import App from "./App.svelte"; + +const target = document.getElementById("app"); +if (target) mount(App, { target }); diff --git a/apps/web/src/views/Certificates.svelte b/apps/web/src/views/Certificates.svelte new file mode 100644 index 0000000..f0b7a4e --- /dev/null +++ b/apps/web/src/views/Certificates.svelte @@ -0,0 +1,245 @@ + + + +
+

Certificates

+ +
+ + +{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} + +{#if certs} +
+

Domi intermediate

+

{#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}

+

Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).

+
+ +

Devices

+ {#if certs.devices.length === 0} +

No device certificates yet

A device certificate lets a phone, computer or Domi app into hosts that ask for one.

+ {:else} +
    + {#each certs.devices as d (d.id)} +
  • + + {d.name} + until {shortDate(d.not_after)} + {#if d.state === "revoked"}{:else if d.state === "expired"}{/if} + {#if confirmRevoke === d.id} + Revoke the certificate of "{d.name}"? It can no longer get in. + + + {:else if d.state === "valid"} + install(d, d.kind === "computer" ? "p12" : "qr") }, + { label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) }, + ]} /> + {/if} +
  • + {/each} +
+ {/if} +{/if} + +{#if newDevice} + + {#if !request} +
+
+ + + {#if nameErr}

{nameErr}

{/if} +

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.

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

Waiting for approval

+

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.

+
+ 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} +
+ + +
+

The file is protected with a one-time password shown next to the QR code.

+ {:else} + {#snippet title()}{request?.message}{/snippet} + {#snippet actions()}{/snippet} + {/if} + {#snippet footer()} + {#if !request} + + + {:else if request.state !== "waiting"} + + {/if} + {/snippet} +
+{/if} + +{#if bundle} + { bundle = null; void refresh(); }}> +
+ {#if bundle.b.qr_svg} + + {/if} +
+

Password for the file

+

{bundle.b.one_time_password}

+

Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).

+
+
+

+ {#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} +

+
+{/if} + + diff --git a/apps/web/src/views/History.svelte b/apps/web/src/views/History.svelte new file mode 100644 index 0000000..70d9be3 --- /dev/null +++ b/apps/web/src/views/History.svelte @@ -0,0 +1,179 @@ + + + +

{host ? `History of ${host}` : "History"}

+{#if host}
{/if} +{#if problem}{#snippet title()}{problem}{/snippet}{/if} + +
+
+ {#if loaded && entries.length === 0} +

No changes yet

Every change you apply is listed here, newest first.

+ {/if} +
    + {#each entries as e, i (e.change_id)} + {@const [k, w] = stateOf(e)} +
  • + +
  • + {/each} +
+ {#if next}{/if} +
+ + {#if chosen && preview} +
+

Version of {when(entry?.at, app.now)}

+ {#if preview.blocked?.code === "restore.not_kept"} +

This change did not stay

+ {#if attempt?.reason}

{attempt.reason.message}

{/if} +

This change was undone at the time, so there is nothing to go back to.

+ {#if attempt?.attempted_host}
{/if} + {:else if preview.blocked?.code === "restore.same"} +

Go back to this version?

+

This version is the same as the current one. Nothing to restore.

+
+ {:else} +

Go back to this version?

+

{n === 1 ? "Restoring puts 1 host back to how it was then:" : `Restoring puts ${n} hosts back to how they were then:`}

+
    + {#each preview.changes as c (c.hostname)} + {#if c.effect === "added"}
  • {c.hostname} is added back
  • + {:else if c.effect === "removed"}
  • {c.hostname} is removed
  • + {:else} + {#each c.fields as f (f.field)} +
  • {c.hostname}: {#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}
  • + {/each} + {/if} + {/each} +
+

Applied as a new commit with the same {app.overview?.site?.watch_seconds ?? 60}-second watch. If health checks fail, it is undone.

+ {#if blocked}

{blocked}

{/if} +
+ + +
+ {/if} +
+ {/if} +
+ +{#if resume} + { resume = null; void load(); }} /> +{/if} +{#if editFrom} + { editFrom = null; void load(); }} /> +{/if} +{longDate(entry?.at)} + + diff --git a/apps/web/src/views/Hosts.svelte b/apps/web/src/views/Hosts.svelte new file mode 100644 index 0000000..36d292b --- /dev/null +++ b/apps/web/src/views/Hosts.svelte @@ -0,0 +1,141 @@ + + + +
+
+

Hosts

+ {#if o}

{countsSentence(o.counts)}

{/if} +
+
+ {#if o} + + {/if} + + {#if blocked}{blocked}{/if} +
+
+ + +{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} + + (app.panel = { kind: "host", resume: id })} onedit={editAgain} /> + +{#if !o && !app.loadError} +
Loading hosts… + {#each [0, 1, 2] as i (i)}
{/each} +
+{:else if app.loadError && !o} + {#snippet title()}This page could not load. Ianitor's control service may be restarting.{/snippet} + {#snippet actions()}{/snippet} +{:else if o && o.hosts.length === 0} +

No hosts yet

Add the first one: the name people type, and where Ianitor should send them.

+{:else if o} + 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} +
+ +{/if} + +{#if panelOpen} + {#key route.edit ?? (app.panel?.kind === "host" ? app.panel.resume : "new")} + + {/key} +{/if} +{#if app.panel?.kind === "share"} + { app.panel = null; void refresh(); }} /> +{/if} +{#if app.panel?.kind === "engine"} + (app.panel = null)} /> +{/if} + + diff --git a/apps/web/src/views/RenewByHand.svelte b/apps/web/src/views/RenewByHand.svelte new file mode 100644 index 0000000..6278c16 --- /dev/null +++ b/apps/web/src/views/RenewByHand.svelte @@ -0,0 +1,110 @@ + + + +

Sign the intermediate by hand

+

Custos cannot sign certificates yet, so the Domi root signs on the offline computer. The root key never comes to this server.

+ +{#if !r} + {#snippet title()}There is no open renewal request.{/snippet} + {#snippet actions()}{/snippet} +{:else} +
+

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 the file to the offline computer that holds the Domi root, then run:

+
ianitor-control ca sign --root <root folder> --csr domi-intermediate-{day}.csr --out domi-intermediate-{day}.crt
+

It asks for the root's passphrase and shows the code; sign only if it is the code above.

+
+
+

Step 3

+

Upload the signed certificate

+ {#if paste} +
+ + +
+ {:else} +
+ + +
+
+ {/if} + {#if err}{/if} +
+
+{/if} + + diff --git a/apps/web/src/views/Settings.svelte b/apps/web/src/views/Settings.svelte new file mode 100644 index 0000000..bda12ba --- /dev/null +++ b/apps/web/src/views/Settings.svelte @@ -0,0 +1,279 @@ + + + +

Settings

+
+ {#each TABS as t, i (t.id)} + + {/each} +
+{#if problem} (problem = null)}>{#snippet title()}{problem}{/snippet}{/if} + +
+ {#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."}

+

Health watch after apply

+

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

+

Signed in

+

{viewer ? (viewer.via === "authelia" ? `${viewer.name} through Authelia` : `API token "${viewer.name}"`) : "Through Authelia"}

+ {:else if tab === "api"} +
+

API tokens

+ + +
+

The API listens on 127.0.0.1 only. Ianitor keeps a hash of each token, never the token.

+ {#if tokens.length === 0} +

No API tokens

Scripts and other Domi apps use a token to talk to Ianitor.

+ {:else} +
    + {#each tokens as t (t.id)} +
  • +
    + {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] && !t.revoked_at} + {#if confirmRevoke === t.id} + Revoke "{t.name}"? Anything using it stops working now. + + + {:else} + + {/if} + {/if} +
  • + {/each} +
+ {/if} + {:else if tab === "share-links"} +
+

Share links

+ {#if active.length}{/if} +
+ {#if app.overview?.engine.running === "caddy"} + {#snippet title()}Caddy is serving, so these links do not work right now. They work again after switching back to Pingora.{/snippet} + {/if} + {#if confirmStopAll} +

Stop all {active.length} active links? Every link made so far stops working. New ones work as usual. +

+ {/if} + {#if links.length === 0} +

No share links

Make one from a host's menu (⋯), Share link.

+ {:else} +
    + {#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" : ""}
    + +
  • + {/each} +
+ {#if ended.length} +
Ended ({ended.length}) +
    {#each ended as l (l.id)}
  • {l.hostname}{l.path_prefix !== "/" ? l.path_prefix : ""}{l.state} {shortDate(l.expires_at)}
  • {/each}
+
+ {/if} + {/if} + {:else} +

Ianitor Domi 0.1.0

+

MPL-2.0

+

Built, tested and signed by Fabrica Domi

+

Source on Gitea

+ {/if} +
+ +{#if made} + closeToken()}> +

Copy it now and save it in Custos.

+

Ianitor cannot show it again; if it is lost, make a new one and revoke this one.

+ (e.currentTarget as HTMLInputElement).select()} /> +
+
+ + + {#if nameErr}

{nameErr}

{/if} +

Rename it now or later, so you know what uses it.

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

+ {#if askClose} +

Close without copying? The token cannot be shown again. +

+ {/if} + {#snippet footer()}{/snippet} +
+{/if} + + diff --git a/apps/web/src/views/SignedIn.svelte b/apps/web/src/views/SignedIn.svelte new file mode 100644 index 0000000..8c2c16d --- /dev/null +++ b/apps/web/src/views/SignedIn.svelte @@ -0,0 +1,33 @@ + + + +
+

IANITOR DOMI

+

You are signed in again.

+

You can close this tab and go back to Ianitor.

+
+ + diff --git a/apps/web/svelte.config.js b/apps/web/svelte.config.js new file mode 100644 index 0000000..b235e46 --- /dev/null +++ b/apps/web/svelte.config.js @@ -0,0 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; + +export default { preprocess: vitePreprocess() }; diff --git a/apps/web/tests/flows.test.ts b/apps/web/tests/flows.test.ts new file mode 100644 index 0000000..7950cba --- /dev/null +++ b/apps/web/tests/flows.test.ts @@ -0,0 +1,202 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// The smoke test of every ROADMAP §4 flow with its clicks counted (handoff §4, §15): the real +// app against a stand-in for control's API. Typing, focus and waiting are not clicks. + +import { cleanup, render, screen, waitFor, within } from "@testing-library/svelte"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import App from "../src/App.svelte"; +import { app } from "../src/lib/app.svelte"; +import { installMock, type Mock } from "./mockApi"; + +let mock: Mock; +let clicks = 0; +let user: ReturnType; + +async function click(el: Element) { + clicks++; + await user.click(el); +} + +function start(path = "/") { + history.replaceState({}, "", path); + app.path = path; + app.panel = null; + app.overview = null; + app.etag = null; + app.signedOut = false; + app.switchResult = null; + app.renewedUntil = null; + app.dismissed = []; + mock = installMock(); + clicks = 0; + user = userEvent.setup(); + render(App); +} + +const called = (method: string, path: string) => mock.calls.some((c) => c.method === method && c.path.startsWith(path)); +const T = { timeout: 5000 }; + +beforeEach(() => { + try { + sessionStorage.clear(); + } catch { + /* none */ + } +}); +afterEach(() => cleanup()); + +describe("ROADMAP §4 flows, clicks counted", () => { + it("Add host: + Host → fill → Apply = 2 clicks, auto-kept", async () => { + start(); + await click(await screen.findByRole("button", { name: "Add a host" })); + await user.type(await screen.findByLabelText("Hostname"), "recipes.home.test"); + await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080"); + await click(screen.getByRole("button", { name: "Apply" })); + // Kept: the panel closes by itself and the new host is in the list. + await waitFor(() => expect(called("GET", "/applies/ch_new")).toBe(true), T); + await waitFor(() => expect(document.querySelector("dialog.ia-panel")).toBeNull(), T); + await screen.findByRole("button", { name: "More for recipes.home.test" }, T); + expect(called("POST", "/hosts")).toBe(true); + const sent = mock.calls.find((c) => c.method === "POST" && c.path === "/hosts")?.body as { host: Record }; + // Every field is sent explicitly, with the design's defaults. + expect(sent.host).toMatchObject({ hostname: "recipes.home.test", tls: "domi", auth: "forward-auth", websockets: true }); + expect(clicks).toBe(2); + }); + + it("Undo last change = 1 click", async () => { + start(); + await click(await screen.findByRole("button", { name: /^Undo: Added recipes\.home\.test/ })); + await waitFor(() => expect(called("POST", "/undo")).toBe(true)); + const body = mock.calls.find((c) => c.path === "/undo" && c.method === "POST")?.body as Record; + expect(body.target_change_id).toBe("ch_1"); + expect(clicks).toBe(1); + }); + + it("Restore: History → pick → Restore = 3 clicks", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + const nav = screen.getAllByRole("navigation", { name: "Main" })[0]; + await click(within(nav).getByRole("link", { name: "History" })); + await click(await screen.findByRole("button", { name: /Changed wiki\.home\.test/ })); + await screen.findByText(/sends traffic to changes from/); + await click(await screen.findByRole("button", { name: "Restore this version" })); + await waitFor(() => expect(called("POST", "/restore")).toBe(true)); + expect(clicks).toBe(3); + }); + + it("Share link: ⋯ → Share link → Copy = 3 clicks (default expiry 7 days)", async () => { + start(); + await click(await screen.findByRole("button", { name: "More for wiki.home.test" })); + await click(await screen.findByRole("menuitem", { name: /Share link/ })); + const copy = await screen.findByRole("button", { name: "Copy link" }); + await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull()); + await click(copy); + await screen.findByText("Copied"); + const mint = mock.calls.find((c) => c.method === "POST" && c.path.endsWith("/share-links"))?.body as Record; + expect(mint.expires_in_s).toBe(604800); + expect(await navigator.clipboard.readText()).toContain("?share=ish1."); + expect(clicks).toBe(3); + }); + + it("Share link on a host with links off: 4 clicks (open question Q1 not decided)", async () => { + start(); + await click(await screen.findByRole("button", { name: "More for photos.home.test" })); + await click(await screen.findByRole("menuitem", { name: /Share link/ })); + await click(await screen.findByRole("button", { name: "Turn on share links" })); + const copy = await screen.findByRole("button", { name: "Copy link" }, T); + await waitFor(() => expect(copy.getAttribute("aria-disabled")).toBeNull()); + await click(copy); + await screen.findByText("Copied"); + expect(called("PATCH", "/hosts/photos.home.test")).toBe(true); + expect(clicks).toBe(4); + }); + + it("Switch engine: engine chip → Switch to Caddy = 2 clicks", async () => { + start(); + await click(await screen.findByRole("button", { name: /^Engine: Pingora/ })); + await click(await screen.findByRole("button", { name: "Switch to Caddy" })); + await waitFor(() => expect(called("POST", "/engine")).toBe(true)); + const body = mock.calls.find((c) => c.method === "POST" && c.path === "/engine")?.body as Record; + expect(body.target).toBe("caddy"); + await screen.findByText("Now serving with Caddy.", {}, T); + expect(clicks).toBe(2); + }); + + it("Device certificate: Certificates → + Device → Issue = 3 clicks; install is the accepted 4th", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + const nav = screen.getAllByRole("navigation", { name: "Main" })[0]; + await click(within(nav).getByRole("link", { name: "Certificates" })); + await click(await screen.findByRole("button", { name: "Add a device certificate" })); + await user.type(await screen.findByLabelText("Device name"), "Mark's phone"); + await click(screen.getByRole("button", { name: "Issue" })); + await screen.findByLabelText("Match code 47 19 83"); + expect(clicks).toBe(3); + // Approved on the server (the stand-in approves on the first poll). + await click(await screen.findByRole("button", { name: "Show QR code" }, T)); + await screen.findByText("ABCD-EFGH-JKLM-NPQR"); + expect(clicks).toBe(4); + }); + + it("Renew intermediate: banner Renew = 1 click", async () => { + start(); + await click(await screen.findByRole("button", { name: "Renew" })); + await waitFor(() => expect(called("POST", "/certs/intermediate/renewal")).toBe(true)); + await screen.findByLabelText("Match code 47 19 83"); + expect(clicks).toBe(1); + }); + + it("API token: ⚙ → API → New token = 3 clicks; Copy token is the accepted 4th", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + const nav = screen.getAllByRole("navigation", { name: "Main" })[0]; + await click(within(nav).getByRole("link", { name: "Settings" })); + await click(await screen.findByRole("tab", { name: "API" })); + await click(await screen.findByRole("button", { name: "New token" })); + const box = (await screen.findByLabelText("New API token")) as HTMLInputElement; + expect(box.value).toBe("ian_tk1_secretvalue"); + expect(clicks).toBe(3); + await click(screen.getByRole("button", { name: "Copy token" })); + expect(await navigator.clipboard.readText()).toBe("ian_tk1_secretvalue"); + expect(clicks).toBe(4); + // The token is never stored by the page. + expect(JSON.stringify({ ...sessionStorage })).not.toContain("ian_tk1"); + expect(JSON.stringify({ ...localStorage })).not.toContain("ian_tk1"); + }); +}); + +describe("sign-in and contact", () => { + it("a 401 without Ianitor's envelope shows the signed-out dialog", async () => { + start(); + await screen.findByRole("button", { name: "Add a host" }); + globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch; + app.etag = null; + await click(screen.getByRole("button", { name: "Add a host" })); + await user.type(await screen.findByLabelText("Hostname"), "x.home.test"); + await user.type(screen.getByLabelText("Send traffic to"), "http://10.0.0.5:8080"); + await click(screen.getByRole("button", { name: "Apply" })); + await screen.findByRole("alertdialog", { name: "Your sign-in has ended" }); + // What was typed is still there. + expect((screen.getByLabelText("Hostname") as HTMLInputElement).value).toBe("x.home.test"); + }); + + it("every request carries the UI header and no token", async () => { + const seen: Headers[] = []; + start(); + const inner = globalThis.fetch; + globalThis.fetch = (async (i: RequestInfo | URL, init?: RequestInit) => { + seen.push(new Headers(init?.headers)); + return inner(i, init); + }) as typeof fetch; + await click(await screen.findByRole("button", { name: /^Undo:/ })); + await waitFor(() => expect(seen.length).toBeGreaterThan(0)); + for (const h of seen) { + expect(h.get("X-Ianitor-UI")).toBe("1"); + expect(h.get("Authorization")).toBeNull(); + } + }); +}); diff --git a/apps/web/tests/mockApi.ts b/apps/web/tests/mockApi.ts new file mode 100644 index 0000000..58967a4 --- /dev/null +++ b/apps/web/tests/mockApi.ts @@ -0,0 +1,174 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// A stateful stand-in for control's API, shaped like the real answers (docs/api.md), so the +// smoke tests can walk every §4 flow and count its clicks. + +type Json = Record; + +export interface Mock { + calls: { method: string; path: string; body: unknown }[]; + state: { + engine: "pingora" | "caddy"; + switching: number; + intermediate: "ok" | "due"; + renewal: boolean; + requestPolls: number; + hostsAdded: string[]; + }; +} + +const now = () => new Date().toISOString(); +const later = (s: number) => new Date(Date.now() + s * 1000).toISOString(); + +function host(hostname: string, share: boolean) { + return { + hostname, + upstreams: ["http://10.0.0.2:3000"], + tls: "domi", + auth: "forward-auth", + websockets: true, + share_links: share, + device_certs: false, + added_at: null, + health: { state: "healthy", last_check_at: now(), latency_ms: 12, since: now(), failure: null, upstreams: [] }, + certificate: { state: "ok", not_after: later(86400 * 80), error_code: null }, + }; +} + +function apply(id: string, state: string, summary: string, hosts: string[]) { + return { + id, + change_id: id, + kind: "add", + summary, + hosts, + state, + created_at: now(), + finished_at: state === "kept" ? now() : null, + steps: ["validate", "compile", "write", "reload", "watch", "push"].map((key) => ({ key, state: state === "kept" ? "done" : "pending" })), + queue: null, + watch: null, + reason: state === "kept" ? { code: "apply.kept", message: `${hosts[0]} is live. Health checks passed for 60 s.` } : null, + errors: [], + commit_short: "4f1c2ab", + push: null, + attempted_host: null, + }; +} + +export function installMock(): Mock { + const m: Mock = { + calls: [], + state: { engine: "pingora", switching: 0, intermediate: "due", renewal: false, requestPolls: 0, hostsAdded: [] }, + }; + + const overview = (): Json => ({ + counts: { hosts: 2 + m.state.hostsAdded.length, healthy: 2, degraded: 0, down: 0, unknown: 0 }, + hosts: [host("wiki.home.test", true), host("photos.home.test", false), ...m.state.hostsAdded.map((h) => host(h, false))], + engine: { + running: m.state.engine, + state: m.state.switching > 0 ? "switching" : "running", + since: now(), + target: null, + switchable: true, + fallback_ready: { built_at: now(), current: true }, + last_error: null, + notes: [], + }, + last_apply: apply("ch_1", "kept", "Added recipes.home.test", ["recipes.home.test"]), + undo: { + available: true, + target: { change_id: "ch_1", summary: "Added recipes.home.test", kept_at: now(), commit_short: "4f1c2ab" }, + effect: "Removes recipes.home.test", + blocked: null, + }, + active_apply: null, + repo: { name: "ianitor-routes", last_push_at: now(), unpushed: 0, push_error_code: null }, + intermediate: + m.state.intermediate === "due" + ? { + state: "due", + subject: "Ianitor Domi Intermediate 2025-12", + not_after: later(86400 * 23), + days_left: 23, + renewal: m.state.renewal + ? { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(3600), approved_at: null, device_id: null, name: null, csr_pem: "-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n", not_after: null, message_code: "pki.renew.manual", message: "Sign this request…", approve_command: "ianitor-control ca sign …", problem: null } + : null, + banner: m.state.renewal ? null : { code: "pki.renew_due", message: "The Domi intermediate certificate expires in 23 days, on 30 November 2026." }, + } + : { state: "ok", subject: "x", not_after: later(86400 * 300), days_left: 300, renewal: null, banner: null }, + site: { forward_auth_configured: true, acme_configured: true, secrets: ["api_key"], watch_seconds: 60, share_links_available: true }, + paused: null, + paused_reason: null, + health_error: null, + rev: "rev1", + viewer: { name: "mark", via: "authelia" }, + server_time: now(), + }); + + const routes: [string, RegExp, (mm: RegExpMatchArray, body: Json) => [number, unknown]][] = [ + ["GET", /^\/overview$/, () => [200, overview()]], + ["POST", /^\/hosts\/validate/, () => [200, { message: "This host can be applied." }]], + ["POST", /^\/hosts$/, (_, b) => { + const h = (b.host as Json).hostname as string; + m.state.hostsAdded.push(h); + return [202, { apply: apply("ch_new", "queued", `Added ${h}`, [h]) }]; + }], + ["GET", /^\/applies\/ch_new$/, () => [200, apply("ch_new", "kept", `Added ${m.state.hostsAdded.at(-1)}`, [m.state.hostsAdded.at(-1) ?? ""])]], + ["GET", /^\/applies\/(.+)$/, (mm) => [200, apply(mm[1], "kept", "Done", ["x.home.test"])]], + ["POST", /^\/undo$/, () => [202, { apply: apply("ch_undo", "queued", "Undid: Added recipes.home.test", ["recipes.home.test"]) }]], + ["GET", /^\/history(\?.*)?$/, () => [200, { entries: [{ change_id: "ch_old", summary: "Changed wiki.home.test", kind: "edit", state: "kept", at: now(), commit_short: "9b20e7d", hosts: ["wiki.home.test"], reason_short: null }], next_before: null }]], + ["GET", /^\/history\/ch_old\/restore-preview$/, () => [200, { restorable: true, same_as_current: false, changes: [{ hostname: "wiki.home.test", effect: "changed", fields: [{ field: "upstreams", from: "http://10.0.0.2:3000", to: "http://10.0.0.9:3000" }] }], blocked: null }]], + ["POST", /^\/restore$/, () => [202, { apply: apply("ch_restore", "queued", "Restored the version of 5 November 2026", ["wiki.home.test"]) }]], + ["POST", /^\/hosts\/([^/]+)\/share-links$/, (mm) => [201, { id: "sl_1", url: `https://${decodeURIComponent(mm[1])}/?share=ish1.abc`, expires_at: later(7 * 86400), path_prefix: "/", has_password: false, warning: null }]], + ["PATCH", /^\/hosts\/([^/]+)$/, (mm) => [202, { apply: apply("ch_share", "queued", `Turned share links on for ${decodeURIComponent(mm[1])}`, [decodeURIComponent(mm[1])]) }]], + ["DELETE", /^\/share-links\/.+$/, () => [204, null]], + ["GET", /^\/engine$/, () => { + if (m.state.switching > 0) { + m.state.switching--; + if (m.state.switching === 0) m.state.engine = "caddy"; + } + return [200, { running: m.state.engine, state: m.state.switching > 0 ? "switching" : "running", target: null, since: now(), switchable: true, last_error: null, notes: [] }]; + }], + ["POST", /^\/engine$/, () => { + m.state.switching = 1; + return [202, { running: m.state.engine, state: "switching", target: "caddy", since: now(), switchable: true, last_error: null, notes: [] }]; + }], + ["GET", /^\/certs$/, () => [200, { intermediate: overview().intermediate, root: { offline: true, subject: "Domi PKI Root", not_after: later(86400 * 3000), sha256: "ab" }, devices: [], device_lifetime_days: 365, server_lifetime_days: 90, approval: "manual", requests: [] }]], + ["POST", /^\/certs\/devices$/, (_, b) => [202, { request_id: "pr_dev", kind: "device", state: "waiting", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: null, device_id: null, name: b.name, csr_pem: null, not_after: null, message_code: "pki.waiting.manual", message: "Approve it on the server…", approve_command: "ianitor-control pki approve 47 19 83", problem: null }]], + ["GET", /^\/pki-requests\/pr_dev$/, () => { + m.state.requestPolls++; + return [200, { request_id: "pr_dev", kind: "device", state: "approved", match_code: "47 19 83", created_at: now(), expires_at: later(600), approved_at: now(), device_id: "dv_1", name: "Mark's phone", csr_pem: null, not_after: null, message_code: "pki.issued", message: "Mark's phone has a certificate.", approve_command: null, problem: null }]; + }], + ["POST", /^\/certs\/devices\/dv_1\/bundle$/, () => [200, { download_url: "https://ui.home.test/api/v1/device-bundles/abc", one_time_password: "ABCD-EFGH-JKLM-NPQR", expires_at: later(600), filename: "domi-device.p12", qr_svg: "" }]], + ["POST", /^\/certs\/intermediate\/renewal$/, () => { + m.state.renewal = true; + return [202, { request_id: "pr_int", kind: "intermediate", state: "waiting", match_code: "47 19 83" }]; + }], + ["GET", /^\/settings$/, () => [200, { repo: { name: "ianitor-routes", last_push_at: now() }, watch_seconds: 60 }]], + ["GET", /^\/tokens$/, () => [200, { items: [] }]], + ["POST", /^\/tokens$/, (_, b) => [201, { id: "tk_1", name: b.name, token: "ian_tk1_secretvalue", expires_at: later(365 * 86400) }]], + ["GET", /^\/share-links$/, () => [200, { items: [], epoch: 0 }]], + ]; + + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.pathname + input.search : input.url; + const path = url.replace(/^.*\/api\/v1/, ""); + const method = (init?.method ?? "GET").toUpperCase(); + const body = init?.body ? JSON.parse(String(init.body)) : {}; + m.calls.push({ method, path, body }); + for (const [mm, re, f] of routes) { + const match = path.match(re); + if (mm === method && match) { + const [status, data] = f(match, body); + const withTime = data && typeof data === "object" ? { ...(data as Json), server_time: now() } : data; + return new Response(status === 204 ? null : JSON.stringify(withTime), { status, headers: { "Content-Type": "application/json" } }); + } + } + return new Response(JSON.stringify({ error: { code: "request.not_found", message: "There is no such API call.", field: null, params: {}, retry_after_s: null, detail: null }, errors: [], request_id: "x" }), { status: 404, headers: { "Content-Type": "application/json" } }); + }) as typeof fetch; + + return m; +} diff --git a/apps/web/tests/setup.ts b/apps/web/tests/setup.ts new file mode 100644 index 0000000..4aadd80 --- /dev/null +++ b/apps/web/tests/setup.ts @@ -0,0 +1,39 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// jsdom lacks a few browser features the UI uses. + +if (typeof HTMLDialogElement !== "undefined") { + const p = HTMLDialogElement.prototype as HTMLDialogElement & Record; + if (!p.showModal) { + p.showModal = function (this: HTMLDialogElement) { + this.setAttribute("open", ""); + }; + p.show = function (this: HTMLDialogElement) { + this.setAttribute("open", ""); + }; + p.close = function (this: HTMLDialogElement) { + this.removeAttribute("open"); + }; + } +} + +const clipboard = { text: "", writeText: async (t: string) => void (clipboard.text = t) }; +Object.defineProperty(globalThis.navigator, "clipboard", { value: clipboard, configurable: true }); +(globalThis as unknown as { __clipboard: typeof clipboard }).__clipboard = clipboard; + +if (!("BroadcastChannel" in globalThis)) { + (globalThis as unknown as { BroadcastChannel: unknown }).BroadcastChannel = class { + onmessage: unknown = null; + postMessage() {} + close() {} + }; +} + +if (!("randomUUID" in crypto)) { + Object.defineProperty(crypto, "randomUUID", { value: () => Math.random().toString(36).slice(2) }); +} + +window.open = () => null; +HTMLAnchorElement.prototype.click = function () {}; diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json new file mode 100644 index 0000000..b898d96 --- /dev/null +++ b/apps/web/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "@tsconfig/svelte/tsconfig.json", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "verbatimModuleSyntax": true, + "isolatedModules": true, + "skipLibCheck": true, + "types": ["vite/client"], + "lib": ["ES2022", "DOM", "DOM.Iterable"] + }, + "include": ["src/**/*.ts", "src/**/*.svelte", "tests/**/*.ts", "../../packages/ui/src/**/*.ts", "../../packages/ui/src/**/*.svelte"] +} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts new file mode 100644 index 0000000..8ce02c2 --- /dev/null +++ b/apps/web/vite.config.ts @@ -0,0 +1,38 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import { defineConfig } from "vitest/config"; + +// Dev server: 127.0.0.1 only (CLAUDE.md), never --host 0.0.0.0. /api goes to control's --dev on +// 127.0.0.1:7878. In production edge sends Authelia's identity and the per-boot proof; in dev +// there is no Authelia, so the dev proxy (never the browser) adds the dev API token from +// $IANITOR_DEV_TOKEN, which `ianitor-control --dev` prints. +const control = process.env.IANITOR_CONTROL ?? "http://127.0.0.1:7878"; +const token = process.env.IANITOR_DEV_TOKEN; + +export default defineConfig({ + plugins: [svelte()], + server: { + host: "127.0.0.1", + port: 5173, + strictPort: true, + proxy: { + "/api": { + target: control, + changeOrigin: true, + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }, + }, + }, + preview: { host: "127.0.0.1" }, + build: { outDir: "dist", sourcemap: false, assetsInlineLimit: 0 }, + resolve: process.env.VITEST ? { conditions: ["browser"] } : undefined, + test: { + environment: "jsdom", + setupFiles: ["./tests/setup.ts"], + include: ["tests/**/*.test.ts"], + testTimeout: 20000, + }, +}); diff --git a/docs/ui-handoff.md b/docs/ui-handoff.md new file mode 100644 index 0000000..fa1e53d --- /dev/null +++ b/docs/ui-handoff.md @@ -0,0 +1,1443 @@ +# Ianitor Domi web UI: hand-off for the Svelte build + +What apps/web and packages/ui are built from. This file is enough by itself: you never need to open +the design artifact. Where the artifact and this file disagree, this file wins, and §14 lists every such place. + +Sources: the approved design (claude.ai artifact "Ianitor Domi — UI", 9 boards, murex palette on Domi), +docs/ui-api.md (the contract), docs/api.md (the built API), crates/control/src/messages.rs (the server's +sentences), ROADMAP §3 and §4, and Mark's decisions of 2026-11-07. + +Conventions in this file: +- "Quoted text" is exact UI copy. `{x}` is a value: from `params` on an error, or from a field. + **Hostnames, addresses (upstreams, paths) and match codes are bold** wherever they appear in a sentence. +- **[built]** means the API exists (Phase 2). **[proposed]** means the shape is mine and the API is not + built yet (engine switch, PKI, sign-in). Build the UI against the proposed shape behind a typed client, + so only the client changes if control lands differently. +- Click counts follow ROADMAP §4: typing is not a click; a click that only opens a menu is a click. + +--- + +## 0. Ground rules for the build + +- Svelte 5 runes, TypeScript strict. apps/web holds no business logic: every decision (validation, + health state, undo target, restore effects) comes from the API. The UI formats and arranges. +- One typed API client (`apps/web/src/lib/api.ts`) owns: base path `/api/v1`, the `X-Ianitor-UI: 1` + header on every request, `redirect: "manual"`, an `Idempotency-Key` per click (see §11.3), the error + envelope, the server-clock offset (§7.2), and the signed-out and lost-contact detection (§10, §11). +- Show the server's `error.message` as the sentence, verbatim. The UI switches on `error.code` only to + decide which buttons to offer, which field to mark and which words to bold (`params`). The table in §12 + gives every code, its sentence and its offer, so you can test that the sentence arrives and that the + right button appears. The UI writes its own sentence only for `ui.*` codes and for the few codes the + server has no sentence for (marked "UI text" in §12). +- Never put a token, share URL, password or one-time password in `localStorage`, `sessionStorage`, the + URL, a log line or an error report. Drop them from component state when their dialog closes. +- Dark only. No light theme, no theme switch. +- No external requests at runtime: fonts are self-hosted (§1.3), no CDN, no analytics. +- Dev server on 127.0.0.1 only (`pnpm --filter web dev`, never `--host`). + +--- + +## 1. Design tokens (packages/ui) + +### 1.1 The block to paste + +`packages/ui/src/tokens.css`. Apply the class `ia` to `` (the artifact puts the tokens on `.ia`; +`:root` would also work, but keep `.ia` so the shared Domi components scope the same way). + +The root font size is left at the browser default (16 px). The artifact rendered with rem = 16 px, so +every rem value below reproduces it exactly, and the UI still follows a user's own font-size setting. +Body text is 0.9375rem (15 px), as drawn. + +```css +.ia { + /* ── Ground and structure: violet-tinted iron black ───────────────────── */ + --ground: #0c0b0f; /* page ground; every ratio is measured on it */ + --colonnade: #121016; /* sidebar, phone bars, menus, dialogs, side panel */ + --surface: #18151d; /* fields, the last-change bar, cards */ + --surface-2: #221d28; /* hover, the current place, a chosen option */ + --hairline: #2c2633; /* dividers only, never a control edge */ + --hairline-strong: #3c3445; /* chip and frame edges (facts, not controls) */ + --control-edge: #7d7189; /* edge of every field, button, segmented control, engine chip */ + + /* ── Text ──────────────────────────────────────────────────────────────── */ + --text: #f1edf3; /* body text, hostnames */ + --text-2: #cfc6d4; /* secondary text, field labels */ + --muted: #a99eb1; /* hints, section labels, times */ + --disabled: #7a7183; /* disabled controls only, never content */ + + /* ── The lead: murex (Tyrian purple) ───────────────────────────────────── */ + --accent: #e0a3dc; /* links, focus ring, the current place, running state */ + --accent-strong: #f2c9ee; /* focus ring on the primary button; match codes */ + --primary-high: #8d3b89; /* primary fill, top */ + --primary-mid: #76306f; /* primary fill, 55 % */ + --primary-low: #5c2257; /* primary fill, foot */ + --primary-edge: #c77cc1; /* primary button edge */ + --on-primary: #ffffff; /* label on the primary fill */ + + /* ── Metal ─────────────────────────────────────────────────────────────── */ + --bronze: #b6adbe; /* ornaments: the interpunct rule (iron, not bronze) */ + --gilt: #f6f0f7; /* the wordmark only */ + + /* ── Second light: quiet iron (Domi's .domi-pill and .domi-status use these) */ + --second: #cfc6d4; + --second-strong: #f1edf3; + --second-edge: #7d7189; + + /* ── Status: blue / amber / vermilion, stepped in lightness (L* 84 / 68 / 58) */ + --healthy: #a6d6fa; /* host answers; a change was kept. Filled dot. */ + --kept: #a6d6fa; + --degraded: #d99a35; /* partly failing; a change was reverted or not applied. Half dot. */ + --reverted: #d99a35; + --down: #e2683a; /* not reachable; needs attention; paused; danger actions. Hollow ring. */ + --danger: #e2683a; + --on-danger: #170804; /* text on a filled danger button (none is planned) */ + --unknown: #a99eb1; /* no health check set; waiting for first check. Dashed ring. */ + --running: #e0a3dc; /* queued, applying, watching, switching, waiting for Custos (= accent) */ + + /* Status washes (banner backgrounds) and edges. color-mix() is what the artifact uses; + the resolved hex is in the comment, for tools that need a literal. */ + --wash-degraded: color-mix(in srgb, var(--degraded) 10%, var(--ground)); /* #201913 */ + --wash-kept: color-mix(in srgb, var(--kept) 10%, var(--ground)); /* #1b1f26 */ + --wash-down: color-mix(in srgb, var(--down) 10%, var(--ground)); /* #211413 */ + --edge-degraded: color-mix(in srgb, var(--degraded) 65%, var(--ground)); /* #916828 */ + --edge-kept: color-mix(in srgb, var(--kept) 65%, var(--ground)); /* #708fa8 */ + --edge-down: color-mix(in srgb, var(--down) 80%, var(--ground)); /* #b75531 */ + --edge-outline: color-mix(in srgb, var(--accent) 60%, var(--ground)); /* #8b668a, outline button */ + --hover-wash: color-mix(in srgb, var(--accent) 8%, transparent); /* quiet button hover */ + --danger-hover: color-mix(in srgb, var(--danger) 7%, transparent); + + /* ── Type ──────────────────────────────────────────────────────────────── */ + --font-inscription: Cinzel, "Trajan Pro", "Cormorant Garamond", Georgia, "Times New Roman", serif; + --font-book: "Cormorant Garamond", Cormorant, "EB Garamond", Garamond, Georgia, "Times New Roman", serif; + --font-hand: Manrope, system-ui, -apple-system, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", Arial, sans-serif; + + --fs-display: 2.6rem; --lh-display: 1.1; /* book 500: a view title ("Hosts") */ + --fs-h2: 1.9rem; --lh-h2: 1.15; /* book 500: panel title; phone view title uses 2.1rem */ + --fs-h3: 1.45rem; --lh-h3: 1.15; /* book 600: dialog and section titles */ + --fs-body: 0.9375rem; --lh-body: 1.6; /* hand 400: everything read (15 px) */ + --fs-host: 0.98rem; /* hand 600: hostname in a row */ + --fs-button: 0.95rem; /* hand 600; 700 on primary */ + --fs-field-label: 0.92rem; /* hand 400, text-2 */ + --fs-hint: 0.88rem; --lh-hint: 1.5; /* hand 400, muted: hints, notes */ + --fs-sub: 0.86rem; /* hand 400, muted: row sub-lines, times */ + --fs-chip: 0.78rem; /* 12.5 px, hand 400, text-2 */ + --fs-state: 0.95rem; /* hand 700, all-small-caps, tracking 0.12em */ + --fs-label: 0.74rem; /* hand 700, tracking 0.26em: SECTION LABELS */ + --fs-nav: 0.95rem; /* sidebar item, hand 600 */ + --fs-tab-phone: 0.78rem; /* bottom-bar label, hand 600 */ + --fs-wordmark: 0.8125rem; /* 13 px Cinzel 500, tracking 0.3em; phone 12 px, 0.26em */ + --fs-code: 2.2rem; /* Cinzel 500, tracking 0.16em: Custos match code */ + --tracking-state: 0.12em; + --tracking-label: 0.26em; + --tracking-wordmark: 0.3em; + + /* ── Spacing (Domi) ────────────────────────────────────────────────────── */ + --space-1: 0.35rem; /* label to its field */ + --space-2: 0.6rem; /* between buttons in a row, list items */ + --space-3: 1rem; /* field to field */ + --space-4: 1.4rem; /* panel padding */ + --space-5: 2rem; /* between sections of a view */ + --space-6: 3.5rem; /* a view's bottom padding */ + --target: 44px; /* minimum height and width of every control and touch target */ + + /* ── Radii ─────────────────────────────────────────────────────────────── */ + --radius-chip: 6px; + --radius-sm: 10px; /* quiet buttons, fields, nav items, menu items */ + --radius: 12px; /* primary button, cards inside panels */ + --radius-lg: 18px; /* panels, banners, the bar, the host list, dialogs */ + --radius-pill: 999px; /* chips, the engine chip */ + + /* ── Shadows ───────────────────────────────────────────────────────────── */ + --leaf-bevel: 0 0 0 1px rgba(199,124,193,0.25), 0 12px 40px -14px rgba(141,59,137,0.6), + inset 0 1px 0 rgba(255,220,250,0.30), inset 0 -2px 0 #3a1237; /* primary button */ + --carved: inset 0 2px 6px rgba(12,11,15,0.8), inset 0 -1px 0 rgba(182,173,190,0.16); /* fields */ + --inset-lit: inset 0 0 18px rgba(224,163,220,0.07); /* current nav item */ + --shadow-dialog: 0 40px 100px -40px rgba(0,0,0,0.95); /* dialogs, menus, popover */ + --scrim: rgba(12,11,15,0.82); /* behind modals */ + + /* ── Focus ─────────────────────────────────────────────────────────────── */ + --focus-ring: 2px solid var(--accent); /* outline, offset 3px, on every :focus-visible */ + --focus-ring-primary: 2px solid var(--accent-strong); + --focus-offset: 3px; + --focus-halo: 0 0 0 4px rgba(224,163,220,0.16); /* fields: border goes accent, plus this halo */ + + /* ── Motion (Domi's transitions; the last three are new for this UI) ──── */ + --dur-color: 0.3s; /* border, background, colour */ + --dur-lift: 0.45s; /* box-shadow, transform (primary hover lifts 1px) */ + --ease: ease; + --dur-tick: 1s; /* watch progress bar: linear, one step per second */ + --dur-enter: 0.18s; /* dialog, panel, menu, toast enter (opacity + 8px) */ + --dur-exit: 0.12s; + + /* ── Layout ────────────────────────────────────────────────────────────── */ + --sidebar-w: 232px; + --main-pad: 26px 32px 40px; /* desktop; phone 18px 16px 20px */ + --gutter-phone: 16px; + --panel-w: 480px; /* add/edit host side panel */ + --dialog-w: 520px; /* share, token, device dialogs */ + --popover-w: 420px; /* engine popover */ + --phone-bar-h: 56px; /* bottom navigation item height */ + --bp-phone: 720px; /* below: phone layout (header + bottom bar) */ + + color-scheme: dark; + background: var(--ground); + color: var(--text); + font-family: var(--font-hand); + font-size: var(--fs-body); + line-height: var(--lh-body); + font-variant-numeric: tabular-nums; +} +.ia *, .ia *::before, .ia *::after { box-sizing: border-box; } +.ia :focus-visible { outline: var(--focus-ring); outline-offset: var(--focus-offset); } +.ia h1, .ia h2, .ia h3, .ia p { margin: 0; } +.ia button { font: inherit; } +@media (prefers-reduced-motion: reduce) { + .ia *, .ia *::before, .ia *::after { animation: none !important; transition: none !important; } +} +``` + +Two things the artifact's theme.css also does, which you must keep in packages/ui: +the Domi button edges raised for contrast (`.domi-btn` edge = `--control-edge`; outline button edge = +`--edge-outline`; danger edge = `--edge-down`; primary edge = `--primary-edge`), and the primary +gradient `linear-gradient(180deg, var(--primary-high) 0%, var(--primary-mid) 55%, var(--primary-low) 100%)`. + +### 1.2 Contrast, every pair used (WCAG 2.x) + +Measured with the resolved hex values above. AA needs 4.5:1 for text, 3:1 for large text (24 px, or +18.7 px bold) and for control edges and focus indicators (1.4.11). + +**Text on the backgrounds it appears on** + +| Text \ background | ground #0c0b0f | colonnade #121016 | surface #18151d | surface-2 #221d28 | wash-degraded #201913 | wash-kept #1b1f26 | wash-down #211413 | +|:--|--:|--:|--:|--:|--:|--:|--:| +| text #f1edf3 | 16.95 | 16.33 | 15.59 | 14.24 | 15.00 | 14.28 | 15.46 | +| text-2 #cfc6d4 | 11.85 | 11.41 | 10.90 | 9.95 | 10.48 | 9.98 | 10.80 | +| muted #a99eb1 | 7.67 | 7.39 | 7.06 | 6.44 | 6.79 | 6.46 | 6.99 | +| accent #e0a3dc (links, running) | 9.76 | 9.39 | 8.97 | 8.19 | 8.63 | 8.22 | 8.89 | +| accent-strong #f2c9ee (match code) | 13.42 | 12.92 | 12.34 | 11.27 | n/u | n/u | n/u | +| healthy / kept #a6d6fa | 12.72 | 12.25 | 11.70 | 10.69 | n/u | 10.72 | n/u | +| degraded / reverted #d99a35 | 8.06 | 7.76 | 7.41 | 6.77 | 7.13 | n/u | n/u | +| down / danger #e2683a | 5.86 | 5.65 | 5.39 | 4.92 | n/u | n/u | 5.34 | +| gilt #f6f0f7 (wordmark) | 17.49 | 16.85 | n/u | n/u | n/u | n/u | n/u | +| disabled #7a7183 | 4.22 | 4.06 | 3.88 | 3.54 | | | | + +n/u = not used together. Every used pair passes AA for small text. `disabled` is below 4.5 by design: +WCAG exempts inactive controls, and a disabled control always has its reason in readable text nearby. +Never use `disabled` for content. + +Button labels on fills: on-primary #fff on primary-high 6.73, on primary-mid 8.67, on primary-low 11.53 +(the label sits across the gradient, so the floor is 6.73). on-danger on down 5.85 (reserved). +Quiet-button hover background (8 % accent over ground, #1d171f): text 15.19, text-2 10.62. + +**Edges and indicators (3:1 needed)** + +| Element | Against | Ratio | +|:--|:--|--:| +| control-edge #7d7189 (fields, quiet buttons, engine chip, segmented control) | ground / colonnade / surface / surface-2 | 4.29 / 4.13 / 3.95 / 3.61 | +| control-edge on banner washes | degraded / kept / down | 3.80 / 3.62 / 3.91 | +| outline-button edge #8b668a | ground / colonnade / surface | 4.08 / 3.93 / 3.75 | +| danger-button edge #b75531 | ground / colonnade | 4.07 / 3.92 | +| primary-edge #c77cc1 | ground / colonnade | 6.62 / 6.37 | +| focus ring accent #e0a3dc | ground / surface-2 | 9.76 / 8.19 | +| focus ring on primary, accent-strong | ground (outside the button) / primary-high | 13.42 / 4.61 | +| banner edges degraded #916828 / kept #708fa8 / down #b75531 | ground | 3.94 / 5.78 / 4.07 | +| status dots healthy / degraded / down / unknown | ground | 12.72 / 8.06 / 5.86 / 7.67 | +| progress fill accent | track surface-2 | 8.19 | +| chosen segment ring (accent 55 % over surface-2, #8b678b) | surface-2 | 3.46 | + +Decoration only, not required to pass: hairline 1.34, hairline-strong 1.65 (dividers and chip edges; +chips are facts, not controls). + +Status colours against each other: healthy/degraded 1.58, degraded/down 1.37. Not enough alone, which is +why every status carries a word and a shape (§2.2). Never colour alone. + +### 1.3 Fonts + +Self-host the Latin woff2 subsets in packages/ui/fonts (all OFL): Cinzel 500; Cormorant Garamond 500, +600, 500 italic; Manrope 400, 600, 700. `font-display: swap`. No Google Fonts request at runtime (the UI +runs on a home server behind Authelia and makes no outside requests). Italic Cormorant is only in the +Domi system; this UI does not use it. + +Where each face goes: Cinzel only for the wordmark "IANITOR DOMI" (written in capitals as is, never +text-transformed) and the Custos match code. Cormorant Garamond (book) only for headings: view title, +panel title, dialog title. Manrope (hand) for everything else. + +--- + +## 2. Components + +Each component lists: what it looks like, states, keyboard, ARIA. Class names follow the artifact +(`ia-*`, `domi-*`) so packages/ui can carry the CSS as drawn; Svelte components wrap them. + +### 2.1 Buttons (`Button.svelte`, Domi `.domi-btn`) + +| Variant | Look | Use | +|:--|:--|:--| +| primary | min-height 50px, padding 0 1.6rem, radius 12px, gradient fill, primary-edge, leaf-bevel, label #fff 700 | at most one per screen: "+ Host", "Apply", "Restore this version", "Copy link", "Issue", "Copy token", "Restore the last kept version" in the needs-attention banner | +| quiet (default) | min-height 44px, padding 0 1.1rem, radius 10px, transparent, control-edge, text-2 600 | Undo, Cancel, Close, secondary actions | +| outline | as quiet, edge #8b668a, label accent | an action inside a banner or card that leads but is not the primary: "Renew", "Edit and try again", "+ Device", "New token", "Switch to Caddy", "Turn on share links and copy link" | +| danger | as quiet, edge #b75531, label danger | "Revoke", "Stop all share links", menu item "Remove host" (as menu text colour) | +| link | no edge, no padding, accent, underline offset 0.2em, hit area ≥ 44px tall (pad vertically) | "More options…", "Show details", "Add a password", "See history" | + +States: hover (quiet: edge accent, bg `--hover-wash`, label text; primary: lifts 1px), focus-visible +(2px accent outline, offset 3px; primary uses accent-strong), active (no extra style), pending, disabled. +- **Pending**: after a click that waits on the API for more than 300 ms, keep the label, add a 16px + spinner before it, set `aria-busy="true"` and `aria-disabled="true"`, ignore further clicks. No width + change (reserve the spinner slot). +- **Disabled**: use `aria-disabled="true"` (not the `disabled` attribute) so the button stays focusable + and its reason can be read: `aria-describedby` points at the visible reason text. Look: label + `--disabled`, edge `--hairline`, no hover. +- Icon-only buttons (`.ia-icon-btn`, 44×44, radius 10px, text-2): always an `aria-label` + ("More for photos.home.example", "Close"). +- Icons are inline stroke SVGs, 18px, stroke 1.8–2.2, `aria-hidden="true"`. The artifact's set: + plus, undo arrow, check, clock, link, pencil, history, trash, key, gear, building (hosts), swap arrows, + copy, chevron down, dots. + +### 2.2 Status: dot and word (`Status.svelte`) + +Always the pair: a 12px shape (decorative, `aria-hidden`) plus a word in small capitals (700, +`font-variant-caps: all-small-caps`, tracking 0.12em, 0.95rem). The word is the accessible text. + +| `data-s` | Dot | Word colour | Words used | +|:--|:--|:--|:--| +| healthy | filled circle, healthy | healthy | "healthy" | +| kept | (no dot; check icon) | kept | "kept" | +| degraded | 2px ring, left half filled, degraded | degraded | "degraded" | +| reverted | (undo-arrow icon) | reverted | "reverted", "not applied" | +| down | 3px hollow ring, down | down | "down", "needs attention", "paused", "renew now", "expired" | +| unknown | 2px dashed ring, unknown | muted | "not checked", "waiting" (pending health), "stopped", "revoked" | +| running | clock icon, accent | accent | "waiting", "applying", "watching", "switching" | + +The degraded dot: `border: 2px solid var(--degraded); background: linear-gradient(90deg, var(--degraded) 50%, transparent 50%)`. +A dot with no word is only allowed where the word is next to it in the same row on phone +(the phone row repeats the word in the sub-line). + +### 2.3 Chips (`Chip.svelte`, `.ia-chip`) + +Facts about a host, not controls: pill, 1px hairline-strong, text-2, 12.5px, `white-space: nowrap`, +padding 1px 10px, gap 6px between chips, wraps. Not focusable, no role. + +| Field | Chip text | +|:--|:--| +| tls = domi | "Domi certificate" | +| tls = letsencrypt | "Let's Encrypt" | +| auth = forward-auth | "Sign-in first" | +| auth = none | no chip (see open question Q11) | +| share_links = true | "Share links on" | +| websockets = false | "No websockets" (G19: no chip when true, the default) | +| access_log = truncated | "Visit log on" | + +### 2.4 Engine chip (`EngineChip.svelte`, `.ia-engine`) + +A control: pill, min-height 44px, padding 0 16px 0 14px, control-edge, surface background, text 600 +0.92rem. Content: status dot · `` "Engine" (muted, 400) · engine name · chevron down. +- Pingora running: dot healthy, "Engine Pingora". +- Caddy running: dot healthy, "Engine Caddy" ``"(fallback)"``. +- Switching: clock icon in accent instead of the dot, "Engine Switching…". +- Stopped (control cannot reach the engine, `engine.state = "stopped"`): dot down, "Engine Pingora" and + the word is announced: accessible name "Engine: Pingora, not answering". +Phone: no "Engine" label (as drawn): dot · name · chevron, padding 0 12px. +`