diff --git a/README.md b/README.md index e19ab5df..196afe2b 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ AI changes code fast, so every change needs something to catch it: |---|---| | **Access & org** | RBAC (menus / buttons / data scopes) · row-level data permissions · department tree · users & roles | | **Import & export** | server-side xlsx / csv export (current filter or selected rows · large exports run in the background and notify you when done · formula-injection safe) · generic import (templates with dropdowns · preview & validation · insert only / upsert / update only · error report · all-or-nothing) · build a whole department tree from one file | -| **Sign-in & security** | captcha · lockout · password history & expiry · SMS code sign-in · two-factor auth (TOTP + recovery codes) · OAuth2 (GitHub / Google) · session management (idle timeout + absolute limit · per-client session caps · tells users why they were signed out · force sign-out) | +| **Sign-in & security** | captcha · lockout · password history & expiry · SMS code sign-in · passkey sign-in · two-factor auth (TOTP + recovery codes) · OAuth2 (GitHub / Google) · session management (idle timeout + absolute limit · per-client session caps · tells users why they were signed out · force sign-out) | | **Workspace** | customizable dashboard (cards appear by permission · layout saved per user on the server) · multi-tab (pin / drag / reload) · command palette ⌘K · shortcuts · guided tour · theme / radius / tab style · per-user time zone · Chinese & English | | **Files & storage** | file manager with previews (pdf / docx / xlsx / images / archives) · local + S3-compatible storage · pre-signed downloads · recycle bin · instant upload · chunked & resumable uploads · attachment panel for any page | | **Approval workflow** | form designer · flow tree (approve / CC / conditional branches) · approve / reject / transfer / send back / take back / add approvers · timeout reminders and auto-actions · drafts · urgent · handover · AI pre-review / form filling / AI approval nodes | @@ -174,7 +174,7 @@ The [E2E report](https://yile2020.github.io/fastapi-react-admin/e2e/) from every **Security** is on by default, and most of it needs no setup: -- Sign-in: image captcha, account and IP lockout, rate limiting, TOTP two-factor +- Sign-in: image captcha, account and IP lockout, rate limiting, TOTP two-factor, passkeys (opt-in) - Permissions: endpoints that need a permission check it and the data scope **in the backend** (hiding a button is only cosmetic); a test cross-checks permission codes between frontend, backend and menu data - Audit: sign-in log, operation log (sensitive fields redacted before storage), field-level data change records (an HMAC signature chain once the signing key is set, so changing, deleting or inserting a row is detected), kept 180 days by default - Deployment: with `ENVIRONMENT=prod` the backend **refuses to start** on weak secrets, a disabled rate limiter, or a database superuser account (the captcha follows its setting and isn't forced) diff --git a/README.zh-CN.md b/README.zh-CN.md index 50c638cf..9e31864d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -113,7 +113,7 @@ AI 改代码很快,所以每一处改动都得有东西兜底: |---|---| | **权限与组织** | RBAC(菜单 / 按钮 / 数据范围)· 行级数据权限 · 部门树 · 用户与角色 | | **导入导出** | 服务端导出 xlsx / csv(按当前筛选或勾选的行 · 大批量转后台、完成发站内消息 · 防公式注入)· 通用导入(带下拉的模板 · 预览校验 · 只新增 / 新增并更新 / 只更新 · 错误报告 · 全部成功才导入)· 一份文件建整棵部门树 | -| **登录与安全** | 图形验证码 · 失败锁定 · 密码历史与过期 · 手机验证码登录 · 二次验证(TOTP + 恢复码)· OAuth2(GitHub / Google)· 会话管理(空闲超时 + 绝对上限 · 按端限制会话数 · 被踢下线说明原因 · 强制下线) | +| **登录与安全** | 图形验证码 · 失败锁定 · 密码历史与过期 · 手机验证码登录 · 通行密钥登录 · 二次验证(TOTP + 恢复码)· OAuth2(GitHub / Google)· 会话管理(空闲超时 + 绝对上限 · 按端限制会话数 · 被踢下线说明原因 · 强制下线) | | **工作区** | 可编辑布局的工作台(卡片按权限出现 · 布局按人存服务端)· 多页签(固定 / 拖拽 / 重新加载)· 命令面板 ⌘K · 快捷键 · 功能引导 · 列表列显隐与拖拽排序(写进地址栏)· 主题色 / 圆角 / 页签外观 · 每人自己的时区 · 中英双语 | | **文件与存储** | 文件管理器 + 在线预览(pdf / docx / xlsx / 图片 / 压缩包)· 本地 + S3 兼容存储 · 预签名直连下载 · 回收站 · 秒传 · 分片上传与断点续传 · 可嵌进任何页面的附件面板 | | **审批流** | 表单设计器 · 流程树(审批 / 抄送 / 条件分支)· 同意 / 驳回 / 转交 / 退回 / 拿回 / 加签 · 超时提醒与自动处理 · 草稿 · 加急 · 离职交接 · AI 预审 / 帮填表单 / AI 审批节点 | @@ -179,7 +179,7 @@ pnpm dev # 打开 http://127.0.0. **安全**:默认开着,大部分不用配置 —— -- 登录:图形验证码、连续输错锁账号和 IP、接口限流、TOTP 二次验证 +- 登录:图形验证码、连续输错锁账号和 IP、接口限流、TOTP 二次验证、通行密钥(配置后开启) - 权限:需要权限的接口在**后端**判权限码和数据范围(前端隐藏按钮只是显示);权限码清单前后端和菜单数据之间有测试对账 - 审计:登录日志、操作日志(敏感字段先打码再落库)、字段级数据变更记录(配了签名密钥后是 HMAC 签名链,改删插一行都校验得出来),默认留存 180 天 - 部署:`ENVIRONMENT=prod` 时弱密钥、关掉接口限流、用数据库超级用户连接,后端都**拒绝启动**(验证码按参数走,不强制) diff --git a/apps/api/backend/.env.example b/apps/api/backend/.env.example index 1893b5db..e529c9ae 100644 --- a/apps/api/backend/.env.example +++ b/apps/api/backend/.env.example @@ -85,6 +85,13 @@ AI_ENCRYPT_SECRET_KEY='' # 生成:python -c "import os;print(os.urandom(32).hex())" MFA_SECRET_KEY='' +# 通行密钥(Passkey)登录:两项都配上才启用,留空 = 登录页不出按钮 +# PASSKEY_RP_ID 是站点域名(不带协议和端口);PASSKEY_ORIGINS 是打开页面的地址(带协议和端口),JSON 数组 +# ⚠️ 不能是 IP:本地开发配 localhost / ["http://localhost:8888"],并且从 http://localhost:8888 打开页面(127.0.0.1 不行) +# 生产必须是正式域名 + https,例如 PASSKEY_RP_ID='example.com'、PASSKEY_ORIGINS='["https://admin.example.com"]' +PASSKEY_RP_ID='' +PASSKEY_ORIGINS='[]' + # 数据变更记录(#260)防篡改链的签名密钥。只放这里、不进库:拿到数据库权限的人改了记录也补不出对的签名 # 留空 = 只防「手滑直接改库」。设了就别换(换了之后旧记录校验不了) # 生成:python -c "import os;print(os.urandom(32).hex())" diff --git "a/apps/api/backend/alembic/versions/20261126_2324-av000000userpasskey_\346\226\260\345\242\236\351\200\232\350\241\214\345\257\206\351\222\245\350\241\250.py" "b/apps/api/backend/alembic/versions/20261126_2324-av000000userpasskey_\346\226\260\345\242\236\351\200\232\350\241\214\345\257\206\351\222\245\350\241\250.py" new file mode 100644 index 00000000..62993b7c --- /dev/null +++ "b/apps/api/backend/alembic/versions/20261126_2324-av000000userpasskey_\346\226\260\345\242\236\351\200\232\350\241\214\345\257\206\351\222\245\350\241\250.py" @@ -0,0 +1,70 @@ +"""新增通行密钥表 + +Revision ID: av000000userpasskey +Revises: au000000aiproxydefault +Create Date: 2026-11-26 23:24:05.952749+08:00 + +通行密钥(Passkey / WebAuthn)登录:一个用户可以有多把,一把一行。唯一键是凭据 ID 的 sha256 +(`credential_hash`)—— 凭据 ID 最长 1364 个字符,直接建唯一索引在 MySQL utf8mb4 下超过索引长度上限。 +不带菜单:管理在个人中心,管理员重置挂在用户管理的行操作上(超管)。 +""" + +import sqlalchemy as sa + +from alembic import op + +import backend.common.model + +# revision identifiers, used by Alembic. +revision = 'av000000userpasskey' +down_revision = 'au000000aiproxydefault' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + 'sys_user_passkey', + sa.Column('id', sa.BigInteger(), autoincrement=False, nullable=False, comment='雪花算法主键 ID'), + sa.Column('user_id', sa.BigInteger(), nullable=False, comment='用户 ID'), + sa.Column( + 'name', + backend.common.model.UniversalStr(length=64), + nullable=False, + comment='名称(用户自己起的,如「我的手机」)', + ), + sa.Column('credential_hash', sa.String(length=64), nullable=False, comment='凭据 ID 的 sha256(唯一键)'), + sa.Column( + 'credential_id', backend.common.model.UniversalText(), nullable=False, comment='凭据 ID(base64url)' + ), + sa.Column( + 'public_key', backend.common.model.UniversalText(), nullable=False, comment='公钥(COSE,base64url)' + ), + sa.Column('sign_count', sa.BigInteger(), nullable=False, comment='签名计数(防克隆)'), + sa.Column('transports', sa.String(length=128), nullable=True, comment='传输方式,逗号分隔'), + sa.Column('aaguid', sa.String(length=36), nullable=True, comment='认证器型号(AAGUID)'), + sa.Column('backed_up', sa.Boolean(), nullable=False, comment='是否已同步备份(云端 Passkey)'), + sa.Column( + 'last_used_time', + backend.common.model.TimeZone(timezone=True), + nullable=True, + comment='最近一次用它登录的时间', + ), + sa.Column('created_time', backend.common.model.TimeZone(timezone=True), nullable=False, comment='创建时间'), + sa.Column('updated_time', backend.common.model.TimeZone(timezone=True), nullable=True, comment='更新时间'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('credential_hash'), + comment='用户通行密钥表', + ) + op.create_index(op.f('ix_sys_user_passkey_id'), 'sys_user_passkey', ['id'], unique=True) + op.create_index(op.f('ix_sys_user_passkey_user_id'), 'sys_user_passkey', ['user_id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_sys_user_passkey_user_id'), table_name='sys_user_passkey') + op.drop_index(op.f('ix_sys_user_passkey_id'), table_name='sys_user_passkey') + op.drop_table('sys_user_passkey') + # ### end Alembic commands ### diff --git a/apps/api/backend/app/admin/AGENTS.md b/apps/api/backend/app/admin/AGENTS.md index 577dfd8c..8b6d49f2 100644 --- a/apps/api/backend/app/admin/AGENTS.md +++ b/apps/api/backend/app/admin/AGENTS.md @@ -344,3 +344,57 @@ SQL Server 2022(`sys.identity_columns` 对这张表 0 行)/ MySQL 8.4;之 `test_export.py::test_a_failed_delete_commit_keeps_the_file`(修前文件已删)· `test_dict_cache_after_commit.py::test_atomic_false_still_swallows_a_key_builder_error_when_a_session_is_passed`(修前 `UnboundLocalError`), 三条修前红、修后绿。`test_revoke_after_commit.py` 的先后断言改成记在最外层 `after_commit` 上(原来记在 `before_commit`,证明不了「提交成功之后」),修后照绿。 + +## 通行密钥(Passkey / WebAuthn)登录 + +`service/passkey_service.py` · `auth_service.passkey_login` · 表 `sys_user_passkey`(迁移 `av000000userpasskey`)· 依赖 `webauthn`(py_webauthn)。 +前端:登录页 `apps/web/src/routes/_guest/-passkey-sign-in.tsx` · 个人中心 `pages/profile/passkey-block.tsx` · 用户管理「安全」抽屉的「清除全部通行密钥」(超管)· +浏览器侧 `packages/platform/src/auth/passkey.ts`(用原生的 WebAuthn L3 JSON 方法,不引 simplewebauthn)。 + +配置:`PASSKEY_RP_ID` + `PASSKEY_ORIGINS` 两项都配才启用(`.env`,不在参数配置里);prod 启动检查要求正式域名 + https、来源主机属于 RP ID(`core/conf.py: _check_passkey`)。 + +| 设计 | 不这样做会怎样 | +|---|---| +| 只做**不先输用户名**的流程(可发现凭据,登录挑战不带 `allowCredentials`) | 先输用户名再要挑战,「这个账号有没有通行密钥」就从挑战里漏出去了(同手机登录的防枚举) | +| 注册和登录都**要求用户验证(UV)** | 捡到一把没锁的安全钥匙就能登 | +| 通行密钥登录**不再走二次验证**(`mfa_gate`),被强制开 MFA 的人也一样 | 带 UV 的通行密钥本身就是两个因素;再要动态码等于白做(这是刻意的) | +| 挑战存 Redis、`GETDEL` 一次性 | 截下来的断言在挑战有效期内能重放 | +| 失败对外一律「通行密钥无效」,原因只进日志;只计入 **IP** 失败,不计入账号 | 区分原因就是凭据核对器;按账号计等于谁都能把别人锁住 | +| 唯一键是凭据 ID 的 sha256,不是凭据 ID | 凭据 ID 最长 1364 字符,MySQL utf8mb4 下唯一索引超长 | +| RP ID / 来源**只从配置读**,不从请求头推 | 换个域名访问就是另一个站;钓鱼代理能改 Host | +| 审计单独登记成「通行密钥」对象(名称 + 所属用户),钥匙材料和计数类列全忽略 | 一对多没法像二次验证那样折叠成用户上的开关;计数每次登录都写,记了就是刷屏 | + +### 🔴 本地开发要从 `localhost` 打开页面,不能用 `127.0.0.1` + +RP ID 不能是 IP:从 `http://127.0.0.1:8888` 打开时浏览器直接 `SecurityError: This is an invalid domain.`,界面上是「当前网址不能使用通行密钥」。 +而硬纪律里「浏览器要开 `127.0.0.1:8888`」(refresh cookie 跨站)那条依然成立 —— 所以开发 / 实测通行密钥时**前后端都换成 localhost**: +后端 `PASSKEY_RP_ID=localhost PASSKEY_ORIGINS='["http://localhost:8888"]'`,前端 `VITE_API_BASE=http://localhost:8088`,页面开 `http://localhost:8888`。 +现有 E2E 全在 `127.0.0.1` 上,通行密钥没有进 E2E 套件(要单开一套 localhost 的配置)。 + +### 🔴 ego 浏览器测不了 WebAuthn,用 Playwright Chromium + CDP 虚拟认证器 + +ego(定制 Chromium)里 `navigator.credentials.create()` 3 毫秒就 `NotAllowedError`,加了 CDP 虚拟认证器、开了焦点模拟也一样 —— 它屏蔽了 WebAuthn。 +Playwright 自带的 Chromium 正常:`ctx.newCDPSession(page)` → `WebAuthn.enable` → `WebAuthn.addVirtualAuthenticator` +(`ctap2` / `internal` / `hasResidentKey` / `hasUserVerification` / `isUserVerified` / `automaticPresenceSimulation`)。⚠️ 虚拟认证器按 CDP 会话生效,启用和使用要在同一个会话里。 + +### 🔴 注册时的用户句柄要读库,不能读登录快照(浏览器实测抓到的) + +**症状**:个人中心「添加」成功,用它登录一律「通行密钥无效」,后端日志「userHandle 和它所属的用户对不上」。 +**根因**:注册时用户句柄(`user.uuid`)取自 `request.user` —— Redis 里的登录快照;登录时按凭据查库里的用户、拿库里的 uuid 比。 +本机几套库(`fba` / `fba_test` / 私有库)共用一个 Redis、管理员的雪花 ID 相同,快照里的 uuid 是别的库写进去的。正常部署不会两边不一致,但注册不该依赖缓存里的字段。 +**修法**:`passkey_service._from_db` 注册时从库里重读用户,**必须包 `bypass_data_scope()`** —— 已登录请求里 DAO 套着当前用户的数据范围, +STAFF 这类「开了过滤、没有规则」的人连自己都查不到(同上面「用户快照」一节刷新 token 那条;第一版没包,测试成片 404)。 +**实测证据**:`test_registration_uses_the_uuid_in_the_database_not_the_cached_snapshot`(篡改 Redis 快照里的 uuid 再注册、登录): +改回用快照 → 这条红;去掉 `bypass_data_scope` → 18 条红。 + +**实测证据**(2026-11-26,PostgreSQL 私有库 + Redis): +- `tests/api_v1/test_passkey.py` 28 条,浏览器那一侧是纯 Python 的软件认证器(P-256,按规范拼 authenticatorData / clientDataJSON / 签名),走真实接口和真的 py_webauthn 校验。 + 变异 12 处各自红:登录不要 UV · 来源放行任意 · 不核对 userHandle · 挑战不作废 · 仍走二次验证 · 失败计入账号 · 查无凭据换一句话 · 注册不要 UV · + 不查账号状态 · 公钥按普通列记审计 · 注册用快照 · 去掉 `bypass_data_scope`。 + ⚠️ 第一版有两处变异没红:「挑战只能用一次」第二次交的是同一份断言(计数没增长,本来就会被拒);「查无 / 已删同一句」只两者互比(它们走同一个分支)—— 改成新签的断言、和固定文案比之后才红 +- 浏览器(Playwright Chromium 1234 + CDP 虚拟认证器,真实前后端,localhost)9 步:登录页有按钮 → 密码登录 → 个人中心添加(认证器里多了一把 `rpId=localhost` 的可发现凭据)→ + 同一台设备再加被拒「已经添加过了」→ 清掉会话后用通行密钥登录进工作台,refresh cookie 可用 → 认证器拒绝用户验证时提示「已取消,或者等太久超时了」→ + 从 `127.0.0.1` 打开点按钮提示「当前网址不能使用通行密钥」→ 删除 → 删掉后再登录「通行密钥无效」 +- 迁移在 PostgreSQL 私有库上 up → down → up;MySQL / SQL Server 没在真库上跑过迁移(CI 的 SQL Server job 会跑模型 ↔ 迁移的一致性检查) + +**没验过**:真实平台认证器(Windows Hello / Touch ID / 安卓)· 手机扫码的跨设备(hybrid)流程 · Safari / Firefox · 桌面端和手机 App(入口隐藏:桌面端渲染层在 `app://local` 上,RP ID 对不上 —— 按规范推出,没实测)。 diff --git a/apps/api/backend/app/admin/api/v1/auth/auth.py b/apps/api/backend/app/admin/api/v1/auth/auth.py index 21be71b7..1833cc29 100644 --- a/apps/api/backend/app/admin/api/v1/auth/auth.py +++ b/apps/api/backend/app/admin/api/v1/auth/auth.py @@ -6,8 +6,10 @@ from starlette.background import BackgroundTasks from backend.app.admin.schema.mfa import MfaChallenge, MfaChallengeParam, MfaSetupInfo, MfaTokenParam +from backend.app.admin.schema.passkey import GetPasskeyAvailability, PasskeyLoginOptions, PasskeyLoginParam from backend.app.admin.schema.token import GetLoginToken, GetMfaEnrollToken, GetNewToken, GetSwaggerToken from backend.app.admin.schema.user import AuthLoginParam, AuthPhoneCaptchaParam, AuthPhoneLoginParam +from backend.app.admin.service import passkey_service from backend.app.admin.service.auth_service import auth_service from backend.common.response.response_schema import ResponseModel, ResponseSchemaModel, response_base from backend.common.security.jwt import DependsJwtAuth @@ -96,6 +98,49 @@ async def phone_login( return response_base.success(data=data) +# ── 通行密钥(Passkey / WebAuthn)登录:三个都是匿名接口 ── + + +@router.get( + '/passkey/enabled', + summary='通行密钥登录开没开(登录页据此决定出不出按钮)', + dependencies=[Depends(RateLimiter(Rate(30, Duration.MINUTE)))], +) +async def passkey_enabled() -> ResponseSchemaModel[GetPasskeyAvailability]: + return response_base.success(data=GetPasskeyAvailability(enabled=passkey_service.enabled())) + + +@router.post( + '/passkey/options', + summary='通行密钥登录:取挑战', + description=( + '不带用户名(可发现凭据)。`options` 原样交给浏览器的 PublicKeyCredential.parseRequestOptionsFromJSON()' + ), + dependencies=[Depends(RateLimiter(Rate(10, Duration.MINUTE)))], +) +async def passkey_login_options() -> ResponseSchemaModel[PasskeyLoginOptions]: + return response_base.success(data=await passkey_service.login_options()) + + +@router.post( + '/passkey/login', + summary='通行密钥登录:交断言', + description='通行密钥要求了用户验证(指纹 / 面容 / PIN),所以这条路不再走二次验证', + dependencies=[Depends(RateLimiter(Rate(10, Duration.MINUTE)))], +) +async def passkey_login( + db: CurrentSessionTransaction, + request: Request, + response: Response, + obj: PasskeyLoginParam, + background_tasks: BackgroundTasks, +) -> ResponseSchemaModel[GetLoginToken]: + data = await auth_service.passkey_login( + db=db, request=request, response=response, obj=obj, background_tasks=background_tasks + ) + return response_base.success(data=data) + + # ── 二次验证(#181):登录第二步。三个都是匿名接口,凭第一步给的 `mfa_token` ── diff --git a/apps/api/backend/app/admin/api/v1/sys/user.py b/apps/api/backend/app/admin/api/v1/sys/user.py index 41e9e383..f53ef99f 100644 --- a/apps/api/backend/app/admin/api/v1/sys/user.py +++ b/apps/api/backend/app/admin/api/v1/sys/user.py @@ -1,4 +1,4 @@ -from typing import Annotated +from typing import Annotated, Any from fastapi import APIRouter, BackgroundTasks, Body, Depends, File, Path, Query, Request, UploadFile from fastapi.responses import Response @@ -15,6 +15,7 @@ from backend.app.admin.schema.export_job import GetExportJobDetail, StartExportParam from backend.app.admin.schema.login_log import GetLoginLogDetail from backend.app.admin.schema.mfa import GetMfaStatus, MfaOtpParam, MfaRecoveryCodes, MfaSetupInfo +from backend.app.admin.schema.passkey import GetPasskeyDetail, PasskeyNameParam, PasskeyRegisterParam from backend.app.admin.schema.role import GetRoleDetail from backend.app.admin.schema.user import ( AddUserParam, @@ -29,6 +30,7 @@ GetUserPreferenceDetail, PutUserPreferenceParam, ) +from backend.app.admin.service import passkey_service from backend.app.admin.service.export_service import export_service from backend.app.admin.service.import_service import import_service from backend.app.admin.service.login_log_service import login_log_service @@ -482,3 +484,62 @@ async def reset_user_mfa( ) -> ResponseModel: await mfa_service.admin_reset(db, pk) return response_base.success() + + +# ── 通行密钥(Passkey):个人中心自助 + 管理员重置 ── +# 只能管自己的:路径里没有用户 ID,别人的那一把按「不存在」处理(404) + + +@router.get('/me/passkeys', summary='获取当前用户的通行密钥', dependencies=[DependsJwtAuth]) +async def get_my_passkeys(db: CurrentSession, request: Request) -> ResponseSchemaModel[list[GetPasskeyDetail]]: + rows = await passkey_service.list_mine(db, request.user.id) + return response_base.success(data=[GetPasskeyDetail.model_validate(r) for r in rows]) + + +@router.post( + '/me/passkeys/options', + summary='添加通行密钥:取注册挑战', + description='`options` 原样交给浏览器的 PublicKeyCredential.parseCreationOptionsFromJSON()', + dependencies=[DependsJwtAuth, Depends(RateLimiter(Rate(10, Duration.MINUTE)))], +) +async def passkey_registration_options(db: CurrentSession, request: Request) -> ResponseSchemaModel[dict[str, Any]]: + return response_base.success(data=await passkey_service.registration_options(db, request.user)) + + +@router.post( + '/me/passkeys', + summary='添加通行密钥:交注册结果', + dependencies=[DependsJwtAuth, Depends(RateLimiter(Rate(10, Duration.MINUTE)))], +) +async def register_my_passkey( + db: CurrentSessionTransaction, request: Request, obj: PasskeyRegisterParam +) -> ResponseSchemaModel[GetPasskeyDetail]: + row = await passkey_service.register(db, request.user, obj.name, obj.credential) + return response_base.success(data=GetPasskeyDetail.model_validate(row)) + + +@router.put('/me/passkeys/{pk}', summary='给自己的通行密钥改名', dependencies=[DependsJwtAuth]) +async def rename_my_passkey( + db: CurrentSessionTransaction, + request: Request, + pk: Annotated[int, Path(description='通行密钥 ID')], + obj: PasskeyNameParam, +) -> ResponseModel: + await passkey_service.rename(db, request.user.id, pk, obj.name) + return response_base.success() + + +@router.delete('/me/passkeys/{pk}', summary='删除自己的一把通行密钥', dependencies=[DependsJwtAuth]) +async def delete_my_passkey( + db: CurrentSessionTransaction, request: Request, pk: Annotated[int, Path(description='通行密钥 ID')] +) -> ResponseModel: + await passkey_service.remove(db, request.user.id, pk) + return response_base.success() + + +@router.delete('/{pk}/passkeys', summary='清掉用户的全部通行密钥(设备丢了)', dependencies=[DependsSuperUser]) +async def reset_user_passkeys( + db: CurrentSessionTransaction, pk: Annotated[int, Path(description='用户 ID')] +) -> ResponseModel: + await passkey_service.admin_reset(db, pk) + return response_base.success() diff --git a/apps/api/backend/app/admin/data_change.py b/apps/api/backend/app/admin/data_change.py index 0d34e68b..57b9fdec 100644 --- a/apps/api/backend/app/admin/data_change.py +++ b/apps/api/backend/app/admin/data_change.py @@ -10,7 +10,7 @@ from collections.abc import Mapping from typing import Any -from backend.app.admin.model import DataRule, DataScope, Dept, Menu, Role, Storage, User, UserMfa +from backend.app.admin.model import DataRule, DataScope, Dept, Menu, Role, Storage, User, UserMfa, UserPasskey from backend.app.admin.model.m2m import data_scope_rule, role_data_scope, role_menu, user_role from backend.common.data_change import ChildValue, Ref, register_audited, register_audited_child, register_audited_set @@ -55,6 +55,31 @@ ) +# 通行密钥:一个用户可以有多把,单独记成一类对象(名字 + 所属用户)—— 一对多没法像二次验证那样折叠成用户上的开关。 +# 「谁给这个账号加了一把通行密钥」「管理员清掉了他的通行密钥」都有记录;凭据 ID / 公钥是钥匙材料, +# 记了没有可读的意义;计数和最近使用时间每次登录都写,记了就是刷屏 +register_audited( + UserPasskey, + entity='user_passkey', + title='通行密钥', + label='name', + fields={'name': '名称'}, + refs={'user_id': ('所属用户', Ref('sys_user', 'username'))}, + ignore={ + 'credential_hash', + 'credential_id', + 'public_key', + 'sign_count', + 'transports', + 'aaguid', + 'backed_up', + 'last_used_time', + 'created_time', + 'updated_time', + }, +) + + def _recovery_batch(row: Mapping[str, Any]) -> frozenset[str]: """这一批恢复码是哪几个(哈希)。重新生成会换掉整批;登录时用掉一个只是标上「用过」,不算改""" try: diff --git a/apps/api/backend/app/admin/model/__init__.py b/apps/api/backend/app/admin/model/__init__.py index aa36202a..70f25def 100644 --- a/apps/api/backend/app/admin/model/__init__.py +++ b/apps/api/backend/app/admin/model/__init__.py @@ -17,5 +17,6 @@ from backend.app.admin.model.storage import Storage as Storage from backend.app.admin.model.user import User as User from backend.app.admin.model.user_mfa import UserMfa as UserMfa +from backend.app.admin.model.user_passkey import UserPasskey as UserPasskey from backend.app.admin.model.user_password_history import UserPasswordHistory as UserPasswordHistory from backend.app.admin.model.user_preference import UserPreference as UserPreference diff --git a/apps/api/backend/app/admin/model/user_passkey.py b/apps/api/backend/app/admin/model/user_passkey.py new file mode 100644 index 00000000..79e5a2f2 --- /dev/null +++ b/apps/api/backend/app/admin/model/user_passkey.py @@ -0,0 +1,37 @@ +from datetime import datetime + +import sqlalchemy as sa + +from sqlalchemy.orm import Mapped, mapped_column + +from backend.common.model import DataClassBase, DateTimeMixin, TimeZone, UniversalStr, UniversalText, id_key + + +# 通行密钥(Passkey / WebAuthn):一个用户可以有多把(手机、电脑、安全钥匙各一把),一把一行。 +# +# 🔴 **唯一键是 `credential_hash`(凭据 ID 的 sha256),不是 `credential_id` 本身。** 规范允许凭据 ID 长到 1023 字节 +# (base64url 1364 个字符),直接建唯一索引在 MySQL utf8mb4 下超出 3072 字节的索引上限;按哈希查也一样快。 +# +# 公钥不是秘密(它只能验签),但也不进审计表 —— 记了没有任何可读的意义(见 `app/admin/data_change.py`)。 +# `sign_count` 每次登录都写,用来发现被克隆的认证器:新的计数不大于库里的就拒 +# (两边都是 0 时不比 —— 同步型 Passkey 恒为 0)。 +# +# 硬删:删掉就是这把钥匙不能再登录,没有「还原」的需要 +# +# ⚠️ 类 docstring 保持一行(会原样成为表注释) +class UserPasskey(DataClassBase, DateTimeMixin): + """用户通行密钥表""" + + __tablename__ = 'sys_user_passkey' + + id: Mapped[id_key] = mapped_column(init=False) + user_id: Mapped[int] = mapped_column(sa.BigInteger, index=True, comment='用户 ID') + name: Mapped[str] = mapped_column(UniversalStr(64), comment='名称(用户自己起的,如「我的手机」)') + credential_hash: Mapped[str] = mapped_column(sa.String(64), unique=True, comment='凭据 ID 的 sha256(唯一键)') + credential_id: Mapped[str] = mapped_column(UniversalText, comment='凭据 ID(base64url)') + public_key: Mapped[str] = mapped_column(UniversalText, comment='公钥(COSE,base64url)') + sign_count: Mapped[int] = mapped_column(sa.BigInteger, default=0, comment='签名计数(防克隆)') + transports: Mapped[str | None] = mapped_column(sa.String(128), default=None, comment='传输方式,逗号分隔') + aaguid: Mapped[str | None] = mapped_column(sa.String(36), default=None, comment='认证器型号(AAGUID)') + backed_up: Mapped[bool] = mapped_column(default=False, comment='是否已同步备份(云端 Passkey)') + last_used_time: Mapped[datetime | None] = mapped_column(TimeZone, default=None, comment='最近一次用它登录的时间') diff --git a/apps/api/backend/app/admin/schema/passkey.py b/apps/api/backend/app/admin/schema/passkey.py new file mode 100644 index 00000000..57ba9f50 --- /dev/null +++ b/apps/api/backend/app/admin/schema/passkey.py @@ -0,0 +1,67 @@ +import json + +from datetime import datetime +from typing import Any, Literal + +from pydantic import ConfigDict, Field, field_validator + +from backend.common.schema import SchemaBase + +#: 浏览器给的凭据 JSON 正常是 1~2 KB;放得宽一点,但不让人塞一个几 MB 的对象进来让服务端去解析 +_CREDENTIAL_MAX_BYTES = 32 * 1024 + + +def _bounded(value: dict[str, Any]) -> dict[str, Any]: + if len(json.dumps(value, ensure_ascii=False)) > _CREDENTIAL_MAX_BYTES: + raise ValueError('credential 太大') + return value + + +class GetPasskeyDetail(SchemaBase): + """通行密钥(只下发展示要用的,公钥 / 凭据 ID 不出网)""" + + model_config = ConfigDict(from_attributes=True) + + id: int = Field(description='通行密钥 ID') + name: str = Field(description='名称') + backed_up: bool = Field(description='是否已同步备份(云端 Passkey,换设备也能用)') + transports: str | None = Field(None, description='传输方式,逗号分隔(internal / hybrid / usb …)') + created_time: datetime = Field(description='添加时间') + last_used_time: datetime | None = Field(None, description='最近一次用它登录的时间') + + +class PasskeyNameParam(SchemaBase): + """改名""" + + name: str = Field(min_length=1, max_length=64, description='名称') + + +class PasskeyRegisterParam(PasskeyNameParam): + """添加:`navigator.credentials.create()` 的结果""" + + credential: dict[str, Any] = Field(description='PublicKeyCredential.toJSON() 的结果') + + _check = field_validator('credential')(_bounded) + + +class PasskeyLoginOptions(SchemaBase): + """登录第一步:挑战。`options` 原样交给 `PublicKeyCredential.parseRequestOptionsFromJSON()`""" + + challenge_id: str = Field(description='挑战编号,第二步原样带回') + options: dict[str, Any] = Field(description='WebAuthn 的 PublicKeyCredentialRequestOptions(JSON 形式)') + + +class PasskeyLoginParam(SchemaBase): + """登录第二步:`navigator.credentials.get()` 的结果""" + + challenge_id: str = Field(min_length=16, max_length=64, description='第一步给的挑战编号') + credential: dict[str, Any] = Field(description='PublicKeyCredential.toJSON() 的结果') + client: Literal['web', 'desktop', 'mobile'] = Field('web', description='登录端') + + _check = field_validator('credential')(_bounded) + + +class GetPasskeyAvailability(SchemaBase): + """登录页据此决定出不出「用通行密钥登录」按钮""" + + enabled: bool = Field(description='服务端是否配置了通行密钥(PASSKEY_RP_ID + PASSKEY_ORIGINS)') diff --git a/apps/api/backend/app/admin/service/auth_service.py b/apps/api/backend/app/admin/service/auth_service.py index 3280481b..205f1f52 100644 --- a/apps/api/backend/app/admin/service/auth_service.py +++ b/apps/api/backend/app/admin/service/auth_service.py @@ -12,6 +12,7 @@ from backend.app.admin.crud.crud_user import user_dao from backend.app.admin.model import User from backend.app.admin.schema.mfa import MfaChallenge, MfaChallengeParam, MfaSetupInfo, MfaTokenParam +from backend.app.admin.schema.passkey import PasskeyLoginParam from backend.app.admin.schema.token import GetLoginToken, GetMfaEnrollToken, GetNewToken from backend.app.admin.schema.user import ( CAPTCHA_UUID_PATTERN, @@ -20,6 +21,7 @@ AuthPhoneLoginParam, ) from backend.app.admin.service import mfa_service as mfa +from backend.app.admin.service import passkey_service from backend.app.admin.service.login_log_service import login_log_service from backend.app.admin.service.mfa_service import gate as mfa_gate from backend.app.admin.service.user_password_history_service import password_security_service @@ -544,6 +546,88 @@ async def phone_login( user=user, # type: ignore ) + async def passkey_login( + self, + *, + db: AsyncSession, + request: Request, + response: Response, + obj: PasskeyLoginParam, + background_tasks: BackgroundTasks, + ) -> GetLoginToken: + """ + 通行密钥登录(第二步;第一步是 `passkey_service.login_options`) + + 🔴 和手机登录同一条:不能只复用「开会话」那段。IP 锁定、停用 / 锁定判定、密码过期、成败计数逐条照做, + 通行密钥替代的只是「密码对不对」那一步。 + + 🔴 **不走二次验证(`mfa_gate`)**:挑战里要求了用户验证(UV),带 UV 的通行密钥本身就是「持有设备 + + 指纹 / 面容 / PIN」两个因素。被策略强制开 MFA 的账号用通行密钥照样直接登进来 —— + 这是刻意的,见 `passkey_service`。 + + 失败只计入 IP(`handle_ip_login_failure`),不计入账号:拿不到私钥的人造不出有效断言, + 按账号计等于谁都能把别人锁住。 + + :param db: 数据库会话 + :param request: 请求对象 + :param response: 响应对象 + :param obj: 挑战编号 + 断言 + :param background_tasks: 后台任务(写登录日志) + :return: + """ + user: User | None = None + try: + ip = ctx.ip + await load_login_config(db) + await password_security_service.check_ip_lock(ip) + try: + user, passkey, new_sign_count = await passkey_service.verify_login(db, obj.challenge_id, obj.credential) + except errors.AuthorizationError: + await password_security_service.handle_ip_login_failure(ip, None) + raise + lock_reason = await password_security_service.peek_lock_reason(user.id, user.status) + if lock_reason is not None: + raise errors.AuthorizationError(msg=lock_reason) + days_remaining = await password_security_service.check_password_expiry_status( + db, user.last_password_changed_time + ) + passkey_service.record_use(passkey, new_sign_count) + await self.mark_login_success(user.id) + access_token_data = await self._open_session( + db=db, request=request, response=response, user=user, client=obj.client + ) + except errors.BaseExceptionError as e: + log.error(f'通行密钥登录错误: {e.msg}') + e.background = BackgroundTask( + login_log_service.create, + user_uuid=user.uuid if user else uuid4_str(), + # 认不出是谁的凭据时没有用户名可记;「-」和别的登录方式里「用户名没对上」那一行一样占位 + username=user.username if user else '-', + login_time=timezone.now(), + status=LoginLogStatusType.fail.value, + msg=e.msg, + ) + raise + except Exception as e: + log.error(f'通行密钥登录错误: {e}') + raise + else: + background_tasks.add_task( + login_log_service.create, + user_uuid=user.uuid, + username=user.username, + login_time=timezone.now(), + status=LoginLogStatusType.success.value, + msg=t('success.login.passkey_success'), + ) + return GetLoginToken( + access_token=access_token_data.access_token, + access_token_expire_time=access_token_data.access_token_expire_time, + session_uuid=access_token_data.session_uuid, + password_expire_days_remaining=days_remaining, + user=user, # type: ignore + ) + @staticmethod async def get_codes(*, db: AsyncSession, request: Request) -> list[str]: """ diff --git a/apps/api/backend/app/admin/service/passkey_service.py b/apps/api/backend/app/admin/service/passkey_service.py new file mode 100644 index 00000000..c49e4fad --- /dev/null +++ b/apps/api/backend/app/admin/service/passkey_service.py @@ -0,0 +1,285 @@ +"""通行密钥(Passkey / WebAuthn):注册、管理、登录时的断言校验。 + +``` +个人中心「添加」── registration_options() ──→ navigator.credentials.create() ──→ register() +登录页「用通行密钥登录」── login_options() ──→ navigator.credentials.get() ──→ auth_service.passkey_login() + └─ verify_login() 校验断言 +``` + +几条设计,每条对应一种静默出错的方式: + +- 🔴 **只做「不先输用户名」的流程(可发现凭据)**:先输用户名再要挑战的话,「这个账号有没有通行密钥」就从挑战里漏出去了 + (同手机登录那条防枚举)。登录挑战里不带 `allowCredentials`,用哪把由认证器挑 +- 🔴 **一律要求用户验证(UV:指纹 / 面容 / PIN)**。带 UV 的通行密钥本身就是「持有设备 + 生物特征 / PIN」两个因素, + 所以通行密钥登录**不再走二次验证**,被强制开 MFA 的账号也一样(`auth_service.passkey_login`)。不要 UV 的话, + 捡到一把没锁的安全钥匙就能登 +- 🔴 **挑战一次性**:存 Redis、`GETDEL` 取,取不到就是过期 / 用过了。断言被截下来重放时挑战已经没了 +- 🔴 **登录失败对外一律同一句「通行密钥无效」**:凭据不存在 / 用户已删 / 签名不对 / 计数倒退 —— + 区分开就是一张凭据核对器。 + 原因进日志。失败计入 IP 失败计数,**不计入账号**:拿不到私钥的人造不出有效断言,按账号计等于谁都能把别人锁住 +- `sign_count`:新的不大于库里的就拒(py_webauthn 在两边都是 0 时不比 —— iCloud / Google 的同步型 Passkey 恒为 0) +""" + +from __future__ import annotations + +import hashlib +import json +import secrets + +from typing import TYPE_CHECKING, Any + +from sqlalchemy import delete, func, select +from webauthn import ( + generate_authentication_options, + generate_registration_options, + options_to_json, + verify_authentication_response, + verify_registration_response, +) +from webauthn.helpers import base64url_to_bytes, bytes_to_base64url +from webauthn.helpers.structs import ( + AuthenticatorSelectionCriteria, + PublicKeyCredentialDescriptor, + ResidentKeyRequirement, + UserVerificationRequirement, +) + +from backend.app.admin.crud.crud_user import user_dao +from backend.app.admin.model import User, UserPasskey +from backend.app.admin.schema.passkey import PasskeyLoginOptions +from backend.common.exception import errors +from backend.common.i18n import t +from backend.common.log import log +from backend.common.security.data_scope import bypass_data_scope +from backend.core.conf import settings +from backend.database.redis import redis_client +from backend.utils.timezone import timezone + +if TYPE_CHECKING: + from sqlalchemy.ext.asyncio import AsyncSession + +#: 认证器声明的传输方式里只认这几个,别的丢掉(这一列只是给人看的提示) +_TRANSPORTS = {'ble', 'cable', 'hybrid', 'internal', 'nfc', 'smart-card', 'usb'} + + +def enabled() -> bool: + """RP ID 和来源都配了才算启用(配一半当没配,生产启动检查会拦)""" + return bool(settings.PASSKEY_RP_ID and settings.PASSKEY_ORIGINS) + + +def _require_enabled() -> None: + if not enabled(): + raise errors.RequestError(msg=t('error.passkey.disabled')) + + +def _key(kind: str, token: str) -> str: + return f'{settings.PASSKEY_REDIS_PREFIX}:{kind}:{token}' + + +def _credential_hash(raw_id: bytes) -> str: + return hashlib.sha256(raw_id).hexdigest() + + +def user_handle(user: User) -> bytes: + """WebAuthn 的 user.id:要不透明、不能含个人信息(用户名 / 邮箱都不行)—— 用用户的 uuid""" + return str(user.uuid).encode() + + +def _invalid() -> errors.AuthorizationError: + return errors.AuthorizationError(msg=t('error.passkey.invalid')) + + +async def _from_db(db: AsyncSession, user: Any) -> User: + """ + 🔴 注册时的用户句柄要用**库里**那一行的 uuid,不能用 `request.user`(Redis 里的登录快照)。 + + 登录时是按凭据查库里的用户、拿它的 uuid 比 userHandle;注册用快照的话,两边一旦不是同一个值, + 这把钥匙就永远登不上(「userHandle 对不上」)。实测:本机几套库共用一个 Redis、管理员的雪花 ID 相同, + 快照里的 uuid 是别的库写进去的 —— 添加成功、登录必失败,界面上只有一句「通行密钥无效」 + """ + # 🔴 要 `bypass_data_scope()`:已登录请求里 DAO 会套上当前用户的数据范围,STAFF 这类「开了过滤、没有规则」的人 + # 连自己都查不到(同 `app/admin` 分册「用户快照」那一节的刷新 token 那条) + with bypass_data_scope(): + row = await user_dao.get(db, user.id) + if row is None: + raise errors.NotFoundError(msg=t('error.user.not_found')) + return row + + +async def list_mine(db: AsyncSession, user_id: int) -> list[UserPasskey]: + rows = await db.scalars(select(UserPasskey).where(UserPasskey.user_id == user_id).order_by(UserPasskey.id)) + return list(rows) + + +async def _own(db: AsyncSession, user_id: int, pk: int) -> UserPasskey: + row = await db.scalar(select(UserPasskey).where(UserPasskey.id == pk, UserPasskey.user_id == user_id)) + if row is None: + # 别人的和不存在的一样:不承认那一行存在 + raise errors.NotFoundError(msg=t('error.passkey.not_found')) + return row + + +async def registration_options(db: AsyncSession, user: Any) -> dict[str, Any]: + """添加一把:生成注册挑战。原样交给 `PublicKeyCredential.parseCreationOptionsFromJSON()`""" + _require_enabled() + user = await _from_db(db, user) + rows = await list_mine(db, user.id) + if len(rows) >= settings.PASSKEY_MAX_PER_USER: + raise errors.RequestError(msg=t('error.passkey.too_many', max=settings.PASSKEY_MAX_PER_USER)) + options = generate_registration_options( + rp_id=settings.PASSKEY_RP_ID, + rp_name=settings.PASSKEY_RP_NAME or settings.FASTAPI_TITLE, + user_id=user_handle(user), + user_name=user.username, + user_display_name=user.nickname or user.username, + timeout=settings.PASSKEY_CHALLENGE_SECONDS * 1000, + authenticator_selection=AuthenticatorSelectionCriteria( + resident_key=ResidentKeyRequirement.REQUIRED, + user_verification=UserVerificationRequirement.REQUIRED, + ), + # 同一个认证器不许登记两次(浏览器会直接报 InvalidStateError) + exclude_credentials=[PublicKeyCredentialDescriptor(id=base64url_to_bytes(r.credential_id)) for r in rows], + ) + # 按人存:同一个人再点一次「添加」就覆盖上一次的挑战,旧的那个弹窗再提交会对不上 + await redis_client.set( + _key('reg', str(user.id)), bytes_to_base64url(options.challenge), ex=settings.PASSKEY_CHALLENGE_SECONDS + ) + return json.loads(options_to_json(options)) + + +async def register(db: AsyncSession, user: User, name: str, credential: dict[str, Any]) -> UserPasskey: + """添加一把:校验注册结果并落库""" + _require_enabled() + challenge = await redis_client.getdel(_key('reg', str(user.id))) + if not challenge: + raise errors.RequestError(msg=t('error.passkey.challenge_expired')) + try: + verified = verify_registration_response( + credential=credential, + expected_challenge=base64url_to_bytes(challenge), + expected_rp_id=settings.PASSKEY_RP_ID, + expected_origin=list(settings.PASSKEY_ORIGINS), + require_user_verification=True, + ) + except Exception as e: + log.info(f'通行密钥注册校验没过(用户 {user.id}):{type(e).__name__}: {e}') + raise errors.RequestError(msg=t('error.passkey.register_failed')) from e + + count = await db.scalar(select(func.count()).select_from(UserPasskey).where(UserPasskey.user_id == user.id)) + if (count or 0) >= settings.PASSKEY_MAX_PER_USER: + raise errors.RequestError(msg=t('error.passkey.too_many', max=settings.PASSKEY_MAX_PER_USER)) + digest = _credential_hash(verified.credential_id) + if await db.scalar(select(UserPasskey.id).where(UserPasskey.credential_hash == digest)) is not None: + raise errors.ConflictError(msg=t('error.passkey.already_registered')) + + declared = (credential.get('response') or {}).get('transports') or [] + transports = ','.join(sorted({x for x in declared if isinstance(x, str) and x in _TRANSPORTS})) or None + row = UserPasskey( + user_id=user.id, + name=name.strip(), + credential_hash=digest, + credential_id=bytes_to_base64url(verified.credential_id), + public_key=bytes_to_base64url(verified.credential_public_key), + sign_count=verified.sign_count, + transports=transports, + aaguid=str(verified.aaguid) if verified.aaguid else None, + backed_up=bool(verified.credential_backed_up), + ) + db.add(row) + await db.flush() + return row + + +async def rename(db: AsyncSession, user_id: int, pk: int, name: str) -> None: + row = await _own(db, user_id, pk) + row.name = name.strip() + + +async def remove(db: AsyncSession, user_id: int, pk: int) -> None: + row = await _own(db, user_id, pk) + await db.delete(row) + + +async def admin_reset(db: AsyncSession, user_id: int) -> int: + """管理员清掉某人的全部通行密钥(设备丢了 / 离职交接)。返回删了几把""" + result = await db.execute(delete(UserPasskey).where(UserPasskey.user_id == user_id)) + return result.rowcount or 0 + + +async def login_options() -> PasskeyLoginOptions: + """登录第一步(匿名)。不带 allowCredentials —— 不先问用户名,见模块说明""" + _require_enabled() + options = generate_authentication_options( + rp_id=settings.PASSKEY_RP_ID, + timeout=settings.PASSKEY_CHALLENGE_SECONDS * 1000, + user_verification=UserVerificationRequirement.REQUIRED, + ) + challenge_id = secrets.token_urlsafe(24) + await redis_client.set( + _key('login', challenge_id), bytes_to_base64url(options.challenge), ex=settings.PASSKEY_CHALLENGE_SECONDS + ) + return PasskeyLoginOptions(challenge_id=challenge_id, options=json.loads(options_to_json(options))) + + +async def verify_login( + db: AsyncSession, challenge_id: str, credential: dict[str, Any] +) -> tuple[User, UserPasskey, int]: + """ + 登录第二步:校验断言,返回(用户, 用的哪一把, 新的签名计数)。不开会话、不记日志 —— 那是 `auth_service` 的事 + + :raises errors.AuthorizationError: 挑战过期 / 用过了,或者「通行密钥无效」(原因只进日志) + """ + _require_enabled() + challenge = await redis_client.getdel(_key('login', challenge_id)) + if not challenge: + raise errors.AuthorizationError(msg=t('error.passkey.challenge_expired')) + + raw_id = credential.get('rawId') or credential.get('id') + try: + raw = base64url_to_bytes(raw_id) if isinstance(raw_id, str) else b'' + except Exception: + raw = b'' + if not raw: + log.info('通行密钥登录:凭据里没有可用的 id') + raise _invalid() + + row = await db.scalar(select(UserPasskey).where(UserPasskey.credential_hash == _credential_hash(raw))) + if row is None: + log.info('通行密钥登录:库里没有这把凭据(可能已被删除 / 管理员重置)') + raise _invalid() + with bypass_data_scope(): # 匿名请求本来没有范围上下文;包上是防将来有人在已登录的上下文里调它 + user = await user_dao.get(db, row.user_id) + if user is None: + log.info(f'通行密钥登录:凭据 {row.id} 的用户已不存在') + raise _invalid() + + handle = (credential.get('response') or {}).get('userHandle') + if handle: + try: + handle_ok = base64url_to_bytes(handle) == user_handle(user) + except Exception: + handle_ok = False + if not handle_ok: + log.warning(f'通行密钥登录:凭据 {row.id} 带的 userHandle 和它所属的用户对不上') + raise _invalid() + + try: + verified = verify_authentication_response( + credential=credential, + expected_challenge=base64url_to_bytes(challenge), + expected_rp_id=settings.PASSKEY_RP_ID, + expected_origin=list(settings.PASSKEY_ORIGINS), + credential_public_key=base64url_to_bytes(row.public_key), + credential_current_sign_count=row.sign_count, + require_user_verification=True, + ) + except Exception as e: + log.warning(f'通行密钥登录:凭据 {row.id}(用户 {user.id})校验没过:{type(e).__name__}: {e}') + raise _invalid() from e + return user, row, verified.new_sign_count + + +def record_use(row: UserPasskey, new_sign_count: int) -> None: + """登录成功后回写计数和最近使用时间(两列都在审计的忽略列里,不出变更记录)""" + row.sign_count = new_sign_count + row.last_used_time = timezone.now() diff --git a/apps/api/backend/app/admin/tests/api_v1/test_passkey.py b/apps/api/backend/app/admin/tests/api_v1/test_passkey.py new file mode 100644 index 00000000..476efd1b --- /dev/null +++ b/apps/api/backend/app/admin/tests/api_v1/test_passkey.py @@ -0,0 +1,389 @@ +"""通行密钥(Passkey / WebAuthn):注册 · 无用户名登录 · 每一种该拒的情形。 + +浏览器那一侧用一个纯 Python 的软件认证器代替(P-256 密钥,按规范拼 authenticatorData / clientDataJSON / 签名), +走的是真实 HTTP 接口和真的 py_webauthn 校验。浏览器 + CDP 虚拟认证器那一层的实测见 `app/admin` 分册「通行密钥」一节。 +""" + +import hashlib +import json +import os +import struct + +from collections.abc import Iterator +from typing import Any + +import cbor2 +import pytest +import sqlalchemy as sa + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec +from starlette.testclient import TestClient +from webauthn.helpers import bytes_to_base64url + +from backend.app.admin.model import UserPasskey +from backend.core.conf import settings +from backend.tests.utils.data_change import changes_of, engine + +RP_ID = 'localhost' +ORIGIN = 'http://localhost:8888' +#: authenticatorData 的标志位 +UP, UV, AT = 0x01, 0x04, 0x40 + + +class SoftAuthenticator: + """一个软件认证器:一把 P-256 密钥、一个凭据 ID、一个签名计数""" + + def __init__(self) -> None: + self.key = ec.generate_private_key(ec.SECP256R1()) + self.credential_id = os.urandom(32) + self.count = 0 + self.user_handle: str | None = None + + def _cose_public_key(self) -> bytes: + numbers = self.key.public_key().public_numbers() + return cbor2.dumps({1: 2, 3: -7, -1: 1, -2: numbers.x.to_bytes(32, 'big'), -3: numbers.y.to_bytes(32, 'big')}) + + def create(self, options: dict[str, Any], *, origin: str = ORIGIN, flags: int = UP | UV | AT) -> dict[str, Any]: + self.user_handle = options['user']['id'] + client_data = json.dumps({ + 'type': 'webauthn.create', + 'challenge': options['challenge'], + 'origin': origin, + }).encode() + self.count += 1 + auth_data = ( + hashlib.sha256(options['rp']['id'].encode()).digest() + + bytes([flags]) + + struct.pack('>I', self.count) + + b'\x00' * 16 # AAGUID + + struct.pack('>H', len(self.credential_id)) + + self.credential_id + + self._cose_public_key() + ) + attestation = cbor2.dumps({'fmt': 'none', 'attStmt': {}, 'authData': auth_data}) + cid = bytes_to_base64url(self.credential_id) + return { + 'id': cid, + 'rawId': cid, + 'type': 'public-key', + 'response': { + 'clientDataJSON': bytes_to_base64url(client_data), + 'attestationObject': bytes_to_base64url(attestation), + 'transports': ['internal', 'made-up'], + }, + 'clientExtensionResults': {}, + } + + def get( + self, + options: dict[str, Any], + *, + origin: str = ORIGIN, + flags: int = UP | UV, + bump: bool = True, + user_handle: str | None = None, + ) -> dict[str, Any]: + client_data = json.dumps({'type': 'webauthn.get', 'challenge': options['challenge'], 'origin': origin}).encode() + if bump: + self.count += 1 + auth_data = hashlib.sha256(options['rpId'].encode()).digest() + bytes([flags]) + struct.pack('>I', self.count) + signature = self.key.sign(auth_data + hashlib.sha256(client_data).digest(), ec.ECDSA(hashes.SHA256())) + cid = bytes_to_base64url(self.credential_id) + return { + 'id': cid, + 'rawId': cid, + 'type': 'public-key', + 'response': { + 'clientDataJSON': bytes_to_base64url(client_data), + 'authenticatorData': bytes_to_base64url(auth_data), + 'signature': bytes_to_base64url(signature), + 'userHandle': user_handle if user_handle is not None else self.user_handle, + }, + 'clientExtensionResults': {}, + } + + +def _bearer(client: TestClient, username: str, password: str) -> dict[str, str]: + body = client.post('/auth/login/swagger', params={'username': username, 'password': password}).json() + return {'Authorization': f'{body["token_type"]} {body["access_token"]}'} + + +def _register(client: TestClient, headers: dict[str, str], auth: SoftAuthenticator, name: str = '我的电脑', **kw: Any): + options = client.post('/sys/users/me/passkeys/options', headers=headers).json() + assert options['code'] == 200, options + return client.post( + '/sys/users/me/passkeys', headers=headers, json={'name': name, 'credential': auth.create(options['data'], **kw)} + ) + + +def _login(client: TestClient, auth: SoftAuthenticator, **kw: Any) -> tuple[Any, dict[str, Any]]: + first = client.post('/auth/passkey/options').json() + assert first['code'] == 200, first + data = first['data'] + credential = auth.get(data['options'], **kw) + return client.post( + '/auth/passkey/login', json={'challenge_id': data['challenge_id'], 'credential': credential} + ), data + + +@pytest.fixture(autouse=True) +def _passkey_on(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, 'PASSKEY_RP_ID', RP_ID) + monkeypatch.setattr(settings, 'PASSKEY_ORIGINS', [ORIGIN]) + + +@pytest.fixture +def me(client: TestClient, temp_user: str) -> Iterator[dict[str, Any]]: + """临时用户 + 它的登录头;收尾硬删它名下的通行密钥(用户本身由 temp_user 硬删)""" + yield {'id': temp_user, 'headers': _bearer(client, 'pytest_tmp_writes', 'Tmp@123456')} + with engine().begin() as conn: + conn.execute(sa.delete(UserPasskey.__table__).where(UserPasskey.__table__.c.user_id == int(temp_user))) + + +@pytest.fixture +def registered(client: TestClient, me: dict[str, Any]) -> tuple[dict[str, Any], SoftAuthenticator, dict[str, Any]]: + auth = SoftAuthenticator() + resp = _register(client, me['headers'], auth) + assert resp.json()['code'] == 200, resp.text + return me, auth, resp.json()['data'] + + +def test_disabled_until_both_settings_are_configured(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, 'PASSKEY_ORIGINS', []) + assert client.get('/auth/passkey/enabled').json()['data'] == {'enabled': False} + resp = client.post('/auth/passkey/options').json() + assert resp['code'] == 400 and 'PASSKEY_RP_ID' in resp['msg'] + monkeypatch.setattr(settings, 'PASSKEY_ORIGINS', [ORIGIN]) + assert client.get('/auth/passkey/enabled').json()['data'] == {'enabled': True} + + +def test_register_then_sign_in_without_a_username(client: TestClient, registered) -> None: + me, auth, detail = registered + assert detail['name'] == '我的电脑' + assert detail['transports'] == 'internal', '只留认得的传输方式' + listed = client.get('/sys/users/me/passkeys', headers=me['headers']).json()['data'] + assert [p['id'] for p in listed] == [detail['id']] + assert 'public_key' not in listed[0] and 'credential_id' not in listed[0], '钥匙材料不出网' + + resp, first = _login(client, auth) + assert 'allowCredentials' not in first['options'] or not first['options']['allowCredentials'], ( + '不能先暴露有哪些凭据' + ) + assert first['options']['userVerification'] == 'required' + body = resp.json() + assert body['code'] == 200, body + headers = {'Authorization': f'Bearer {body["data"]["access_token"]}'} + assert client.get('/sys/users/me', headers=headers).json()['data']['username'] == 'pytest_tmp_writes' + used = client.get('/sys/users/me/passkeys', headers=me['headers']).json()['data'][0] + assert used['last_used_time'] is not None + + +def test_a_challenge_can_be_used_once(client: TestClient, registered) -> None: + _, auth, _ = registered + first = client.post('/auth/passkey/options').json()['data'] + credential = auth.get(first['options']) + ok = client.post('/auth/passkey/login', json={'challenge_id': first['challenge_id'], 'credential': credential}) + assert ok.json()['code'] == 200 + # 🔴 第二次用一份**新签的**断言(计数增长了):只重交同一份的话计数检查本来就会拒,证明不了挑战被作废(变异实测过) + fresh = auth.get(first['options']) + again = client.post('/auth/passkey/login', json={'challenge_id': first['challenge_id'], 'credential': fresh}) + assert again.json()['code'] == 403, '同一个挑战第二次用' + + +def test_replaying_an_assertion_under_a_new_challenge_is_rejected(client: TestClient, registered) -> None: + _, auth, _ = registered + resp, first = _login(client, auth) + assert resp.json()['code'] == 200 + stolen = auth.get(first['options'], bump=False) # 截下来的旧断言(旧挑战、旧计数) + fresh = client.post('/auth/passkey/options').json()['data'] + replay = client.post('/auth/passkey/login', json={'challenge_id': fresh['challenge_id'], 'credential': stolen}) + assert replay.json()['code'] == 403 + + +@pytest.mark.parametrize( + ('kwargs', 'why'), + [ + ({'origin': 'https://evil.example'}, '别的站点'), + ({'flags': UP}, '没做用户验证(UV)'), + ({'bump': False}, '签名计数没增长(像是被克隆的认证器)'), + ({'user_handle': bytes_to_base64url(b'someone-else')}, 'userHandle 对不上'), + ], + ids=['origin', 'no-uv', 'counter', 'user-handle'], +) +def test_bad_assertions_get_the_same_message(client: TestClient, registered, kwargs: dict[str, Any], why: str) -> None: + _, auth, _ = registered + assert _login(client, auth)[0].json()['code'] == 200, '前提:这把钥匙本来能登' + resp, _ = _login(client, auth, **kwargs) + body = resp.json() + assert body['code'] == 403, why + assert body['msg'] == '通行密钥无效,请换一把或用密码登录', f'{why}:失败原因不能对外区分' + + +def test_unknown_and_deleted_credentials_look_the_same(client: TestClient, registered) -> None: + me, auth, detail = registered + stranger = SoftAuthenticator() + stranger.user_handle = auth.user_handle + unknown = _login(client, stranger)[0].json() + assert client.delete(f'/sys/users/me/passkeys/{detail["id"]}', headers=me['headers']).json()['code'] == 200 + deleted = _login(client, auth)[0].json() + # 🔴 和固定文案比,不只两者互比:「不存在」「已删」走同一个分支,换了说法两边一起变(变异实测过) + assert unknown['code'] == deleted['code'] == 403 + assert unknown['msg'] == deleted['msg'] == '通行密钥无效,请换一把或用密码登录' + + +def test_registration_requires_user_verification_and_the_right_origin(client: TestClient, me) -> None: + for kwargs in ({'flags': UP | AT}, {'origin': 'https://evil.example'}): + resp = _register(client, me['headers'], SoftAuthenticator(), **kwargs).json() + assert resp['code'] == 400, kwargs + assert client.get('/sys/users/me/passkeys', headers=me['headers']).json()['data'] == [] + + +def test_the_same_authenticator_cannot_be_added_twice(client: TestClient, registered) -> None: + me, auth, _ = registered + resp = _register(client, me['headers'], auth, name='同一把').json() + assert resp['code'] == 409 + + +def test_per_user_limit(client: TestClient, registered, monkeypatch: pytest.MonkeyPatch) -> None: + me, _, _ = registered + monkeypatch.setattr(settings, 'PASSKEY_MAX_PER_USER', 1) + resp = client.post('/sys/users/me/passkeys/options', headers=me['headers']).json() + assert resp['code'] == 400 and '1' in resp['msg'] + + +def test_someone_elses_passkey_is_not_found(client: TestClient, registered, token_headers: dict[str, str]) -> None: + _, _, detail = registered + # 管理员也不行:「我的」接口只认本人;管理员要清走的是重置接口 + assert ( + client.put(f'/sys/users/me/passkeys/{detail["id"]}', headers=token_headers, json={'name': 'x'}).json()['code'] + == 404 + ) + assert client.delete(f'/sys/users/me/passkeys/{detail["id"]}', headers=token_headers).json()['code'] == 404 + + +def test_disabled_user_cannot_sign_in(client: TestClient, registered, token_headers: dict[str, str]) -> None: + me, auth, _ = registered + assert ( + client.put(f'/sys/users/{me["id"]}/permissions', headers=token_headers, params={'type': 'status'}).json()[ + 'code' + ] + == 200 + ) + body = _login(client, auth)[0].json() + assert body['code'] == 403 and body['msg'] != '通行密钥无效,请换一把或用密码登录', ( + '钥匙是对的,可以如实说明账号状态' + ) + + +def test_passkey_sign_in_skips_the_second_factor( + client: TestClient, registered, monkeypatch: pytest.MonkeyPatch +) -> None: + """带 UV 的通行密钥本身就是两个因素:被强制开 MFA 的人也不再走 mfa_gate""" + from backend.app.admin.service import auth_service as module + + async def boom(*_a: Any, **_kw: Any) -> None: # ruff: ignore[unused-async] - 顶掉的原函数是 async + raise AssertionError('通行密钥登录不该走二次验证') + + monkeypatch.setattr(module, 'mfa_gate', boom) + _, auth, _ = registered + assert _login(client, auth)[0].json()['code'] == 200 + + +def test_failures_count_against_the_ip_not_the_account( + client: TestClient, registered, monkeypatch: pytest.MonkeyPatch +) -> None: + from backend.app.admin.service.user_password_history_service import password_security_service as pss + + calls: list[str] = [] + real_ip = pss.handle_ip_login_failure + + async def ip_failure(ip: str, username: str | None = None) -> None: + calls.append('ip') + await real_ip(ip, username) + + async def account_failure(*_a: Any, **_kw: Any) -> None: # ruff: ignore[unused-async] - 顶掉的原函数是 async + calls.append('account') + + monkeypatch.setattr(pss, 'handle_ip_login_failure', ip_failure) + monkeypatch.setattr(pss, 'handle_login_failure', account_failure) + _, auth, _ = registered + assert _login(client, auth, origin='https://evil.example')[0].json()['code'] == 403 + assert calls == ['ip'], '拿不到私钥的人造不出有效断言,按账号计等于谁都能把别人锁住' + assert _login(client, auth)[0].json()['code'] == 200, '之后照样能登(顺带把 IP 计数清零)' + + +def test_superuser_can_clear_someones_passkeys(client: TestClient, registered, token_headers: dict[str, str]) -> None: + me, auth, _ = registered + assert client.delete(f'/sys/users/{me["id"]}/passkeys', headers=me['headers']).json()['code'] in (401, 403), ( + '非超管不能重置' + ) + assert client.delete(f'/sys/users/{me["id"]}/passkeys', headers=token_headers).json()['code'] == 200 + assert _login(client, auth)[0].json()['code'] == 403 + + +def test_changes_are_recorded_but_sign_ins_are_not(client: TestClient, registered) -> None: + me, auth, detail = registered + assert _login(client, auth)[0].json()['code'] == 200 # 回写计数 / 最近使用时间:都在忽略列里 + assert ( + client.put(f'/sys/users/me/passkeys/{detail["id"]}', headers=me['headers'], json={'name': '我的手机'}).json()[ + 'code' + ] + == 200 + ) + assert client.delete(f'/sys/users/me/passkeys/{detail["id"]}', headers=me['headers']).json()['code'] == 200 + records = changes_of('user_passkey', detail['id']) + assert [r['action'] for r in records] == ['create', 'update', 'delete'], records + blob = json.dumps(records, ensure_ascii=False, default=str) + assert 'public_key' not in blob and 'credential' not in blob, '钥匙材料不进审计表' + + +@pytest.mark.parametrize( + ('rp_id', 'origins', 'problem'), + [ + ('', [], None), + ('example.com', ['https://example.com', 'https://admin.example.com'], None), + ('example.com', [], '要一起配'), + ('', ['https://example.com'], '要一起配'), + ('localhost', ['http://localhost:8888'], '正式域名'), + ('10.0.0.8', ['https://10.0.0.8'], '正式域名'), + ('example.com', ['http://example.com'], 'https'), + ('example.com', ['https://evil.com'], '不属于'), + ('example.com', ['https://notexample.com'], '不属于'), + ], + ids=['off', 'ok', 'origins-missing', 'rp-missing', 'localhost', 'ip', 'http', 'foreign', 'suffix-trick'], +) +def test_production_check(rp_id: str, origins: list[str], problem: str | None) -> None: + from types import SimpleNamespace + + from backend.core.conf import _check_passkey + + result = _check_passkey(SimpleNamespace(PASSKEY_RP_ID=rp_id, PASSKEY_ORIGINS=origins)) + if problem is None: + assert result is None + else: + assert result is not None and problem in result, result + + +def test_registration_uses_the_uuid_in_the_database_not_the_cached_snapshot(client: TestClient, me) -> None: + """🔴 浏览器实测踩出来的:注册时用户句柄取自 Redis 里的登录快照,登录时取自库 —— 两边不一致就永远登不上。 + + 本机几套库共用一个 Redis、管理员的雪花 ID 相同,快照里的 uuid 是别的库写进去的: + 添加成功,用它登录一律「通行密钥无效」。 + 这里把快照里的 uuid 改掉来复现 + """ + from backend.database.redis import redis_client + + key = f'{settings.JWT_USER_REDIS_PREFIX}:{me["id"]}' + assert client.get('/sys/users/me', headers=me['headers']).json()['code'] == 200 # 焐热快照 + raw = client.portal.call(redis_client.get, key) + assert raw, '前提:登录快照在 Redis 里(不然改不了它,这条证明不了什么)' + snapshot = json.loads(raw) + snapshot['uuid'] = '00000000-0000-4000-8000-000000000000' + client.portal.call(redis_client.set, key, json.dumps(snapshot)) + try: + auth = SoftAuthenticator() + assert _register(client, me['headers'], auth).json()['code'] == 200 + assert _login(client, auth)[0].json()['code'] == 200 + finally: + client.portal.call(redis_client.delete, key) diff --git a/apps/api/backend/core/conf.py b/apps/api/backend/core/conf.py index 66bab610..585ff580 100644 --- a/apps/api/backend/core/conf.py +++ b/apps/api/backend/core/conf.py @@ -8,6 +8,7 @@ from pathlib import Path from re import Pattern from typing import Any, Literal +from urllib.parse import urlparse from pydantic import Field, model_validator from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict @@ -137,6 +138,10 @@ def settings_customise_sources( f'{FASTAPI_API_V1_PATH}/auth/mfa/verify', f'{FASTAPI_API_V1_PATH}/auth/mfa/setup', f'{FASTAPI_API_V1_PATH}/auth/mfa/enroll', + # 通行密钥登录的三个匿名接口:登录页问「开没开」、取挑战、交断言。同手机登录,精确匹配 + f'{FASTAPI_API_V1_PATH}/auth/passkey/enabled', + f'{FASTAPI_API_V1_PATH}/auth/passkey/options', + f'{FASTAPI_API_V1_PATH}/auth/passkey/login', # 登录页的公告(#190,通知公告插件):本来就不需要登录,放进来是为了浏览器里留着一个**过期**的 token 时 # 登录页照样拉得到 —— 不放的话带着坏 token 的请求先被 JWT 中间件 401,公告区一直显示「加载失败」 f'{FASTAPI_API_V1_PATH}/sys/notices/public', @@ -189,6 +194,17 @@ def settings_customise_sources( # 扫了码还没确认的那把密钥在 Redis 里放多久 MFA_SETUP_SECONDS: int = 60 * 10 + # 通行密钥(Passkey / WebAuthn)登录。两项都配上才启用,空 = 不启用(登录页不出按钮、接口回「未启用」)。 + # 🔴 不从请求头推断:凭据绑在 RP ID 上,按 Host 推的话换个域名访问就是另一个站,钓鱼代理也能改 Host。 + # 🔴 RP ID 不能是 IP(浏览器直接拒:SecurityError: This is an invalid domain)—— 本地开发要从 localhost 打开页面, + # 不能用 127.0.0.1,见 app/admin 分册「通行密钥」一节 + PASSKEY_RP_ID: str = '' # 站点域名,不带协议和端口:example.com · 本地开发 localhost + PASSKEY_ORIGINS: list[str] = [] # 页面来源,带协议和端口:["https://example.com"] · ["http://localhost:8888"] + PASSKEY_RP_NAME: str = '' # 认证器上显示的站点名;空 = FASTAPI_TITLE + PASSKEY_REDIS_PREFIX: str = 'fba:passkey' + PASSKEY_CHALLENGE_SECONDS: int = 60 * 5 # 一次注册 / 登录的挑战有效期 + PASSKEY_MAX_PER_USER: int = 10 + # JWT JWT_USER_REDIS_PREFIX: str = 'fba:user' @@ -939,6 +955,26 @@ def _check_import_default_password(s: Settings) -> str | None: return None +def _check_passkey(s: Settings) -> str | None: + """通行密钥:RP ID 和来源都配了才启用。prod 下来源必须是 https、主机必须是 RP ID 本身或它的子域""" + rp_id = (getattr(s, 'PASSKEY_RP_ID', '') or '').strip().lower() + origins = list(getattr(s, 'PASSKEY_ORIGINS', []) or []) + if not rp_id and not origins: + return None + if not rp_id or not origins: + return 'PASSKEY_RP_ID 和 PASSKEY_ORIGINS 要一起配(只配一个等于没启用,登录页也不会出按钮)' + if rp_id.replace('.', '').isdigit() or ':' in rp_id or rp_id == 'localhost': + return f'PASSKEY_RP_ID={rp_id!r} 在 prod 必须是正式域名(不能是 IP / localhost / 带端口)' + for origin in origins: + parsed = urlparse(origin) + host = (parsed.hostname or '').lower() + if parsed.scheme != 'https': + return f'PASSKEY_ORIGINS 里的 {origin!r} 在 prod 必须是 https' + if host != rp_id and not host.endswith(f'.{rp_id}'): + return f'PASSKEY_ORIGINS 里的 {origin!r} 不属于 PASSKEY_RP_ID={rp_id!r}(主机得是它本身或它的子域)' + return None + + def _check_webhook_private_network(s: Settings) -> str | None: """打开它 = Webhook 投递能打到回环 / 内网地址(SSRF),而端点 URL 是有权限的管理员随手填的(#167)""" if getattr(s, 'OPEN_WEBHOOK_ALLOW_PRIVATE_NETWORK', False): @@ -1031,6 +1067,7 @@ def check_production_settings(s: Settings) -> None: _check_import_default_password(s), _check_webhook_private_network(s), _check_bot_url_prefixes(s), + _check_passkey(s), )) found = [p for p in problems if p] diff --git a/apps/api/backend/locale/en-US.yml b/apps/api/backend/locale/en-US.yml index 6c34c349..04ed78bd 100644 --- a/apps/api/backend/locale/en-US.yml +++ b/apps/api/backend/locale/en-US.yml @@ -145,6 +145,14 @@ error: setup_expired: Setup expired, please scan the code again setup_required: Please finish setting up two-factor authentication first swagger_unsupported: This account uses two-factor authentication; sign in from the login page (the Swagger shortcut cannot do the second step) + passkey: + already_registered: This passkey has already been added + challenge_expired: This request has expired. Please try again + disabled: Passkey sign-in is not enabled (an administrator must set PASSKEY_RP_ID and PASSKEY_ORIGINS) + invalid: This passkey is not valid. Try another one or sign in with your password + not_found: Passkey not found + register_failed: The passkey could not be added. Please try again (open the page on this site's address and complete fingerprint, face or PIN verification) + too_many: You can add at most {max} passkeys. Remove one you no longer use first notice: not_found: Notice does not exist attachment_invalid: The attachment does not exist, or you are not allowed to use that file @@ -612,6 +620,7 @@ login_event: success: login: mfa_success: Signed in (two-factor) + passkey_success: Signed in (passkey) oauth2_success: Login success (OAuth2) success: Login success diff --git a/apps/api/backend/locale/zh-CN.yml b/apps/api/backend/locale/zh-CN.yml index d55e670c..1cef15b3 100644 --- a/apps/api/backend/locale/zh-CN.yml +++ b/apps/api/backend/locale/zh-CN.yml @@ -146,6 +146,14 @@ error: setup_expired: 绑定已过期,请重新扫码 setup_required: 请先完成二次验证的绑定 swagger_unsupported: 这个账号开启了二次验证,请从登录页登录(Swagger 调试口做不了第二步) + passkey: + already_registered: 这把通行密钥已经添加过了 + challenge_expired: 操作已过期,请重试 + disabled: 系统没有开启通行密钥登录(管理员要先配置 PASSKEY_RP_ID 和 PASSKEY_ORIGINS) + invalid: 通行密钥无效,请换一把或用密码登录 + not_found: 通行密钥不存在 + register_failed: 通行密钥没能添加,请重试(要用当前网站的地址打开页面,并完成指纹 / 面容 / PIN 验证) + too_many: 最多只能添加 {max} 把通行密钥,请先删掉不用的 notice: not_found: 通知公告不存在 attachment_invalid: 附件不存在,或者你没有权限使用这个文件 @@ -711,6 +719,7 @@ login_event: success: login: mfa_success: 登录成功(二次验证) + passkey_success: 登录成功(通行密钥) oauth2_success: 登录成功(OAuth2) success: 登录成功 diff --git a/apps/api/pyproject.toml b/apps/api/pyproject.toml index ab734844..094ef6f0 100644 --- a/apps/api/pyproject.toml +++ b/apps/api/pyproject.toml @@ -83,6 +83,7 @@ dependencies = [ "tencentcloud-sdk-python-common[async]>=3.1.153", # plugin/sms(异步客户端要这个 extra,带 httpx) "tencentcloud-sdk-python-sms>=3.1.153", # plugin/sms(腾讯云官方 SDK) "user-agents>=2.2.0", + "webauthn>=3.0.1", # 通行密钥(Passkey)登录:注册 / 断言的校验 ] dynamic = ["version"] diff --git a/apps/api/requirements.txt b/apps/api/requirements.txt index 290dfba3..c9913383 100644 --- a/apps/api/requirements.txt +++ b/apps/api/requirements.txt @@ -97,6 +97,8 @@ cachebox==6.2.5 # via fastapi-react-admin-api cappa==0.32.2 # via fastapi-react-admin-api +cbor2==6.3.0 + # via webauthn celery==5.6.3 # via # celery-aio-pool @@ -146,6 +148,8 @@ cryptography==50.0.0 # joserfc # moto # pyjwt + # pyopenssl + # webauthn darabonba-core==1.0.9 # via # alibabacloud-dysmsapi20170525 @@ -436,6 +440,12 @@ py-ip2region==3.0.4 # via fastapi-react-admin-api py-partiql-parser==0.6.3 # via moto +pyasn1==0.6.5 + # via + # pyasn1-modules + # webauthn +pyasn1-modules==0.4.2 + # via webauthn pycparser==3.0 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' # via cffi pydantic==2.13.4 @@ -480,6 +490,8 @@ pymysql==1.2.0 # via fastapi-react-admin-api pyodbc==5.3.0 # via aioodbc +pyopenssl==26.4.0 + # via webauthn pyparsing==3.3.3 # via moto pypdf==6.21.4 @@ -638,6 +650,7 @@ typing-extensions==4.16.0 # pydantic # pydantic-core # pydantic-extra-types + # pyopenssl # referencing # rich-toolkit # sqlakeyset @@ -691,6 +704,8 @@ watchfiles==1.2.0 # via uvicorn wcwidth==0.8.2 # via prompt-toolkit +webauthn==3.0.1 + # via fastapi-react-admin-api websocket-client==1.9.2 # via darabonba-core websockets==17.0.1 diff --git a/apps/api/uv.lock b/apps/api/uv.lock index e91c1b9f..32b5b2fc 100644 --- a/apps/api/uv.lock +++ b/apps/api/uv.lock @@ -2189,6 +2189,245 @@ wheels = [ }, ] +[[package]] +name = "cbor2" +version = "6.3.0" +source = { registry = "https://mirrors.aliyun.com/pypi/simple" } +sdist = { + url = "https://mirrors.aliyun.com/pypi/packages/df/61/be007e3421969a4a318b486e4eaf4205872bbc1baf063ea7e679f74015cf/cbor2-6.3.0.tar.gz", + hash = "sha256:fd4d6b3533e966eec3fb33ce0f17e925fc09b512500ab7770867ebec7d7d5dc1" +} +wheels = [ + { + url = "https://mirrors.aliyun.com/pypi/packages/ee/87/505bcf5577e6ba16dbcc3727415ecd9545a7ec0fe998fc29320255328b2c/cbor2-6.3.0-cp311-cp311-macosx_11_0_arm64.whl", + hash = "sha256:397b1c6a6709f79ab1419dfeb586042fb995c12ccfd0cb5ea9f9001d99cad690" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/30/c1/937ab39ca1ed18d71ecb3d857a2db771ea654f3186b52afae3fd8e5a5c24/cbor2-6.3.0-cp311-cp311-manylinux_2_28_aarch64.whl", + hash = "sha256:9253098c278540523cc27b9bedaf7d1d1655d2961b2ae1e6e43fc6592240016b" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/3e/aa/fde8c2765fc91ef632b2c44a255de8f4cd7c4af6267060068f6207ff6bed/cbor2-6.3.0-cp311-cp311-manylinux_2_28_x86_64.whl", + hash = "sha256:ebe634e9fe6ae36b3fe1c42d280c4ecb368397efbcd497f8d5826d48e9093f1b" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/15/f1/f12f74b446b39e504f154ec3b6672ee88d417dd40d2ea735a2f72ce6000f/cbor2-6.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", + hash = "sha256:1533d5c1949a449ebc05dd8ebb85db097e26b479fd5b1634e765e4b8e8e3bc35" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/bd/65/6f10cecc5c731881bd3526a8ad661f5ba53fced49fd7506d8a482ab03a96/cbor2-6.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", + hash = "sha256:d724f0d6e8da9c13c9462da7de0e08ab8aabebb4badac2acc42ce55fc8d9fbd5" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/21/df/96fad5630c4727e80e53b9837240620baa28d2b51fa48cc505a5bf591c0a/cbor2-6.3.0-cp311-cp311-win32.whl", + hash = "sha256:f230528fb190c0bbd99b4d083d65b074f3a8e511fe8430e1e1740a4c7218a7d8" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/8d/86/ae37c1ec6fc55a132fcdea3ebf84783dcd675cd485ddde4807ffe09ee5b5/cbor2-6.3.0-cp311-cp311-win_amd64.whl", + hash = "sha256:d34621f0edc236e741fdc33846a212e1480b4b1b3a93fba108e6bd0b1e6b0827" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/f3/f4/5837cca2aaa44339655385835ea62d6f0f04181a3351b6a41eeead089506/cbor2-6.3.0-cp311-cp311-win_arm64.whl", + hash = "sha256:956f193a6fe3c7f5af9db9743230be7ef076ed39455eba84542bd54ebe77a8d8" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/38/6f/82721eee6930cc5383783053161f9df48754716dfa1104234ede9a6cc41c/cbor2-6.3.0-cp312-cp312-macosx_11_0_arm64.whl", + hash = "sha256:89512d266cdbb80cd4fae62672824b131c5d235e97f7490afcd0d47f7ff9ae6d" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/2a/58/be854c9ee7a22e342085bb08697d60ee141e9cc294bd2856cf1025e230fd/cbor2-6.3.0-cp312-cp312-manylinux_2_28_aarch64.whl", + hash = "sha256:ddeafc6f7f61cca8f276c7e3d9b5631a14f70f476ca9d03d099fd70021721c7f" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/a2/4a/5885d21ec7654f1261c6af07ad4103732400013cf023394659691042fb3c/cbor2-6.3.0-cp312-cp312-manylinux_2_28_x86_64.whl", + hash = "sha256:4f160b662059cc30ced4436fca332f4c27d0259698a5bde8373c9c6f829aabdf" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/12/7d/a902bcf439e25fc72b53d432d64841afcdbf063c08d435e87fb27362056d/cbor2-6.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", + hash = "sha256:1335ecfed5bb0df37460f7dc4d2f3ce10ae242924b2a8e529c481330784acd82" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/b3/cd/9aeaa7c45839b854ad9d86adf80a6b0bbe73cdf47d84ffbe794b93e7e06c/cbor2-6.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", + hash = "sha256:68faecfbeb247594b298cc0c79ccc00f2c7ad87c19430963032fdf424e740f4d" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/05/fc/f185b697db064ccb027ca3e10a68c1d0709cc4e0fdcc877b33ca8dfc2652/cbor2-6.3.0-cp312-cp312-win32.whl", + hash = "sha256:e8be95a449543f2e0bff31d0e8819b3d20895ee32927384ae05782f92b3d63c7" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/36/12/504f36ab1cd9f1f73869d6171a9ddcf5a18e17335766dcbd3cd3b4c5c8c2/cbor2-6.3.0-cp312-cp312-win_amd64.whl", + hash = "sha256:037acb087ed47278489bf85ff36ec6dce82d3d7529568a2d9977e05c8717b8a8" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/f2/65/37e5b464981556cef57231b35ffd57c62260f46c79ef1019550c757acaae/cbor2-6.3.0-cp312-cp312-win_arm64.whl", + hash = "sha256:0ff787e28c623d0788f1ac13663220689c0ba3696d729c19485cd322a33740e8" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/0c/cf/1297ed2a31423792937d21eee46e9481f4e7d1939e9ff057a8a3ed32f3ab/cbor2-6.3.0-cp313-cp313-macosx_11_0_arm64.whl", + hash = "sha256:988cd609e31a3f88ea29cea60cc87a09d214664bf1f101477bea8db5e7b0b8c3" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/56/4d/1d44118262ee8e4ee6ff1c4bbd7ae73b3b98ada515e852866bd3dd97b057/cbor2-6.3.0-cp313-cp313-manylinux_2_28_aarch64.whl", + hash = "sha256:07bc75c65a843b0ac4f3bb15533c993fd60c2ee934c6fc57361ae6530636c7c6" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/67/40/56e3d8e84f29438a360c4092b40fa76bf7d28ea9ec966ced4a4004674a58/cbor2-6.3.0-cp313-cp313-manylinux_2_28_x86_64.whl", + hash = "sha256:5f7c4e8cb1bdc3c138d6f0beb48762ae31c00cf4abae9fbfb41e76a941f2b0db" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/fe/52/3c0b180551c967e926ddffb6e93fd49a85a01323655b541445fcec0558f7/cbor2-6.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", + hash = "sha256:449e98b5c0ac040bab58869f2ff70873d3bc13f9deb410502ca2a071ebc81eff" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/98/3d/913a59379f88b7b42634b6661c682ff1495c1129f62d1782167e63354d45/cbor2-6.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", + hash = "sha256:9acae7ac21cca02b67082700adcfad611622bf452de9d5376cbf71e651b2f387" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/fd/73/1a4d56e4ace718ed991640e653b074180d75b50aa5b812cf42a3da795a94/cbor2-6.3.0-cp313-cp313-win32.whl", + hash = "sha256:b3fccdf561b27d482d825844ce1b347775c703d792459d0f02a213c88dde3552" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/ad/cf/d750512a4ad708e09e6f312fa9551b92103516e9fc76427ec0e80f232e85/cbor2-6.3.0-cp313-cp313-win_amd64.whl", + hash = "sha256:83511f59935b304169ef4c7b6a5ff36ef56514b72c6c6ec650aec4879e24f29a" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/bf/91/591b1c273c1b256020870a67020eb278752ec843b698082844ab1a40e825/cbor2-6.3.0-cp313-cp313-win_arm64.whl", + hash = "sha256:377b587068ea97d8d7e992e7a77f20cc6726b2c151b5b7ef986dadca47d48c33" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/97/c5/39d987e19221b5ff1b2423965e2cb294c72b4150127d774ba6681597a6bd/cbor2-6.3.0-cp314-cp314-macosx_11_0_arm64.whl", + hash = "sha256:8fb13bfca5df10b9b791a3d33d031c920e6b0d1d743abffd28e926585e2c40fc" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/63/7e/4418c6403a8bd88655bd06d1c453be3e923a8104a46296a1a895d054e9ab/cbor2-6.3.0-cp314-cp314-manylinux_2_28_aarch64.whl", + hash = "sha256:2aded9db2335a7396956f991d5eca77046c355a5ab586f8c718c92c375d67840" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/d7/76/1aa318c7e0ffa296b6576e2e54b8a96746dfda2e3ea22a7363823561e6a7/cbor2-6.3.0-cp314-cp314-manylinux_2_28_x86_64.whl", + hash = "sha256:f82e4f891ffd297dd9a54ba34f556917f156b1dab1527640dfc74ae4c6562cf8" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/10/95/4c5e83d088bba588f4b1fb0a9dae8a8a43d9c0a660587e4711e45827c1e2/cbor2-6.3.0-cp314-cp314-musllinux_1_2_aarch64.whl", + hash = "sha256:541fa487422ed69b85f395dcd8bd36da138f76aa0766d65aecac64c1e6851f4c" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/71/a2/72e8633a043819f6d87b403abdc443d9765ac15917fcd3b0654bd24e46ce/cbor2-6.3.0-cp314-cp314-musllinux_1_2_x86_64.whl", + hash = "sha256:184d7526837d6435ed2f7c198df1fa0ce9c1ffcadf78fe7875f6be9321e892de" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/c6/e0/6e924583b8ade953731c3e2aa210a228758fe35cacf4e14bae7978fd35ae/cbor2-6.3.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", + hash = "sha256:15c2e17287bd09cb30e1c534d32d6c9ef29b9eded18ebe4e6be9634cbe306834" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/7d/e3/c2f8c471a8787af7f154664659828b4e344aaa3626e957c261eb61dc7fb0/cbor2-6.3.0-cp314-cp314-win32.whl", + hash = "sha256:cf63051c8733187fb61332c26177a510a008a996ed2d80e77495e6d7c9c7927a" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/c4/63/7ee9537c6938dc9bcdcbc602d20b016e07003bcf4c8a8129eabcbb0a4bf6/cbor2-6.3.0-cp314-cp314-win_amd64.whl", + hash = "sha256:3ca1f8070af8f44ea4a196b9b788818ebe9eb4345a130999201965c03e6b0713" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/52/62/bd58667e3023cdb276a34b0bd3ba92d4b11a0fe6ebfef16313c37e99d787/cbor2-6.3.0-cp314-cp314-win_arm64.whl", + hash = "sha256:bc50c4a25f2a8c5a8545ef9aac1cdc361acf874521fed75f97c637e7971e82fb" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/4a/62/879f7e2dd1a9dee40c8dcdcc2789d8153135afa5349b401e20cad9df6163/cbor2-6.3.0-cp314-cp314t-macosx_11_0_arm64.whl", + hash = "sha256:e27a28cad25365cd93a7e6ff0da23c9bab30ebe2942d4c0ffd05683de7c661ae" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/02/90/be3ae9af1e3188c0359723fe5615bc5242a0887923b6acf76e7914de0f78/cbor2-6.3.0-cp314-cp314t-manylinux_2_28_aarch64.whl", + hash = "sha256:1f5c0c75c287d59a2ead3a05feecea1246d9c65d7324a59abb6935bfe7df9aef" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/2f/28/9b71e9592207499ce9aa7485d9bad43d863ae18585b0a2bdfd7833498f44/cbor2-6.3.0-cp314-cp314t-manylinux_2_28_x86_64.whl", + hash = "sha256:92995bdfbde99e43a9ac173364042e835fd2ce729ad3f229e76eeac3f56d2e07" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/4a/c2/80e04599fea2553317a88364670ffa3fc19d4bd3c8e410bb996d6d13f474/cbor2-6.3.0-cp314-cp314t-musllinux_1_2_aarch64.whl", + hash = "sha256:2b821cd271723248901f9796bf3c63b2b724e78482df86b4210e8eb293c01a3a" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/7d/4b/626e66e84b1698b850de90bcdca054628864c897f520d71ab4b2d84a25da/cbor2-6.3.0-cp314-cp314t-musllinux_1_2_x86_64.whl", + hash = "sha256:812cf7f2d59aca474eeeb09583821e7660d490ecb3f3a75b25aef773225aff9d" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/08/44/10566c4261238335aa0708732c08478ac6bd7e4636d5cff7992fb3bf2502/cbor2-6.3.0-cp314-cp314t-win32.whl", + hash = "sha256:af143bac7b11a199d0fb66f7cb9de15cb205bb466819dd22855910e52a8523e5" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/f0/b7/4f919e4e11c988277a7ad32614a951fb25577fb4e7270801ddc5feda007b/cbor2-6.3.0-cp314-cp314t-win_amd64.whl", + hash = "sha256:64d3c99181ab0ac788c66ab6855aec0a4d8a2ae1de59907cee612339cf19a9f8" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/d6/8f/f2c4a01fce964daaf77a86cc0c11e6a54c23544951c7efaf335ed3399b59/cbor2-6.3.0-cp314-cp314t-win_arm64.whl", + hash = "sha256:c912a3b0f71594d0f6d3bf5ff36426d888f0d0bbfa91af52efc74a131b93c241" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/50/81/6ac85a76a8ca7a4a8c55dc363b8d31b046c0da30f859b8020dbe64b56aea/cbor2-6.3.0-cp315-cp315-macosx_11_0_arm64.whl", + hash = "sha256:e4e36d190fb55072640ac77dd8259c4f3adecbfe43bfc4f6e567f2eac5e0c334" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/c6/b4/b87ee7d7d7c2b8c6b54fd08d8044ae308898010905fee6b7695eadde3997/cbor2-6.3.0-cp315-cp315-manylinux_2_28_aarch64.whl", + hash = "sha256:fda2b6a74f73ce4d47a0252e726f6fb2dd30cb70ba39ded74979822d7fa1e1ce" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/0d/a1/ded213b748de46e1953c01dbdb71756ad234cd0277903bcdcdd7272cc3ba/cbor2-6.3.0-cp315-cp315-manylinux_2_28_x86_64.whl", + hash = "sha256:58514b189113dad4c6192babd1a157bd45f6f6fb48b478ef5fc0d2a38c085b15" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/f3/ab/672888d32af0915492059f975db1b4bec7a8fb709593310bdda5ce3b6bde/cbor2-6.3.0-cp315-cp315-musllinux_1_2_aarch64.whl", + hash = "sha256:96f54a8900a0bb263916cb2064b4cbea9ba186c8a7519964ff2c74d00a001fc1" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/09/ce/fbea667c514caa76fe50b097c8f70f0c4380da4beb4531bb7a5681669d9b/cbor2-6.3.0-cp315-cp315-musllinux_1_2_x86_64.whl", + hash = "sha256:49f02de4b57a139c3e7d0d114bd2f3131845afaec01a3d21df52b5b90b996572" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/b6/8c/8bbce14109cd6421f18512808246b6ed04eaf23c2f1e3bf21b6fa706d6db/cbor2-6.3.0-cp315-cp315-win32.whl", + hash = "sha256:cd8daf6b6a49edb78bb5a90c59dcd2128e6d73671f8a42cd6ad2e054268e56a4" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/12/73/e200f1273821243f31b62acc10c44a10d759d397bd7cb746f09fa8ad4020/cbor2-6.3.0-cp315-cp315-win_amd64.whl", + hash = "sha256:ea0500a1d050d1b427ca723b7e262fd8a5499880323ee7b14ad3817d1e185862" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/fe/c3/a91587e4f63b9559b7b6c21eac785ddd4180506bae3877de846c36240d5d/cbor2-6.3.0-cp315-cp315-win_arm64.whl", + hash = "sha256:f67deeea9c0e0e110d33dd2075ba8665cb9e2b37ec7322ad177c7943e2196433" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/32/25/09886d8f544784496beac007fe10389ccac6d2976696b5c77e69bdcb5078/cbor2-6.3.0-cp315-cp315t-macosx_11_0_arm64.whl", + hash = "sha256:bc85c16bcaed3bd6446509ac45a425877146437a608e9e867d4dbf40ea95072b" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/c4/0c/7ab759490bacedc5363a806a2573e485c1fbc847fc7681464cf967f714be/cbor2-6.3.0-cp315-cp315t-manylinux_2_28_aarch64.whl", + hash = "sha256:561284712838fe517abfce73f71dc2c72b5b38fde4a42be5f509d0d586856a23" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/ba/15/4be4373d9f712ca04e2e17a55ed3be578ce7cb81f8e8cbfff11c3e3a998e/cbor2-6.3.0-cp315-cp315t-manylinux_2_28_x86_64.whl", + hash = "sha256:188953a34ccb75aa8eda79d30a030cd684b87cabc8d22b8b0b12b26eebfcd522" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/3a/73/a265005dfd6c3d8df5be62b91075418672e9cf2b39e5d57ca24a40e6242d/cbor2-6.3.0-cp315-cp315t-musllinux_1_2_aarch64.whl", + hash = "sha256:76ba2594041b90c29bae8d0079f29cbb3f86133b195e71ffecf1d8b3c40cd821" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/2e/28/3ec6b6496219e04424104d3fc9f9b2978b009fdc5dc1494d8a5be855d25a/cbor2-6.3.0-cp315-cp315t-musllinux_1_2_x86_64.whl", + hash = "sha256:c578dcac82e3befeb79d0dc8909ea89eed809a57dc131c4f874ce77d469fe37a" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/95/d2/98569eacb45cdd1288465715124e4b682536c62fa5d4669b39c09da7f1e7/cbor2-6.3.0-cp315-cp315t-win32.whl", + hash = "sha256:0078f68b5a652bf391cb03f8a25a20358faf667bf0bb9ef32d3c1f220ce174f8" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/7d/e8/5ba1c9cb32df768e61622a8d34dfa7ec70276cde6e2b8a643a3b63be08da/cbor2-6.3.0-cp315-cp315t-win_amd64.whl", + hash = "sha256:549495bf5df0e90060f2d29abf1a6fbd1bd6ce339da5b68d1e51aff3f1c00669" + }, + { + url = "https://mirrors.aliyun.com/pypi/packages/49/a4/c53ad58f723c1a8ac95501f278e3d28f8a35c8ca5f48f110c80f01528e8a/cbor2-6.3.0-cp315-cp315t-win_arm64.whl", + hash = "sha256:8b1a04a575bcde18de582fdbcd872ffec83ebeb91bfada3fed2478040ad76059" + }, +] + [[package]] name = "celery" version = "5.6.3" @@ -3923,6 +4162,7 @@ dependencies = [ { name = "tencentcloud-sdk-python-common", extra = ["async"] }, { name = "tencentcloud-sdk-python-sms" }, { name = "user-agents" }, + { name = "webauthn" }, ] [package.dev-dependencies] @@ -4015,6 +4255,7 @@ requires-dist = [ }, { name = "tencentcloud-sdk-python-sms", specifier = ">=3.1.153" }, { name = "user-agents", specifier = ">=2.2.0" }, + { name = "webauthn", specifier = ">=3.0.1" }, ] [package.metadata.requires-dev] @@ -10115,6 +10356,39 @@ wheels = [ }, ] +[[package]] +name = "pyasn1" +version = "0.6.5" +source = { registry = "https://mirrors.aliyun.com/pypi/simple" } +sdist = { + url = "https://mirrors.aliyun.com/pypi/packages/88/7e/3c0da41061a2021cac7cd524fd57092adbe5b515e8bf9005702e366802e2/pyasn1-0.6.5.tar.gz", + hash = "sha256:6b11616a6bcf3a40e635f082bb232fa57b5e0dd7f517bd7ddd69ec3794508a47" +} +wheels = [ + { + url = "https://mirrors.aliyun.com/pypi/packages/19/1f/3eefd5c84c35cae44549ce1c7f7e58f7945b34f5a6bce07a135438522073/pyasn1-0.6.5-py3-none-any.whl", + hash = "sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587" + }, +] + +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://mirrors.aliyun.com/pypi/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { + url = "https://mirrors.aliyun.com/pypi/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", + hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6" +} +wheels = [ + { + url = "https://mirrors.aliyun.com/pypi/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", + hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a" + }, +] + [[package]] name = "pycparser" version = "3.0" @@ -10861,6 +11135,25 @@ wheels = [ }, ] +[[package]] +name = "pyopenssl" +version = "26.4.0" +source = { registry = "https://mirrors.aliyun.com/pypi/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { + url = "https://mirrors.aliyun.com/pypi/packages/3f/e8/7325d258199b159eb2c03fe32107533e2832e70e63f4fb88a6aa00023201/pyopenssl-26.4.0.tar.gz", + hash = "sha256:28dfcce0162b9211413e26dfbfdf1d24317fbeba18fc93c12400a1856b2a0bc7" +} +wheels = [ + { + url = "https://mirrors.aliyun.com/pypi/packages/51/ad/2cf6d3fa2fae5c79e1ed9960c0d42badd0f94d81dd12b50604cdc839e648/pyopenssl-26.4.0-py3-none-any.whl", + hash = "sha256:f0eb0cb2d581d3ad2b9c489468485e7f2ab6727d08401bcf9d824c3caddf3c1c" + }, +] + [[package]] name = "pyparsing" version = "3.3.3" @@ -14229,6 +14522,28 @@ wheels = [ }, ] +[[package]] +name = "webauthn" +version = "3.0.1" +source = { registry = "https://mirrors.aliyun.com/pypi/simple" } +dependencies = [ + { name = "cbor2" }, + { name = "cryptography" }, + { name = "pyasn1" }, + { name = "pyasn1-modules" }, + { name = "pyopenssl" }, +] +sdist = { + url = "https://mirrors.aliyun.com/pypi/packages/1e/e6/31390f9f2226722d758483b2b56822c3ef89ea577523d99d5eaf0220d2fc/webauthn-3.0.1.tar.gz", + hash = "sha256:da862342c91fc03fbcf9a89cee7346e55c56f8b93fbaf66cfe8a55e2f0a05f6c" +} +wheels = [ + { + url = "https://mirrors.aliyun.com/pypi/packages/ea/5e/cc651030a1d43010234247ab4361aac17276f62b185975100ba62aa00cf7/webauthn-3.0.1-py3-none-any.whl", + hash = "sha256:9927b2f530773bd1d7f8194cd643a2e634a20995ea31f2d8f7a3e70b11c93e31" + }, +] + [[package]] name = "websocket-client" version = "1.9.2" diff --git a/apps/docs/src/content/docs/en/features/login-security.mdx b/apps/docs/src/content/docs/en/features/login-security.mdx index 58eccfa4..0270fb9a 100644 --- a/apps/docs/src/content/docs/en/features/login-security.mdx +++ b/apps/docs/src/content/docs/en/features/login-security.mdx @@ -20,12 +20,12 @@ For devices, idle timeouts and forced sign-out, see [Session management](/en/fea ## UI entry points - **Sign-in page** (`/sign-in`): everyone can open it. -- **Profile** (`/profile`): change your password, bind a phone or authenticator, link third-party accounts, and review recent sign-ins. -- **System → Users** (`/system/user`): superusers reset passwords and two-factor for others. +- **Profile** (`/profile`): change your password, bind a phone or authenticator, manage passkeys, link third-party accounts, and review recent sign-ins. +- **System → Users** (`/system/user`): superusers reset passwords and two-factor for others, or clear all of someone's passkeys. - **System → Config** (`/plugins/config`): change policies with `sys:config:edit`. - **Logs → Sign-in log** (`/log/login`): inspect attempts with `log:login:list`. -Password and two-factor resets require a **superuser**, regardless of menu permissions. +Password resets, two-factor resets and clearing passkeys require a **superuser**, regardless of menu permissions. ## Sign-in methods @@ -34,6 +34,7 @@ Password and two-factor resets require a **superuser**, regardless of menu permi | Username and password | Enter your account, password and the image captcha enabled by default | | SMS code | The SMS plugin must be installed; first verify and bind your number in Profile | | GitHub / Google | The OAuth2 plugin must be configured; sign in with your password first and link your account in Profile | +| Passkey | An admin has configured passkeys in `.env`; sign in with your password first and add one in Profile | An admin-entered or imported phone number cannot be used for SMS sign-in until its owner verifies it. Unknown third-party accounts are refused by default; [automatic registration settings](/en/reference/security-config/#change-settings-in-env) must be enabled explicitly. @@ -77,6 +78,20 @@ Under **System → Config → Sign-in policy**, set **Require two-factor**: An unenrolled user must bind an authenticator during the next web sign-in before entering the system. Required users cannot turn it off. The mobile app accepts codes, but initial enrollment must be completed on the web. +## Passkeys + +A passkey replaces the password with a fingerprint, face or device PIN, and you do not type your account name. An admin first sets `PASSKEY_RP_ID` and `PASSKEY_ORIGINS` in `apps/api/backend/.env` and restarts the backend (see [security settings](/en/reference/security-config/#change-settings-in-env)). Until then the sign-in page hides the button and Profile cannot add one. + +1. Sign in with your password, open **Profile → Security → Passkey**, give it a name and click **Add a passkey**, then follow the browser or system prompt. +2. Sign out, click **Sign in with a passkey** on the sign-in page, pick this passkey and verify. + +**What success looks like:** you land in the app without entering an account or password, and the passkey's row in Profile shows when it was last used. + +- A passkey already proves both "has this device" and "is this person", so passkey sign-in **does not ask for a two-factor code**, and the two-factor requirement policy does not apply to it. +- Disabled, locked and password-expired accounts are still refused. A failed attempt counts only toward the IP limit, because the account is not known at that point. +- Each user can add up to 10 passkeys and rename or delete them in Profile. If someone loses their device, a superuser can clear all of their passkeys under Users. +- The page's domain must match the configuration. For local development open `http://localhost:8888`; browsers refuse passkeys on `127.0.0.1`. + ## Password rules | Rule | Default | Allowed range | @@ -112,7 +127,8 @@ Superusers view and revoke sessions under **Monitoring → Active sessions**. Th ## Limitations -- The only second factors are TOTP and recovery codes: no passkeys (WebAuthn), no hardware keys, and SMS is not offered as a second factor. +- The only second factors are TOTP and recovery codes. Passkeys replace the password but are not a second factor, and SMS is not offered as one. +- Passkeys work only in the web app: the desktop app treats them as unsupported (its window is not on the site's domain), and the mobile app does not support them yet. - No self-service password recovery or self-registration (except third-party sign-in with auto-registration explicitly turned on). - The password expiry reminder is not shown in the web client yet, and an expired password cannot be changed by its owner; see [above](#password-rules). - Session operations use single-instance Redis Lua scripts; Redis Cluster has not been tested. See [Session management](/en/features/login-sessions/). diff --git a/apps/docs/src/content/docs/en/features/overview.md b/apps/docs/src/content/docs/en/features/overview.md index 57713887..6646d805 100644 --- a/apps/docs/src/content/docs/en/features/overview.md +++ b/apps/docs/src/content/docs/en/features/overview.md @@ -11,7 +11,7 @@ Everything below is on `main`. The table matches the Features table in the [READ |---|---|---| | **Access & org** | RBAC (menus / buttons / data scopes) · row-level data permissions · department tree · users & roles | [Users and roles](/en/features/rbac/) · [Data permissions](/en/features/data-permissions/) | | **Import & export** | server-side xlsx / csv export (current filter or selected rows · large exports run in the background and notify you when done · formula-injection safe) · generic import (templates with dropdowns · preview & validation · insert only / upsert / update only · error report · all-or-nothing) · build a whole department tree from one file | [Import and export](/en/features/import-export/) | -| **Sign-in & security** | captcha · lockout · password history & expiry · SMS code sign-in · two-factor auth (TOTP + recovery codes) · OAuth2 (GitHub / Google) · session management (idle timeout + absolute limit · per-client session caps · tells users why they were signed out · force sign-out) | [Sign-in and security](/en/features/login-security/) | +| **Sign-in & security** | captcha · lockout · password history & expiry · SMS code sign-in · passkey sign-in · two-factor auth (TOTP + recovery codes) · OAuth2 (GitHub / Google) · session management (idle timeout + absolute limit · per-client session caps · tells users why they were signed out · force sign-out) | [Sign-in and security](/en/features/login-security/) | | **Workspace** | customizable dashboard (cards appear by permission · layout saved per user on the server) · multi-tab (pin / drag / reload) · command palette ⌘K · shortcuts · guided tour · column visibility and drag-to-reorder (kept in the URL) · theme / radius / tab style · per-user time zone · Chinese & English | [Workspace](/en/features/workspace/) · [Multi-tab](/en/features/multi-tab/) | | **Files & storage** | file manager with previews (pdf / docx / xlsx / images / archives) · local + S3-compatible storage · pre-signed downloads · recycle bin · instant upload · chunked & resumable uploads · attachment panel for any page | [Files and storage](/en/features/file-storage/) | | **Approval workflow** | form designer · flow tree (approve / CC / conditional branches) · approve / reject / transfer / send back / take back / add approvers · timeout reminders and auto-actions · drafts · urgent · handover · AI pre-review / form filling / AI approval nodes | [Approval workflow](/en/features/approval-workflow/) | @@ -30,7 +30,7 @@ The desktop app loads the web build directly, so **everything on the web is on t | Feature | Web menu | Plugin | Mobile app | |---|---|---|---| -| Sign-in and security | Profile · Monitoring → Active sessions · System → Config | SMS sign-in needs `sms`, third-party sign-in needs `oauth2` | Password / SMS sign-in, can enter a two-factor code; users required to enrol must do so on the web first | +| Sign-in and security | Profile · Monitoring → Active sessions · System → Config | SMS sign-in needs `sms`, third-party sign-in needs `oauth2` | Password / SMS sign-in, can enter a two-factor code; users required to enrol must do so on the web first; no passkeys yet | | Users · roles · departments · menus | System → Users / Roles / Departments / Menus | | User list → detail → delete (as a pattern to copy) | | Data permissions | System → Data permissions | | Filtering happens in the backend, so lists in the app are scoped the same way | | Multi-tab · dashboard | — (shell) · Dashboard | | The home tab is a fixed layout (notices, my approvals, shortcuts); no layout editing, no tabs | diff --git a/apps/docs/src/content/docs/en/reference/security-config.mdx b/apps/docs/src/content/docs/en/reference/security-config.mdx index 02b9ba5f..378a1a95 100644 --- a/apps/docs/src/content/docs/en/reference/security-config.mdx +++ b/apps/docs/src/content/docs/en/reference/security-config.mdx @@ -60,6 +60,9 @@ Edit `apps/api/backend/.env` and restart the API. | Key | Default | Notes | |---|---|---| | `MFA_SECRET_KEY` | empty | Encrypts TOTP secrets; empty = two-factor cannot be turned on | +| `PASSKEY_RP_ID` · `PASSKEY_ORIGINS` | empty · `[]` | The domain passkeys are bound to (no scheme or port) and the allowed page origins. Passkeys turn on only when both are set; setting just one fails at startup. In production the ID must be a domain and the origins HTTPS pages under it | +| `PASSKEY_RP_NAME` | empty | Site name shown by the authenticator; empty = `FASTAPI_TITLE` | +| `PASSKEY_MAX_PER_USER` · `PASSKEY_CHALLENGE_SECONDS` | `10` · `300` | Passkeys per user, and the time limit for one add or sign-in | | `LOGIN_IP_LOCK_THRESHOLD` · `LOGIN_IP_LOCK_SECONDS` | `30` · `900` | Per-IP lockout across accounts; threshold 0 = off | | `TRUSTED_PROXIES` | `[]` | Addresses or ranges of your reverse proxies. Empty = no forwarding header is trusted; behind a proxy without it, the backend sees only the proxy's IP, so IP lockout, rate limits and the sign-in log all use the wrong address | | `TOKEN_EXPIRE_SECONDS` | `1800` | Access token lifetime | @@ -85,7 +88,7 @@ The SMS route requires the image captcha first; each number has a 60-second cool The error message **does not distinguish** "no such user", "wrong password" and "account locked", and the timing is evened out too: a bcrypt check takes about 190 ms, while a lookup that finds no user takes about 5 ms, a 40x gap that needs no statistics to spot. So when the user does not exist, an equivalent check runs against a dummy hash (`_DUMMY_PASSWORD_HASH` at the top of [`auth_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/auth_service.py)). -The sign-in endpoints are also rate-limited per IP and path: 5 a minute; the captcha endpoint allows 5 every 30 seconds. +The sign-in endpoints are also rate-limited per IP and path: 5 a minute; the captcha endpoint allows 5 every 30 seconds; passkey sign-in allows 10 a minute for fetching a challenge and 10 for submitting it. The allowed ranges are enforced by the **backend**, not just by the input boxes (`DYNAMIC_INT_BOUNDS` in [`dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/dynamic_config.py)). It was tested once: calling the API directly with an admin token could set the minimum length to 999, after which nobody could change their password. @@ -98,6 +101,7 @@ The second step lasts 5 minutes and allows 5 attempts. Failed codes count toward ## Extension notes - **A new sign-in method must call `mfa_service.gate()`** after confirming the identity; it decides whether to open the session or ask for the second step. SMS sign-in repeats every check that password sign-in makes (IP lockout, disabled accounts, password expiry, failure counting); the code replaces only the "is the password right" step. Reusing just the "open a session" part would skip all of them. +- **Passkey sign-in deliberately skips `gate()`**: it already verified the device and the person (user verification is required), so a code would only add a step. Otherwise it repeats the password sign-in checks: IP lockout, disabled and locked accounts, password expiry, and resetting the failure count on success. A failure is counted against the IP only, since the account is not known yet; an unknown passkey and a deleted one get the same message. - **A new endpoint that works without signing in** goes into `TOKEN_REQUEST_PATH_EXCLUDE` as a full path, not a prefix. - **A new way to sign someone out** calls only `session_store.revoke` / `revoke_user`; do not delete the `fba:session*` Redis keys yourself. Those two functions also record the reason, push the live message and close the connection. Before sessions were reworked, seven files each deleted tokens on their own, and one deleted only the access token, so a kicked user could refresh and be back. @@ -106,11 +110,12 @@ Details and the pitfalls behind them are in the sign-in sessions section of [`co ## Source code - Sign-in flow: [`auth_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/auth_service.py) · endpoints in [`api/v1/auth/auth.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/api/v1/auth/auth.py) +- Passkeys: [`passkey_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/passkey_service.py) · personal endpoints under `/me/passkeys` in [`api/v1/sys/user.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/api/v1/sys/user.py) - Two-factor: [`mfa_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/mfa_service.py) · [`utils/totp.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/totp.py) - Sessions: [`common/security/session.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/common/security/session.py) · active sessions endpoints in [`monitor/online.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/api/v1/monitor/online.py) - Password rules: [`user_password_history_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/user_password_history_service.py) · runtime config in [`utils/dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/dynamic_config.py) - Third-party sign-in: [`plugin/oauth2/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/oauth2) -- Frontend: sign-in page [`sign-in.tsx`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/web/src/routes/_guest/sign-in.tsx) · Profile [`pages/profile/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/profile) · Active sessions [`pages/log-online/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/log-online) · session and refresh [`auth/session.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/auth/session.ts) +- Frontend: sign-in page [`sign-in.tsx`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/web/src/routes/_guest/sign-in.tsx) · Profile [`pages/profile/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/profile) · Active sessions [`pages/log-online/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/log-online) · passkeys in the browser [`auth/passkey.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/auth/passkey.ts) · session and refresh [`auth/session.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/auth/session.ts) ## Tests @@ -123,6 +128,7 @@ Backend tests run against a real database and Redis: - [`test_session.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_session.py) (29 tests): background polling does not keep a session alive, coming back after the idle limit and clicking once does not revive it, the grace period replays the same pair, presenting an old token after it ends the session, and a matching session ID with the wrong secret does **not** revoke anything (otherwise a session ID seen in a log would be enough to sign someone out). Several were mutation-checked: break the condition and the test fails immediately. - [`test_mfa.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_mfa.py) (16 tests): recovery codes work once, a correct password does not reset the failure count, the token dies after too many attempts, required users enrol during sign-in and cannot turn it off, and it cannot be required without a key. +- [`test_passkey.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_passkey.py) (28 tests): a software authenticator really registers and signs in. A challenge works once; a replayed assertion, a wrong origin, a missing user verification, a counter going backwards and a mismatched user handle are all refused; duplicates and the per-user limit are refused; nobody can see or delete another user's passkeys; disabled accounts cannot sign in; sign-in skips two-factor; failures count only against the IP. 12 deliberate mutations each turned a test red. - [`test_auth.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_auth.py): an unknown user and a wrong password look the same, **including timing**; a wrong password does not reveal a lockout; a forced sign-out also revokes the refresh token. - [`test_phone_login.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/sms/tests/test_phone_login.py): unknown and unverified numbers look "sent", a provider failure is indistinguishable from an unknown number, and SMS sign-in also requires two-factor. - The OAuth2 plugin's [`tests/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/oauth2/tests): unknown accounts are not auto-created by default, state binding, only verified emails are trusted. diff --git a/apps/docs/src/content/docs/features/login-security.mdx b/apps/docs/src/content/docs/features/login-security.mdx index 4efc9066..0c212dbf 100644 --- a/apps/docs/src/content/docs/features/login-security.mdx +++ b/apps/docs/src/content/docs/features/login-security.mdx @@ -20,12 +20,12 @@ import ProductShot from '../../../components/ProductShot.astro' ## 界面入口 - **登录页**(`/sign-in`):所有人都能访问。 -- **个人中心**(`/profile`):修改自己的密码、绑定手机号和验证器、关联第三方账号、查看最近登录记录。 -- **系统管理 → 用户管理**(`/system/user`):超级管理员为他人重置密码或二次验证。 +- **个人中心**(`/profile`):修改自己的密码、绑定手机号和验证器、管理通行密钥、关联第三方账号、查看最近登录记录。 +- **系统管理 → 用户管理**(`/system/user`):超级管理员为他人重置密码、二次验证,或清除全部通行密钥。 - **系统管理 → 参数配置**(`/plugins/config`):调整策略,需要 `sys:config:edit`。 - **日志管理 → 登录日志**(`/log/login`):查看登录记录,需要 `log:login:list`。 -重置密码和二次验证按**超级管理员**判定,只授予菜单权限还不能操作。 +重置密码、二次验证和清除通行密钥按**超级管理员**判定,只授予菜单权限还不能操作。 ## 登录方式 @@ -34,6 +34,7 @@ import ProductShot from '../../../components/ProductShot.astro' | 账号密码 | 输入账号、密码,以及默认开启的图形验证码 | | 手机验证码 | 系统已安装短信插件;本人先在个人中心验证并绑定手机号 | | GitHub / Google | 系统已配置 OAuth2 插件;先用账号密码登录,在个人中心关联第三方账号 | +| 通行密钥 | 管理员已在 `.env` 配好通行密钥;本人先用密码登录,在个人中心添加 | 管理员录入或导入的手机号,需要本人验证后才能用于登录。陌生第三方账号默认不能登录;开放自动注册需另行[配置](/reference/security-config/#在-env-中修改)。 @@ -77,6 +78,20 @@ python -c "import os;print(os.urandom(32).hex())" 尚未绑定的用户,下次在网页登录时需要先完成绑定才能进入系统。被强制的用户不能自己关闭。手机 App 支持输入动态码,但首次绑定需要在网页端完成。 +## 通行密钥 + +通行密钥(Passkey)用指纹、面容或设备 PIN 代替密码,登录时不用输入账号。管理员先在 `apps/api/backend/.env` 设置 `PASSKEY_RP_ID` 和 `PASSKEY_ORIGINS` 并重启后端(见[登录安全配置](/reference/security-config/#在-env-中修改));没配时登录页不显示这个按钮,个人中心也不能添加。 + +1. 用密码登录,打开「个人中心 → 安全 → 通行密钥」,起个名字后点「添加通行密钥」,按浏览器或系统的提示验证。 +2. 退出后在登录页点「用通行密钥登录」,选中这把钥匙并验证。 + +**看到什么算成功:** 不输账号密码直接进入系统;个人中心里这一行显示「最近使用」的时间。 + +- 通行密钥本身已经验证了「持有这台设备」和「是本人」两件事,所以这种登录**不再要求二次验证动态码**,强制二次验证的策略对它也不生效。 +- 停用、锁定和密码过期的账号照样会被拒绝;验证失败只计入 IP 的失败次数(这时还不知道是哪个账号)。 +- 每人最多添加 10 把,可以在个人中心改名、删除;验证器丢了的人可以请超级管理员在「用户管理」里一次清除。 +- 页面地址的域名要和配置一致。本地开发请从 `http://localhost:8888` 打开,从 `127.0.0.1` 打开时浏览器会直接拒绝。 + ## 密码规则 | 规则 | 默认 | 可改范围 | @@ -112,7 +127,8 @@ python -c "import os;print(os.urandom(32).hex())" ## 已知限制 -- 第二因素只有 TOTP 和恢复码,没有通行密钥(WebAuthn)、硬件密钥,也没有用短信当第二因素。 +- 第二因素只有 TOTP 和恢复码;通行密钥只能代替密码登录,不能当第二因素,也没有用短信当第二因素。 +- 通行密钥只在网页端可用:桌面端按不支持处理(窗口地址不是网站域名),手机 App 还没有接。 - 没有自助找回密码和自助注册(第三方登录显式打开自动建号的除外)。 - 密码到期提醒在网页端还没显示出来;过期后本人不能自助改密码,见[上文](#密码规则)。 - 会话依赖单实例 Redis 的 Lua 脚本,尚未在 Redis Cluster 上实测,见[登录会话](/features/login-sessions/)。 diff --git a/apps/docs/src/content/docs/features/overview.md b/apps/docs/src/content/docs/features/overview.md index b4cc8e2d..f7a2de72 100644 --- a/apps/docs/src/content/docs/features/overview.md +++ b/apps/docs/src/content/docs/features/overview.md @@ -11,7 +11,7 @@ sidebar: |---|---|---| | **权限与组织** | RBAC(菜单 / 按钮 / 数据范围)· 行级数据权限 · 部门树 · 用户与角色 | [用户与角色](/features/rbac/) · [数据权限](/features/data-permissions/) | | **导入导出** | 服务端导出 xlsx / csv(按当前筛选或勾选的行 · 大批量转后台、完成发站内消息 · 防公式注入)· 通用导入(带下拉的模板 · 预览校验 · 只新增 / 新增并更新 / 只更新 · 错误报告 · 全部成功才导入)· 一份文件建整棵部门树 | [导入导出](/features/import-export/) | -| **登录与安全** | 图形验证码 · 失败锁定 · 密码历史与过期 · 手机验证码登录 · 二次验证(TOTP + 恢复码)· OAuth2(GitHub / Google)· 会话管理(空闲超时 + 绝对上限 · 按端限制会话数 · 被踢下线说明原因 · 强制下线) | [登录与安全](/features/login-security/) | +| **登录与安全** | 图形验证码 · 失败锁定 · 密码历史与过期 · 手机验证码登录 · 通行密钥登录 · 二次验证(TOTP + 恢复码)· OAuth2(GitHub / Google)· 会话管理(空闲超时 + 绝对上限 · 按端限制会话数 · 被踢下线说明原因 · 强制下线) | [登录与安全](/features/login-security/) | | **工作区** | 可编辑布局的工作台(卡片按权限出现 · 布局按人存服务端)· 多页签(固定 / 拖拽 / 重新加载)· 命令面板 ⌘K · 快捷键 · 功能引导 · 列表列显隐与拖拽排序(写进地址栏)· 主题色 / 圆角 / 页签外观 · 每人自己的时区 · 中英双语 | [工作台与界面](/features/workspace/) · [多页签](/features/multi-tab/) | | **文件与存储** | 文件管理器 + 在线预览(pdf / docx / xlsx / 图片 / 压缩包)· 本地 + S3 兼容存储 · 预签名直连下载 · 回收站 · 秒传 · 分片上传与断点续传 · 可嵌进任何页面的附件面板 | [文件与存储](/features/file-storage/) | | **审批流** | 表单设计器 · 流程树(审批 / 抄送 / 条件分支)· 同意 / 驳回 / 转交 / 退回 / 拿回 / 加签 · 超时提醒与自动处理 · 草稿 · 加急 · 离职交接 · AI 预审 / 帮填表单 / AI 审批节点 | [审批流](/features/approval-workflow/) | @@ -30,7 +30,7 @@ sidebar: | 功能 | 网页端菜单 | 插件 | 手机 App | |---|---|---|---| -| 登录与安全 | 个人中心 · 系统监控 → 在线用户 · 系统管理 → 参数配置 | 手机验证码登录要 `sms`,第三方登录要 `oauth2` | 密码 / 手机验证码登录,能输动态码;被强制开二次验证、还没绑定的人要先到网页端绑定 | +| 登录与安全 | 个人中心 · 系统监控 → 在线用户 · 系统管理 → 参数配置 | 手机验证码登录要 `sms`,第三方登录要 `oauth2` | 密码 / 手机验证码登录,能输动态码;被强制开二次验证、还没绑定的人要先到网页端绑定;还不支持通行密钥 | | 用户 · 角色 · 部门 · 菜单 | 系统管理 → 用户 / 角色 / 部门 / 菜单管理 | | 用户列表 → 详情 → 删除(作为可照抄的范式) | | 数据权限 | 系统管理 → 数据权限 | | 过滤在后端,App 调到的列表一样受约束 | | 多页签 · 工作台 | —(外壳)· 仪表盘 | | 首页是固定的公告 + 我的审批 + 入口,不能编辑布局;没有多页签 | diff --git a/apps/docs/src/content/docs/reference/security-config.mdx b/apps/docs/src/content/docs/reference/security-config.mdx index f7810488..71f55368 100644 --- a/apps/docs/src/content/docs/reference/security-config.mdx +++ b/apps/docs/src/content/docs/reference/security-config.mdx @@ -60,6 +60,9 @@ description: 登录、密码与会话的配置键、默认值和生效顺序, | 键 | 默认值 | 说明 | |---|---|---| | `MFA_SECRET_KEY` | 空 | 加密 TOTP 密钥用;留空 = 不能开二次验证 | +| `PASSKEY_RP_ID` · `PASSKEY_ORIGINS` | 空 · `[]` | 通行密钥绑定的域名(不带协议和端口)和允许的页面地址;两个都配才开启,只配一个启动报错。生产环境要求是域名、地址走 HTTPS 且在这个域名下 | +| `PASSKEY_RP_NAME` | 空 | 认证器里显示的站点名;空 = 用 `FASTAPI_TITLE` | +| `PASSKEY_MAX_PER_USER` · `PASSKEY_CHALLENGE_SECONDS` | `10` · `300` | 每人最多几把、一次添加或登录的时限 | | `LOGIN_IP_LOCK_THRESHOLD` · `LOGIN_IP_LOCK_SECONDS` | `30` · `900` | 单 IP 跨账号的失败锁定;阈值 0 = 关闭 | | `TRUSTED_PROXIES` | `[]` | 反代的地址或网段。空 = 不采信任何转发头;部署在反代后面却不填,后端看到的 IP 全是反代的,IP 锁定、限流、登录日志里的 IP 都跟着错 | | `TOKEN_EXPIRE_SECONDS` | `1800` | access token 有效期 | @@ -85,7 +88,7 @@ TLS 在上游终结时,入口代理必须覆盖客户端传入的 `X-Forwarded 错误提示**不区分**「用户不存在」「密码错」「账号已锁」,耗时也抹平了:bcrypt 校验一次约 190 ms,而查无此人只要约 5 ms,40 倍的差距不用任何统计手段就能看出来。所以用户不存在时也拿一个假哈希跑一遍等价的校验([`auth_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/auth_service.py) 顶部的 `_DUMMY_PASSWORD_HASH`)。 -登录接口本身还按「IP + 路径」限流:每分钟 5 次;取图形验证码的接口每 30 秒 5 次。 +登录接口本身还按「IP + 路径」限流:每分钟 5 次;取图形验证码的接口每 30 秒 5 次;通行密钥登录的取挑战和提交各每分钟 10 次。 可改范围是**后端**卡的,不只是界面上的输入框([`dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/dynamic_config.py) 的 `DYNAMIC_INT_BOUNDS`)。曾经实测过:带管理员 token 直接调接口,最小长度能被写成 999,结果是所有人都改不了密码。 @@ -98,6 +101,7 @@ TOTP 使用 6 位数字、30 秒时间片、SHA-1,前后各容忍一个时间 ## 扩展须知 - **新的登录方式要过 `mfa_service.gate()`**:身份确认之后调它,决定是直接开会话还是进入第二步。手机验证码登录就是逐条照抄了密码登录的检查(IP 锁定、停用判定、密码过期、成败计数),验证码替代的只是「密码对不对」这一步 —— 只复用「开会话」那一段的话,这些检查全会漏掉。 +- **通行密钥登录刻意不过 `gate()`**:它已经验证了设备和本人(要求用户验证,UV),再要动态码只是多一步。除此之外照抄密码登录的检查:IP 锁定、停用、账号锁定、密码过期、成功清零计数。验证失败时还不知道是哪个账号,只计 IP;不认识的钥匙和已删除的钥匙返回同一句话。 - **不用登录就能调的新接口**,要加进 `TOKEN_REQUEST_PATH_EXCLUDE`,写完整路径、不要写成前缀。 - **新的「让某人下线」的入口**,只调 `session_store.revoke` / `revoke_user`,不要自己删 `fba:session*` 的 Redis key:这两个函数会顺带写原因、推实时消息、断开连接。会话改造之前,有 7 个文件各自删 token,其中一处只删了 access token —— 被踢的人刷新一下就回来了。 @@ -106,11 +110,12 @@ TOTP 使用 6 位数字、30 秒时间片、SHA-1,前后各容忍一个时间 ## 代码位置 - 登录流程:[`auth_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/auth_service.py) · 接口 [`api/v1/auth/auth.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/api/v1/auth/auth.py) +- 通行密钥:[`passkey_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/passkey_service.py) · 个人接口在 [`api/v1/sys/user.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/api/v1/sys/user.py) 的 `/me/passkeys` - 二次验证:[`mfa_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/mfa_service.py) · [`utils/totp.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/totp.py) - 会话:[`common/security/session.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/common/security/session.py) · 在线用户接口 [`monitor/online.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/api/v1/monitor/online.py) - 密码策略:[`user_password_history_service.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/service/user_password_history_service.py) · 运行时配置 [`utils/dynamic_config.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/utils/dynamic_config.py) - 第三方登录:[`plugin/oauth2/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/oauth2) -- 前端:登录页 [`sign-in.tsx`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/web/src/routes/_guest/sign-in.tsx) · 个人中心 [`pages/profile/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/profile) · 在线用户 [`pages/log-online/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/log-online) · 会话与刷新 [`auth/session.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/auth/session.ts) +- 前端:登录页 [`sign-in.tsx`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/web/src/routes/_guest/sign-in.tsx) · 个人中心 [`pages/profile/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/profile) · 在线用户 [`pages/log-online/`](https://github.com/yile2020/fastapi-react-admin/tree/main/packages/platform/src/pages/log-online) · 通行密钥的浏览器那一侧 [`auth/passkey.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/auth/passkey.ts) · 会话与刷新 [`auth/session.ts`](https://github.com/yile2020/fastapi-react-admin/blob/main/packages/platform/src/auth/session.ts) ## 测试 @@ -123,6 +128,7 @@ TOTP 使用 6 位数字、30 秒时间片、SHA-1,前后各容忍一个时间 - [`test_session.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_session.py)(29 条):后台轮询不续命、离开超过空闲时长回来点一下也不复活、宽限期内回放同一组令牌、宽限期外作废整个会话、会话 ID 对得上但 secret 对不上**不**撤销(否则凭日志里看得到的会话 ID 就能把人踢下线)。其中几条做过变异检验:把对应的判断改掉,测试当场红。 - [`test_mfa.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_mfa.py)(16 条):恢复码只能用一次、密码对了不清零失败计数、试满次数后令牌作废、被强制的人登录时绑定且不能自己关、没配密钥不能强制。 +- [`test_passkey.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_passkey.py)(28 条):用一个软件认证器真走注册和登录。同一个挑战只能用一次、旧断言回放被拒、地址不对 / 没做用户验证 / 计数器倒退 / 用户句柄不符都被拒、重复添加和超过上限被拒、看不到也删不了别人的钥匙、停用账号登不进、登录不走二次验证、失败只计 IP。做过 12 处变异检验,全部当场红。 - [`test_auth.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/app/admin/tests/api_v1/test_auth.py):用户不存在和密码错的响应一样、**耗时**也一样、错密码不暴露账号已锁、强制下线连 refresh token 一起作废。 - [`test_phone_login.py`](https://github.com/yile2020/fastapi-react-admin/blob/main/apps/api/backend/plugin/sms/tests/test_phone_login.py):没注册 / 没验证的号看起来也「发了」、厂商故障和陌生号码不可区分、手机登录也要过二次验证。 - OAuth2 插件的 [`tests/`](https://github.com/yile2020/fastapi-react-admin/tree/main/apps/api/backend/plugin/oauth2/tests):陌生账号默认不建号、state 绑定、只认已验证的邮箱。 diff --git a/apps/web/src/routes/_guest/-passkey-sign-in.tsx b/apps/web/src/routes/_guest/-passkey-sign-in.tsx new file mode 100644 index 00000000..433fec0c --- /dev/null +++ b/apps/web/src/routes/_guest/-passkey-sign-in.tsx @@ -0,0 +1,66 @@ +import * as React from "react" +import { useTranslation } from "react-i18next" +import { useQuery, useQueryClient } from "@tanstack/react-query" +import { IconFingerprint, IconLoader2 } from "@tabler/icons-react" +import { passkeyEnabledQuery, passkeyErrorMessage, passkeySupported } from "@admin/platform/auth/passkey" +import { loginByPasskey } from "@admin/platform/auth/session" +import { Alert } from "@admin/ui/components/alert" +import { Button } from "@admin/ui/components/button" + +/** + * 登录页的「用通行密钥登录」。密码 / 手机两种方式下面都有,不用先输用户名(用哪把由认证器挑)。 + * + * - 不显示的两种情况:浏览器不支持(含桌面端,见 `auth/passkey.ts`)· 服务端**明确**说没开 + * - 🔴 「开没开」那个查询**失败**时照样显示按钮:藏起来就是把服务端错误伪装成「没有这个功能」(硬纪律 9), + * 点了按钮会走到真实的报错 + * - 查询还在路上时先不显示,免得按钮闪一下又没了 + */ +export function PasskeySignIn({ onDone }: { onDone: () => Promise }) { + const { t } = useTranslation() + const qc = useQueryClient() + const enabled = useQuery(passkeyEnabledQuery) + const [pending, setPending] = React.useState(false) + const [error, setError] = React.useState(null) + + if (!passkeySupported() || enabled.isPending || enabled.data?.enabled === false) return null + + async function signIn() { + setError(null) + setPending(true) + try { + await loginByPasskey(qc) + await onDone() + } catch (err) { + setError(passkeyErrorMessage(err, t)) + } finally { + setPending(false) + } + } + + return ( +
+
+ + {t("或者")} + +
+ + {error && ( + + {error} + + )} +
+ ) +} diff --git a/apps/web/src/routes/_guest/sign-in.tsx b/apps/web/src/routes/_guest/sign-in.tsx index ee979b98..02d71975 100644 --- a/apps/web/src/routes/_guest/sign-in.tsx +++ b/apps/web/src/routes/_guest/sign-in.tsx @@ -44,6 +44,7 @@ import { ThemeMenu } from "@/components/theme-menu" import { BRAND } from "@/lib/brand" import { DesktopServerForm, DesktopServerLine, needsDesktopServer } from "@/routes/_guest/-desktop-server" import { MfaStep } from "@/routes/_guest/-mfa-step" +import { PasskeySignIn } from "@/routes/_guest/-passkey-sign-in" import { PublicNotices } from "@/routes/_guest/-public-notices" import { SignInBrandPanel, SignInBrandStrip } from "@/routes/_guest/-sign-in-brand" @@ -381,7 +382,8 @@ function SignInPage() { ) : mfa ? ( ) : ( - /* 两个面板给同一个 min-h:切登录方式时「欢迎回来」不会上下跳 */ + <> + {/* 两个面板给同一个 min-h:切登录方式时「欢迎回来」不会上下跳 */} setMethod(v as Method)} className="mt-7"> {/* 下划线页签而不是胶囊组:胶囊是 shadcn 的默认长相,一眼就是模板 */} @@ -573,6 +575,9 @@ function SignInPage() { + {/* 通行密钥:两种登录方式下面都有,不用先输用户名 */} + + )} {!serverForm && setServerForm(true)} />} diff --git a/packages/api/src/schema.d.ts b/packages/api/src/schema.d.ts index 533c38d2..bc1ef649 100644 --- a/packages/api/src/schema.d.ts +++ b/packages/api/src/schema.d.ts @@ -81,6 +81,63 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/auth/passkey/enabled": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** 通行密钥登录开没开(登录页据此决定出不出按钮) */ + get: operations["passkey_enabled_api_v1_auth_passkey_enabled_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/passkey/options": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * 通行密钥登录:取挑战 + * @description 不带用户名(可发现凭据)。`options` 原样交给浏览器的 PublicKeyCredential.parseRequestOptionsFromJSON() + */ + post: operations["passkey_login_options_api_v1_auth_passkey_options_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/auth/passkey/login": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * 通行密钥登录:交断言 + * @description 通行密钥要求了用户验证(指纹 / 面容 / PIN),所以这条路不再走二次验证 + */ + post: operations["passkey_login_api_v1_auth_passkey_login_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/auth/mfa/verify": { parameters: { query?: never; @@ -944,6 +1001,79 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/sys/users/me/passkeys": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** 获取当前用户的通行密钥 */ + get: operations["get_my_passkeys_api_v1_sys_users_me_passkeys_get"]; + put?: never; + /** 添加通行密钥:交注册结果 */ + post: operations["register_my_passkey_api_v1_sys_users_me_passkeys_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/sys/users/me/passkeys/options": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * 添加通行密钥:取注册挑战 + * @description `options` 原样交给浏览器的 PublicKeyCredential.parseCreationOptionsFromJSON() + */ + post: operations["passkey_registration_options_api_v1_sys_users_me_passkeys_options_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/sys/users/me/passkeys/{pk}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** 给自己的通行密钥改名 */ + put: operations["rename_my_passkey_api_v1_sys_users_me_passkeys__pk__put"]; + post?: never; + /** 删除自己的一把通行密钥 */ + delete: operations["delete_my_passkey_api_v1_sys_users_me_passkeys__pk__delete"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/sys/users/{pk}/passkeys": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** 清掉用户的全部通行密钥(设备丢了) */ + delete: operations["reset_user_passkeys_api_v1_sys_users__pk__passkeys_delete"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/sys/data-rules/models": { parameters: { query?: never; @@ -8470,6 +8600,54 @@ export interface components { */ created_time: string; }; + /** + * GetPasskeyAvailability + * @description 登录页据此决定出不出「用通行密钥登录」按钮 + */ + GetPasskeyAvailability: { + /** + * Enabled + * @description 服务端是否配置了通行密钥(PASSKEY_RP_ID + PASSKEY_ORIGINS) + */ + enabled: boolean; + }; + /** + * GetPasskeyDetail + * @description 通行密钥(只下发展示要用的,公钥 / 凭据 ID 不出网) + */ + GetPasskeyDetail: { + /** + * Id + * @description 通行密钥 ID + */ + id: string | number; + /** + * Name + * @description 名称 + */ + name: string; + /** + * Backed Up + * @description 是否已同步备份(云端 Passkey,换设备也能用) + */ + backed_up: boolean; + /** + * Transports + * @description 传输方式,逗号分隔(internal / hybrid / usb …) + */ + transports?: string | null; + /** + * Created Time + * Format: date-time + * @description 添加时间 + */ + created_time: string; + /** + * Last Used Time + * @description 最近一次用它登录的时间 + */ + last_used_time?: string | null; + }; /** * GetRecycledFileDetail * @description 回收站里的文件 @@ -11193,6 +11371,78 @@ export interface components { total_pages: number; links: components["schemas"]["_Links"]; }; + /** + * PasskeyLoginOptions + * @description 登录第一步:挑战。`options` 原样交给 `PublicKeyCredential.parseRequestOptionsFromJSON()` + */ + PasskeyLoginOptions: { + /** + * Challenge Id + * @description 挑战编号,第二步原样带回 + */ + challenge_id: string; + /** + * Options + * @description WebAuthn 的 PublicKeyCredentialRequestOptions(JSON 形式) + */ + options: { + [key: string]: unknown; + }; + }; + /** + * PasskeyLoginParam + * @description 登录第二步:`navigator.credentials.get()` 的结果 + */ + PasskeyLoginParam: { + /** + * Challenge Id + * @description 第一步给的挑战编号 + */ + challenge_id: string; + /** + * Credential + * @description PublicKeyCredential.toJSON() 的结果 + */ + credential: { + [key: string]: unknown; + }; + /** + * Client + * @description 登录端 + * @default web + * @enum {string} + */ + client: "web" | "desktop" | "mobile"; + }; + /** + * PasskeyNameParam + * @description 改名 + */ + PasskeyNameParam: { + /** + * Name + * @description 名称 + */ + name: string; + }; + /** + * PasskeyRegisterParam + * @description 添加:`navigator.credentials.create()` 的结果 + */ + PasskeyRegisterParam: { + /** + * Name + * @description 名称 + */ + name: string; + /** + * Credential + * @description PublicKeyCredential.toJSON() 的结果 + */ + credential: { + [key: string]: unknown; + }; + }; /** PingResult */ PingResult: { /** @@ -12148,6 +12398,38 @@ export interface components { msg: string; data: components["schemas"]["GetOpenAppDetail"]; }; + /** ResponseSchemaModel[GetPasskeyAvailability] */ + ResponseSchemaModel_GetPasskeyAvailability_: { + /** + * Code + * @description 返回状态码 + * @default 200 + */ + code: number; + /** + * Msg + * @description 返回信息 + * @default 请求成功 + */ + msg: string; + data: components["schemas"]["GetPasskeyAvailability"]; + }; + /** ResponseSchemaModel[GetPasskeyDetail] */ + ResponseSchemaModel_GetPasskeyDetail_: { + /** + * Code + * @description 返回状态码 + * @default 200 + */ + code: number; + /** + * Msg + * @description 返回信息 + * @default 请求成功 + */ + msg: string; + data: components["schemas"]["GetPasskeyDetail"]; + }; /** ResponseSchemaModel[GetRoleWithRelationDetail] */ ResponseSchemaModel_GetRoleWithRelationDetail_: { /** @@ -12868,6 +13150,22 @@ export interface components { msg: string; data: components["schemas"]["PageData_GetWebhookDeliveryRow_"]; }; + /** ResponseSchemaModel[PasskeyLoginOptions] */ + ResponseSchemaModel_PasskeyLoginOptions_: { + /** + * Code + * @description 返回状态码 + * @default 200 + */ + code: number; + /** + * Msg + * @description 返回信息 + * @default 请求成功 + */ + msg: string; + data: components["schemas"]["PasskeyLoginOptions"]; + }; /** ResponseSchemaModel[PingResult] */ ResponseSchemaModel_PingResult_: { /** @@ -13422,6 +13720,23 @@ export interface components { /** Data */ data: components["schemas"]["GetNoticePublicItem"][]; }; + /** ResponseSchemaModel[list[GetPasskeyDetail]] */ + ResponseSchemaModel_list_GetPasskeyDetail__: { + /** + * Code + * @description 返回状态码 + * @default 200 + */ + code: number; + /** + * Msg + * @description 返回信息 + * @default 请求成功 + */ + msg: string; + /** Data */ + data: components["schemas"]["GetPasskeyDetail"][]; + }; /** ResponseSchemaModel[list[GetRoleDetail]] */ ResponseSchemaModel_list_GetRoleDetail__: { /** @@ -15454,6 +15769,79 @@ export interface operations { }; }; }; + passkey_enabled_api_v1_auth_passkey_enabled_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_GetPasskeyAvailability_"]; + }; + }; + }; + }; + passkey_login_options_api_v1_auth_passkey_options_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_PasskeyLoginOptions_"]; + }; + }; + }; + }; + passkey_login_api_v1_auth_passkey_login_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["PasskeyLoginParam"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_GetLoginToken_"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; mfa_verify_api_v1_auth_mfa_verify_post: { parameters: { query?: never; @@ -17499,6 +17887,179 @@ export interface operations { }; }; }; + get_my_passkeys_api_v1_sys_users_me_passkeys_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_list_GetPasskeyDetail__"]; + }; + }; + }; + }; + register_my_passkey_api_v1_sys_users_me_passkeys_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["PasskeyRegisterParam"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_GetPasskeyDetail_"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + passkey_registration_options_api_v1_sys_users_me_passkeys_options_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_dict_str__Any__"]; + }; + }; + }; + }; + rename_my_passkey_api_v1_sys_users_me_passkeys__pk__put: { + parameters: { + query?: never; + header?: never; + path: { + /** @description 通行密钥 ID */ + pk: number; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["PasskeyNameParam"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseModel"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + delete_my_passkey_api_v1_sys_users_me_passkeys__pk__delete: { + parameters: { + query?: never; + header?: never; + path: { + /** @description 通行密钥 ID */ + pk: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseModel"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + reset_user_passkeys_api_v1_sys_users__pk__passkeys_delete: { + parameters: { + query?: never; + header?: never; + path: { + /** @description 用户 ID */ + pk: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseModel"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; get_data_rule_models_api_v1_sys_data_rules_models_get: { parameters: { query?: never; diff --git a/packages/i18n/src/locales/en-US.json b/packages/i18n/src/locales/en-US.json index dbd488b7..2de056c4 100644 --- a/packages/i18n/src/locales/en-US.json +++ b/packages/i18n/src/locales/en-US.json @@ -727,6 +727,7 @@ "删除选项": "Delete option", "删除通知": "Delete notification", "删除通知公告": "Delete notice", + "删除通行密钥": "Remove passkey", "删除部门": "Delete department", "判断不了": "Unknown", "利落": "Sharp", @@ -871,6 +872,7 @@ "只列出前端真实存在的 {{n}} 个路由 —— 从根上杜绝死链。": "Lists only the {{n}} routes that exist in the frontend — dead links are impossible by construction.", "只列出对一个群说得通的通知。「抄送给你」「你有新的待办」这类对着本人说的不能推到群里。": "Only notifications that make sense to a whole group are listed. Ones addressed to a single person (\"CC'd to you\", \"You have a new task\") cannot be pushed to a group.", "只取发起人部门(或部门及下级)里有这个角色的人;取不到时按「找不到审批人」处理,不会放开成全公司": "Only people with this role in the initiator's department (or below); if none, it is treated as \"no approver found\", never widened to the whole company", + "只在这台设备上": "This device only", "只填主机名(不带 https://)。默认 dysmsapi.aliyuncs.com;VPC 内可用 dysmsapi-vpc.cn-hangzhou.aliyuncs.com 这类地域接入点": "Host name only (no https://). Defaults to dysmsapi.aliyuncs.com; inside a VPC use a regional endpoint like dysmsapi-vpc.cn-hangzhou.aliyuncs.com", "只对这个节点的审批人生效;隐藏的字段服务端直接不下发": "Applies to this step's approvers only; hidden fields are never sent by the server", "只导出选中的 {{n}} 条": "Export {{n}} selected", @@ -1258,9 +1260,11 @@ "已发布版本": "Published version", "已取消": "Canceled", "已取消移动「{{name}}」": "Cancelled moving \"{{name}}\"", + "已取消,或者等太久超时了": "Cancelled, or it took too long and timed out", "已受理": "Accepted", "已受理(厂商已接单,送达看运营商回执)": "Accepted (the provider took the request; delivery depends on the carrier receipt)", "已同意": "Approved", + "已同步到云端": "Synced to the cloud", "已启用": "Enabled", "已固定": "Pinned", "已在其他标签页退出登录": "You signed out in another tab.", @@ -1293,6 +1297,7 @@ "已放弃": "Abandoned", "已新建": "Created", "已有同名视图": "A view with this name already exists", + "已清除": "Cleared", "已生成到草稿:检查之后再保存或发布": "Generated into the draft: review it before saving or publishing", "已用空间": "Space used", "已确认阅读": "Marked as read", @@ -1404,8 +1409,10 @@ "当前标签页的内容区。筛选、分页这些视图状态都记在地址栏里,刷新浏览器也能原样恢复。": "The content of the current tab. Filters and pagination live in the address bar, so a browser refresh restores them exactly.", "当前没有有效会话": "No valid sessions", "当前浏览器不支持流式响应": "This browser does not support streaming responses", + "当前浏览器或客户端不支持通行密钥。请用较新的 Chrome、Edge、Safari 或 Firefox 打开网页版。": "This browser or client doesn't support passkeys. Open the web version in a recent Chrome, Edge, Safari or Firefox.", "当前登录用户 ID": "Current user ID", "当前登录用户部门 ID": "Current user’s department ID", + "当前网址不能使用通行密钥,请用系统配置的域名打开页面": "Passkeys can't be used at this address. Open the page on the domain configured for this system", "当前角色有改过还没保存的授权,切走会丢掉这些改动。": "This role has unsaved permission changes; leaving will discard them.", "当前页面用的还是旧版前端,刷新后继续使用。": "This tab is still running the old frontend. Reload to continue.", "当前频率": "Current freq", @@ -1462,6 +1469,7 @@ "我的": "Me", "我的审批": "My approvals", "我的工作": "My work", + "我的设备": "My device", "或": "or", "或签": "Any one", "或签 · 一人同意即可": "Any one approves", @@ -1469,6 +1477,7 @@ "或者": "OR", "截止触发时间": "Expiry time", "所属应用": "App", + "所属用户": "Owner", "所属类型:{{name}}": "Type: {{name}}", "所有人必须二次验证": "two-factor required for everyone", "所有人必须开": "Required for everyone", @@ -1674,6 +1683,7 @@ "改了什么": "What changed", "改办理人": "Reassign", "改动会立刻生效(后端在登录 / 验证码 / 改密码路径上实时读这张表)。": "Changes take effect immediately — the backend reads this table live on the sign-in, captcha and password paths.", + "改名": "Rename", "改哪一位的待办": "Whose task", "改地址会退出当前登录 —— token 是跟着服务器发的。": "Changing the address signs you out — tokens belong to the server that issued them.", "改好之后点「重新提交」,审批从头开始": "Make your changes and click “Submit again”. Approval starts over.", @@ -1882,6 +1892,7 @@ "最近一次": "Last attempt", "最近一次 {{at}}": "Last at {{at}}", "最近使用": "Last used", + "最近使用 {{time}}": "Last used {{time}}", "最近失败": "Last failure", "最近成功": "Last success", "最近有哪些人改过东西?": "Who has changed things recently?", @@ -2214,6 +2225,7 @@ "添加": "Add", "添加 {{n}} 人": "Add {{n}}", "添加一行": "Add row", + "添加于 {{time}}": "Added {{time}}", "添加分组": "Add group", "添加列": "Add column", "添加失败,请稍后重试": "Add failed, please try again later", @@ -2224,6 +2236,7 @@ "添加用户到「{{name}}」": "Add users to “{{name}}”", "添加节点": "Add step", "添加选项": "Add option", + "添加通行密钥": "Add a passkey", "添加附件": "Add attachment", "清单从开放接口的声明里自动收集。没勾的接口调用时返回 403;每个接口返回哪些字段见对接文档": "The list is collected from the open API declarations. Unchecked APIs return 403; see the integration guide for the fields each API returns", "清空": "Clear", @@ -2237,7 +2250,9 @@ "清空短信发送日志": "Clear SMS logs", "清空重填": "Clear and start over", "清除": "Clear", + "清除全部通行密钥": "Clear all passkeys", "清除图标": "Clear icon", + "清除失败": "Could not clear", "清除格式": "Clear formatting", "清除筛选": "Clear filters", "渠道": "Channel", @@ -2295,6 +2310,8 @@ "用认证器(Google Authenticator、Microsoft Authenticator、1Password 等)扫下面的二维码,再输入它显示的 6 位码。": "Scan the QR code below with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password …), then enter the 6-digit code it shows.", "用认证器(Google Authenticator、Microsoft Authenticator、1Password 等)扫这个二维码,再输入它显示的 6 位码确认。": "Scan this QR code with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password …), then enter the 6-digit code it shows to confirm.", "用这个模板配{{label}}": "Use this template for {{label}}", + "用这台设备的指纹、面容或 PIN 直接登录,不用输密码,也不用再输动态码。一个账号可以给每台设备各加一把。": "Sign in with this device's fingerprint, face or PIN, with no password and no one-time code. Add one for each device you use.", + "用通行密钥登录": "Sign in with a passkey", "用默认的几个": "Use the defaults", "由外部系统 {{channel}} 以你的身份发起,只有你点确认才会执行。": "Requested by the external system {{channel}} on your behalf. It only runs if you confirm.", "由申请内容里的人员决定": "Decided by a person field in the request", @@ -2369,6 +2386,7 @@ "确定": "Confirm", "确定删除「{{label}}」吗?": "Delete “{{label}}”?", "确定删除「{{name}}」吗?其下的字典项也会一并失效。": "Delete “{{name}}”? Its dictionary entries stop working too.", + "确定删除「{{name}}」吗?删掉之后就不能再用它登录了。": "Remove \"{{name}}\"? You won't be able to sign in with it any more.", "确定删除「{{name}}」吗?文件会一起删掉。": "Delete \"{{name}}\"? The file is deleted too.", "确定删除「{{name}}」吗?磁盘文件与所有业务关联会一并删除,此操作不可撤销。": "Delete “{{name}}”? The stored file and all of its attachments links are removed too. This cannot be undone.", "确定删除「{{name}}」吗?部门下还有成员时不能删除,要先把他们调到别的部门。": "Delete “{{name}}”? A department that still has members can’t be deleted; move them to another department first.", @@ -2390,6 +2408,8 @@ "确定删除选中的 {{n}} 条通知吗?此操作不可撤销。": "Delete the {{n}} selected notifications? This can't be undone.", "确定卸载「{{summary}}({{name}})」吗?": "Uninstall “{{summary}} ({{name}})”?", "确定把「{{who}}」设为超级管理员吗?": "Make “{{who}}” a superuser?", + "确定清除": "Clear", + "确定清除「{{name}}」的全部通行密钥?清除后马上不能再用它们登录。": "Clear all passkeys for \"{{name}}\"? They stop working for sign-in immediately.", "确定重置": "Reset", "确定重置「{{name}}」的二次验证?原来的认证器和恢复码会立即失效。": "Reset two-factor for \"{{name}}\"? Their current authenticator and recovery codes stop working immediately.", "确定({{n}})": "Done ({{n}})", @@ -2494,6 +2514,7 @@ "系统管理": "System", "系统级动态参数。登录与口令策略是活的 —— 改完立刻对所有人生效。": "System-wide dynamic parameters. Sign-in and password policies are live — changes apply to everyone immediately.", "系统运行": "System", + "系统还没有开启通行密钥登录,请联系管理员。": "Passkey sign-in isn't enabled yet. Contact your administrator.", "系统通知": "System notice", "系统里有哪些用户?": "What users are in the system?", "系统里有哪些角色?": "What roles exist in the system?", @@ -2749,6 +2770,7 @@ "设为默认": "Set as default", "设为默认配置(同一时间只有一条)": "Set as default configuration (only one at a time)", "设备": "Device", + "设备丢了或离职交接时用。清除后这个人加过的所有通行密钥都不能再登录,要用密码等别的方式登录后重新添加。": "Use this when a device is lost or someone is leaving. After clearing, none of this person's passkeys can sign in; they sign in another way (such as a password) and add new ones.", "设备数不限": "any number of devices", "设备类型": "Device", "设置": "Settings", @@ -2869,6 +2891,7 @@ "资料": "Profile", "资料已保存": "Profile saved", "走系统代理": "Use system proxy", + "起个名字,比如「我的手机」": "Give it a name, like \"My phone\"", "超时": "Timeout", "超时处理": "When overdue", "超时(秒)": "Timeout (seconds)", @@ -2951,6 +2974,7 @@ "还没有数据范围。先去「系统管理 › 数据权限」建一个,再回来绑定。": "No data scopes yet. Create one under System › Data permissions, then come back to bind it.", "还没有文件": "No files yet", "还没有流程。新建一个:先搭表单,再画审批流程,最后发布": "No workflows yet. Create one: build the form, draw the flow, then publish", + "还没有添加通行密钥。": "No passkeys yet.", "还没有用户": "No users yet", "还没有用户持有这个角色": "No users hold this role yet", "还没有登录记录": "No sign-in records yet", @@ -2958,6 +2982,7 @@ "还没有通知": "No notifications yet", "还没有通知公告": "No notices yet", "还没有配置任何菜单": "No menus configured yet", + "还没用它登录过": "Never used to sign in", "这一分钟发够了,排到下一分钟": "Hit this minute's limit; queued for the next minute", "这一条不在链上:没经过应用、直接写进表里的": "Not on the chain: written straight into the table, bypassing the app", "这一条变更记录的字段对比和出处": "Field comparison and origin of this change record", @@ -2997,6 +3022,7 @@ "这些订阅已经匹配不到任何事件:{{list}}": "These subscriptions no longer match any event: {{list}}", "这只是通用参考。能不能通过由服务端的口令策略决定,被拒时会显示具体原因。": "This is a general guide only. The server's password policy decides whether it is accepted; you will see the exact reason if it is rejected.", "这台设备上没有能打开文件的应用": "No app on this device can open this file", + "这台设备上的通行密钥已经添加过了": "A passkey on this device has already been added", "这台设备的系统时区是 {{zone}},和上面选的不一致 —— 界面按上面选的显示。": "This device's system time zone is {{zone}}, which differs from the one selected above — the UI follows the selection above.", "这家厂商在当前环境不可用,发送会被拒绝": "This provider is unavailable in the current environment; sending will be rejected", "这家厂商按位置填模板变量:按厂商模板里 {1}、{2} 的顺序挑业务参数,末尾用不到的位留空。": "This provider fills template variables by position: pick business parameters in the order of {1}, {2} in the provider template; leave unused trailing slots empty.", @@ -3089,6 +3115,8 @@ "通知类型": "Notification type", "通知类型已变更": "Notification type changed", "通知走邮件 / 短信的每一次投递都留痕,跳过和失败也记。点时间看完整地址和错误原文。": "Every email or SMS delivery is recorded, including skips and failures. Click the time to see the full address and raw error.", + "通行密钥": "Passkey", + "通行密钥操作失败,请稍后重试": "The passkey operation failed. Please try again later", "通过": "Approved", "通道": "Channel", "逻辑核心数": "Logical cores", diff --git a/packages/i18n/src/locales/zh-CN.json b/packages/i18n/src/locales/zh-CN.json index 9261acdf..9e1992f1 100644 --- a/packages/i18n/src/locales/zh-CN.json +++ b/packages/i18n/src/locales/zh-CN.json @@ -727,6 +727,7 @@ "删除选项": "删除选项", "删除通知": "删除通知", "删除通知公告": "删除通知公告", + "删除通行密钥": "删除通行密钥", "删除部门": "删除部门", "判断不了": "判断不了", "利落": "利落", @@ -871,6 +872,7 @@ "只列出前端真实存在的 {{n}} 个路由 —— 从根上杜绝死链。": "只列出前端真实存在的 {{n}} 个路由 —— 从根上杜绝死链。", "只列出对一个群说得通的通知。「抄送给你」「你有新的待办」这类对着本人说的不能推到群里。": "只列出对一个群说得通的通知。「抄送给你」「你有新的待办」这类对着本人说的不能推到群里。", "只取发起人部门(或部门及下级)里有这个角色的人;取不到时按「找不到审批人」处理,不会放开成全公司": "只取发起人部门(或部门及下级)里有这个角色的人;取不到时按「找不到审批人」处理,不会放开成全公司", + "只在这台设备上": "只在这台设备上", "只填主机名(不带 https://)。默认 dysmsapi.aliyuncs.com;VPC 内可用 dysmsapi-vpc.cn-hangzhou.aliyuncs.com 这类地域接入点": "只填主机名(不带 https://)。默认 dysmsapi.aliyuncs.com;VPC 内可用 dysmsapi-vpc.cn-hangzhou.aliyuncs.com 这类地域接入点", "只对这个节点的审批人生效;隐藏的字段服务端直接不下发": "只对这个节点的审批人生效;隐藏的字段服务端直接不下发", "只导出选中的 {{n}} 条": "只导出选中的 {{n}} 条", @@ -1258,9 +1260,11 @@ "已发布版本": "已发布版本", "已取消": "已取消", "已取消移动「{{name}}」": "已取消移动「{{name}}」", + "已取消,或者等太久超时了": "已取消,或者等太久超时了", "已受理": "已受理", "已受理(厂商已接单,送达看运营商回执)": "已受理(厂商已接单,送达看运营商回执)", "已同意": "已同意", + "已同步到云端": "已同步到云端", "已启用": "已启用", "已固定": "已固定", "已在其他标签页退出登录": "已在其他标签页退出登录", @@ -1293,6 +1297,7 @@ "已放弃": "已放弃", "已新建": "已新建", "已有同名视图": "已有同名视图", + "已清除": "已清除", "已生成到草稿:检查之后再保存或发布": "已生成到草稿:检查之后再保存或发布", "已用空间": "已用空间", "已确认阅读": "已确认阅读", @@ -1404,8 +1409,10 @@ "当前标签页的内容区。筛选、分页这些视图状态都记在地址栏里,刷新浏览器也能原样恢复。": "当前标签页的内容区。筛选、分页这些视图状态都记在地址栏里,刷新浏览器也能原样恢复。", "当前没有有效会话": "当前没有有效会话", "当前浏览器不支持流式响应": "当前浏览器不支持流式响应", + "当前浏览器或客户端不支持通行密钥。请用较新的 Chrome、Edge、Safari 或 Firefox 打开网页版。": "当前浏览器或客户端不支持通行密钥。请用较新的 Chrome、Edge、Safari 或 Firefox 打开网页版。", "当前登录用户 ID": "当前登录用户 ID", "当前登录用户部门 ID": "当前登录用户部门 ID", + "当前网址不能使用通行密钥,请用系统配置的域名打开页面": "当前网址不能使用通行密钥,请用系统配置的域名打开页面", "当前角色有改过还没保存的授权,切走会丢掉这些改动。": "当前角色有改过还没保存的授权,切走会丢掉这些改动。", "当前页面用的还是旧版前端,刷新后继续使用。": "当前页面用的还是旧版前端,刷新后继续使用。", "当前频率": "当前频率", @@ -1462,6 +1469,7 @@ "我的": "我的", "我的审批": "我的审批", "我的工作": "我的工作", + "我的设备": "我的设备", "或": "或", "或签": "或签", "或签 · 一人同意即可": "或签 · 一人同意即可", @@ -1469,6 +1477,7 @@ "或者": "或者", "截止触发时间": "截止触发时间", "所属应用": "所属应用", + "所属用户": "所属用户", "所属类型:{{name}}": "所属类型:{{name}}", "所有人必须二次验证": "所有人必须二次验证", "所有人必须开": "所有人必须开", @@ -1674,6 +1683,7 @@ "改了什么": "改了什么", "改办理人": "改办理人", "改动会立刻生效(后端在登录 / 验证码 / 改密码路径上实时读这张表)。": "改动会立刻生效(后端在登录 / 验证码 / 改密码路径上实时读这张表)。", + "改名": "改名", "改哪一位的待办": "改哪一位的待办", "改地址会退出当前登录 —— token 是跟着服务器发的。": "改地址会退出当前登录 —— token 是跟着服务器发的。", "改好之后点「重新提交」,审批从头开始": "改好之后点「重新提交」,审批从头开始", @@ -1882,6 +1892,7 @@ "最近一次": "最近一次", "最近一次 {{at}}": "最近一次 {{at}}", "最近使用": "最近使用", + "最近使用 {{time}}": "最近使用 {{time}}", "最近失败": "最近失败", "最近成功": "最近成功", "最近有哪些人改过东西?": "最近有哪些人改过东西?", @@ -2214,6 +2225,7 @@ "添加": "添加", "添加 {{n}} 人": "添加 {{n}} 人", "添加一行": "添加一行", + "添加于 {{time}}": "添加于 {{time}}", "添加分组": "添加分组", "添加列": "添加列", "添加失败,请稍后重试": "添加失败,请稍后重试", @@ -2224,6 +2236,7 @@ "添加用户到「{{name}}」": "添加用户到「{{name}}」", "添加节点": "添加节点", "添加选项": "添加选项", + "添加通行密钥": "添加通行密钥", "添加附件": "添加附件", "清单从开放接口的声明里自动收集。没勾的接口调用时返回 403;每个接口返回哪些字段见对接文档": "清单从开放接口的声明里自动收集。没勾的接口调用时返回 403;每个接口返回哪些字段见对接文档", "清空": "清空", @@ -2237,7 +2250,9 @@ "清空短信发送日志": "清空短信发送日志", "清空重填": "清空重填", "清除": "清除", + "清除全部通行密钥": "清除全部通行密钥", "清除图标": "清除图标", + "清除失败": "清除失败", "清除格式": "清除格式", "清除筛选": "清除筛选", "渠道": "渠道", @@ -2295,6 +2310,8 @@ "用认证器(Google Authenticator、Microsoft Authenticator、1Password 等)扫下面的二维码,再输入它显示的 6 位码。": "用认证器(Google Authenticator、Microsoft Authenticator、1Password 等)扫下面的二维码,再输入它显示的 6 位码。", "用认证器(Google Authenticator、Microsoft Authenticator、1Password 等)扫这个二维码,再输入它显示的 6 位码确认。": "用认证器(Google Authenticator、Microsoft Authenticator、1Password 等)扫这个二维码,再输入它显示的 6 位码确认。", "用这个模板配{{label}}": "用这个模板配{{label}}", + "用这台设备的指纹、面容或 PIN 直接登录,不用输密码,也不用再输动态码。一个账号可以给每台设备各加一把。": "用这台设备的指纹、面容或 PIN 直接登录,不用输密码,也不用再输动态码。一个账号可以给每台设备各加一把。", + "用通行密钥登录": "用通行密钥登录", "用默认的几个": "用默认的几个", "由外部系统 {{channel}} 以你的身份发起,只有你点确认才会执行。": "由外部系统 {{channel}} 以你的身份发起,只有你点确认才会执行。", "由申请内容里的人员决定": "由申请内容里的人员决定", @@ -2369,6 +2386,7 @@ "确定": "确定", "确定删除「{{label}}」吗?": "确定删除「{{label}}」吗?", "确定删除「{{name}}」吗?其下的字典项也会一并失效。": "确定删除「{{name}}」吗?其下的字典项也会一并失效。", + "确定删除「{{name}}」吗?删掉之后就不能再用它登录了。": "确定删除「{{name}}」吗?删掉之后就不能再用它登录了。", "确定删除「{{name}}」吗?文件会一起删掉。": "确定删除「{{name}}」吗?文件会一起删掉。", "确定删除「{{name}}」吗?磁盘文件与所有业务关联会一并删除,此操作不可撤销。": "确定删除「{{name}}」吗?磁盘文件与所有业务关联会一并删除,此操作不可撤销。", "确定删除「{{name}}」吗?部门下还有成员时不能删除,要先把他们调到别的部门。": "确定删除「{{name}}」吗?部门下还有成员时不能删除,要先把他们调到别的部门。", @@ -2390,6 +2408,8 @@ "确定删除选中的 {{n}} 条通知吗?此操作不可撤销。": "确定删除选中的 {{n}} 条通知吗?此操作不可撤销。", "确定卸载「{{summary}}({{name}})」吗?": "确定卸载「{{summary}}({{name}})」吗?", "确定把「{{who}}」设为超级管理员吗?": "确定把「{{who}}」设为超级管理员吗?", + "确定清除": "确定清除", + "确定清除「{{name}}」的全部通行密钥?清除后马上不能再用它们登录。": "确定清除「{{name}}」的全部通行密钥?清除后马上不能再用它们登录。", "确定重置": "确定重置", "确定重置「{{name}}」的二次验证?原来的认证器和恢复码会立即失效。": "确定重置「{{name}}」的二次验证?原来的认证器和恢复码会立即失效。", "确定({{n}})": "确定({{n}})", @@ -2494,6 +2514,7 @@ "系统管理": "系统管理", "系统级动态参数。登录与口令策略是活的 —— 改完立刻对所有人生效。": "系统级动态参数。登录与口令策略是活的 —— 改完立刻对所有人生效。", "系统运行": "系统运行", + "系统还没有开启通行密钥登录,请联系管理员。": "系统还没有开启通行密钥登录,请联系管理员。", "系统通知": "系统通知", "系统里有哪些用户?": "系统里有哪些用户?", "系统里有哪些角色?": "系统里有哪些角色?", @@ -2749,6 +2770,7 @@ "设为默认": "设为默认", "设为默认配置(同一时间只有一条)": "设为默认配置(同一时间只有一条)", "设备": "设备", + "设备丢了或离职交接时用。清除后这个人加过的所有通行密钥都不能再登录,要用密码等别的方式登录后重新添加。": "设备丢了或离职交接时用。清除后这个人加过的所有通行密钥都不能再登录,要用密码等别的方式登录后重新添加。", "设备数不限": "设备数不限", "设备类型": "设备类型", "设置": "设置", @@ -2869,6 +2891,7 @@ "资料": "资料", "资料已保存": "资料已保存", "走系统代理": "走系统代理", + "起个名字,比如「我的手机」": "起个名字,比如「我的手机」", "超时": "超时", "超时处理": "超时处理", "超时(秒)": "超时(秒)", @@ -2951,6 +2974,7 @@ "还没有数据范围。先去「系统管理 › 数据权限」建一个,再回来绑定。": "还没有数据范围。先去「系统管理 › 数据权限」建一个,再回来绑定。", "还没有文件": "还没有文件", "还没有流程。新建一个:先搭表单,再画审批流程,最后发布": "还没有流程。新建一个:先搭表单,再画审批流程,最后发布", + "还没有添加通行密钥。": "还没有添加通行密钥。", "还没有用户": "还没有用户", "还没有用户持有这个角色": "还没有用户持有这个角色", "还没有登录记录": "还没有登录记录", @@ -2958,6 +2982,7 @@ "还没有通知": "还没有通知", "还没有通知公告": "还没有通知公告", "还没有配置任何菜单": "还没有配置任何菜单", + "还没用它登录过": "还没用它登录过", "这一分钟发够了,排到下一分钟": "这一分钟发够了,排到下一分钟", "这一条不在链上:没经过应用、直接写进表里的": "这一条不在链上:没经过应用、直接写进表里的", "这一条变更记录的字段对比和出处": "这一条变更记录的字段对比和出处", @@ -2997,6 +3022,7 @@ "这些订阅已经匹配不到任何事件:{{list}}": "这些订阅已经匹配不到任何事件:{{list}}", "这只是通用参考。能不能通过由服务端的口令策略决定,被拒时会显示具体原因。": "这只是通用参考。能不能通过由服务端的口令策略决定,被拒时会显示具体原因。", "这台设备上没有能打开文件的应用": "这台设备上没有能打开文件的应用", + "这台设备上的通行密钥已经添加过了": "这台设备上的通行密钥已经添加过了", "这台设备的系统时区是 {{zone}},和上面选的不一致 —— 界面按上面选的显示。": "这台设备的系统时区是 {{zone}},和上面选的不一致 —— 界面按上面选的显示。", "这家厂商在当前环境不可用,发送会被拒绝": "这家厂商在当前环境不可用,发送会被拒绝", "这家厂商按位置填模板变量:按厂商模板里 {1}、{2} 的顺序挑业务参数,末尾用不到的位留空。": "这家厂商按位置填模板变量:按厂商模板里 {1}、{2} 的顺序挑业务参数,末尾用不到的位留空。", @@ -3089,6 +3115,8 @@ "通知类型": "通知类型", "通知类型已变更": "通知类型已变更", "通知走邮件 / 短信的每一次投递都留痕,跳过和失败也记。点时间看完整地址和错误原文。": "通知走邮件 / 短信的每一次投递都留痕,跳过和失败也记。点时间看完整地址和错误原文。", + "通行密钥": "通行密钥", + "通行密钥操作失败,请稍后重试": "通行密钥操作失败,请稍后重试", "通过": "通过", "通道": "通道", "逻辑核心数": "逻辑核心数", diff --git a/packages/i18n/src/server-data-keys.json b/packages/i18n/src/server-data-keys.json index e1ba34f7..4ff95c44 100644 --- a/packages/i18n/src/server-data-keys.json +++ b/packages/i18n/src/server-data-keys.json @@ -186,6 +186,7 @@ "恢复码", "截止触发时间", "所属应用", + "所属用户", "手机号", "手机号验证时间", "批量删除参数配置", @@ -413,6 +414,7 @@ "通知渠道", "通知策略", "通知类型", + "通行密钥", "邮件", "邮箱", "邮箱密码", diff --git a/packages/platform/src/auth/passkey.ts b/packages/platform/src/auth/passkey.ts new file mode 100644 index 00000000..c3c6c9fa --- /dev/null +++ b/packages/platform/src/auth/passkey.ts @@ -0,0 +1,89 @@ +import { queryOptions } from '@tanstack/react-query' + +import { api } from '../api-client/client' +import { ApiError } from '../api-client/errors' +import { tryDesktop } from '../desktop' + +/** + * 通行密钥(Passkey / WebAuthn)的浏览器那一侧。登录接在 `session.ts` 的 `loginByPasskey`, + * 管理在个人中心(`pages/profile/passkey-block.tsx`)。 + * + * - 用浏览器原生的 WebAuthn L3 JSON 方法(`parseCreationOptionsFromJSON` / `parseRequestOptionsFromJSON` / `toJSON`), + * 不引 `@simplewebauthn/browser`:服务端给的 options 原样交进去,结果原样交回去 + * - 🔴 **桌面端一律当不支持**:渲染层跑在 `app://local` 上,凭据绑的是网站域名(RP ID),对不上 —— 按规范推出,没实测 + * - 🔴 **本地开发要从 `localhost` 打开页面**:RP ID 不能是 IP,从 `127.0.0.1` 打开时浏览器直接报 `SecurityError` + * (实测:Chrome 156 `This is an invalid domain.`)。见 `app/admin` 分册「通行密钥」 + */ + +/** 浏览器支不支持(三个 JSON 方法都在、不在桌面端) */ +export function passkeySupported(): boolean { + if (typeof window === 'undefined' || tryDesktop()) return false + const pkc = window.PublicKeyCredential as unknown as + | { + parseCreationOptionsFromJSON?: unknown + parseRequestOptionsFromJSON?: unknown + prototype?: { toJSON?: unknown } + } + | undefined + return ( + typeof pkc?.parseCreationOptionsFromJSON === 'function' && + typeof pkc?.parseRequestOptionsFromJSON === 'function' && + typeof pkc?.prototype?.toJSON === 'function' + ) +} + +/** 服务端开没开(配了 PASSKEY_RP_ID + PASSKEY_ORIGINS)。匿名接口,登录页用 */ +export const passkeyEnabledQuery = queryOptions({ + queryKey: ['auth', 'passkey', 'enabled'] as const, + queryFn: () => api.GET<{ enabled: boolean }>('/api/v1/auth/passkey/enabled'), + staleTime: 5 * 60_000, +}) + +type Json = Record + +/** 浏览器那一步被用户取消 / 超时:调用方据此不显示成「出错了」那种红字 */ +export class PasskeyCancelled extends Error {} + +function toCredentialJson(credential: Credential | null): Json { + if (!credential) throw new PasskeyCancelled() + return (credential as PublicKeyCredential).toJSON() as unknown as Json +} + +/** 注册:服务端的 creation options → `navigator.credentials.create()` → 交回服务端的 JSON */ +export async function createPasskeyCredential(options: Json): Promise { + const publicKey = PublicKeyCredential.parseCreationOptionsFromJSON( + options as unknown as PublicKeyCredentialCreationOptionsJSON + ) + return toCredentialJson(await navigator.credentials.create({ publicKey })) +} + +/** 登录:服务端的 request options → `navigator.credentials.get()` → 交回服务端的 JSON */ +export async function getPasskeyAssertion(options: Json): Promise { + const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON( + options as unknown as PublicKeyCredentialRequestOptionsJSON + ) + return toCredentialJson(await navigator.credentials.get({ publicKey })) +} + +/** + * 浏览器 / 服务端的错误 → 给人看的一句话。 + * + * 浏览器那一侧的 `DOMException` 名字比 message 可靠(message 各浏览器各写各的、还是英文)。 + * 「取消 / 超时」两件事浏览器故意不区分(隐私考虑,都是 `NotAllowedError`),这里也只能合成一句。 + */ +export function passkeyErrorMessage(err: unknown, t: (key: string) => string): string { + if (err instanceof ApiError) return err.message + if (err instanceof PasskeyCancelled) return t('已取消,或者等太久超时了') + const name = err instanceof DOMException ? err.name : '' + switch (name) { + case 'NotAllowedError': + case 'AbortError': + return t('已取消,或者等太久超时了') + case 'InvalidStateError': + return t('这台设备上的通行密钥已经添加过了') + case 'SecurityError': + return t('当前网址不能使用通行密钥,请用系统配置的域名打开页面') + default: + return t('通行密钥操作失败,请稍后重试') + } +} diff --git a/packages/platform/src/auth/session.ts b/packages/platform/src/auth/session.ts index 28a02870..97c13348 100644 --- a/packages/platform/src/auth/session.ts +++ b/packages/platform/src/auth/session.ts @@ -7,6 +7,7 @@ import { useAiDrawerStore } from '../pages/ai-chat/drawer-store' import { useUploadStore } from '../shell/upload-store' import { tryDesktop } from '../desktop' import type { AuthLoginOutcome } from '../desktop/contract' +import { getPasskeyAssertion } from './passkey' /** 会话结束的原因码与提示文案(和移动端共用的那一份在 `@admin/api`)。登录页从这里取,不直接依赖那个包 */ export { isSessionEndReason, SESSION_END_MESSAGE, type SessionEndReason } from '@admin/api' @@ -126,6 +127,24 @@ export async function loginByPhone(qc: QueryClient, param: PhoneLoginParam): Pro return challenge } +/** + * 通行密钥登录:取挑战 → 浏览器弹指纹 / 面容 / PIN → 交断言 → 拿到会话。 + * + * 不先问用户名(用哪把由认证器挑);也不会再要二次验证 —— 通行密钥本身就要求了用户验证,后端这条路不走 MFA。 + * 只有网页端:桌面端的渲染层跑在 `app://local` 上,凭据绑的网站域名对不上,入口不显示(`passkeySupported`)。 + * 浏览器那一步被取消 / 超时抛 `PasskeyCancelled`,服务端拒了抛 `ApiError`,交给 `passkeyErrorMessage` 翻成一句话。 + */ +export async function loginByPasskey(qc: QueryClient): Promise { + const first = await api.POST<{ challenge_id: string; options: Record }>( + '/api/v1/auth/passkey/options' + ) + const credential = await getPasskeyAssertion(first.options) + const res = await api.POST('/api/v1/auth/passkey/login', { + body: { challenge_id: first.challenge_id, credential, client: 'web' }, + }) + afterLogin(qc, res.access_token) +} + /** * 二次验证:登录第二步(动态码或恢复码)。 * 动态码字段叫 `otp`:后端按这个键名把它从操作日志里脱掉(`OPERA_LOG_REDACT_KEYS`) diff --git a/packages/platform/src/pages/profile/api.ts b/packages/platform/src/pages/profile/api.ts index 6d1f2774..927fbf01 100644 --- a/packages/platform/src/pages/profile/api.ts +++ b/packages/platform/src/pages/profile/api.ts @@ -3,6 +3,7 @@ import { queryOptions, useMutation, useQueryClient } from '@tanstack/react-query import { api, API_BASE, uploadFile } from '../../api-client/client' import type { LoginLog } from '../_shared/login-log' import { t } from '@admin/i18n' +import { createPasskeyCredential } from '../../auth/passkey' import { authKeys } from '../../auth/queries' /** @@ -359,3 +360,54 @@ export const useMfaEnable = () => useMfaAction<{ recovery_codes: string[] }>('/a export const useMfaDisable = () => useMfaAction('/api/v1/sys/users/me/mfa/disable') export const useMfaRegenerate = () => useMfaAction<{ recovery_codes: string[] }>('/api/v1/sys/users/me/mfa/recovery-codes') + +// ─── 通行密钥(Passkey)───────────────────────────────────────────────────── + +export type Passkey = { + id: string + name: string + backed_up: boolean + transports: string | null + created_time: string + last_used_time: string | null +} + +export const passkeyKeys = { list: ['profile', 'passkeys'] as const } + +export const passkeysQuery = queryOptions({ + queryKey: passkeyKeys.list, + queryFn: () => api.GET('/api/v1/sys/users/me/passkeys'), +}) + +/** 添加一把:取注册挑战 → 浏览器弹指纹 / 面容 / PIN → 交注册结果。浏览器那一步的错原样抛(`passkeyErrorMessage` 翻译) */ +export function useAddPasskey() { + const qc = useQueryClient() + return useMutation({ + meta: { suppressErrorToast: true }, + mutationFn: async (name: string) => { + const options = await api.POST>('/api/v1/sys/users/me/passkeys/options') + const credential = await createPasskeyCredential(options) + return api.POST('/api/v1/sys/users/me/passkeys', { body: { name, credential } }) + }, + onSuccess: () => qc.invalidateQueries({ queryKey: passkeyKeys.list }), + }) +} + +export function useRenamePasskey() { + const qc = useQueryClient() + return useMutation({ + meta: { suppressErrorToast: true }, + mutationFn: ({ id, name }: { id: string; name: string }) => + api.PUT(`/api/v1/sys/users/me/passkeys/${id}`, { body: { name } }), + onSuccess: () => qc.invalidateQueries({ queryKey: passkeyKeys.list }), + }) +} + +export function useDeletePasskey() { + const qc = useQueryClient() + return useMutation({ + meta: { suppressErrorToast: true }, + mutationFn: (id: string) => api.DELETE(`/api/v1/sys/users/me/passkeys/${id}`), + onSuccess: () => qc.invalidateQueries({ queryKey: passkeyKeys.list }), + }) +} diff --git a/packages/platform/src/pages/profile/index.tsx b/packages/platform/src/pages/profile/index.tsx index 49ec4061..56c7628c 100644 --- a/packages/platform/src/pages/profile/index.tsx +++ b/packages/platform/src/pages/profile/index.tsx @@ -2,7 +2,7 @@ import * as React from 'react' import { Trans, useTranslation } from 'react-i18next' import { useQuery, useQueryClient } from '@tanstack/react-query' import { - IconAlertTriangle, IconAt, IconAuth2fa, IconBellRinging, IconCheck, IconClock, IconDeviceMobile, IconExternalLink, IconFileExport, IconIdBadge2, + IconAlertTriangle, IconAt, IconAuth2fa, IconFingerprint, IconBellRinging, IconCheck, IconClock, IconDeviceMobile, IconExternalLink, IconFileExport, IconIdBadge2, IconInfoCircle, IconKey, IconLoader2, IconMail, IconPhoto, IconPlugConnected, IconShieldLock, IconSignature, IconUpload, IconUser, } from '@tabler/icons-react' @@ -29,6 +29,7 @@ import { StatusBadge, StatusPill } from '../_shared/status' import { PasswordStrength } from './password-strength' import { ExportsPanel } from './exports-panel' import { MfaBlock } from './mfa-block' +import { PasskeyBlock } from './passkey-block' import { NotifyPrefsPanel } from './notify-prefs-panel' import { RecentLogins } from './recent-logins' import { @@ -954,6 +955,15 @@ function SecurityPanel({ me }: { me?: CurrentUser }) { > + {/* 通行密钥:不用密码、用指纹 / 面容 / PIN 登录。和二次验证挨着 —— 都是「这个号还靠什么守着」 */} + } + testId="profile-passkey" + > + + {/* 最近登录放最后:前两块是「我主动改什么」,这块是「有没有人动过我的号」, 属于事后核查。数据源和坑见 `recent-logins.tsx`。 diff --git a/packages/platform/src/pages/profile/passkey-block.tsx b/packages/platform/src/pages/profile/passkey-block.tsx new file mode 100644 index 00000000..29478630 --- /dev/null +++ b/packages/platform/src/pages/profile/passkey-block.tsx @@ -0,0 +1,185 @@ +import { useQuery } from '@tanstack/react-query' +import * as React from 'react' +import { useTranslation } from 'react-i18next' + +import { formatDateTime } from '@admin/i18n' +import { Alert } from '@admin/ui/components/alert' +import { Button } from '@admin/ui/components/button' +import { Input } from '@admin/ui/components/input' +import { QueryError } from '@admin/ui/components/query-error' +import { Skeleton } from '@admin/ui/components/skeleton' + +import { passkeyEnabledQuery, passkeyErrorMessage, passkeySupported } from '../../auth/passkey' +import { ConfirmDialog } from '../../shell/confirm-dialog' +import { StatusPill } from '../_shared/status' +import { passkeysQuery, useAddPasskey, useDeletePasskey, useRenamePasskey, type Passkey } from './api' + +/** + * 个人中心「安全」里的通行密钥:添加 · 改名 · 删除。登录页那一侧在 `apps/web/src/routes/_guest/-passkey-sign-in.tsx`。 + * + * - 浏览器不支持 / 服务端没开时**照样列出已有的**(能删),只是不给「添加」—— 别让人以为钥匙没了 + * - 浏览器那一步被取消不是错误,提示用普通语气(`passkeyErrorMessage` 已经区分) + */ +export function PasskeyBlock() { + const { t } = useTranslation() + const list = useQuery(passkeysQuery) + const enabled = useQuery(passkeyEnabledQuery) + const add = useAddPasskey() + const rename = useRenamePasskey() + const del = useDeletePasskey() + const [name, setName] = React.useState('') + const [error, setError] = React.useState(null) + const [editing, setEditing] = React.useState<{ id: string; name: string } | null>(null) + const [pendingDelete, setPendingDelete] = React.useState(null) + const [deleteError, setDeleteError] = React.useState(null) + const supported = passkeySupported() + + if (list.error) return void list.refetch()} /> + if (!list.data) return + + async function onAdd(e: React.FormEvent) { + e.preventDefault() + setError(null) + try { + await add.mutateAsync(name.trim() || t('我的设备')) + setName('') + } catch (err) { + setError(passkeyErrorMessage(err, t)) + } + } + + async function onRename(e: React.FormEvent) { + e.preventDefault() + if (!editing) return + setError(null) + try { + await rename.mutateAsync({ id: editing.id, name: editing.name.trim() }) + setEditing(null) + } catch (err) { + setError(passkeyErrorMessage(err, t)) + } + } + + const canAdd = supported && enabled.data?.enabled !== false + + return ( +
+ {list.data.length === 0 ? ( +

+ {t('还没有添加通行密钥。')} +

+ ) : ( +
    + {list.data.map((p) => ( +
  • + {editing?.id === p.id ? ( +
    + setEditing({ id: p.id, name: e.target.value })} + maxLength={64} + autoFocus + className="h-8" + data-testid="passkey-rename-input" + /> + + +
    + ) : ( + <> + + {p.name} + + + {p.backed_up ? t('已同步到云端') : t('只在这台设备上')} + + + {t('添加于 {{time}}', { time: formatDateTime(p.created_time) })} + {' · '} + {p.last_used_time + ? t('最近使用 {{time}}', { time: formatDateTime(p.last_used_time) }) + : t('还没用它登录过')} + + + + + + + )} +
  • + ))} +
+ )} + + {!supported ? ( +

+ {t('当前浏览器或客户端不支持通行密钥。请用较新的 Chrome、Edge、Safari 或 Firefox 打开网页版。')} +

+ ) : enabled.data?.enabled === false ? ( +

+ {t('系统还没有开启通行密钥登录,请联系管理员。')} +

+ ) : null} + + {canAdd ? ( +
+ setName(e.target.value)} + maxLength={64} + placeholder={t('起个名字,比如「我的手机」')} + data-testid="passkey-name-input" + /> + +
+ ) : null} + + {error ? ( + + {error} + + ) : null} + + !o && setPendingDelete(null)} + title={t('删除通行密钥')} + description={ + pendingDelete ? t('确定删除「{{name}}」吗?删掉之后就不能再用它登录了。', { name: pendingDelete.name }) : '' + } + error={deleteError} + confirmText={t('删除')} + destructive + pending={del.isPending} + onConfirm={async () => { + if (!pendingDelete) return + try { + await del.mutateAsync(pendingDelete.id) + setPendingDelete(null) + } catch (err) { + setDeleteError(passkeyErrorMessage(err, t)) + } + }} + /> +
+ ) +} diff --git a/packages/platform/src/pages/user/api.ts b/packages/platform/src/pages/user/api.ts index 4674284e..1ff40d23 100644 --- a/packages/platform/src/pages/user/api.ts +++ b/packages/platform/src/pages/user/api.ts @@ -222,6 +222,14 @@ export function useResetUserPassword() { }) } +/** 清掉用户的全部通行密钥(超管):设备丢了 / 离职交接。清完这个人只能用密码等别的方式登录 */ +export function useResetUserPasskeys() { + return useMutation({ + meta: { suppressErrorToast: true }, + mutationFn: (id: string) => api.DELETE(`/api/v1/sys/users/${id}/passkeys`), + }) +} + /** 重置用户的二次验证(#181,超管):手机丢了的人下次登录重新绑定(被强制的)/ 直接关掉(没被强制的) */ export function useResetUserMfa() { return useMutation({ diff --git a/packages/platform/src/pages/user/security-sheet.tsx b/packages/platform/src/pages/user/security-sheet.tsx index 68d1090b..ee35a129 100644 --- a/packages/platform/src/pages/user/security-sheet.tsx +++ b/packages/platform/src/pages/user/security-sheet.tsx @@ -15,7 +15,7 @@ import { usePerm } from '../../auth/use-perm' import { ConfirmDialog } from '../../shell/confirm-dialog' import { FormSection } from '../_shared/form-fields' import { - useResetUserMfa, useResetUserPassword, useToggleUserPermission, + useResetUserMfa, useResetUserPasskeys, useResetUserPassword, useToggleUserPermission, type User, type UserPermissionType, } from './api' @@ -83,6 +83,9 @@ export function UserSecuritySheet({ const resetMfa = useResetUserMfa() const [mfaConfirm, setMfaConfirm] = React.useState(false) const [mfaState, setMfaState] = React.useState<{ kind: 'idle' | 'ok' | 'error'; msg?: string }>({ kind: 'idle' }) + const resetPasskeys = useResetUserPasskeys() + const [passkeyConfirm, setPasskeyConfirm] = React.useState(false) + const [passkeyState, setPasskeyState] = React.useState<{ kind: 'idle' | 'ok' | 'error'; msg?: string }>({ kind: 'idle' }) const [busy, setBusy] = React.useState(null) const [flagError, setFlagError] = React.useState(null) @@ -98,6 +101,7 @@ export function UserSecuritySheet({ setFlagError(null) setPwd(''); setPwd2(''); setPwdState('idle'); setPwdMsg(null) setMfaState({ kind: 'idle' }) + setPasskeyState({ kind: 'idle' }) }, [open, user?.id]) if (!user) return null @@ -268,6 +272,34 @@ export function UserSecuritySheet({ )} + + {/* ── 通行密钥 ── */} + +

+ {t('设备丢了或离职交接时用。清除后这个人加过的所有通行密钥都不能再登录,要用密码等别的方式登录后重新添加。')} +

+
+ + {passkeyState.kind === 'ok' && ( + + + {t('已清除')} + + )} + {passkeyState.kind === 'error' && ( + + + {passkeyState.msg} + + )} +
+
@@ -294,6 +326,24 @@ export function UserSecuritySheet({ } }} /> + { + setPasskeyConfirm(false) + try { + await resetPasskeys.mutateAsync(user.id) + setPasskeyState({ kind: 'ok' }) + } catch (e) { + setPasskeyState({ kind: 'error', msg: e instanceof ApiError ? e.message : t('清除失败') }) + } + }} + /> !o && setPendingFlag(null)}