Files
ianitor/apps/web/src/views/Certificates.svelte
T

256 lines
12 KiB
Svelte

<!-- SPDX-License-Identifier: CPAL-1.0
- Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
- License 1.0: see LICENSE (its Exhibit A is this file's notice). -->
<script lang="ts">
// Handoff §13: Certificates → + Device → Issue (3 clicks), approval with the match code, then
// the install (the accepted 4th click). Until Custos can approve, approval is the server
// command control names (docs/pki.md).
import { onDestroy, onMount } from "svelte";
import { TextField } from "@domi/ui";
import { Banner, Button, Dialog, Icon, Segmented, Status } from "@ianitor/ui";
import HostMenu from "../components/HostMenu.svelte";
import IntermediateBanner from "../components/IntermediateBanner.svelte";
import { ApiError, del, get, post, sentence } from "../lib/api";
import { app, navigate, refresh, secondsLeft, toast } from "../lib/app.svelte";
import { atTime, shortDate } from "../lib/format";
import type { Bundle, CertsView, DeviceRow, PkiRequest } from "../lib/types";
let { newDevice }: { newDevice: boolean } = $props();
let certs = $state<CertsView | null>(null);
let problem = $state<string | null>(null);
let name = $state("");
let kind = $state<"phone" | "computer" | "app">("phone");
let nameErr = $state<string | null>(null);
let issuing = $state(false);
let request = $state<PkiRequest | null>(null);
let bundle = $state<{ device: DeviceRow | { id: string; name: string; kind: string }; b: Bundle; format: string } | null>(null);
let confirmRevoke = $state<string | null>(null);
let timer: ReturnType<typeof setTimeout> | undefined;
async function load() {
try {
certs = await get<CertsView>("/certs");
problem = null;
} catch (e) {
problem = sentence(e);
}
}
onMount(load);
onDestroy(() => clearTimeout(timer));
async function issue(e?: Event) {
e?.preventDefault();
issuing = true;
nameErr = null;
try {
request = await post<PkiRequest>("/certs/devices", { name, kind });
poll();
} catch (err) {
if (err instanceof ApiError && err.body.field === "name") nameErr = err.body.message;
else problem = sentence(err);
} finally {
issuing = false;
}
}
function poll() {
clearTimeout(timer);
timer = setTimeout(async () => {
if (!request) return;
try {
request = await get<PkiRequest>(`/pki-requests/${encodeURIComponent(request.request_id)}`);
} catch {
/* keep waiting */
}
if (request?.state === "waiting") poll();
else void load();
}, 2000);
}
async function cancelRequest() {
if (!request) return;
await del(`/pki-requests/${encodeURIComponent(request.request_id)}`).catch(() => {});
request = null;
closeForm();
}
async function install(d: { id: string; name: string; kind: string }, format: "qr" | "p12") {
try {
const b = await post<Bundle>(`/certs/devices/${encodeURIComponent(d.id)}/bundle`, { format });
bundle = { device: d, b, format };
if (format === "p12") {
// The link's GET is only a page (so link previews cannot use it up); this browser is
// signed in on the same host, so it posts to the path and saves the file itself.
const res = await fetch(new URL(b.download_url, location.href).pathname, { method: "POST", credentials: "same-origin" });
if (!res.ok) {
problem = "The install file could not be downloaded. Choose Install again for a new link.";
return;
}
const href = URL.createObjectURL(await res.blob());
const a = document.createElement("a");
a.href = href;
a.download = `${d.name}.p12`;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(href), 10_000);
}
} catch (e) {
problem = sentence(e);
}
}
async function revoke(d: DeviceRow) {
try {
await del(`/certs/devices/${encodeURIComponent(d.id)}`);
toast(`Revoked. ${d.name} can no longer get in.`);
confirmRevoke = null;
await load();
} catch (e) {
problem = sentence(e);
}
}
function closeForm() {
clearTimeout(timer);
name = "";
nameErr = null;
if (request?.state !== "approved") request = null;
navigate("/certificates");
}
const lifetime = $derived(certs?.device_lifetime_days ?? 365);
// The server caps it at the intermediate's end (Q7); without one it cannot issue anyway.
const until = $derived(shortDate(certs?.device_valid_until ?? new Date(Date.now() + lifetime * 86_400_000).toISOString()));
const capped = $derived(
!!certs?.device_valid_until && Date.parse(certs.device_valid_until) < Date.now() + (lifetime - 1) * 86_400_000,
);
const intState = $derived.by((): [import("@ianitor/ui").StatusKind, string] => {
switch (certs?.intermediate?.state) {
case "ok": return ["healthy", "valid"];
case "due": return ["degraded", "renew soon"];
case "urgent": return ["down", "renew now"];
case "expired": return ["down", "expired"];
default: return ["unknown", "not set up"];
}
});
const kindIcon = (k: string) => (k === "phone" ? "phone" : k === "computer" ? "laptop" : "app") as "phone" | "laptop" | "app";
const issuedDevice = $derived(request?.state === "approved" && request.device_id ? { id: request.device_id, name: request.name ?? name, kind } : null);
</script>
<div class="head">
<h1 class="ia-display">Certificates</h1>
<Button variant="outline" icon="plus" label="Add a device certificate" onclick={() => navigate("/certificates/new")}>Device</Button>
</div>
<IntermediateBanner />
{#if problem}<Banner tone="notice" live="status" ondismiss={() => (problem = null)}>{#snippet title()}{problem}{/snippet}</Banner>{/if}
{#if certs}
<section class="ia-card">
<p class="ia-label">Domi intermediate</p>
<p><Status kind={intState[0]} word={intState[1]} /> {#if certs.intermediate?.not_after}expires {shortDate(certs.intermediate.not_after)}{/if}</p>
<p class="ia-sub">Root stays offline ({certs.root.subject}, until {shortDate(certs.root.not_after)}).</p>
</section>
<p class="ia-label">Devices</p>
{#if certs.devices.length === 0}
<div class="ia-frame"><h2 class="ia-h3">No device certificates yet</h2><p class="ia-text2">A device certificate lets a phone, computer or Domi app into hosts that ask for one.</p></div>
{:else}
<ul class="devices">
{#each certs.devices as d (d.id)}
<li>
<Icon name={kindIcon(d.kind)} />
<span class="dname">{d.name}</span>
<span class="ia-muted">until {shortDate(d.not_after)}</span>
{#if d.state === "revoked"}<Status kind="unknown" word="revoked {d.revoked_at ? shortDate(d.revoked_at) : ''}" />{:else if d.state === "expired"}<Status kind="down" word="expired" />{:else if Date.parse(d.not_after) - app.now < 30 * 86_400_000}<Status kind="degraded" word="renew soon" />{/if}
{#if confirmRevoke === d.id}
<span class="confirm">Revoke the certificate of "{d.name}"? It can no longer get in.
<Button small onclick={() => (confirmRevoke = null)} data-autofocus>Cancel</Button>
<Button small variant="danger" onclick={() => revoke(d)}>Revoke</Button></span>
{:else if d.state === "valid"}
<HostMenu hostname={d.name} items={[
{ label: "Install on the device", icon: "key", run: () => install(d, d.kind === "computer" ? "p12" : "qr") },
{ label: "Revoke", icon: "trash", danger: true, divider: true, run: () => (confirmRevoke = d.id) },
]} />
{/if}
</li>
{/each}
</ul>
{/if}
{/if}
{#if newDevice}
<Dialog title="New device certificate" kind="panel" onclose={closeForm}>
{#if !request}
<form id="device-form" onsubmit={issue} class="form">
<TextField id="device-name" label="Device name" bind:value={name} autocomplete="off" action="send"
actionLabel="Request the certificate" clearOnSend={false} error={nameErr ?? undefined}
hint="Shown in this list and inside the certificate." />
<Segmented legend="What is it" name="kind" bind:value={kind} options={[{ value: "phone", label: "Phone or tablet" }, { value: "computer", label: "Computer" }, { value: "app", label: "Domi app" }]} />
<p class="ia-hint">{#if capped}Valid until {until}, when the Domi intermediate certificate ends (renew it to issue for a full year).{:else}Valid for {lifetime} days, until {until}.{/if} It lets this device into hosts that ask for a Domi device certificate.</p>
</form>
{:else if request.state === "waiting"}
<p class="ia-status" data-s="running"><Icon name="clock" /><strong>Waiting for approval</strong></p>
<p>Custos cannot approve device certificates yet, so approve it on the server, and only if it shows the same code:</p>
<p class="ia-code" aria-label="Match code {request.match_code}">{request.match_code}</p>
{#if request.approve_command}<p class="ia-hint">Run on the server:</p><pre class="ia-secret ia-cmd">{request.approve_command}</pre>{/if}
<p class="ia-muted">The request stays open for 10 minutes ({Math.floor(secondsLeft(request.expires_at) / 60)}:{String(secondsLeft(request.expires_at) % 60).padStart(2, "0")} left). Nothing is issued until it is approved.</p>
<div><Button onclick={cancelRequest}>Cancel request</Button></div>
<span class="sr-only" aria-live="polite">Waiting for approval. Code {request.match_code}.</span>
{:else if issuedDevice}
<Banner tone="kept" live="status">{#snippet title()}<strong>{issuedDevice.name} has a certificate.</strong> Approved {atTime(request?.approved_at, app.now)}.{/snippet}</Banner>
<div class="buttons">
<Button variant="outline" onclick={() => install(issuedDevice, "qr")}>Show QR code</Button>
<Button onclick={() => install(issuedDevice, "p12")}>Download file (.p12)</Button>
</div>
<p class="ia-hint">The file is protected with a one-time password shown next to the QR code.</p>
{:else}
<Banner tone="notice" live="status">{#snippet title()}{request?.message}{/snippet}
{#snippet actions()}<Button variant="outline" onclick={() => { request = null; void issue(); }}>Try again</Button>{/snippet}</Banner>
{/if}
{#snippet footer()}
{#if !request}
<Button onclick={closeForm}>Cancel</Button>
<Button variant="primary" type="submit" form="device-form" pending={issuing}>Issue</Button>
{:else if request.state !== "waiting"}
<Button onclick={() => { request = null; closeForm(); void load(); }}>Close</Button>
{/if}
{/snippet}
</Dialog>
{/if}
{#if bundle}
<Dialog title="Install on {bundle.device.name}" onclose={() => { bundle = null; void refresh(); }}>
<div class="install">
{#if bundle.b.qr_svg}
<div class="ia-qr" role="img" aria-label="QR code for downloading the certificate">{@html bundle.b.qr_svg}</div>
{/if}
<div>
<p class="ia-label">Password for the file</p>
<p class="otp">{bundle.b.one_time_password}</p>
<p class="ia-hint">Works once, for 10 minutes ({Math.floor(secondsLeft(bundle.b.expires_at) / 60)}:{String(secondsLeft(bundle.b.expires_at) % 60).padStart(2, "0")} left).</p>
</div>
</div>
<p class="ia-text2">
{#if bundle.device.kind === "computer"}Open the downloaded file and enter the password when it asks.
{:else if bundle.device.kind === "app"}In the app, choose Import certificate, pick the file, and enter the password.
{:else}Scan the code with the device's camera, open the link, and enter the password when it asks. Then allow the certificate in the device's settings.{/if}
</p>
</Dialog>
{/if}
<style>
.head { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; flex-wrap: wrap; }
.devices { list-style: none; margin: 0; padding: 0; border: 1px solid var(--domi-line); border-radius: var(--radius-lg); }
.devices li { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; min-height: 56px; padding: 6px 10px 6px 16px; border-top: 1px solid var(--domi-line); }
.devices li:first-child { border-top: 0; }
.dname { font-weight: 600; flex: 1 1 140px; }
.confirm { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; flex-basis: 100%; }
.form { display: flex; flex-direction: column; gap: 16px; }
.buttons { display: flex; gap: 8px; flex-wrap: wrap; }
.install { display: flex; gap: 20px; flex-wrap: wrap; align-items: flex-start; }
.otp { font-weight: 700; font-size: 1.4rem; letter-spacing: 0.08em; }
</style>