Repository Public
1"use client";2import { useState } from "react";3import { apiDelete, apiPatch, apiPost, type Schemas } from "@/api/client";4import { ApiError } from "@/api/errors";5import { useApiList } from "@/api/query";6import { clientInfo } from "@/features/auth/client";7import { useI18n } from "@/i18n";8import { createPasskey, WebAuthnError, webauthnSupported } from "@/lib/webauthn";9import { useSession } from "@/shell/session";10import { unwrapPublicKey } from "@/shell/stepup";11import { Badge, Banner, Button, ConfirmDialog, DataStamp, Dialog, EmptyState, ErrorState, Icon, SkeletonRows, TextField, Tooltip, useErrorMessage, useToast } from "@/ui";12import { activeCount } from "./logic";13import { useAct } from "./useAct";1415type Passkey = Schemas["Passkey"];16type Session = Schemas["Session"];17type Device = Schemas["Device"];1819export function SecuritySection() {20 return (21 <div className="stack-lg" data-testid="screen-settings-security">22 <Passkeys />23 <Sessions />24 <Devices />25 </div>26 );27}2829function Passkeys() {30 const { t, fmt } = useI18n();31 const toast = useToast();32 const explain = useErrorMessage();33 const list = useApiList("/me/passkeys");34 const { busy, act } = useAct();35 const [adding, setAdding] = useState(false);36 const [label, setLabel] = useState("");37 const [addError, setAddError] = useState<string | null>(null);38 const [addBusy, setAddBusy] = useState(false);39 const [rename, setRename] = useState<Passkey | null>(null);40 const [remove, setRemove] = useState<Passkey | null>(null);41 const [lastRefused, setLastRefused] = useState(false);42 const active = activeCount(list.items);4344 const add = async () => {45 setAddBusy(true);46 setAddError(null);47 try {48 const name = label.trim() || clientInfo().label || "";49 const challenge = await apiPost("/auth/webauthn/registration/begin", { body: name ? { label: name } : {} });50 const credential = await createPasskey(unwrapPublicKey(challenge.public_key));51 await apiPost("/auth/webauthn/registration/finish", { body: { challenge_id: challenge.challenge_id, credential, ...(name ? { label: name } : {}) } });52 toast({ tone: "ok", title: t("settings.passkeys.added") });53 setAdding(false);54 setLabel("");55 list.refetch();56 } catch (e) {57 if (e instanceof WebAuthnError) setAddError(e.reason === "cancelled" ? t("settings.passkeys.addCancelled") : e.reason === "duplicate" ? t("settings.passkeys.addDuplicate") : t("settings.passkeys.addFailed"));58 else {59 const m = explain(e);60 setAddError(m.detail ? `${m.title} — ${m.detail}` : m.title);61 }62 } finally {63 setAddBusy(false);64 }65 };6667 const doRemove = async (p: Passkey) => {68 const r = await act(() => apiDelete("/me/passkeys/{id}", { path: { id: p.id } }), { ok: t("settings.passkeys.removed"), invalidate: ["/me/passkeys"], silentError: true });69 setRemove(null);70 if (!r.ok) {71 if (r.error instanceof ApiError && r.error.code === "last_passkey") setLastRefused(true);72 else toast({ tone: "critical", ...explain(r.error) });73 }74 };7576 return (77 <section className="section" aria-labelledby="set-passkeys">78 <div className="section-head">79 <h2 id="set-passkeys">{t("settings.passkeys.title")}</h2>80 <div className="row"><DataStamp at={list.ready ? list.updatedAt : undefined} /><Button icon="plus" variant="primary" onClick={() => { setAddError(null); setAdding(true); }} disabled={!webauthnSupported()} data-testid="passkey-add">{t("settings.passkeys.add")}</Button></div>81 </div>82 <p className="muted">{t("settings.passkeys.intro")}</p>83 {lastRefused ? <Banner tone="warning" role="alert"><span data-testid="passkey-last-refused">{t("settings.passkeys.lastRefused")}</span></Banner> : null}84 {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : !list.ready ? <SkeletonRows rows={2} /> : (85 <ul className="set-list" aria-label={t("settings.passkeys.title")}>86 {list.items.map((p) => {87 const last = !p.revoked_at && active <= 1;88 return (89 <li key={p.id} className="set-row" data-testid="passkey-row" data-passkey-id={p.id} data-revoked={p.revoked_at ? "true" : "false"}>90 <Icon name="passkey" size={18} />91 <div className="grow stack-sm">92 <div className="row-wrap"><strong data-testid="passkey-label">{p.label || t("settings.passkeys.unnamed")}</strong>93 {p.revoked_at ? <Badge tone="offline">{t("settings.passkeys.revoked")}</Badge> : null}94 <Badge tone="neutral" icon={p.backup_state ? "ok" : "device"}>{p.backup_state ? t("settings.passkeys.synced") : p.backup_eligible ? t("settings.passkeys.syncable") : t("settings.passkeys.deviceBound")}</Badge>95 </div>96 <div className="set-meta">97 <span>{t("settings.created", { time: fmt.dateTime(p.created_at) })}</span>98 <span>{p.last_used_at ? t("settings.passkeys.lastUsed", { time: fmt.relative(p.last_used_at) }) : t("settings.passkeys.neverUsed")}</span>99 {p.transports.length > 0 ? <span className="mono">{p.transports.join(", ")}</span> : null}100 </div>101 </div>102 {!p.revoked_at ? (103 <div className="row">104 <Button size="sm" icon="edit" onClick={() => setRename(p)} data-testid="passkey-rename">{t("settings.rename")}</Button>105 {last ? (106 <Tooltip content={t("settings.passkeys.lastProtected")} placement="end" focusable><Button size="sm" variant="danger" icon="trash" disabled data-testid="passkey-remove">{t("common.remove")}</Button></Tooltip>107 ) : <Button size="sm" variant="danger" icon="trash" onClick={() => setRemove(p)} data-testid="passkey-remove">{t("common.remove")}</Button>}108 </div>109 ) : null}110 </li>111 );112 })}113 </ul>114 )}115 <Banner tone="info" icon="shield">{t("settings.passkeys.recovery")}</Banner>116117 <Dialog open={adding} onClose={() => setAdding(false)} title={t("settings.passkeys.addTitle")} description={t("settings.passkeys.addBody")} dismissable={!addBusy}118 footer={<><Button onClick={() => setAdding(false)} disabled={addBusy}>{t("common.cancel")}</Button><Button variant="primary" icon="passkey" loading={addBusy} onClick={() => void add()} data-testid="passkey-add-submit">{t("settings.passkeys.create")}</Button></>}>119 <TextField label={t("settings.passkeys.label")} hint={t("settings.passkeys.labelHint")} value={label} onChange={setLabel} maxLength={64} data-testid="passkey-add-label" />120 {addError ? <Banner tone="critical" role="alert"><span data-testid="passkey-add-error">{addError}</span></Banner> : null}121 </Dialog>122 {rename ? <RenameDialog passkey={rename} onClose={() => setRename(null)} /> : null}123 <ConfirmDialog open={remove !== null} onClose={() => setRemove(null)} danger busy={busy} title={t("settings.passkeys.removeTitle")} body={t("settings.passkeys.removeBody", { label: remove?.label || t("settings.passkeys.unnamed") })} confirmLabel={t("common.remove")} onConfirm={() => { if (remove) void doRemove(remove); }} />124 </section>125 );126}127128function RenameDialog({ passkey, onClose }: { passkey: Passkey; onClose: () => void }) {129 const { t } = useI18n();130 const { busy, act } = useAct();131 const [label, setLabel] = useState(passkey.label);132 const invalid = label.trim().length < 1 || label.trim().length > 64;133 const save = async () => {134 const r = await act(() => apiPatch("/me/passkeys/{id}", { path: { id: passkey.id }, body: { label: label.trim() } }), { ok: t("settings.passkeys.renamed"), invalidate: ["/me/passkeys"] });135 if (r.ok) onClose();136 };137 return (138 <Dialog open onClose={onClose} title={t("settings.passkeys.renameTitle")} dismissable={!busy}139 footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} disabled={invalid} onClick={() => void save()} data-testid="passkey-rename-submit">{t("common.save")}</Button></>}>140 <form onSubmit={(e) => { e.preventDefault(); if (!invalid) void save(); }}>141 <TextField label={t("settings.passkeys.label")} value={label} onChange={setLabel} required maxLength={64} autoFocus data-testid="passkey-rename-input" />142 </form>143 </Dialog>144 );145}146147function Sessions() {148 const { t, fmt } = useI18n();149 const session = useSession();150 const list = useApiList("/me/sessions");151 const { busy, act } = useAct();152 const [target, setTarget] = useState<Session | null>(null);153 const revoke = async (s: Session) => {154 const r = await act(() => apiDelete("/me/sessions/{id}", { path: { id: s.id } }), { ok: t("settings.sessions.revoked"), invalidate: s.current ? [] : ["/me/sessions"] });155 setTarget(null);156 if (r.ok && s.current) await session.signOut();157 };158 return (159 <section className="section" aria-labelledby="set-sessions">160 <div className="section-head"><h2 id="set-sessions">{t("settings.sessions.title")}</h2><DataStamp at={list.ready ? list.updatedAt : undefined} /></div>161 <p className="muted">{t("settings.sessions.intro")}</p>162 {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : !list.ready ? <SkeletonRows rows={2} /> : list.items.length === 0 ? <EmptyState compact title={t("settings.sessions.empty")} /> : (163 <ul className="set-list" aria-label={t("settings.sessions.title")}>164 {list.items.map((s) => (165 <li key={s.id} className="set-row" data-testid="session-row" data-session-id={s.id} data-current={s.current ? "true" : "false"}>166 <Icon name={s.kind === "bearer" ? "device" : "monitor"} size={18} />167 <div className="grow stack-sm">168 <div className="row-wrap"><strong>{s.device_label || t("settings.sessions.unknownDevice")}</strong>169 {s.current ? <Badge tone="ok">{t("settings.current")}</Badge> : null}170 <Badge tone="neutral" icon={false}>{t(`settings.sessions.kind.${s.kind}`)}</Badge>171 </div>172 <div className="set-meta">173 <span>{t("settings.created", { time: fmt.dateTime(s.created_at) })}</span>174 <span>{t("settings.lastSeen", { time: fmt.relative(s.last_seen_at) })}</span>175 <span>{t("settings.sessions.idle", { time: fmt.time(s.idle_expires_at, { seconds: false }) })}</span>176 <span>{t("settings.sessions.absolute", { time: fmt.dateTime(s.absolute_expires_at) })}</span>177 {s.ip ? <span className="mono">{s.ip}</span> : null}178 {s.user_agent ? <span className="set-ua" title={s.user_agent}>{s.user_agent}</span> : null}179 </div>180 </div>181 <Button size="sm" variant="danger" onClick={() => setTarget(s)} data-testid="session-revoke">{s.current ? t("settings.sessions.signOutThis") : t("settings.revoke")}</Button>182 </li>183 ))}184 </ul>185 )}186 <ConfirmDialog open={target !== null} onClose={() => setTarget(null)} danger busy={busy} title={t("settings.sessions.revokeTitle")} body={target?.current ? t("settings.sessions.revokeCurrentBody") : t("settings.sessions.revokeBody")} confirmLabel={t("settings.revoke")} onConfirm={() => { if (target) void revoke(target); }} />187 </section>188 );189}190191function Devices() {192 const { t, fmt } = useI18n();193 const session = useSession();194 const list = useApiList("/me/devices");195 const { busy, act } = useAct();196 const [target, setTarget] = useState<Device | null>(null);197 const revoke = async (d: Device) => {198 const r = await act(() => apiDelete("/me/devices/{id}", { path: { id: d.id } }), { ok: t("settings.devices.revoked"), invalidate: ["/me/devices", "/me/sessions"] });199 setTarget(null);200 if (r.ok && d.current) await session.refresh(); // its sessions are gone: the shell returns to sign-in201 };202 return (203 <section className="section" aria-labelledby="set-devices">204 <div className="section-head"><h2 id="set-devices">{t("settings.devices.title")}</h2><DataStamp at={list.ready ? list.updatedAt : undefined} /></div>205 <p className="muted">{t("settings.devices.intro")}</p>206 {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : !list.ready ? <SkeletonRows rows={2} /> : list.items.length === 0 ? <EmptyState compact title={t("settings.devices.empty")} /> : (207 <ul className="set-list" aria-label={t("settings.devices.title")}>208 {list.items.map((d) => (209 <li key={d.id} className="set-row" data-testid="device-row" data-device-id={d.id} data-current={d.current ? "true" : "false"} data-revoked={d.revoked_at ? "true" : "false"}>210 <Icon name={d.kind === "web" ? "monitor" : "device"} size={18} />211 <div className="grow stack-sm">212 <div className="row-wrap"><strong>{d.label || t("settings.sessions.unknownDevice")}</strong>213 {d.current ? <Badge tone="ok">{t("settings.current")}</Badge> : null}214 {d.revoked_at ? <Badge tone="offline">{t("settings.devices.revokedBadge")}</Badge> : null}215 <Badge tone="neutral" icon={false}>{t(`settings.devices.kind.${d.kind}`)}</Badge>216 </div>217 <div className="set-meta">218 {d.model || d.os_version ? <span>{[d.model, d.os_version].filter(Boolean).join(" · ")}</span> : null}219 {d.app_version ? <span className="mono">{d.app_version}</span> : null}220 <span>{d.last_seen_at ? t("settings.lastSeen", { time: fmt.relative(d.last_seen_at) }) : t("settings.neverSeen")}</span>221 <span>{d.push_enabled ? t("settings.devices.pushOn", { env: d.push_env ?? "" }) : t("settings.devices.pushOff")}</span>222 </div>223 </div>224 {!d.revoked_at ? <Button size="sm" variant="danger" onClick={() => setTarget(d)} data-testid="device-revoke">{t("settings.revoke")}</Button> : null}225 </li>226 ))}227 </ul>228 )}229 <ConfirmDialog open={target !== null} onClose={() => setTarget(null)} danger busy={busy} title={t("settings.devices.revokeTitle")} body={target?.current ? t("settings.devices.revokeCurrentBody") : t("settings.devices.revokeBody")} confirmLabel={t("settings.revoke")} onConfirm={() => { if (target) void revoke(target); }} />230 </section>231 );232}233