Skip to content
File

Blob: ui/client/App.svelte

18.5 KB
1<script lang="ts">
2 import { onDestroy, tick } from "svelte";
3 import { createQuery } from "@tanstack/svelte-query";
4 import Button from "../shared/Button.svelte";
5 import Shell from "../shared/Shell.svelte";
6 import ScrollRegion from "../shared/ScrollRegion.svelte";
7 import { queryClient } from "../shared/query";
8 import DomainTokens from "./DomainTokens.svelte";
9 import CustomDomains from "./CustomDomains.svelte";
10 import WebProtection from "./WebProtection.svelte";
11 import {
12 APIError,
13 errorMessage,
14 hostnameQueryOptions,
15 requestAPI,
16 statusQueryOptions,
17 type RegisteredTunnel,
18 type SyncResult,
19 type TunnelSyncResult,
20 } from "./api";
21 
22 interface TunnelRow extends Partial<TunnelSyncResult> {
23 hostname: string;
24 target: string;
25 headerHost?: string;
26 registered: boolean;
27 }
28 
29 type RemovalAction = "unpublish" | "release";
30 type Confirmation = { action: RemovalAction; tunnel: TunnelRow; trigger: HTMLButtonElement };
31 type Notice = {
32 tone: "success" | "warning" | "error";
33 title: string;
34 detail?: string;
35 saveFailed?: boolean;
36 restore?: string | null;
37 };
38 
39 let pendingAction = $state<RemovalAction | "synchronize" | "refresh" | "">("");
40 let confirmation = $state<Confirmation | null>(null);
41 let confirmButton = $state<HTMLButtonElement>();
42 let tunnelsHeading = $state<HTMLHeadingElement>();
43 let tunnelNotice = $state<Notice | null>(null);
44 const writes = new AbortController();
45 const statusQuery = createQuery(() => ({
46 ...statusQueryOptions,
47 refetchInterval: pendingAction ? false : 15_000,
48 }));
49 const hostnameQuery = createQuery(() => ({
50 ...hostnameQueryOptions,
51 refetchInterval: pendingAction ? false : 15_000,
52 }));
53 
54 const status = $derived(statusQuery.data);
55 const registered = $derived(hostnameQuery.data);
56 const statusError = $derived(statusQuery.error?.message ?? "");
57 const listError = $derived(hostnameQuery.error?.message ?? "");
58 const refreshing = $derived(pendingAction === "refresh" || statusQuery.isLoading || hostnameQuery.isLoading);
59 const synchronization = $derived(status?.synchronization);
60 const connectedNodes = $derived(status?.connectedNodes ?? []);
61 const actionBusy = $derived(Boolean(pendingAction));
62 const unsavedChanges = $derived(Boolean(synchronization?.attemptedAt && !synchronization.saved));
63 const tunnelRows = $derived(mergeTunnels(registered, synchronization?.tunnels));
64 const configuredCount = $derived(synchronization?.tunnels?.length ?? 0);
65 const syncIssue = $derived<Notice | null>(
66 synchronization?.error || status?.pending || unsavedChanges
67 ? {
68 tone: "warning",
69 title: unsavedChanges ? "Changes not saved." : "Synchronization incomplete.",
70 detail: synchronization?.error,
71 }
72 : null,
73 );
74 const syncNotice = $derived(
75 syncIssue && tunnelNotice?.tone === "success" ? syncIssue : tunnelNotice || syncIssue,
76 );
77 
78 function mergeTunnels(hostnames: RegisteredTunnel[] | undefined, outcomes?: TunnelSyncResult[]): TunnelRow[] {
79 const rows = new Map<string, TunnelRow>();
80 for (const [index, tunnel] of (outcomes ?? []).entries()) {
81 rows.set(tunnel.hostname || `unassigned:${index}`, { ...tunnel, registered: false });
82 }
83 for (const tunnel of hostnames ?? []) {
84 const outcome = rows.get(tunnel.hostname);
85 rows.set(tunnel.hostname, {
86 ...tunnel,
87 target: outcomes ? "" : tunnel.target === "(unused)" ? "" : tunnel.target,
88 headerHost: outcome && outcome.target !== tunnel.target ? "" : tunnel.headerHost,
89 ...outcome,
90 registered: true,
91 });
92 }
93 return [...rows.values()];
94 }
95 
96 function timeLabel(value: string | number | null | undefined): string {
97 return value
98 ? new Date(value).toLocaleTimeString([], {
99 hour: "2-digit",
100 minute: "2-digit",
101 second: "2-digit",
102 })
103 : "Not checked";
104 }
105 
106 function publicationLabel(tunnel: TunnelRow): string {
107 if (!tunnel.target) return tunnel.registered ? "Reserved" : "No target";
108 if (tunnel.published && tunnel.error) return "Partially published";
109 if (tunnel.published) return "Published";
110 if (tunnel.error) return "Not published";
111 return "Not checked";
112 }
113 
114 function restorationSnippet(tunnel: TunnelRow): string {
115 return ` - hostname: ${JSON.stringify(tunnel.hostname)}\n target: ${JSON.stringify(tunnel.target || "http://127.0.0.1:8080")}${tunnel.headerHost ? `\n headerHost: ${JSON.stringify(tunnel.headerHost)}` : ""}`;
116 }
117 
118 async function refresh() {
119 if (refreshing || pendingAction) return;
120 pendingAction = "refresh";
121 await Promise.allSettled([statusQuery.refetch(), hostnameQuery.refetch()]);
122 pendingAction = "";
123 }
124 
125 async function synchronize() {
126 if (pendingAction || refreshing) return;
127 pendingAction = "synchronize";
128 tunnelNotice = null;
129 try {
130 await Promise.all([statusQueryOptions, hostnameQueryOptions].map(({ queryKey }) => queryClient.cancelQueries({ queryKey })));
131 await requestAPI("/api/reload", { method: "POST", signal: writes.signal });
132 tunnelNotice = { tone: "success", title: "Synchronized and saved." };
133 } catch (error) {
134 const outcome = error instanceof APIError ? error.data as Partial<SyncResult> | undefined : undefined;
135 if (outcome?.applied && outcome.tunnels && status) {
136 queryClient.setQueryData(statusQueryOptions.queryKey, {
137 ...status,
138 synchronization: {
139 applied: true,
140 saved: outcome.saved ?? false,
141 error: outcome.error,
142 attemptedAt: outcome.attemptedAt,
143 tunnels: outcome.tunnels,
144 },
145 }, { updatedAt: statusQuery.dataUpdatedAt });
146 }
147 tunnelNotice = {
148 tone: outcome?.applied ? "warning" : "error",
149 title: outcome?.applied
150 ? outcome.saved
151 ? "Saved; publication incomplete."
152 : "Applied; save failed."
153 : outcome
154 ? "Configuration not applied."
155 : "Synchronization result unknown.",
156 detail: errorMessage(error),
157 };
158 } finally {
159 pendingAction = "";
160 await refresh();
161 }
162 }
163 
164 async function askRemoval(action: RemovalAction, tunnel: TunnelRow, trigger: HTMLButtonElement) {
165 if (pendingAction || refreshing) return;
166 confirmation = { action, tunnel, trigger };
167 await tick();
168 confirmButton?.focus();
169 }
170 
171 function cancelRemoval() {
172 if (pendingAction) return;
173 const trigger = confirmation?.trigger;
174 confirmation = null;
175 trigger?.focus();
176 }
177 
178 async function removeTunnel() {
179 if (!confirmation || pendingAction || refreshing) return;
180 const { action, tunnel } = confirmation;
181 pendingAction = action;
182 tunnelNotice = null;
183 try {
184 await Promise.all([statusQueryOptions, hostnameQueryOptions].map(({ queryKey }) => queryClient.cancelQueries({ queryKey })));
185 await requestAPI(`/api/${action}/${encodeURIComponent(tunnel.hostname)}`, { method: "POST", signal: writes.signal });
186 tunnelNotice = {
187 tone: "success",
188 title: `${tunnel.hostname} ${action === "unpublish" ? "unpublished" : "released"}.`,
189 restore: action === "unpublish" ? restorationSnippet(tunnel) : null,
190 };
191 confirmation = null;
192 } catch (error) {
193 const outcome = error instanceof APIError ? error.data as Partial<SyncResult> | undefined : undefined;
194 const applied = outcome?.applied;
195 tunnelNotice = {
196 tone: applied ? "warning" : "error",
197 title: applied
198 ? `${tunnel.hostname} ${action === "unpublish" ? "unpublished" : "released"}; saving failed.`
199 : outcome
200 ? `Could not ${action} ${tunnel.hostname}.`
201 : `Could not confirm ${action} for ${tunnel.hostname}.`,
202 detail: errorMessage(error),
203 saveFailed: applied,
204 restore: applied && action === "unpublish" ? restorationSnippet(tunnel) : null,
205 };
206 if (applied) confirmation = null;
207 } finally {
208 pendingAction = "";
209 await refresh();
210 if (!confirmation) tunnelsHeading?.focus();
211 }
212 }
213 
214 onDestroy(() => writes.abort());
215</script>
216 
217<svelte:head>
218 <title>Specter · Client manager</title>
219 <meta name="description" content="Manage Specter tunnels and custom domains." />
220</svelte:head>
221 
222<svelte:window onkeydown={(event) => { if (event.key === "Escape") cancelRemoval(); }} />
223 
224<Shell label="Client manager" home="#main-content">
225 <section id="tunnels" class="min-w-0 scroll-mt-6" aria-labelledby="tunnels-heading">
226 <div class="mb-3.5 flex flex-col items-start justify-between gap-3.5 min-[600px]:flex-row min-[600px]:items-center min-[600px]:gap-4">
227 <h1 id="tunnels-heading" class="text-2xl leading-tight font-bold tracking-tight" bind:this={tunnelsHeading} tabindex="-1">
228 Tunnels <span class="ms-1.5 text-sm font-medium text-muted">{tunnelRows.length}</span>
229 </h1>
230 <div class="flex flex-wrap items-center gap-2">
231 <Button onclick={refresh} disabled={refreshing || actionBusy}>{refreshing ? "Refreshing…" : "Refresh"}</Button>
232 <Button variant="primary" onclick={synchronize} disabled={actionBusy || refreshing}>{pendingAction === "synchronize" ? "Synchronizing…" : "Synchronize"}</Button>
233 </div>
234 </div>
235 
236 <div class="mb-4 flex flex-col gap-2.5 border-y border-line py-2.5 min-[600px]:flex-row min-[600px]:flex-wrap min-[600px]:gap-x-8 min-[600px]:gap-y-4 [&>div]:flex [&>div]:min-w-0 [&>div]:flex-wrap [&>div]:items-center [&>div]:gap-2.5" aria-busy={statusQuery.isFetching}>
237 <div><span class="min-w-[7.625rem] text-[0.8125rem] text-muted min-[600px]:min-w-0">Server</span><span class="font-mono text-[0.8125rem] wrap-anywhere">{status?.apex || (statusError ? "Unavailable" : "Loading…")}</span></div>
238 <div>
239 <span class="min-w-[7.625rem] text-[0.8125rem] text-muted min-[600px]:min-w-0">Connected</span>
240 <span class={status && !connectedNodes.length ? 'text-warning' : ''}>
241 {#if status}<span class={['me-1.5 inline-block size-1.5 rounded-full align-[1px]', connectedNodes.length ? 'bg-success' : 'bg-warning']} aria-hidden="true"></span>{connectedNodes.length} {connectedNodes.length === 1 ? "node" : "nodes"}{:else}Not checked{/if}
242 </span>
243 </div>
244 <div><span class="min-w-[7.625rem] text-[0.8125rem] text-muted min-[600px]:min-w-0">Last sync</span><span>{synchronization?.attemptedAt ? timeLabel(synchronization.attemptedAt) : "Not attempted"}</span></div>
245 </div>
246 
247 {#if syncNotice}
248 <div class={[
249 'my-2.5 rounded-md border bg-chrome px-3 py-2 wrap-anywhere',
250 syncNotice.tone === 'success' && 'border-success/40 text-success',
251 syncNotice.tone === 'warning' && 'border-warning/40 text-warning',
252 syncNotice.tone === 'error' && 'border-danger/40 text-danger',
253 ]} role="status">
254 <strong class="font-semibold">{syncNotice.title}</strong>
255 {#if status?.pending}<span> Retry {status.retryAt ? timeLabel(status.retryAt) : "pending"}.</span>{/if}
256 {#if unsavedChanges || (syncNotice.saveFailed && statusError)}<p class="mt-1">Review the YAML before reloading or restarting.</p>{/if}
257 {#if syncNotice.detail}<details class="mt-1"><summary class="cursor-pointer text-[0.8125rem] text-zinc-200">Error details</summary><p class="mt-2">{syncNotice.detail}</p></details>{/if}
258 {#if syncNotice.restore}
259 <details class="my-2"><summary class="cursor-pointer py-1 font-medium text-zinc-200">Restore tunnel</summary><p class="mt-2">Add under <code>tunnels:</code>, restore other options, then synchronize.</p><pre class="my-3 overflow-auto rounded-md border border-line bg-chrome px-3.5 py-3 font-mono text-[0.8125rem] leading-relaxed whitespace-pre-wrap">{syncNotice.restore}</pre></details>
260 {/if}
261 </div>
262 {/if}
263 {#if statusError || listError}
264 <div class="my-2.5 rounded-md border border-danger/40 bg-chrome px-3 py-2 text-danger wrap-anywhere" role="status">
265 {#if statusError}<div><strong class="font-semibold">Status unavailable.</strong>{#if status} Snapshot {timeLabel(statusQuery.dataUpdatedAt)}.{/if}<details class="mt-1"><summary class="cursor-pointer text-[0.8125rem] text-zinc-200">Status error</summary><p class="mt-2">{statusError}</p></details></div>{/if}
266 {#if listError}<div><strong class="font-semibold">Hostnames unavailable.</strong>{#if registered} Snapshot {timeLabel(hostnameQuery.dataUpdatedAt)}.{/if}<details class="mt-1"><summary class="cursor-pointer text-[0.8125rem] text-zinc-200">Hostname error</summary><p class="mt-2">{listError}</p></details></div>{/if}
267 </div>
268 {/if}
269 
270 <div aria-busy={refreshing}>
271 {#if !registered && refreshing && !tunnelRows.length}
272 <div class="rounded-md border border-line bg-chrome px-4 py-4.5" role="status">Loading tunnels…</div>
273 {:else if tunnelRows.length === 0}
274 <div class="rounded-md border border-line bg-chrome px-4 py-4.5">{#if statusError || listError}No data. Refresh to retry.{:else}No tunnels. <a href="#configuration" class="text-accent-300 underline underline-offset-4 hover:text-accent-200">Add a target</a>, then synchronize.{/if}</div>
275 {:else}
276 <ScrollRegion label="Tunnels" class="bg-chrome">
277 <table class="w-full min-w-[760px] table-fixed border-collapse text-start [&_td]:px-3.5 [&_td]:py-2.5 [&_td]:align-top [&_td]:wrap-anywhere [&_th]:px-3.5 [&_th]:py-2.5 [&_th]:text-start [&_th]:align-top [&_th]:wrap-anywhere">
278 <thead class="text-xs text-muted [&_th]:font-medium"><tr><th class="w-1/4" scope="col">Hostname</th><th class="w-[27%]" scope="col">Local target</th><th class="w-1/4" scope="col">Publication</th><th class="w-[23%]" scope="col">Actions</th></tr></thead>
279 <tbody>
280 {#each tunnelRows as tunnel, index (tunnel.hostname || `unassigned:${index}`)}
281 <tr class="border-t border-line hover:bg-surface/50">
282 <th scope="row" class="font-medium"><span class="font-mono text-[0.8125rem]">{tunnel.hostname || "Awaiting hostname"}</span></th>
283 <td><span class={['font-mono text-[0.8125rem]', !tunnel.target && 'text-muted']}>{tunnel.target || "None"}</span>{#if tunnel.headerHost}<span class="mt-1 block text-xs text-muted">Host: <span class="font-mono">{tunnel.headerHost}</span></span>{/if}</td>
284 <td>
285 <span class={['text-[0.8125rem]', tunnel.published && !tunnel.error && 'text-success', tunnel.error && 'text-warning']}>{publicationLabel(tunnel)}</span>
286 {#if tunnel.published}<span class="mt-1 block text-xs text-muted">{tunnel.publishedEndpoints} {tunnel.publishedEndpoints === 1 ? "endpoint" : "endpoints"}</span>{/if}
287 {#if tunnel.error}<details class="mt-1"><summary class="cursor-pointer text-[0.8125rem] text-zinc-200">Error</summary><p class="mt-2 text-xs text-danger">{tunnel.error}</p></details>{/if}
288 </td>
289 <td>
290 <div class="flex flex-wrap items-center justify-end gap-1.5">
291 <Button size="sm" disabled={actionBusy || refreshing || !tunnel.hostname || !tunnel.target} aria-label={`Unpublish ${tunnel.hostname || "unassigned tunnel"}`} onclick={(event) => askRemoval("unpublish", tunnel, event.currentTarget)}>Unpublish</Button>
292 <Button size="sm" variant="danger" disabled={actionBusy || refreshing || !tunnel.hostname} aria-label={`Release ${tunnel.hostname || "unassigned tunnel"}`} onclick={(event) => askRemoval("release", tunnel, event.currentTarget)}>Release</Button>
293 </div>
294 </td>
295 </tr>
296 {#if confirmation?.tunnel.hostname === tunnel.hostname}
297 <tr class="border-t border-line bg-surface"><td colspan="4">
298 <div class="flex flex-wrap items-center justify-between gap-4" role="group" aria-label={`${confirmation.action === "unpublish" ? "Unpublish" : "Release"} ${tunnel.hostname}`}>
299 <p class="max-w-[68ch] text-zinc-300">{confirmation.action === "unpublish" ? "Remove target from YAML; keep hostname." : "Remove target from YAML; release hostname for others to claim."}</p>
300 <div class="flex flex-wrap items-center gap-2"><Button onclick={cancelRemoval} disabled={Boolean(pendingAction)}>Cancel</Button><Button bind:element={confirmButton} variant="danger" onclick={removeTunnel} disabled={actionBusy || refreshing}>{pendingAction ? "Applying…" : confirmation.action === "unpublish" ? "Confirm unpublish" : "Confirm release"}</Button></div>
301 </div>
302 </td></tr>
303 {/if}
304 {/each}
305 </tbody>
306 </table>
307 </ScrollRegion>
308 {/if}
309 </div>
310 <p class="mt-2.5 text-[0.8125rem] text-muted min-[600px]:text-xs">Publication: last acknowledgement; target health unchecked.</p>
311 </section>
312 
313 <WebProtection />
314 
315 <div class="mt-6 grid grid-cols-1 gap-7 border-t border-line pt-5 min-[600px]:grid-cols-2 min-[800px]:gap-8">
316 <CustomDomains />
317 <section id="configuration" class="min-w-0 scroll-mt-6 border-t border-line pt-5 min-[600px]:border-0 min-[600px]:pt-0" aria-labelledby="configuration-heading">
318 <h2 id="configuration-heading" class="mb-3.5 text-lg leading-snug font-semibold tracking-tight">Configuration</h2>
319 <dl class="mb-2.5 [&>div]:grid [&>div]:grid-cols-[9.375rem_minmax(0,1fr)] [&>div]:gap-4 [&>div]:py-0.5 [&_dd]:wrap-anywhere [&_dt]:text-muted">
320 <div><dt>Configured tunnels</dt><dd>{status ? configuredCount : "Unavailable"}</dd></div>
321 <div><dt>Disk state</dt><dd class={synchronization?.attemptedAt && !synchronization.saved ? 'text-warning' : ''}>{!synchronization?.attemptedAt ? "Not checked" : synchronization.saved ? "Saved" : "Unsaved"}</dd></div>
322 </dl>
323 <details class="my-2">
324 <summary class="cursor-pointer py-1 font-medium text-zinc-200">Edit tunnels</summary>
325 <pre class="my-3 overflow-auto rounded-md border border-line bg-chrome px-3.5 py-3 font-mono text-[0.8125rem] leading-relaxed whitespace-pre-wrap" aria-label="Example tunnel configuration">{"tunnels:\n - target: http://127.0.0.1:8080\n # hostname: app.example.com"}</pre>
326 <p class="mt-1.5 mb-2.5 max-w-[72ch] text-[0.8125rem] leading-relaxed text-muted">Edit your existing YAML, then synchronize. Keep credentials intact. Omit hostname for automatic assignment; otherwise use a reserved or verified hostname.</p>
327 </details>
328 </section>
329 </div>
330 
331 <DomainTokens />
332 
333 <footer class="mt-6 flex justify-end border-t border-line py-3 text-xs text-muted">{statusQuery.dataUpdatedAt ? `Checked ${timeLabel(statusQuery.dataUpdatedAt)}` : statusError ? "Status unavailable" : "Connecting…"}</footer>
334</Shell>