552 lines
25 KiB
Svelte
552 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 { Checkbox, Select, TextField } from "@domi/ui";
|
|
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 = "";
|
|
|
|
// Every text field carries its seal (domi-design TextField): `next` moves to the next field, and the last text
|
|
// field of the form applies it, as the Apply button does. The last one depends on what is shown.
|
|
const lastField = $derived.by(() => {
|
|
const keys = ["hostname", ...host.upstreams.map((_, i) => `upstreams[${i}]`)];
|
|
if (more) {
|
|
if (host.hc) keys.push("health_check.path");
|
|
for (const [list, rules, secrets] of [["request_headers", host.req, true], ["response_headers", host.resp, false]] as const) {
|
|
rules.forEach((r, i) => {
|
|
keys.push(`${list}[${i}].name`);
|
|
if (r.action === "set" && !(secrets && r.kind === "secret")) keys.push(`${list}[${i}].value`);
|
|
});
|
|
}
|
|
}
|
|
return keys.at(-1);
|
|
});
|
|
const seal = (key: string) =>
|
|
key === lastField ? { action: "save" as const, actionLabel: "Apply this host" } : { action: "next" as const, actionLabel: undefined };
|
|
|
|
// ---- 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="ia-field" onfocusout={() => blur("hostname")}>
|
|
<TextField id={fieldId("hostname")} label="Hostname" bind:value={host.hostname} readonly={!!hostname}
|
|
spellcheck={false} inputmode="url" autocomplete="off" {...seal("hostname")}
|
|
error={errAt("hostname") && touched["hostname"] ? errAt("hostname").message : undefined}
|
|
hint={hostname ? "To use another address, add a new host and remove this one." : undefined} />
|
|
{#if errAt("hostname") && touched["hostname"] && errAt("hostname").params?.suggestion}
|
|
<div><button type="button" class="ia-link" onclick={() => { host.hostname = errAt("hostname").params.suggestion; blur("hostname"); }}>Use {errAt("hostname").params.suggestion}</button></div>
|
|
{/if}
|
|
</div>
|
|
|
|
{#each host.upstreams as _, i (i)}
|
|
{@const f = `upstreams[${i}]`}
|
|
{@const err = errAt(f) ?? (i === 0 ? errAt("upstreams") : undefined)}
|
|
{@const shown = err && (touched[f] || touched["upstreams"])}
|
|
<div class="ia-field" onfocusout={() => blur(f)}>
|
|
<div class="row">
|
|
<div class="grow">
|
|
<TextField id={fieldId(f)} label={i === 0 ? "Send traffic to" : `Also send traffic to, address ${i + 1}`} hideLabel={i > 0}
|
|
bind:value={host.upstreams[i]} spellcheck={false} inputmode="url" autocomplete="off" {...seal(f)}
|
|
error={shown ? err.message : undefined}
|
|
hint={i === 0 && host.upstreams.length === 1 ? "Add another address later for a second server." : undefined} />
|
|
</div>
|
|
{#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 shown && err.params?.suggestion}
|
|
<div><button type="button" class="ia-link" onclick={() => { host.upstreams[i] = err.params.suggestion; blur(f); }}>Use {err.params.suggestion}</button></div>
|
|
{/if}
|
|
</div>
|
|
{/each}
|
|
<div><button type="button" class="ia-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="ia-error"><Icon name="ring" />{errAt("auth").message}</p>{/if}
|
|
|
|
<div>
|
|
<button type="button" class="ia-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="ia-field">
|
|
<span class="ia-field-label">Health check</span>
|
|
<Checkbox bind:checked={host.hc} label="Check that it answers" />
|
|
<p class="ia-hint">Ianitor asks this address regularly and shows the result on the main screen.</p>
|
|
</div>
|
|
{#if host.hc}
|
|
<div class="ia-field" onfocusout={() => blur("health_check.path")}>
|
|
<TextField id={fieldId("health_check.path")} label="Health check address" bind:value={host.hcPath} spellcheck={false}
|
|
autocomplete="off" {...seal("health_check.path")} error={errAt("health_check.path")?.message}
|
|
hint="Use an address that answers without signing in, like /health." />
|
|
</div>
|
|
<div class="ia-field">
|
|
<label class="ia-field-label" for={fieldId("health_check.interval_secs")}>Checks every</label>
|
|
<div class="row"><input id={fieldId("health_check.interval_secs")} class="ia-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="ia-error"><Icon name="ring" />{errAt("health_check.interval_secs").message}</p>{/if}
|
|
</div>
|
|
{/if}
|
|
<div class="ia-field">
|
|
<span class="ia-field-label">Websockets</span>
|
|
<Checkbox bind:checked={host.websockets} label="Allow websockets" />
|
|
<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="ia-field">
|
|
<span class="ia-field-label">Share links</span>
|
|
<Checkbox bind:checked={host.share_links} label="Allow share links" />
|
|
<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="ia-field">
|
|
<span class="ia-field-label">Device certificates</span>
|
|
<Checkbox bind:checked={host.device_certs} label="Only devices with a Domi device certificate" />
|
|
<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="ia-field">
|
|
<span class="ia-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" }]} />
|
|
<div onfocusout={() => blur(p + ".name")}>
|
|
<TextField id={fieldId(p + ".name")} label="Header name" bind:value={r.name} spellcheck={false} autocomplete="off" {...seal(p + ".name")} />
|
|
</div>
|
|
{#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 label="Secret" bind:value={r.secret} options={(site?.secrets ?? []).map((s) => ({ value: s, label: s }))} />
|
|
{:else}
|
|
<div onfocusout={() => blur(p + ".value")}>
|
|
<TextField label="Value" hideLabel bind:value={r.value} spellcheck={false} autocomplete="off" {...seal(p + ".value")} />
|
|
</div>
|
|
{/if}
|
|
{/if}
|
|
{#each Object.entries(errors).filter(([k]) => k.startsWith(p)) as [, e] (e.code + e.field)}<p class="ia-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="ia-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; }
|
|
.grow { flex: 1 1 auto; min-width: 0; }
|
|
.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>
|