Files
ianitor/apps/web/src/components/HostPanel.svelte
T

539 lines
25 KiB
Svelte

<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/. -->
<script lang="ts">
// Handoff §6 and §7: the add/edit panel, its validation on blur, Apply, and the progress and
// outcome of the apply it starts. Every decision comes from control; the form only carries it.
import { onDestroy, onMount } from "svelte";
import { Banner, Button, Details, Dialog, Icon, Segmented } from "@ianitor/ui";
import ApplyProgress from "./ApplyProgress.svelte";
import { ApiError, call, del, get, newKey, sentence } from "../lib/api";
import { app, changesBlocked, refresh, restoreLastKept, toast } from "../lib/app.svelte";
import { FINAL, follow } from "../lib/applies";
import { firstSentence } from "../lib/format";
import type { ApplyView, ErrorBody, HeaderRule, HostSpec } from "../lib/types";
let {
hostname,
resume,
prefill,
focusField,
onclose,
}: {
hostname?: string;
resume?: string;
prefill?: HostSpec | null;
focusField?: string;
onclose: () => void;
} = $props();
const site = $derived(app.overview?.site ?? null);
const signinOk = $derived(site?.forward_auth_configured ?? false);
// ---- the form
type Rule = { action: "set" | "remove"; name: string; kind: "value" | "secret"; value: string; secret: string };
let host = $state({
hostname: "",
upstreams: [""],
tls: "domi" as "domi" | "letsencrypt",
auth: "forward-auth" as "forward-auth" | "none",
websockets: true,
share_links: false,
device_certs: false,
access_log: "off" as "off" | "truncated",
hc: false,
hcPath: "/",
hcEvery: 30,
req: [] as Rule[],
resp: [] as Rule[],
});
let rev = $state<string | null>(null);
let more = $state(false);
let loading = $state(true);
let notFound = $state<string | null>(null);
let errors = $state<Record<string, ErrorBody>>({});
let touched = $state<Record<string, boolean>>({});
let summary = $state("");
let underFooter = $state("");
let conflict = $state<ErrorBody | null>(null);
let topError = $state<ApiError | null>(null);
let idem = newKey();
let lastBody = "";
// ---- the apply
let apply = $state<ApplyView | null>(null);
let restoring = $state(false);
let restoreProblem = $state<string | null>(null);
let phase = $state<"form" | "progress">("form");
let stop: (() => void) | undefined;
let closeTimer: ReturnType<typeof setTimeout> | undefined;
function fromSpec(s: HostSpec) {
host.hostname = s.hostname;
host.upstreams = s.upstreams.length ? [...s.upstreams] : [""];
host.tls = s.tls;
host.auth = s.auth;
host.websockets = s.websockets;
host.share_links = s.share_links;
host.device_certs = !!s.device_certs;
host.access_log = s.access_log;
host.hc = !!s.health_check;
host.hcPath = s.health_check?.path ?? "/";
host.hcEvery = s.health_check?.interval_secs ?? 30;
const rule = (r: HeaderRule): Rule => ({ action: r.action, name: r.name, kind: r.secret ? "secret" : "value", value: r.value ?? "", secret: r.secret ?? "" });
host.req = (s.request_headers ?? []).map(rule);
host.resp = (s.response_headers ?? []).map(rule);
if (host.hc || host.req.length || host.resp.length || !host.websockets || host.share_links || host.access_log !== "off" || host.device_certs) more = true;
}
function spec(): HostSpec {
const rules = (rs: Rule[]): HeaderRule[] =>
rs.map((r) =>
r.action === "remove"
? { action: "remove", name: r.name }
: r.kind === "secret"
? { action: "set", name: r.name, secret: r.secret }
: { action: "set", name: r.name, value: r.value },
);
// The UI always sends every field explicitly (the schema's own defaults differ).
return {
hostname: host.hostname.trim(),
upstreams: host.upstreams.map((u) => u.trim()).filter((u, i) => u !== "" || i === 0),
tls: host.tls,
auth: host.auth,
websockets: host.websockets,
share_links: host.share_links,
device_certs: host.device_certs,
access_log: host.access_log,
health_check: host.hc ? { path: host.hcPath, interval_secs: Number(host.hcEvery) } : null,
request_headers: rules(host.req),
response_headers: rules(host.resp),
};
}
onMount(async () => {
if (resume) {
phase = "progress";
stop = follow(resume, onApply);
}
if (prefill) {
fromSpec(prefill);
} else if (hostname) {
try {
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
fromSpec(d.host);
rev = d.rev;
} catch (e) {
notFound = sentence(e);
}
} else {
rev = app.overview?.rev ?? null;
if (!signinOk) host.auth = "none";
}
// A form saved before this tab went to sign in comes back (App.svelte, signIn).
try {
const raw = sessionStorage.getItem(DRAFT);
const d = raw ? (JSON.parse(raw) as { hostname: string; host: typeof host }) : null;
if (d && d.hostname === (hostname ?? "") && !resume) {
Object.assign(host, d.host);
more = more || d.host.hc || d.host.req.length > 0 || d.host.resp.length > 0;
}
sessionStorage.removeItem(DRAFT);
} catch {
/* no storage: nothing to bring back */
}
loading = false;
if (phase === "form") {
// The Dialog focused its heading while this said "Loading…": now the first field
// (Hostname; Send traffic to when editing), so typing right after opening works.
const f = focusField ?? (hostname ? "upstreams[0]" : "hostname");
if (f.startsWith("health_check")) more = true;
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
}
window.addEventListener("ianitor:save-draft", saveDraft);
});
const DRAFT = "ianitor-draft";
function saveDraft() {
if (phase !== "form") return;
try {
sessionStorage.setItem(DRAFT, JSON.stringify({ hostname: hostname ?? "", host: $state.snapshot(host) }));
} catch {
/* no storage */
}
}
onDestroy(() => {
stop?.();
clearTimeout(closeTimer);
if (typeof window !== "undefined") window.removeEventListener("ianitor:save-draft", saveDraft);
});
function fieldId(f: string): string {
return "f-" + f.replace(/[^a-z0-9]+/gi, "-");
}
const errAt = (f: string) => errors[f];
function setErrors(list: ErrorBody[], only?: string) {
const next: Record<string, ErrorBody> = only ? { ...errors } : {};
if (only) {
for (const k of Object.keys(next)) if (k === only || k.startsWith(only + "[")) delete next[k];
}
for (const e of list) {
const f = e.field ?? "";
if (!f) continue;
if (only && !(f === only || f.startsWith(only + "["))) continue;
next[f] = e;
}
errors = next;
}
// Validation on blur (§2.10): only the field that lost focus, debounced.
let blurTimer: ReturnType<typeof setTimeout> | undefined;
function blur(field: string) {
touched[field] = true;
clearTimeout(blurTimer);
blurTimer = setTimeout(async () => {
try {
await call("POST", `/hosts/validate?mode=${hostname ? "edit" : "create"}`, spec());
setErrors([], field);
} catch (e) {
if (e instanceof ApiError) setErrors(e.errors.length ? e.errors : [e.body], field);
}
}, 300);
}
async function submit(e?: Event) {
e?.preventDefault();
if (changesBlocked()) return;
const body = spec();
const text = JSON.stringify(body);
if (text !== lastBody) {
idem = newKey();
lastBody = text;
}
underFooter = "";
conflict = null;
topError = null;
try {
const path = hostname ? `/hosts/${encodeURIComponent(hostname)}` : "/hosts";
const a = await call<{ apply: ApplyView }>(hostname ? "PUT" : "POST", path, { host: body, base_rev: rev }, { idem });
const ap = a.data?.apply;
if (!ap) return;
apply = ap;
phase = "progress";
stop?.();
stop = follow(ap.id, onApply);
} catch (err) {
if (!(err instanceof ApiError)) {
topError = null;
underFooter = sentence(err);
return;
}
if (err.code === "change.conflict") {
conflict = err.body;
return;
}
if (err.code === "change.unchanged") {
underFooter = "This is the same as what is live now, so nothing changed.";
return;
}
const list = err.errors.length ? err.errors : err.body.field ? [err.body] : [];
if (list.length) {
setErrors(list);
for (const x of list) if (x.field) touched[x.field] = true;
summary = `${list.length} ${list.length === 1 ? "thing" : "things"} to fix before Apply.`;
const first = list.find((x) => x.field)?.field;
if (first?.startsWith("health_check") || first?.includes("headers")) more = true;
if (first) setTimeout(() => document.getElementById(fieldId(first))?.focus(), 0);
} else {
topError = err;
}
}
}
function onApply(a: ApplyView) {
apply = a;
if (a.state === "kept") {
if (a.kind !== "remove") app.focusHost = a.hosts[0] ?? null;
closeTimer = setTimeout(() => onclose(), 1500);
}
}
async function cancelQueued() {
if (!apply) return;
try {
await del(`/applies/${encodeURIComponent(apply.id)}`);
toast("Cancelled before it started. Nothing changed.");
stop?.();
phase = "form";
apply = null;
} catch (e) {
underFooter = sentence(e);
}
}
function editAgain(field?: string) {
stop?.();
phase = "form";
apply = null;
idem = newKey();
const f = field ?? "upstreams[0]";
if (f.startsWith("health_check")) {
more = true;
host.hc = true;
}
setTimeout(() => document.getElementById(fieldId(f))?.focus(), 0);
}
async function keepMine() {
if (!hostname) {
rev = app.overview?.rev ?? rev;
} else {
try {
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
rev = d.rev;
} catch {
/* keep the old rev */
}
}
await refresh();
if (!hostname) rev = app.overview?.rev ?? rev;
conflict = null;
}
async function useTheirs() {
if (!hostname) return;
const d = await get<{ host: HostSpec; rev: string }>(`/hosts/${encodeURIComponent(hostname)}`);
fromSpec(d.host);
rev = d.rev;
conflict = null;
}
const name = $derived(host.hostname.trim() || hostname || "the host");
const heading = $derived.by(() => {
if (phase !== "progress" || !apply) return hostname ? `Edit ${hostname}` : "New host";
const h = apply.hosts[0] ?? name;
switch (apply.kind) {
case "add":
return `Adding ${h}`;
case "remove":
return `Removing ${h}`;
case "share_links":
return `Turning on share links for ${h}`;
case "undo":
return `Undoing: ${apply.summary.replace(/^Undid: /, "")}`;
case "restore":
return apply.summary.replace(/^Restored /, "Restoring ");
default:
return `Changing ${h}`;
}
});
const reasonOffer = $derived.by(() => {
const c = apply?.reason?.code ?? "";
if (/apply\.reverted\.(not_found|redirect|sign_in)$/.test(c)) return { label: "Edit health check", field: "health_check.path" };
if (/apply\.(interrupted|reverted\.edge_lost|interrupted\.queued)$/.test(c)) return { label: "Try again", field: "" };
if (c.startsWith("apply.reverted") || c === "apply.failed.validation" || c.startsWith("pki.")) return { label: "Edit and try again", field: apply?.reason?.field ?? undefined };
return null;
});
const blocked = $derived(changesBlocked());
const shareWarning = $derived(host.auth === "none" && host.share_links);
</script>
<Dialog title={heading} kind="panel" {onclose}>
{#if loading}
<p class="ia-muted">Loading…</p>
{:else if notFound}
<Banner tone="notice" live="status">{#snippet title()}{notFound}{/snippet}
{#snippet actions()}<Button onclick={onclose}>Back to hosts</Button>{/snippet}
</Banner>
{:else if phase === "progress" && apply}
<div aria-live="polite" class="sr-only">
{#if apply.state === "queued"}Waiting for another change to finish.{:else if apply.state === "watching"}Watching health checks.{:else if apply.state === "kept"}Kept. {apply.reason?.message}{:else if apply.state === "reverted"}Reverted. {apply.reason?.message}{:else if apply.state === "failed"}Not applied. {apply.reason?.message}{/if}
</div>
<ApplyProgress {apply} oncancel={cancelQueued} />
{#if apply.state === "kept"}
<Banner tone="kept">
{#snippet title()}<span class="ia-status" data-s="kept"><span class="word">kept</span></span> <strong>{apply?.hosts[0] ?? name}</strong> {apply?.kind === "remove" ? "is removed." : "is live."}{/snippet}
{(apply.reason?.message ?? "").replace(/^\S+ is (live|removed)\.\s*/, "")}{#if apply.commit_short} Saved as commit {apply.commit_short}{apply.push?.state === "pushed" ? " and pushed to Gitea" : ""}.{/if}
</Banner>
{:else if apply.state === "reverted" || apply.state === "failed"}
{@const parts = firstSentence(apply.reason?.message ?? "")}
<Banner tone="notice" live="status">
{#snippet title()}<span class="ia-status" data-s="reverted"><span class="word">{apply?.state === "failed" ? "not applied" : "reverted"}</span></span> <strong>{parts[0]}</strong>{/snippet}
{#if parts[1]}Reason: {parts[1]}{/if}
{#snippet actions()}
{#if reasonOffer}
<Button variant="outline" onclick={() => (reasonOffer?.field === "" ? (editAgain(), submit()) : editAgain(reasonOffer?.field))}>{reasonOffer.label}</Button>
{/if}
{/snippet}
</Banner>
{#if apply.reason?.detail}<Details detail={apply.reason.detail} />{/if}
<p class="ia-hint">Your form is kept. History records the attempt as {apply.state === "failed" ? "not applied" : "reverted"}.</p>
{:else if apply.state === "needs_attention"}
<Banner tone="down" live="alert">{#snippet title()}<strong>Ianitor could not undo a failed change.</strong>{/snippet}{apply.reason?.message}
{#if restoreProblem}<p role="status">{restoreProblem}</p>{/if}
{#snippet actions()}
{#if app.overview?.undo?.target}<Button variant="primary" pending={restoring} onclick={async () => { restoring = true; restoreProblem = await restoreLastKept(); restoring = false; }}>Restore the last kept version</Button>{/if}
{/snippet}
</Banner>
{/if}
{:else}
<form id="host-form" onsubmit={submit} novalidate>
{#if summary}<p class="sr-only" role="alert">{summary}</p>{/if}
{#if conflict}
<Banner tone="notice" live="status">
{#snippet title()}{conflict?.message}{/snippet}
{#snippet actions()}<Button onclick={keepMine}>Keep my edits</Button>{#if hostname}<Button onclick={useTheirs}>Use the new version</Button>{/if}{/snippet}
</Banner>
{/if}
{#if topError}
<Banner tone="notice" live="status">{#snippet title()}{sentence(topError)}{/snippet}</Banner>
{#if topError.body.detail}<Details detail={topError.body.detail} reference={topError.requestId} />{/if}
{/if}
<div class="domi-field">
<label class="domi-field-label" for={fieldId("hostname")}>Hostname</label>
<input id={fieldId("hostname")} class="domi-input" bind:value={host.hostname} readonly={!!hostname}
autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
aria-invalid={errAt("hostname") && touched["hostname"] ? "true" : undefined}
aria-describedby="{fieldId('hostname')}-e {fieldId('hostname')}-h" onblur={() => blur("hostname")} />
{#if errAt("hostname") && touched["hostname"]}
<p class="domi-error" id="{fieldId('hostname')}-e"><Icon name="ring" />{errAt("hostname").message}
{#if errAt("hostname").params?.suggestion}
<button type="button" class="domi-btn link" onclick={() => { host.hostname = errAt("hostname").params.suggestion; blur("hostname"); }}>Use {errAt("hostname").params.suggestion}</button>
{/if}
</p>
{/if}
{#if hostname}<p class="ia-hint" id="{fieldId('hostname')}-h">To use another address, add a new host and remove this one.</p>{/if}
</div>
{#each host.upstreams as _, i (i)}
{@const f = `upstreams[${i}]`}
{@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)}
<div class="domi-field">
{#if i === 0}<label class="domi-field-label" for={fieldId(f)}>Send traffic to</label>{/if}
<div class="row">
<input id={fieldId(f)} class="domi-input" bind:value={host.upstreams[i]} autocapitalize="none" spellcheck="false" inputmode="url" autocomplete="off"
aria-label={i === 0 ? undefined : `Also send traffic to, address ${i + 1}`}
aria-invalid={err && (touched[f] || touched["upstreams"]) ? "true" : undefined}
aria-describedby="{fieldId(f)}-e" onblur={() => blur(f)} />
{#if i > 0}<button type="button" class="ia-icon-btn" aria-label="Remove this address" onclick={() => host.upstreams.splice(i, 1)}><Icon name="trash" /></button>{/if}
</div>
{#if err && (touched[f] || touched["upstreams"])}
<p class="domi-error" id="{fieldId(f)}-e"><Icon name="ring" />{err.message}
{#if err.params?.suggestion}<button type="button" class="domi-btn link" onclick={() => { host.upstreams[i] = err.params.suggestion; blur(f); }}>Use {err.params.suggestion}</button>{/if}
</p>
{/if}
{#if i === 0 && host.upstreams.length === 1}<p class="ia-hint">Add another address later for a second server.</p>{/if}
</div>
{/each}
<div><button type="button" class="domi-btn link" onclick={() => host.upstreams.push("")}>Add another address</button></div>
<Segmented legend="Certificate" name="tls" bind:value={host.tls}
options={[{ value: "domi", label: "Domi certificate" }, { value: "letsencrypt", label: "Let's Encrypt" }]} />
<p class="ia-hint">Domi for home devices only; Let's Encrypt for a public site.</p>
<Segmented legend="Who can open it" name="auth" bind:value={host.auth} disabled={signinOk ? [] : ["forward-auth"]}
options={[{ value: "forward-auth", label: "Sign in first" }, { value: "none", label: "Anyone" }]} />
{#if !signinOk}<p class="ia-hint">Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository.</p>{/if}
{#if errAt("auth")}<p class="domi-error"><Icon name="ring" />{errAt("auth").message}</p>{/if}
<div>
<button type="button" class="domi-btn link" aria-expanded={more} aria-controls="more-options" onclick={() => (more = !more)}>
More options: headers, websockets, health check, share links, visit log
</button>
</div>
{#if more}
<div id="more-options" class="more">
<div class="domi-field">
<span class="domi-field-label">Health check</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.hc} /> Check that it answers</label>
<p class="ia-hint">Ianitor asks this address regularly and shows the result on the main screen.</p>
</div>
{#if host.hc}
<div class="domi-field">
<label class="domi-field-label" for={fieldId("health_check.path")}>Health check address</label>
<input id={fieldId("health_check.path")} class="domi-input" bind:value={host.hcPath} aria-invalid={errAt("health_check.path") ? "true" : undefined} onblur={() => blur("health_check.path")} />
{#if errAt("health_check.path")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.path").message}</p>{/if}
<p class="ia-hint">Use an address that answers without signing in, like /health.</p>
</div>
<div class="domi-field">
<label class="domi-field-label" for={fieldId("health_check.interval_secs")}>Checks every</label>
<div class="row"><input id={fieldId("health_check.interval_secs")} class="domi-input narrow" type="number" min="1" max="3600" bind:value={host.hcEvery} onblur={() => blur("health_check.interval_secs")} /> <span class="ia-text2">seconds</span></div>
{#if errAt("health_check.interval_secs")}<p class="domi-error"><Icon name="ring" />{errAt("health_check.interval_secs").message}</p>{/if}
</div>
{/if}
<div class="domi-field">
<span class="domi-field-label">Websockets</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.websockets} /> Allow websockets</label>
<p class="ia-hint">Live updates for apps like Home Assistant. Leave on unless you know the app does not need them.</p>
</div>
<div class="domi-field">
<span class="domi-field-label">Share links</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.share_links} /> Allow share links</label>
<p class="ia-hint">Lets you make links that open this host without signing in, until they expire.</p>
{#if shareWarning}<p class="ia-hint">Anyone can already open {name}, so a share link changes nothing.</p>{/if}
</div>
<div class="domi-field">
<span class="domi-field-label">Device certificates</span>
<label class="ia-check"><input type="checkbox" bind:checked={host.device_certs} /> Only devices with a Domi device certificate</label>
<p class="ia-hint">Phones, computers and apps need a certificate from Certificates before they can open it.</p>
</div>
<Segmented legend="Visit log" name="access_log" bind:value={host.access_log} options={[{ value: "off", label: "Off" }, { value: "truncated", label: "On" }]} />
<p class="ia-hint">On keeps a log on this server, with visitor addresses shortened.</p>
{#each [{ list: "request_headers", rules: host.req, title: "Header rules sent to your service", secrets: true }, { list: "response_headers", rules: host.resp, title: "Header rules sent back to visitors", secrets: false }] as group (group.list)}
<div class="domi-field">
<span class="domi-field-label">{group.title}</span>
{#each group.rules as r, i (i)}
{@const p = `${group.list}[${i}]`}
<div class="rule ia-card">
<Segmented legend="Rule {i + 1}" name="{p}-action" bind:value={r.action} options={[{ value: "set", label: "Set" }, { value: "remove", label: "Remove" }]} />
<label class="domi-field-label" for={fieldId(p + ".name")}>Header name</label>
<input id={fieldId(p + ".name")} class="domi-input" bind:value={r.name} onblur={() => blur(p + ".name")} />
{#if r.action === "set"}
{#if group.secrets}
<Segmented legend="Value" name="{p}-kind" bind:value={r.kind} disabled={(site?.secrets.length ?? 0) === 0 ? ["secret"] : []} options={[{ value: "value", label: "Fixed value" }, { value: "secret", label: "Secret" }]} />
{/if}
{#if r.kind === "secret" && group.secrets}
<select class="domi-input" bind:value={r.secret} aria-label="Secret">
{#each site?.secrets ?? [] as s (s)}<option value={s}>{s}</option>{/each}
</select>
{:else}
<input class="domi-input" bind:value={r.value} aria-label="Value" onblur={() => blur(p + ".value")} />
{/if}
{/if}
{#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}<p class="domi-error"><Icon name="ring" />{e.message}</p>{/each}
<button type="button" class="ia-icon-btn" aria-label="Remove this rule" onclick={() => group.rules.splice(i, 1)}><Icon name="trash" /></button>
</div>
{/each}
<div><button type="button" class="domi-btn link" onclick={() => group.rules.push({ action: "set", name: "", kind: "value", value: "", secret: site?.secrets[0] ?? "" })}>Add a rule</button></div>
{#if group.secrets && (site?.secrets.length ?? 0) === 0}<p class="ia-hint">No secrets are listed in ianitor.toml.</p>{/if}
</div>
{/each}
</div>
{/if}
</form>
{/if}
{#snippet footer()}
{#if phase === "form" && !loading && !notFound}
{#if underFooter}<p class="ia-hint full" role="status">{underFooter}</p>{/if}
{#if blocked}<p class="ia-hint full" id="apply-blocked">{blocked}</p>{/if}
<Button onclick={onclose}>Cancel</Button>
<Button variant="primary" type="submit" form="host-form" disabled={!!blocked} describedby={blocked ? "apply-blocked" : undefined}>Apply</Button>
{:else if phase === "progress" && apply && FINAL.includes(apply.state)}
<Button onclick={onclose}>Close</Button>
{/if}
{/snippet}
</Dialog>
<style>
form { display: flex; flex-direction: column; gap: 16px; }
.row { display: flex; gap: 8px; align-items: center; }
.more { display: flex; flex-direction: column; gap: 16px; }
.rule { display: flex; flex-direction: column; gap: 8px; }
.narrow { max-width: 8rem; }
.full { flex-basis: 100%; }
</style>