From 834fdf038600813c3d3c14e3af72355732af14fd Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:04:43 +0800 Subject: [PATCH 1/2] =?UTF-8?q?ONE-447:=202FA=20=E8=AE=BE=E7=BD=AE=20UI?= =?UTF-8?q?=EF=BC=88TOTP=20+=20Passkey=20=E7=AE=A1=E7=90=86=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后台新增「安全 / 两步验证」选项卡,对接后端既有 /api/auth/passkey/* 端点,worker/ 零改动。 - web/src/lib/api.ts:新增 registerPasskey / listCredentials / deleteCredentials / getTotpStatus / totpSetup / totpEnable / totpDisable;WebAuthn 的 b64url↔二进制 转换沿用 loginPasskey 的现行手写模式,未引入 @simplewebauthn/browser。 - web/src/lib/types.ts:新增 TotpStatus / TotpSetup / PasskeyCredential 契约类型。 - web/src/components/admin/security-panel.tsx(新):TOTP 启用(二维码 + 密钥 + 验证码确认)、停用(密码二次确认,403 就地报错)、Passkey 注册/列表/清除。 - web/src/components/admin/admin-page.tsx:挂载新页签(放在「导入导出」与「系统管理」之间)。 - web/src/components/ui/alert-dialog.tsx(新):radix-nova 的 AlertDialog 原件, 破坏性操作(移除全部 Passkey)用它,不手搓确认框。 - web/package.json:新增 qrcode.react@^4.2.0(零运行时依赖、React 19 peer、 内联 SVG,不手搓二维码编码)。 安全纪律:TOTP secret 只存组件内存,不落 localStorage、不打日志、不进评论/提交。 2FA 管理这组接口不设 dev mock(与 setup 三件套同口径),避免假的「已启用」骗人。 --- pnpm-lock.yaml | 15 + web/package.json | 1 + web/src/components/admin/admin-page.tsx | 20 +- web/src/components/admin/security-panel.tsx | 608 ++++++++++++++++++++ web/src/components/ui/alert-dialog.tsx | 164 ++++++ web/src/lib/api.ts | 133 ++++- web/src/lib/types.ts | 22 + 7 files changed, 956 insertions(+), 7 deletions(-) create mode 100644 web/src/components/admin/security-panel.tsx create mode 100644 web/src/components/ui/alert-dialog.tsx diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0178df4..46de1bd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -249,6 +249,9 @@ importers: next-themes: specifier: ^0.4.6 version: 0.4.6(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + qrcode.react: + specifier: ^4.2.0 + version: 4.2.0(react@19.3.1) radix-ui: specifier: ^1.8.1 version: 1.8.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -4782,6 +4785,14 @@ packages: } engines: { node: ">=16.0.0" } + qrcode.react@4.2.0: + resolution: + { + integrity: sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==, + } + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + qs@6.16.1: resolution: { @@ -8375,6 +8386,10 @@ snapshots: pvutils@1.2.0: {} + qrcode.react@4.2.0(react@19.3.1): + dependencies: + react: 19.3.1 + qs@6.16.1: dependencies: es-define-property: 1.0.1 diff --git a/web/package.json b/web/package.json index f4d0ab4..1edb193 100644 --- a/web/package.json +++ b/web/package.json @@ -19,6 +19,7 @@ "lucide-react": "^1.61.0", "motion": "^14.6.0", "next-themes": "^0.4.6", + "qrcode.react": "^4.2.0", "radix-ui": "^1.8.1", "react": "^19.3.1", "react-dom": "^19.3.1", diff --git a/web/src/components/admin/admin-page.tsx b/web/src/components/admin/admin-page.tsx index 83d94bd..97e5636 100644 --- a/web/src/components/admin/admin-page.tsx +++ b/web/src/components/admin/admin-page.tsx @@ -1,21 +1,24 @@ -import * as React from "react"; import { ArrowLeft } from "lucide-react"; +import * as React from "react"; import { Group, Panel, Separator } from "react-resizable-panels"; -import { Button } from "@/components/ui/button"; -import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { CategoryPanel, LinkPanel } from "@/components/admin/crud-panels"; +import { SecurityPanel } from "@/components/admin/security-panel"; import { ImportExportPanel, SearchEnginePanel, SettingsPanel, } from "@/components/admin/settings-panels"; import { SystemPanel } from "@/components/admin/system-panel"; +import { Button } from "@/components/ui/button"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { useNavStore } from "@/lib/nav-store"; /** - * 后台(/admin):分类 / 链接 / 搜索引擎 / 站点设置 CRUD + 导入导出 + 系统管理, - * 列表用 dnd-kit 拖拽排序(含上移/下移键盘替代)。 - * 后台数据由 store(useNavStore.adminData)承载,本页只负责加载与分发。 + * 后台(/admin):分类 / 链接 / 搜索引擎 / 站点设置 CRUD + 导入导出 + 安全(两步验证) + * + 系统管理,列表用 dnd-kit 拖拽排序(含上移/下移键盘替代)。 + * 后台数据由 store(useNavStore.adminData)承载,本页只负责加载与分发; + * 安全区的数据(2FA 状态、Passkey 凭据)属会话期敏感数据,由 SecurityPanel 自行拉取, + * 不进全局 store。 */ export function AdminPage({ onBack }: { onBack: () => void }) { const adminData = useNavStore((s) => s.adminData); @@ -59,6 +62,7 @@ export function AdminPage({ onBack }: { onBack: () => void }) { 搜索引擎 站点设置 导入导出 + 安全 / 两步验证 系统管理 @@ -101,6 +105,10 @@ export function AdminPage({ onBack }: { onBack: () => void }) { /> + + + + diff --git a/web/src/components/admin/security-panel.tsx b/web/src/components/admin/security-panel.tsx new file mode 100644 index 0000000..631e06c --- /dev/null +++ b/web/src/components/admin/security-panel.tsx @@ -0,0 +1,608 @@ +import { + Copy, + KeyRound, + Loader2, + ShieldCheck, + ShieldOff, + Smartphone, + Trash2, +} from "lucide-react"; +import { QRCodeSVG } from "qrcode.react"; +import * as React from "react"; +import { toast } from "sonner"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Separator } from "@/components/ui/separator"; +import { + ApiError, + deleteCredentials, + getTotpStatus, + listCredentials, + registerPasskey, + totpDisable, + totpEnable, + totpSetup, +} from "@/lib/api"; +import type { PasskeyCredential, TotpSetup, TotpStatus } from "@/lib/types"; + +/** + * 后台「安全 / 两步验证」选项卡:TOTP 与 Passkey 两种第二因素的设置面。 + * + * 端点全部复用后端既有实现(worker/src/routes/passkey.ts),前端不新增契约: + * - TOTP:GET /totp 读状态 → POST /totp/setup 取 secret + otpauth URI → + * 展示二维码/密钥 → POST /totp/enable 验证码确认;停用 POST /totp/disable + * 必须再输一次账号密码(后端 403 校验)。 + * - Passkey:POST register/options → navigator.credentials.create → + * POST register/verify;GET /credentials 列表;DELETE /credentials 清除。 + * + * 敏感值纪律:secret 只活在本组件的内存状态里(不写 localStorage、不进日志、 + * 不进 console),设置流程结束或取消即丢弃;otpauth URI 只喂给二维码,不上屏。 + */ + +/** 把接口失败翻成可读文案;401 统一按会话失效处理(与后台其他区一致)。 */ +function describeError(e: unknown, fallback: string): string { + if (e instanceof ApiError) { + if (e.status === 401) return "会话已失效,请重新登录。"; + return e.detail ?? e.message ?? fallback; + } + if (e instanceof DOMException) { + if (e.name === "NotAllowedError" || e.name === "AbortError") { + return "操作已取消,或该设备/浏览器不支持 Passkey。"; + } + if (e.name === "SecurityError") { + return "当前页面不是安全上下文(需 HTTPS 或 localhost),无法使用 Passkey。"; + } + } + if (e instanceof Error && e.message === "passkey cancelled") { + return "操作已取消。"; + } + return fallback; +} + +function formatTime(value: string): string { + const time = new Date(value); + if (Number.isNaN(time.getTime())) return value; + return time.toLocaleString("zh-CN", { hour12: false }); +} + +export function SecurityPanel() { + const [totp, setTotp] = React.useState(null); + const [totpError, setTotpError] = React.useState(null); + /** 只在设置流程里存在的待确认密钥(取消/确认成功即丢弃) */ + const [setup, setSetup] = React.useState(null); + const [code, setCode] = React.useState(""); + const [busy, setBusy] = React.useState< + "totp-load" | "totp-setup" | "totp-enable" | "totp-disable" | null + >(null); + + const [credentials, setCredentials] = React.useState< + PasskeyCredential[] | null + >(null); + const [credError, setCredError] = React.useState(null); + const [passkeyBusy, setPasskeyBusy] = React.useState< + "register" | "delete" | null + >(null); + + const [disableOpen, setDisableOpen] = React.useState(false); + const [disableError, setDisableError] = React.useState(null); + const [password, setPassword] = React.useState(""); + const [confirmOpen, setConfirmOpen] = React.useState(false); + + const loadTotp = React.useCallback(async () => { + setBusy("totp-load"); + try { + setTotp(await getTotpStatus()); + setTotpError(null); + } catch (e) { + setTotpError(describeError(e, "读取两步验证状态失败,请稍后重试。")); + } finally { + setBusy(null); + } + }, []); + + const loadCredentials = React.useCallback(async () => { + try { + setCredentials(await listCredentials()); + setCredError(null); + } catch (e) { + setCredError(describeError(e, "读取 Passkey 凭据失败,请稍后重试。")); + } + }, []); + + React.useEffect(() => { + void loadTotp(); + void loadCredentials(); + }, [loadTotp, loadCredentials]); + + // ─── TOTP ────────────────────────────────────────────────────────────────── + + const startTotp = async () => { + setBusy("totp-setup"); + setTotpError(null); + try { + setSetup(await totpSetup()); + setCode(""); + } catch (e) { + setTotpError(describeError(e, "生成密钥失败,请稍后重试。")); + } finally { + setBusy(null); + } + }; + + const cancelTotp = () => { + // 丢弃待确认密钥;后端 challenge 10 分钟内自然过期 + setSetup(null); + setCode(""); + }; + + const confirmTotp = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy("totp-enable"); + setTotpError(null); + try { + await totpEnable(code.trim()); + setSetup(null); + setCode(""); + toast.success("两步验证已启用,下次登录需要输入验证码"); + await loadTotp(); + } catch (err) { + setTotpError(describeError(err, "验证码不正确,请重试。")); + } finally { + setBusy(null); + } + }; + + const disableTotp = async (e: React.FormEvent) => { + e.preventDefault(); + setBusy("totp-disable"); + setDisableError(null); + try { + await totpDisable(password); + setDisableOpen(false); + setPassword(""); + toast.success("两步验证已停用"); + await loadTotp(); + } catch (err) { + // 后端密码不对回 403:错误就地显示在确认框里(面板上的 Alert 会被弹窗遮住) + setDisableError( + err instanceof ApiError && err.status === 403 + ? "密码不正确,请重新输入。" + : describeError(err, "停用失败,请稍后重试。"), + ); + } finally { + setBusy(null); + } + }; + + const copySecret = async (secret: string) => { + try { + await navigator.clipboard.writeText(secret); + toast.success("密钥已复制到剪贴板"); + } catch { + toast.error("复制失败,请手动选择密钥文本复制"); + } + }; + + // ─── Passkey ─────────────────────────────────────────────────────────────── + + const addPasskey = async () => { + setPasskeyBusy("register"); + setCredError(null); + try { + await registerPasskey(); + toast.success("Passkey 已注册,可用它登录"); + await loadCredentials(); + } catch (e) { + setCredError(describeError(e, "注册 Passkey 失败,请稍后重试。")); + } finally { + setPasskeyBusy(null); + } + }; + + const removeAllPasskeys = async () => { + setPasskeyBusy("delete"); + setCredError(null); + try { + await deleteCredentials(); + setConfirmOpen(false); + toast.success("已清除全部 Passkey"); + await loadCredentials(); + } catch (e) { + setCredError(describeError(e, "清除 Passkey 失败,请稍后重试。")); + } finally { + setPasskeyBusy(null); + } + }; + + const webAuthnSupported = + typeof window !== "undefined" && + typeof window.PublicKeyCredential !== "undefined"; + + return ( +
+
+

安全 / 两步验证

+

+ 单人站点:这两步验证只保护你自己的账号,不影响访客看到的公开页。 +

+
+ + {/* ─── TOTP ─────────────────────────────────────────────────────────── */} + + + + + + 用 Google Authenticator、1Password、Authy 等应用生成 6 + 位验证码;开启后密码登录需再输一次验证码。 + + + + {totpError && ( + + 操作未完成 + + {totpError} + + + )} + + {!totp ? ( + totpError ? null : ( +

+

+ ) + ) : ( +
+
+ 状态 + {totp.enabled ? ( + + + ) : ( + + + )} +
+ + {totp.enabled ? ( + + ) : ( + + )} +
+ )} + + {setup && ( + <> + +
+
+ {/* 二维码由 qrcode.react 生成(内联 SVG),不手搓编码 */} + +
+ +
+

+ 用验证器 App + 扫描二维码;无法扫码时,手动录入下面的密钥(类型:基于时间)。 +

+ +
+ +
+ e.currentTarget.select()} + /> + +
+

+ 密钥等同密码,请勿截图外发;完成设置后本页不再显示。 +

+
+ +
+ + setCode(e.target.value)} + required + /> +
+ +
+ + +
+
+
+ + )} +
+
+ + {/* ─── Passkey ──────────────────────────────────────────────────────── */} + + + + + + 用设备自带的指纹 / 面容 / + 安全密钥免密登录。登录页「Passkey」页签使用这里的凭据。 + + + + {credError && ( + + 操作未完成 + + {credError} + + + )} + + {!credentials ? ( + credError ? null : ( +

+

+ ) + ) : credentials.length === 0 ? ( +

+ 还没有注册任何 Passkey。 +

+ ) : ( +
    + {credentials.map((cred, index) => ( +
  • +
    + + Passkey #{index + 1} + + + {cred.id.slice(0, 12)}…(已使用 {cred.counter} 次) + +
    + + 创建于 {formatTime(cred.createdAt)} + +
  • + ))} +
+ )} + + + +
+ + + + + + {webAuthnSupported + ? "注册时会调用系统弹窗,需 HTTPS 或 localhost。" + : "当前浏览器不支持 WebAuthn,无法注册 Passkey。"} + +
+ +

+ 移除后这些设备不能再用于登录;密码(及已启用的 TOTP)不受影响。 +

+
+
+ + {/* 停用 TOTP:二次确认 + 密码校验(后端 /totp/disable 要求密码) */} + { + setDisableOpen(open); + if (!open) { + setPassword(""); + setDisableError(null); + } + }} + > + + + 停用两步验证 + + 停用后密码登录不再需要验证码。请输入当前账号密码确认。 + + +
+ {disableError && ( + + 停用未完成 + {disableError} + + )} +
+ + setPassword(e.target.value)} + required + autoFocus + /> +
+ + + + +
+
+
+ + {/* 移除全部 Passkey:破坏性操作走 AlertDialog(不可撤销) */} + + + + 移除全部 Passkey? + + 将清除当前账号下的 {credentials?.length ?? 0} 个 Passkey + 凭据(后端 DELETE /credentials + 的实现为整账号清除,不支持单条删除)。清除后这些设备不能再用于登录,且无法撤销。 + + + + + { + e.preventDefault(); + void removeAllPasskeys(); + }} + > + {passkeyBusy === "delete" && ( + + + + +
+ ); +} diff --git a/web/src/components/ui/alert-dialog.tsx b/web/src/components/ui/alert-dialog.tsx new file mode 100644 index 0000000..12bb4f4 --- /dev/null +++ b/web/src/components/ui/alert-dialog.tsx @@ -0,0 +1,164 @@ +import * as React from "react"; +import { cn } from "cn"; +import { AlertDialog as AlertDialogPrimitive } from "radix-ui"; + +import { buttonVariants } from "@/components/ui/button"; + +/** + * Radix AlertDialog(破坏性操作确认专用):与 dialog.tsx 同一套 radix-nova 视觉, + * 关键差别是遮罩点击 / Esc 不会关闭、没有右上角关闭键、必须显式选 Action 或 Cancel。 + */ +function AlertDialog({ + ...props +}: React.ComponentProps) { + return ; +} + +function AlertDialogTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogPortal({ + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + + ); +} + +function AlertDialogHeader({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function AlertDialogFooter({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ); +} + +function AlertDialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogAction({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function AlertDialogCancel({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +export { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogOverlay, + AlertDialogPortal, + AlertDialogTitle, + AlertDialogTrigger, +}; diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index c5048cc..2fdb219 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -8,6 +8,8 @@ import type { AdminCategory, AdminLink, AdminSystem, + ImportCategory, + PasskeyCredential, PrivateData, PublicData, SearchEngine, @@ -15,7 +17,8 @@ import type { SetupResult, SetupState, SiteSettings, - ImportCategory, + TotpSetup, + TotpStatus, } from "./types"; export const USE_MOCK = import.meta.env.DEV; @@ -272,6 +275,134 @@ export async function loginPasskey(username?: string): Promise { }); } +// ─── 两步验证管理(同属 /api/auth/passkey/*,需登录会话)────────────────────── +// +// 这一组刻意没有 dev mock(与 setup 三件套同口径):TOTP secret 与 Passkey 凭据 +// 是真实安全物,mock 出来的「已启用 / 已注册」只会在联调时骗人。开发时需连真实 +// worker;未连时管理面显示错误态而非假数据。 + +export interface RegistrationOptionsJSON { + challenge: string; + rp: { id?: string; name: string }; + user: { id: string; name: string; displayName: string }; + pubKeyCredParams: { type: "public-key"; alg: number }[]; + timeout?: number; + excludeCredentials?: { id: string; type: "public-key" }[]; + authenticatorSelection?: AuthenticatorSelectionCriteria; + attestation?: AttestationConveyancePreference; +} + +/** + * Passkey 注册:POST register/options → navigator.credentials.create → register/verify。 + * WebAuthn 的 JSON ↔ 二进制转换沿用 loginPasskey 的现行手写模式(b64url ↔ ArrayBuffer), + * 不额外引入 @simplewebauthn/browser。 + */ +export async function registerPasskey(): Promise<{ credentialId: string }> { + const options = await request( + `${API.auth}/passkey/register/options`, + { method: "POST", body: JSON.stringify({}) }, + ); + + const publicKey: PublicKeyCredentialCreationOptions = { + challenge: b64urlToBuffer(options.challenge), + rp: { id: options.rp.id, name: options.rp.name }, + user: { + id: b64urlToBuffer(options.user.id), + name: options.user.name, + displayName: options.user.displayName, + }, + pubKeyCredParams: options.pubKeyCredParams, + timeout: options.timeout, + excludeCredentials: options.excludeCredentials?.map((c) => ({ + id: b64urlToBuffer(c.id), + type: "public-key" as const, + })), + authenticatorSelection: options.authenticatorSelection, + attestation: options.attestation, + }; + + const credential = (await navigator.credentials.create({ + publicKey, + })) as PublicKeyCredential | null; + if (!credential) throw new Error("passkey cancelled"); + + const attestation = credential.response as AuthenticatorAttestationResponse; + const transports = attestation.getTransports?.() ?? []; + + return request<{ credentialId: string }>( + `${API.auth}/passkey/register/verify`, + { + method: "POST", + body: JSON.stringify({ + id: credential.id, + rawId: bufferToB64url(credential.rawId), + type: credential.type, + response: { + clientDataJSON: bufferToB64url(attestation.clientDataJSON), + attestationObject: bufferToB64url(attestation.attestationObject), + ...(transports.length > 0 ? { transports } : {}), + }, + clientExtensionResults: credential.getClientExtensionResults(), + ...(credential.authenticatorAttachment + ? { authenticatorAttachment: credential.authenticatorAttachment } + : {}), + }), + }, + ); +} + +/** GET /api/auth/passkey/credentials —— 当前账号的 Passkey 凭据列表 */ +export async function listCredentials(): Promise { + const res = await request<{ credentials: PasskeyCredential[] }>( + `${API.auth}/passkey/credentials`, + { cache: "no-store" }, + ); + return res.credentials; +} + +/** + * DELETE /api/auth/passkey/credentials —— + * 后端(worker/src/routes/passkey.ts)实现是「清除该账号全部 Passkey」,没有按 id + * 删除的端点,所以前端也没有单条删除入口(契约缺口已提在 ONE-447 评论)。 + */ +export async function deleteCredentials(): Promise { + await request(`${API.auth}/passkey/credentials`, { method: "DELETE" }); +} + +/** GET /api/auth/passkey/totp —— 只读启用态 */ +export async function getTotpStatus(): Promise { + return request(`${API.auth}/passkey/totp`, { + cache: "no-store", + }); +} + +/** + * POST /api/auth/passkey/totp/setup —— 取待确认的一次性 secret + otpauth URI。 + * 返回值只在本次设置流程的内存/组件状态里用,不写 localStorage、不打日志。 + */ +export async function totpSetup(): Promise { + return request(`${API.auth}/passkey/totp/setup`, { + method: "POST", + body: JSON.stringify({}), + }); +} + +/** POST /api/auth/passkey/totp/enable —— 校验 6 位验证码并落地 secret */ +export async function totpEnable(code: string): Promise { + await request(`${API.auth}/passkey/totp/enable`, { + method: "POST", + body: JSON.stringify({ code }), + }); +} + +/** POST /api/auth/passkey/totp/disable —— 需再输一次账号密码(后端校验 403) */ +export async function totpDisable(password: string): Promise { + await request(`${API.auth}/passkey/totp/disable`, { + method: "POST", + body: JSON.stringify({ password }), + }); +} + // ─── 后台(/api/admin/*,各实体独立 CRUD)────────────────────────────────────── export interface AdminData { diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 90b7ec5..a71b8e7 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -117,6 +117,28 @@ export interface AdminSystem { ledger: string[]; } +// ─── 两步验证(/api/auth/passkey/*,字段对齐 worker/src/routes/passkey.ts)────── + +/** `GET /api/auth/passkey/totp` —— 只回启用态,绝不回 secret。 */ +export interface TotpStatus { + enabled: boolean; +} + +/** `POST /api/auth/passkey/totp/setup` —— 待确认的一次性密钥(仅存内存,不落盘不打日志)。 */ +export interface TotpSetup { + /** base32 密钥,供手动录入(等同凭据,不得写日志/评论/提交) */ + secret: string; + /** `otpauth://` URI,仅用于生成二维码 */ + uri: string; +} + +/** `GET /api/auth/passkey/credentials` 单条凭据(后端只回 id / counter / createdAt)。 */ +export interface PasskeyCredential { + id: string; + counter: number; + createdAt: string; +} + // ─── 导入导出 ───────────────────────────────────────────────────────────────── export interface ImportLink { From 1617cd363939f37f988ecd7484b0ec8ca9017b66 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:38:59 +0800 Subject: [PATCH 2/2] =?UTF-8?q?ONE-447=20=E8=BF=94=E5=B7=A5=EF=BC=9A?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E3=80=8C=E7=A7=BB=E9=99=A4=E5=85=A8=E9=83=A8?= =?UTF-8?q?=20Passkey=E3=80=8D=E7=A1=AE=E8=AE=A4=E5=BC=B9=E7=AA=97=202=20?= =?UTF-8?q?=E5=A4=84=20should-fix=20+=201=20=E5=A4=84=20nit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 评审(ONE-475:无 blocking,2 should-fix + 1 nit): 1. 取消按钮空白(无文案 / 无 Accessible Name) - `web/src/components/ui/alert-dialog.tsx`:`AlertDialogCancel` 接 children 并兜底 「取消」,原件层面杜绝空按钮。 - `web/src/components/admin/security-panel.tsx`:调用处显式传「取消」。 2. 失败报错被遮罩遮挡 - `removeAllPasskeys()` 失败改为写入独立的 `deleteError`,在 `AlertDialogContent` 内联渲染(原来写到底层卡片,模态遮罩下不可见);弹窗保持打开可重试,loading 复位; 打开/关闭弹窗时清空该错误。401 与其它失败给不同文案,不再直出后端英文原文。 3. nit:TOTP 6 位码输入过滤非数字 - `onChange` 改为 `replace(/\D/g, "").slice(0, 6)`,并去掉 `maxLength`:否则粘贴 「1 2 3 4 5 6」会先被截到 6 个字符再过滤,剩下半个码("123")。 仅前端,worker/ 零改动。 --- web/src/components/admin/security-panel.tsx | 43 ++++++++++++++++++--- web/src/components/ui/alert-dialog.tsx | 9 ++++- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/web/src/components/admin/security-panel.tsx b/web/src/components/admin/security-panel.tsx index 631e06c..13c7690 100644 --- a/web/src/components/admin/security-panel.tsx +++ b/web/src/components/admin/security-panel.tsx @@ -115,6 +115,8 @@ export function SecurityPanel() { const [disableError, setDisableError] = React.useState(null); const [password, setPassword] = React.useState(""); const [confirmOpen, setConfirmOpen] = React.useState(false); + /** 移除全部 Passkey 的失败原因:就地挂在确认弹窗内(列表侧 Alert 会被遮罩挡住) */ + const [deleteError, setDeleteError] = React.useState(null); const loadTotp = React.useCallback(async () => { setBusy("totp-load"); @@ -229,14 +231,21 @@ export function SecurityPanel() { const removeAllPasskeys = async () => { setPasskeyBusy("delete"); - setCredError(null); + setDeleteError(null); try { await deleteCredentials(); setConfirmOpen(false); + setCredError(null); toast.success("已清除全部 Passkey"); await loadCredentials(); } catch (e) { - setCredError(describeError(e, "清除 Passkey 失败,请稍后重试。")); + // 失败时弹窗保持打开,原因写在弹窗内:底层卡片的 Alert 在模态遮罩下不可见, + // 用户只会看到 loading 停住而不知道为什么失败(Tony 评审 should-fix)。 + setDeleteError( + e instanceof ApiError && e.status === 401 + ? "会话已失效,请重新登录。" + : "清除 Passkey 失败,请稍后重试。", + ); } finally { setPasskeyBusy(null); } @@ -382,9 +391,12 @@ export function SecurityPanel() { inputMode="numeric" autoComplete="one-time-code" placeholder="6 位数字" - maxLength={6} value={code} - onChange={(e) => setCode(e.target.value)} + onChange={(e) => + // 只留数字并截到 6 位:不设 maxLength,否则粘贴「1 2 3 4 5 6」 + // 会先被截成 6 个字符再过滤,剩下半个码 + setCode(e.target.value.replace(/\D/g, "").slice(0, 6)) + } required />
@@ -490,6 +502,7 @@ export function SecurityPanel() { variant="destructive" onClick={() => { setCredError(null); + setDeleteError(null); setConfirmOpen(true); }} disabled={ @@ -575,7 +588,13 @@ export function SecurityPanel() { {/* 移除全部 Passkey:破坏性操作走 AlertDialog(不可撤销) */} - + { + setConfirmOpen(open); + if (!open) setDeleteError(null); + }} + > 移除全部 Passkey? @@ -585,8 +604,20 @@ export function SecurityPanel() { 的实现为整账号清除,不支持单条删除)。清除后这些设备不能再用于登录,且无法撤销。 + + {deleteError && ( + + 清除未完成 + + {deleteError} + + + )} + - + + 取消 + ) { return ( @@ -145,7 +146,11 @@ function AlertDialogCancel({ data-slot="alert-dialog-cancel" className={cn(buttonVariants({ variant: "outline" }), className)} {...props} - /> + > + {/* 兜底文案:Cancel 不允许渲染成空按钮(无 Accessible Name,且 AlertDialog + 会拦截 Esc/遮罩,空按钮等于把用户关在弹窗里) */} + {children ?? "取消"} + ); }