Repository Public
1"use client";2import { useState } from "react";3import { apiDelete, apiPost, type Schemas } from "@/api/client";4import { useApiList } from "@/api/query";5import { NodeLink } from "@/features/shared/nodes";6import { useI18n } from "@/i18n";7import { Banner, Button, ConfirmDialog, CopyButton, DataStamp, DataTable, Dialog, ErrorState, FreshnessBadge, KeyValue, LoadMore, SelectField, SkeletonRows, StateDot, Tag, TextAreaField, TextField, Unmeasured, type Column, type Tone } from "@/ui";8import { Gate } from "./SettingsFrame";9import { parseTtl } from "./logic";10import { useAct } from "./useAct";1112type Agent = Schemas["Agent"];13type Token = Schemas["EnrollmentToken"];14const TOKEN_TONE: Record<Token["status"], Tone> = { pending: "info", consumed: "ok", expired: "offline", revoked: "offline" };1516export function AgentsSection() {17 return <Gate permission="agents.manage"><Agents /></Gate>;18}1920function Agents() {21 const { t, fmt } = useI18n();22 const agents = useApiList("/agents", { query: { limit: 100 } }, { refetchInterval: 60_000 });23 const tokens = useApiList("/agents/enrollment-tokens", { query: { limit: 50 } });24 const { busy, act } = useAct();25 const [revoke, setRevoke] = useState<Agent | null>(null);26 const [reason, setReason] = useState("");27 const [creating, setCreating] = useState(false);28 const [revokeToken, setRevokeToken] = useState<Token | null>(null);2930 const agentCols: Column<Agent>[] = [31 { id: "node", header: t("common.node"), cell: (a) => <NodeLink id={a.node_id} alias={a.node_alias} />, sortValue: (a) => a.node_alias },32 { id: "state", header: t("common.state"), cell: (a) => (a.revoked_at ? <span title={a.revoked_reason}><StateDot tone="offline" icon="denied" label={t("settings.agents.revoked")} /></span> : <FreshnessBadge freshness={a.freshness} />), sortValue: (a) => (a.revoked_at ? "z" : a.freshness) },33 { id: "version", header: t("settings.agents.version"), mono: true, cell: (a) => a.version, sortValue: (a) => a.version },34 { id: "os", header: t("settings.agents.os"), hide: "md", cell: (a) => a.os, sortValue: (a) => a.os },35 { id: "seen", header: t("settings.agents.lastSeen"), hide: "sm", cell: (a) => (a.last_seen_at ? <time dateTime={a.last_seen_at} className="num" title={fmt.dateTime(a.last_seen_at, { seconds: true })}>{fmt.relative(a.last_seen_at)}</time> : <span className="faint">{t("common.never")}</span>), sortValue: (a) => (a.last_seen_at ? Date.parse(a.last_seen_at) : undefined) },36 { id: "caps", header: t("settings.agents.capabilities"), hide: "md", cell: (a) => (a.capabilities.length === 0 ? <span className="faint">{t("common.none")}</span> : <span className="mcc-chips">{a.capabilities.slice(0, 4).map((c) => <Tag key={c}>{c}</Tag>)}{a.capabilities.length > 4 ? <span className="faint" title={a.capabilities.join(", ")}>+{a.capabilities.length - 4}</span> : null}</span>) },37 { id: "cert", header: t("settings.agents.cert"), hide: "md", cell: (a) => <span title={`SHA-256 ${a.cert_fingerprint_sha256} · ${a.cert_serial}`}><span className="num">{fmt.date(a.cert_not_after)}</span> <span className="mono faint">{a.cert_fingerprint_sha256.slice(0, 8)}…</span></span>, sortValue: (a) => Date.parse(a.cert_not_after) },38 { id: "overhead", header: t("settings.agents.overhead"), hide: "md", align: "right", cell: (a) => (a.overhead && (a.overhead.cpu_pct !== undefined || a.overhead.rss_bytes !== undefined) ? <span>{a.overhead.cpu_pct !== undefined ? fmt.percent(a.overhead.cpu_pct, 1) : "—"} · {a.overhead.rss_bytes !== undefined ? fmt.bytes(a.overhead.rss_bytes) : "—"}</span> : <Unmeasured availability="not_observed" />) },39 { id: "act", header: t("common.actions"), srOnlyHeader: true, shrink: true, cell: (a) => (a.revoked_at ? null : <Button size="sm" variant="danger" onClick={() => { setReason(""); setRevoke(a); }} data-testid="agent-revoke">{t("settings.revoke")}</Button>) },40 ];41 const tokenCols: Column<Token>[] = [42 { id: "alias", header: t("settings.agents.nodeAlias"), mono: true, cell: (k) => k.node_alias, sortValue: (k) => k.node_alias },43 { id: "kind", header: t("common.type"), cell: (k) => t(`states.nodeKind.${k.node_kind}`) },44 { id: "status", header: t("common.state"), cell: (k) => <StateDot tone={TOKEN_TONE[k.status]} label={t(`settings.agents.tokenStatus.${k.status}`)} />, sortValue: (k) => k.status },45 { id: "created", header: t("common.created"), hide: "sm", cell: (k) => <span className="num">{fmt.dateTime(k.created_at)}</span>, sortValue: (k) => Date.parse(k.created_at) },46 { id: "expires", header: t("settings.invitations.expires"), cell: (k) => <span className="num">{fmt.relative(k.expires_at)}</span>, sortValue: (k) => Date.parse(k.expires_at) },47 { id: "act", header: t("common.actions"), srOnlyHeader: true, shrink: true, cell: (k) => (k.status === "pending" ? <Button size="sm" variant="danger" onClick={() => setRevokeToken(k)}>{t("settings.revoke")}</Button> : null) },48 ];4950 return (51 <div className="stack-lg" data-testid="screen-settings-agents">52 <section className="section" aria-labelledby="set-agents">53 <div className="section-head"><h2 id="set-agents">{t("settings.agents.title")}</h2><DataStamp at={agents.ready ? agents.updatedAt : undefined} /></div>54 <p className="muted">{t("settings.agents.intro")}</p>55 {agents.error && !agents.ready ? <ErrorState error={agents.error} onRetry={agents.refetch} /> : !agents.ready ? <SkeletonRows rows={5} /> : (56 <DataTable caption={t("settings.agents.title")} columns={agentCols} rows={agents.items} rowKey={(a) => a.id} initialSort={{ id: "node", dir: "asc" }} empty={<span className="muted">{t("settings.agents.empty")}</span>} />57 )}58 <LoadMore hasMore={agents.hasMore} loading={agents.loadingMore} onMore={agents.loadMore} />59 </section>60 <section className="section" aria-labelledby="set-tokens">61 <div className="section-head">62 <h2 id="set-tokens">{t("settings.agents.tokens")}</h2>63 <div className="row"><DataStamp at={tokens.ready ? tokens.updatedAt : undefined} /><Button variant="primary" icon="plus" onClick={() => setCreating(true)} data-testid="enroll-create">{t("settings.agents.createToken")}</Button></div>64 </div>65 <p className="muted">{t("settings.agents.tokensIntro")}</p>66 {tokens.error && !tokens.ready ? <ErrorState error={tokens.error} onRetry={tokens.refetch} /> : !tokens.ready ? <SkeletonRows rows={3} /> : (67 <DataTable caption={t("settings.agents.tokens")} columns={tokenCols} rows={tokens.items} rowKey={(k) => k.id} empty={<span className="muted">{t("settings.agents.tokensEmpty")}</span>} />68 )}69 <LoadMore hasMore={tokens.hasMore} loading={tokens.loadingMore} onMore={tokens.loadMore} />70 </section>7172 <Dialog open={revoke !== null} onClose={() => setRevoke(null)} title={t("settings.agents.revokeTitle", { node: revoke?.node_alias ?? "" })} description={t("settings.agents.revokeBody")} dismissable={!busy}73 footer={<><Button onClick={() => setRevoke(null)} disabled={busy}>{t("common.cancel")}</Button>74 <Button variant="danger" loading={busy} disabled={reason.trim() === ""} data-testid="agent-revoke-submit"75 onClick={() => { if (revoke) void act(() => apiPost("/agents/{id}/revoke", { path: { id: revoke.id }, body: { reason: reason.trim() } }), { ok: t("settings.agents.revokedDone"), invalidate: ["/agents", "/nodes"] }).then((r) => { if (r.ok) setRevoke(null); }); }}>{t("settings.revoke")}</Button></>}>76 <TextAreaField label={t("settings.agents.reason")} required value={reason} onChange={setReason} maxLength={300} />77 </Dialog>78 {creating ? <TokenDialog onClose={() => setCreating(false)} /> : null}79 <ConfirmDialog open={revokeToken !== null} onClose={() => setRevokeToken(null)} danger busy={busy} title={t("settings.agents.revokeTokenTitle")} body={revokeToken?.node_alias} confirmLabel={t("settings.revoke")}80 onConfirm={() => { if (revokeToken) void act(() => apiDelete("/agents/enrollment-tokens/{id}", { path: { id: revokeToken.id } }), { ok: t("settings.agents.tokenRevoked"), invalidate: ["/agents"] }).then(() => setRevokeToken(null)); }} />81 </div>82 );83}8485/** Creates an enrollment token and shows it once with the install command. Kept in dialog state only. */86function TokenDialog({ onClose }: { onClose: () => void }) {87 const { t, fmt } = useI18n();88 const { busy, act } = useAct();89 const [alias, setAlias] = useState("");90 const [kind, setKind] = useState<Schemas["NodeKind"]>("mac");91 const [ttl, setTtl] = useState("15");92 const [tried, setTried] = useState(false);93 const [created, setCreated] = useState<Schemas["EnrollmentTokenCreated"] | null>(null);94 const ttlValue = parseTtl(ttl);95 const aliasOk = /^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$/.test(alias.trim());96 const submit = async () => {97 setTried(true);98 if (!aliasOk || ttlValue === null) return;99 const r = await act(() => apiPost("/agents/enrollment-tokens", { body: { node_alias: alias.trim(), node_kind: kind, ttl_minutes: ttlValue } }), { invalidate: ["/agents"] });100 if (r.ok) setCreated(r.value);101 };102 if (created) {103 return (104 <Dialog open onClose={onClose} title={t("settings.agents.tokenTitle")} size="wide" dismissable={false} footer={<Button variant="primary" onClick={onClose} data-testid="enroll-done">{t("settings.invitations.done")}</Button>}>105 <Banner tone="warning" icon="warning" role="alert">{t("settings.agents.tokenWarning")}</Banner>106 <div className="stack-sm">107 <span className="caps">{t("settings.agents.installCommand")}</span>108 <pre className="mcc-log" tabIndex={0} aria-label={t("settings.agents.installCommand")} data-testid="enroll-command">{created.install_hint}</pre>109 <div className="row"><CopyButton text={created.install_hint}>{t("settings.agents.copyCommand")}</CopyButton></div>110 </div>111 <KeyValue items={[112 { label: t("settings.agents.token"), value: <span className="row-wrap"><code className="set-secret" data-testid="enroll-token">{created.token}</code><CopyButton text={created.token} /></span> },113 { label: t("settings.agents.caFingerprint"), value: <span className="row-wrap"><code className="set-secret">{created.ca_fingerprint_sha256}</code><CopyButton text={created.ca_fingerprint_sha256} /></span> },114 { label: t("settings.agents.nodeAlias"), value: <span className="mono">{created.enrollment_token.node_alias}</span> },115 { label: t("settings.invitations.expires"), value: <span className="num">{fmt.dateTime(created.enrollment_token.expires_at, { seconds: true })}</span> },116 ]} />117 </Dialog>118 );119 }120 return (121 <Dialog open onClose={onClose} title={t("settings.agents.createToken")} description={t("settings.agents.createBody")} dismissable={!busy}122 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void submit()} data-testid="enroll-submit">{t("common.create")}</Button></>}>123 <form className="mcc-form" onSubmit={(e) => { e.preventDefault(); void submit(); }} noValidate>124 <TextField label={t("settings.agents.nodeAlias")} hint={t("settings.agents.aliasHint")} required mono value={alias} onChange={setAlias} autoCapitalize="none" spellCheck={false} maxLength={63} error={tried && !aliasOk ? t("settings.agents.aliasInvalid") : undefined} data-testid="enroll-alias" />125 <div className="mcc-form-row">126 <SelectField label={t("common.type")} value={kind} onChange={setKind} options={(["mac", "linux", "nas"] as const).map((k) => ({ value: k, label: t(`states.nodeKind.${k}`) }))} />127 <TextField label={t("settings.invitations.ttl")} hint={t("settings.agents.ttlHint")} required mono inputMode="numeric" value={ttl} onChange={setTtl} error={tried && ttlValue === null ? t("settings.invitations.ttlInvalid") : undefined} />128 </div>129 </form>130 </Dialog>131 );132}133