File
Blob: ui/client/DomainTokens.svelte
| 1 | <script lang="ts"> |
| 2 | import { onDestroy, tick } from "svelte"; |
| 3 | import { createQuery, queryOptions } from "@tanstack/svelte-query"; |
| 4 | import Button from "../shared/Button.svelte"; |
| 5 | import ScrollRegion from "../shared/ScrollRegion.svelte"; |
| 6 | import { INPUT_CLASSES } from "../shared/styles"; |
| 7 | import { queryClient } from "../shared/query"; |
| 8 | import { errorMessage, hostnameQueryOptions, requestAPI, type DomainToken, type MintedToken, type RevokeOutcome } from "./api"; |
| 9 | |
| 10 | const tokenOptions = queryOptions({ |
| 11 | queryKey: ['client', 'tokens'], |
| 12 | queryFn: ({ signal }) => requestAPI<DomainToken[]>('/api/tokens', { signal }), |
| 13 | }); |
| 14 | const tokens = createQuery(() => tokenOptions); |
| 15 | const hostnames = createQuery(() => hostnameQueryOptions); |
| 16 | const writes = new AbortController(); |
| 17 | let hostname = $state(""); |
| 18 | let hostnameNotice = $state(""); |
| 19 | let expiresAt = $state(""); |
| 20 | let minted = $state<MintedToken | null>(null); |
| 21 | let pending = $state<{ kind: 'refresh' | 'mint' } | { kind: 'revoke'; id: string } | null>(null); |
| 22 | let actionError = $state(""); |
| 23 | let notice = $state(""); |
| 24 | let copyNotice = $state(""); |
| 25 | let confirmation = $state<{ grant: DomainToken; trigger: HTMLButtonElement } | null>(null); |
| 26 | let cancelButton = $state<HTMLButtonElement>(); |
| 27 | let tokenInput = $state<HTMLInputElement>(); |
| 28 | let heading = $state<HTMLHeadingElement>(); |
| 29 | const grants = $derived(tokens.data); |
| 30 | const choices = $derived((hostnames.data ?? []).map((item) => item.hostname).filter(Boolean).sort((a, b) => a.localeCompare(b))); |
| 31 | const hostnamePlaceholder = $derived(!hostnames.data |
| 32 | ? hostnames.isError && !hostnames.isFetching ? "Hostnames unavailable" : "Loading hostnames…" |
| 33 | : choices.length ? "Select hostname…" : "No registered hostnames"); |
| 34 | const showHostnameHelp = $derived(Boolean(hostnames.isError || hostnameNotice || (hostnames.data && !choices.length))); |
| 35 | const refreshing = $derived(pending?.kind === "refresh" || tokens.isFetching); |
| 36 | const busy = $derived(refreshing || Boolean(pending)); |
| 37 | const canMint = $derived(!busy && choices.includes(hostname)); |
| 38 | const error = $derived(actionError || (tokens.error ? `${grants ? "Showing previous token list. " : ""}${tokens.error.message}` : "")); |
| 39 | |
| 40 | $effect(() => { |
| 41 | if (hostname && hostnames.data && !choices.includes(hostname)) { |
| 42 | hostname = ""; |
| 43 | hostnameNotice = "Selected hostname is no longer registered."; |
| 44 | } |
| 45 | }); |
| 46 | |
| 47 | async function refresh() { |
| 48 | if (busy) return; |
| 49 | pending = { kind: "refresh" }; |
| 50 | actionError = ""; |
| 51 | await Promise.allSettled([tokens.refetch(), hostnames.refetch()]); |
| 52 | pending = null; |
| 53 | if (confirmation && grants && !grants.some((grant) => grant.id === confirmation?.grant.id)) { |
| 54 | confirmation = null; |
| 55 | await tick(); |
| 56 | heading?.focus(); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | async function mint() { |
| 61 | if (!canMint) return; |
| 62 | pending = { kind: "mint" }; |
| 63 | actionError = ""; |
| 64 | notice = ""; |
| 65 | try { |
| 66 | const expiry = expiresAt ? new Date(expiresAt).toISOString() : undefined; |
| 67 | const result = await requestAPI<MintedToken>("/api/tokens", { |
| 68 | method: "POST", |
| 69 | signal: writes.signal, |
| 70 | headers: { "Content-Type": "application/json" }, |
| 71 | body: JSON.stringify({ hostname: hostname.trim(), expiresAt: expiry }), |
| 72 | }); |
| 73 | minted = result; |
| 74 | queryClient.setQueryData(tokenOptions.queryKey, (current) => current && [...current, result.grant]); |
| 75 | copyNotice = ""; |
| 76 | await tick(); |
| 77 | selectToken(); |
| 78 | } catch (cause) { |
| 79 | actionError = errorMessage(cause); |
| 80 | } finally { |
| 81 | pending = null; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | function selectToken() { |
| 86 | tokenInput?.focus(); |
| 87 | tokenInput?.select(); |
| 88 | } |
| 89 | |
| 90 | async function copy() { |
| 91 | if (!minted) return; |
| 92 | try { |
| 93 | await navigator.clipboard.writeText(minted.token); |
| 94 | copyNotice = "Token copied."; |
| 95 | } catch { |
| 96 | selectToken(); |
| 97 | copyNotice = "Token selected. Copy it using your browser or keyboard."; |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | async function askRevoke(grant: DomainToken, trigger: HTMLButtonElement) { |
| 102 | if (busy) return; |
| 103 | confirmation = { grant, trigger }; |
| 104 | await tick(); |
| 105 | cancelButton?.focus(); |
| 106 | } |
| 107 | |
| 108 | function cancelRevoke() { |
| 109 | if (pending) return; |
| 110 | const trigger = confirmation?.trigger; |
| 111 | confirmation = null; |
| 112 | trigger?.focus(); |
| 113 | } |
| 114 | |
| 115 | async function revoke() { |
| 116 | if (!confirmation || busy) return; |
| 117 | const grant = confirmation.grant; |
| 118 | pending = { kind: "revoke", id: grant.id }; |
| 119 | actionError = ""; |
| 120 | notice = ""; |
| 121 | try { |
| 122 | const result = await requestAPI<RevokeOutcome>(`/api/tokens/${encodeURIComponent(grant.id)}/revoke`, { method: "POST", signal: writes.signal }); |
| 123 | if (result.revoked) { |
| 124 | if (minted?.grant.id === grant.id) minted = null; |
| 125 | if (result.indexError) { |
| 126 | actionError = `Access revoked; list cleanup failed. Revoke again to finish: ${result.indexError}`; |
| 127 | queryClient.setQueryData(tokenOptions.queryKey, (current) => current?.map((item) => item.id === grant.id ? { ...item, incomplete: true } : item)); |
| 128 | } else { |
| 129 | queryClient.setQueryData(tokenOptions.queryKey, (current) => current?.filter((item) => item.id !== grant.id)); |
| 130 | notice = "Token revoked."; |
| 131 | } |
| 132 | confirmation = null; |
| 133 | await tick(); |
| 134 | heading?.focus(); |
| 135 | } |
| 136 | } catch (cause) { |
| 137 | actionError = errorMessage(cause); |
| 138 | } finally { |
| 139 | pending = null; |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | onDestroy(() => writes.abort()); |
| 144 | </script> |
| 145 | |
| 146 | <svelte:window onkeydown={(event) => { if (event.key === "Escape" && confirmation) cancelRevoke(); }} /> |
| 147 | |
| 148 | <section class="mt-6 min-w-0 border-t border-line pt-5" aria-labelledby="tokens-heading"> |
| 149 | <div class="mb-3.5 flex items-center justify-between gap-3"> |
| 150 | <h2 id="tokens-heading" bind:this={heading} tabindex="-1" class="text-lg leading-snug font-semibold tracking-tight">Domain tokens</h2> |
| 151 | <Button size="sm" disabled={busy} onclick={refresh}>{refreshing ? "Refreshing…" : "Refresh"}</Button> |
| 152 | </div> |
| 153 | <form class={['flex flex-wrap items-end gap-3', showHostnameHelp ? 'mb-1.5' : 'mb-3.5']} onsubmit={(event) => { event.preventDefault(); void mint(); }}> |
| 154 | <div class="min-w-0 grow basis-64"> |
| 155 | <label for="token-hostname" class="mb-1.5 block font-medium">Hostname</label> |
| 156 | <select id="token-hostname" class={INPUT_CLASSES} bind:value={hostname} onchange={() => { hostnameNotice = ""; }} disabled={Boolean(pending) || !choices.length} aria-describedby="token-hostname-help" aria-busy={hostnames.isFetching} required> |
| 157 | <option value="" disabled>{hostnamePlaceholder}</option> |
| 158 | {#each choices as host (host)}<option value={host}>{host}</option>{/each} |
| 159 | </select> |
| 160 | </div> |
| 161 | <div class="min-w-0 grow basis-56"> |
| 162 | <label for="token-expiry" class="mb-1.5 block font-medium">Expiry <span class="font-normal text-muted">(optional)</span></label> |
| 163 | <input id="token-expiry" type="datetime-local" class={INPUT_CLASSES} bind:value={expiresAt} disabled={Boolean(pending)} /> |
| 164 | </div> |
| 165 | <Button type="submit" variant="primary" disabled={!canMint}>{pending?.kind === "mint" ? "Minting…" : "Mint token"}</Button> |
| 166 | </form> |
| 167 | <p id="token-hostname-help" class={['text-[0.8125rem] text-muted', showHostnameHelp && 'mb-3.5']} aria-live="polite"> |
| 168 | {#if hostnames.isError} |
| 169 | {!hostnames.data ? "Refresh to retry." : "Using previous hostname list."} |
| 170 | {:else if hostnameNotice} |
| 171 | {hostnameNotice} |
| 172 | {:else if hostnames.data && !choices.length} |
| 173 | <a href="#configuration" class="text-accent-300 underline underline-offset-4 hover:text-accent-200">Add a tunnel</a> to register a hostname. |
| 174 | {/if} |
| 175 | </p> |
| 176 | |
| 177 | {#if minted} |
| 178 | <div class="my-3.5"> |
| 179 | <label for="minted-token" class="mb-1.5 block font-medium wrap-anywhere">New token for <span class="font-mono text-[0.8125rem]">{minted.grant.hostname}</span></label> |
| 180 | <div class="flex min-w-0 gap-2"> |
| 181 | <input id="minted-token" bind:this={tokenInput} class={[INPUT_CLASSES, 'min-w-0 font-mono text-[0.8125rem]']} readonly value={minted.token} aria-describedby="token-once" onfocus={(event) => event.currentTarget.select()} onclick={(event) => event.currentTarget.select()} /> |
| 182 | <Button disabled={pending?.kind === "mint"} onclick={copy}>Copy</Button> |
| 183 | </div> |
| 184 | <p id="token-once" class="mt-1.5 text-[0.8125rem] text-muted">Copy now; you cannot retrieve it later.</p> |
| 185 | <p class={['text-[0.8125rem] text-muted', copyNotice && 'mt-1.5']} aria-live="polite">{copyNotice}</p> |
| 186 | </div> |
| 187 | {/if} |
| 188 | |
| 189 | <div aria-live="polite" aria-busy={busy}> |
| 190 | {#if error} |
| 191 | <div class="my-2.5 rounded-md border border-danger/40 bg-chrome px-3 py-2 text-danger wrap-anywhere"> |
| 192 | {#if error.length > 180}<details open><summary class="cursor-pointer font-medium">Token request needs attention</summary><p class="mt-2">{error}</p></details>{:else}{error}{/if} |
| 193 | </div> |
| 194 | {/if} |
| 195 | {#if notice}<p class="my-2.5 text-success">{notice}</p>{/if} |
| 196 | </div> |
| 197 | |
| 198 | {#if grants?.length} |
| 199 | <ScrollRegion label="Domain tokens" class="bg-chrome"> |
| 200 | <table class="w-full min-w-[640px] table-fixed border-collapse text-start [&_td]:px-3.5 [&_td]:py-2.5 [&_td]:align-top [&_th]:px-3.5 [&_th]:py-2.5 [&_th]:text-start"> |
| 201 | <thead class="text-xs text-muted [&_th]:font-medium"><tr><th scope="col" class="w-[28%]">Hostname</th><th scope="col" class="w-[30%]">Grant ID</th><th scope="col" class="w-[26%]">Expiry</th><th scope="col" class="w-[16%]">Action</th></tr></thead> |
| 202 | <tbody> |
| 203 | {#each grants as grant (grant.id)} |
| 204 | <tr class={['border-t border-line hover:bg-surface/50', confirmation?.grant.id === grant.id && 'bg-surface']}> |
| 205 | <th scope="row" class="font-mono text-[0.8125rem] font-medium wrap-anywhere">{grant.hostname || "Unknown"}</th> |
| 206 | <td><span class="block truncate font-mono text-[0.8125rem]" title={grant.id}>{grant.id}</span></td> |
| 207 | <td class="text-[0.8125rem]">{#if grant.incomplete}<span class="text-warning">Incomplete</span>{:else}{grant.expiresAt ? new Date(grant.expiresAt).toLocaleString() : "No expiry"}{/if}</td> |
| 208 | <td><Button size="sm" variant="danger" disabled={busy} aria-label={`Revoke ${grant.id}`} aria-expanded={confirmation?.grant.id === grant.id} onclick={(event) => askRevoke(grant, event.currentTarget)}>Revoke</Button></td> |
| 209 | </tr> |
| 210 | {/each} |
| 211 | </tbody> |
| 212 | </table> |
| 213 | </ScrollRegion> |
| 214 | {:else} |
| 215 | <p class="rounded-md border border-line bg-chrome px-3.5 py-3 text-muted">{grants ? "No domain tokens." : refreshing ? "Loading tokens…" : "Token list unavailable."}</p> |
| 216 | {/if} |
| 217 | {#if confirmation} |
| 218 | <div class="mt-2.5 flex min-w-0 flex-wrap items-center justify-between gap-3 rounded-md border border-line bg-surface px-3.5 py-3" role="group" aria-label="Confirm token revocation"> |
| 219 | <div class="min-w-0 max-w-[68ch] text-zinc-300"> |
| 220 | <p class="wrap-anywhere">Revoke token{#if confirmation.grant.hostname} for <span class="font-mono text-[0.8125rem]">{confirmation.grant.hostname}</span>{/if}?</p> |
| 221 | <p class="mt-1 text-[0.8125rem] text-muted">Ends this token's access; running sidecars may take up to 2 minutes to disconnect.</p> |
| 222 | </div> |
| 223 | <div class="flex flex-wrap gap-2"><Button bind:element={cancelButton} disabled={Boolean(pending)} onclick={cancelRevoke}>Cancel</Button><Button variant="danger" disabled={busy} onclick={revoke}>{pending?.kind === "revoke" && pending.id === confirmation.grant.id ? "Revoking…" : "Confirm revoke"}</Button></div> |
| 224 | </div> |
| 225 | {/if} |
| 226 | </section> |