"use client"; import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { AlertTriangle, Check, Fingerprint, KeyRound, Loader2, Pencil, Trash2, X, } from "lucide-react"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { SettingsCard } from "@/components/settings/settings-card"; import { SettingsCardHeader } from "@/components/settings/_card-header"; import { SettingsCardActions } from "@/components/settings/_card-actions"; import { EmptyState } from "@/components/ui/empty-state"; import { formatDate } from "@/lib/format"; import { useTranslations } from "@/lib/i18n/context"; import { queryKeys } from "@/lib/query-keys"; import { ApiError, apiDelete, apiGet, apiPatch, apiPost, } from "@/lib/api/api-fetch"; import { describePasskeyError } from "@/lib/passkey-errors"; import { describeStepUp } from "./security-keys-card"; import { ReproofCancelledError, useRecentProof } from "./use-recent-proof"; interface PasskeyInfo { id: string; name: string; credentialDeviceType: string; credentialBackedUp: boolean; createdAt: string; lastUsedAt: string | null; } type ReauthMethod = "password" | "passkey" | "totp" | "webauthn"; type ExistingFactorProof = | { method: "password"; password: string } | { method: "totp"; code: string } | { method: "passkey" | "webauthn"; challengeId: string; credential: unknown; }; /** * Primary-passkey management: list (name, device, backup, created, last used), * add (registration ceremony), rename, and delete. The passwordless-primary * passkey home — distinct from the second-factor security keys above. */ export function PasskeyListSection({ isAuthenticated, }: { isAuthenticated: boolean; }) { const { t } = useTranslations(); const queryClient = useQueryClient(); const [msg, setMsg] = useState(null); const [editingId, setEditingId] = useState(null); const [editName, setEditName] = useState(""); const [reauthOpen, setReauthOpen] = useState(false); const [reauthMethod, setReauthMethod] = useState("password"); const [reauthSecret, setReauthSecret] = useState(""); const { data: passkeys } = useQuery({ queryKey: queryKeys.passkeys(), queryFn: async () => apiGet("/api/auth/passkeys"), enabled: isAuthenticated, }); const add = useMutation({ mutationFn: async ({ method, secret, }: { method: ReauthMethod; secret: string; }) => { const webauthn = await import("@simplewebauthn/browser"); let freshFactor: ExistingFactorProof; if (method === "password") { freshFactor = { method, password: secret }; } else if (method === "totp") { freshFactor = { method, code: secret }; } else { const assertionChallenge = await apiPost<{ options: Parameters< typeof webauthn.startAuthentication >[0]["optionsJSON"]; challengeId: string; }>("/api/auth/passkey/register-options", { method }); const credential = await webauthn.startAuthentication({ optionsJSON: assertionChallenge.options, }); freshFactor = { method, challengeId: assertionChallenge.challengeId, credential, }; } const { options, challengeId } = await apiPost<{ options: Parameters< typeof webauthn.startRegistration >[0]["optionsJSON"]; challengeId: string; }>("/api/auth/passkey/register-options", freshFactor); const credential = await webauthn.startRegistration({ optionsJSON: options, }); await apiPost("/api/auth/passkey/register-verify", { challengeId, credential, }); }, onSuccess: () => { setMsg(null); setReauthOpen(false); setReauthSecret(""); setReauthMethod("password"); queryClient.invalidateQueries({ queryKey: queryKeys.passkeys() }); }, onError: (err) => { if (err instanceof ApiError) { setMsg(err.message || t("settings.passkeyRegistrationFailed")); } else { const { key, params } = describePasskeyError(err); setMsg(t(key, params)); } }, }); const rename = useMutation({ mutationFn: async ({ id, name }: { id: string; name: string }) => { await apiPatch(`/api/auth/passkeys/${id}`, { name }); }, onSuccess: () => { setEditingId(null); setMsg(null); queryClient.invalidateQueries({ queryKey: queryKeys.passkeys() }); }, onError: (err: Error) => setMsg(err.message), }); // Removal is step-up gated: a second factor, or on a passkey-only account a // passkey, proved within five minutes. The server names what clears it and // the shared dialog collects that, then the removal runs again. const recentProof = useRecentProof({ description: t("settings.reproof.descriptionChange"), }); const remove = useMutation({ mutationFn: async (id: string) => { await recentProof.run(() => apiDelete(`/api/auth/passkeys/${id}`)); }, onSuccess: () => { setMsg(null); queryClient.invalidateQueries({ queryKey: queryKeys.passkeys() }); }, // A refusal the dialog could not take up keeps its own sentence. The // server's prose says "second-factor", which is wrong for the passkey-only // account this card mostly serves, so it names the recovery that always // exists on the web: sign in again. onError: (err: Error) => { if (err instanceof ReproofCancelledError) return; setMsg( describeStepUp(err, err.message, t("settings.passkeyStepUpRequired")), ); }, }); const DEVICE_TYPE_LABELS: Record = { singleDevice: t("settings.singleDevice"), multiDevice: t("settings.multiDevice"), }; return ( {recentProof.dialog}
{!passkeys || passkeys.length === 0 ? ( ) : (
    {passkeys.map((pk) => (
    {editingId === pk.id ? (
    { e.preventDefault(); rename.mutate({ id: pk.id, name: editName.trim() }); }} > setEditName(e.target.value)} maxLength={64} aria-label={t("settings.passkeyName")} autoFocus />
    ) : ( <>

    {pk.name}

    {DEVICE_TYPE_LABELS[pk.credentialDeviceType] ?? pk.credentialDeviceType} {pk.credentialBackedUp ? t("settings.backedUp") : t("common.no")} {pk.lastUsedAt ? t("settings.security.keys.lastUsed", { date: formatDate(pk.lastUsedAt), }) : t("settings.security.keys.neverUsed")}
    )}
    {editingId !== pk.id && (
    {t("settings.deletePasskey")} {t("settings.deletePasskeyDescription")} {t("common.cancel")} remove.mutate(pk.id)} > {remove.isPending && ( )} {t("common.delete")}
    )}
    ))}
)} {msg && !reauthOpen && (
{msg}
)} { if (add.isPending) return; setReauthOpen(open); if (open) setMsg(null); }} > {t("settings.passkeyReauth.title")} {t("settings.passkeyReauth.description")}
{( [ ["password", t("settings.passkeyReauth.methods.password")], ["totp", t("settings.passkeyReauth.methods.totp")], ["passkey", t("settings.passkeyReauth.methods.passkey")], ["webauthn", t("settings.passkeyReauth.methods.webauthn")], ] satisfies Array<[ReauthMethod, string]> ).map(([method, label]) => ( ))}
{reauthMethod === "password" && ( setReauthSecret(event.target.value)} placeholder={t("settings.passkeyReauth.currentPassword")} aria-label={t("settings.passkeyReauth.currentPassword")} autoFocus /> )} {reauthMethod === "totp" && ( setReauthSecret(event.target.value.replace(/\D/g, "")) } placeholder={t( "settings.passkeyReauth.authenticatorPlaceholder", )} aria-label={t("settings.passkeyReauth.authenticatorCode")} autoFocus /> )} {msg && (
{msg}
)} {t("common.cancel")} { event.preventDefault(); add.mutate({ method: reauthMethod, secret: reauthSecret, }); }} > {add.isPending && ( )} {t("settings.passkeyReauth.verifyAndAdd")}
); }