feat(web): TOTP QR code and recovery codes, passkey management and passkey login

- Account & security: TOTP setup renders the otpauth URL as a QR code
  (qr-code-styling) with the secret as a fallback, shows the 8 recovery
  codes once after enabling (copy / download), and offers regenerate and
  disable (verification code or recovery code) when enabled.
- New Passkey block: add (named, @simplewebauthn/browser), rename, delete;
  hidden outside a secure context.
- Login page: "用 Passkey 登录" when a passkey is registered and the
  browser supports it; the TOTP step can switch to a recovery code.
- Account menu links to the settings block instead of its own TOTP
  dialog, so enabling always shows the recovery codes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-28 20:22:27 +08:00
1 parent b0e5d539ed
commit dd0167fe85
6 files changed
+739 -308

No files matched your search

@@ -1,9 +1,10 @@
import { PasswordChangeRequest, type SessionInfo, TotpCode } from "@umt/contracts";
import { PasswordChangeRequest, type SessionInfo } from "@umt/contracts";
import { KeyRound, LoaderCircle, LogOut, ShieldCheck, UserRound } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router";
import { toast } from "sonner";
import { z } from "zod";
import { useChangePassword, useLogout, useTotpAction, useTotpStatus } from "~/api/auth.ts";
import { useChangePassword, useLogout } from "~/api/auth.ts";
import { Button } from "~/components/ui/button.tsx";
import {
Dialog,
@@ -105,156 +106,11 @@ function ChangePasswordDialog({ open, onOpenChange }: { open: boolean; onOpenCha
);
}
/** 二次验证(TOTP):未开启 → 生成密钥 → 在验证器里添加 → 输入 6 位码确认;已开启 → 当前密码 + 验证码关闭 */
function TotpDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {
const status = useTotpStatus(open);
const action = useTotpAction();
const [setup, setSetup] = useState<{ secret: string; uri: string } | null>(null);
const [code, setCode] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const enabled = status.data?.enabled === true;
const reset = () => {
setSetup(null);
setCode("");
setPassword("");
setError(null);
};
const close = (o: boolean) => {
if (action.isPending) return;
if (!o) reset();
onOpenChange(o);
};
const begin = async () => {
setError(null);
try {
const r = await action.mutateAsync({ action: "begin" });
if (r.secret && r.otpauthUri) setSetup({ secret: r.secret, uri: r.otpauthUri });
} catch (err) {
setError(errorMessage(err));
}
};
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!TotpCode.safeParse(code).success) {
setError("验证码为 6 位数字");
return;
}
setError(null);
try {
if (enabled) {
if (!password) {
setError("输入当前密码");
return;
}
await action.mutateAsync({ action: "disable", password, code });
toast.success("已关闭二次验证");
} else {
await action.mutateAsync({ action: "enable", code });
toast.success("已开启二次验证");
}
reset();
onOpenChange(false);
} catch (err) {
setError(errorMessage(err));
}
};
const grouped = setup?.secret.replace(/(.{4})/g, "$1 ").trim();
return (
<Dialog open={open} onOpenChange={close}>
<DialogContent>
<DialogHeader>
<DialogTitle>二次验证(TOTP)</DialogTitle>
<DialogDescription>
{status.isLoading
? "读取状态…"
: enabled
? "已开启。关闭需要当前密码和验证码。"
: "未开启。开启后登录还要输入验证器里的 6 位验证码。"}
</DialogDescription>
</DialogHeader>
{!enabled && !setup ? (
<div className="grid gap-2">
{status.data?.pending ? (
<p className="text-meta text-muted-foreground">有一个未确认的密钥;重新生成会作废它。</p>
) : null}
{error ? <p className="text-meta text-destructive">{error}</p> : null}
</div>
) : (
<form id="totp-form" onSubmit={submit} className="grid gap-1" noValidate>
{setup ? (
<div className="mb-2 grid gap-1.5">
<p className="text-meta text-muted-foreground">
在验证器里手动输入下面的密钥,或粘贴 otpauth 链接。密钥只显示这一次。
</p>
<code className="rounded-md bg-muted px-2 py-1.5 font-mono text-sm break-all select-all">
{grouped}
</code>
<code className="rounded-md bg-muted px-2 py-1.5 font-mono text-meta break-all text-muted-foreground select-all">
{setup.uri}
</code>
</div>
) : null}
{enabled ? (
<FormField label="当前密码" htmlFor="totp-pwd">
<Input
id="totp-pwd"
type="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</FormField>
) : null}
<FormField label="验证码" htmlFor="totp-code" error={error ?? undefined}>
<Input
id="totp-code"
inputMode="numeric"
autoComplete="one-time-code"
maxLength={6}
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
aria-invalid={!!error}
/>
</FormField>
</form>
)}
<DialogFooter>
<Button variant="outline" onClick={() => close(false)} disabled={action.isPending}>
取消
</Button>
{!enabled && !setup ? (
<Button onClick={begin} disabled={action.isPending || status.isLoading}>
{action.isPending ? <LoaderCircle className="animate-spin" /> : null}
生成密钥
</Button>
) : (
<Button
type="submit"
form="totp-form"
variant={enabled ? "destructive" : "default"}
disabled={action.isPending}
>
{action.isPending ? <LoaderCircle className="animate-spin" /> : null}
{enabled ? "关闭二次验证" : "确认开启"}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}
/** 右上角账户弹层:当前身份、会话到期、改密、二次验证、登出 */
export function AccountMenu({ session }: { session: SessionInfo }) {
const [open, setOpen] = useState(false);
const [pwdOpen, setPwdOpen] = useState(false);
const [totpOpen, setTotpOpen] = useState(false);
const navigate = useNavigate();
const logout = useLogout();
const actor = session.actor;
const isCookie = !!session.expiresAt;
@@ -305,7 +161,8 @@ export function AccountMenu({ session }: { session: SessionInfo }) {
type="button"
onClick={() => {
setOpen(false);
setTotpOpen(true);
// 开启时要扫码、保存恢复码,放在设置页的账户与安全里做
navigate({ pathname: "/console/settings", hash: "#account/totp" });
}}
className="flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 py-2 text-left text-body text-foreground hover:bg-foreground/[0.06]"
>
@@ -329,7 +186,6 @@ export function AccountMenu({ session }: { session: SessionInfo }) {
</PopoverContent>
</Popover>
<ChangePasswordDialog open={pwdOpen} onOpenChange={setPwdOpen} />
<TotpDialog open={totpOpen} onOpenChange={setTotpOpen} />
</>
);
}