Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(login): 接入邮箱登录人机验证 (#3000)
bobo1e9f95437e90
diff --git a/apps/desktop/src/main/__tests__/authCaptchaIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/authCaptchaIpcSecurity.test.tsnew file mode 100644index 0000000000..915edd5a1b--- /dev/null+++ b/apps/desktop/src/main/__tests__/authCaptchaIpcSecurity.test.ts@@ -0,0 +1,26 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++/**+ * bootstrap-electron 依赖完整 Electron 启动环境,Node 单测不能直接 import。+ * 这里锁住 CAPTCHA URL IPC 的授权顺序;统一 guard 自身的 senderFrame、顶层+ * frame、已登记 Cindy 窗口与 URL 判据由 security/trustedAppRenderer.test 覆盖。+ */+describe('desktop captcha challenge URL IPC boundary', () => {+ const source = readFileSync(resolve(__dirname, '..', 'bootstrap-electron.ts'), 'utf8');++ it('在读取认证端点前拒绝非可信 sender', () => {+ const start = source.indexOf("ipcMain.handle('auth:get-captcha-challenge-url'");+ const end = source.indexOf("ipcMain.handle('auth:logout'", start);+ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const handler = source.slice(start, end);+ const guard = handler.indexOf('assertTrustedAppRendererEvent(event);');+ const readUrl = handler.indexOf('authManager.getLoginCaptchaChallengeUrl()');+ expect(guard).toBeGreaterThanOrEqual(0);+ expect(readUrl).toBeGreaterThan(guard);+ });+});diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.tsindex 0c02a3cff1..23de91145e 100644--- a/apps/desktop/src/main/__tests__/webview-security.test.ts+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts@@ -19,7 +19,7 @@import { EventEmitter } from 'node:events';-import type { BrowserWindow, WebContents } from 'electron';+import type { BrowserWindow, Session, WebContents } from 'electron';import { afterEach, describe, expect, it, vi } from 'vitest';const nativeSurfaceMocks = vi.hoisted(() => ({@@ -32,7 +32,11 @@ vi.mock('../rsb-browser-bridge/native-popup-surfaces', () => ({attributeRsbNativePopupSurface: nativeSurfaceMocks.attribute,}));-import { BROWSER_PARTITION } from '../../shared/webviewPartition';+import {+ BROWSER_PARTITION,+ LOGIN_CAPTCHA_CANCEL_HASH,+ LOGIN_CAPTCHA_PARTITION,+} from '../../shared/webviewPartition';import { getEffectiveAppShortcuts, type AppShortcutId } from '../../shared/appShortcuts';import {BLANK_POPUP_WINDOW_WEB_PREFERENCES,@@ -43,12 +47,17 @@ import {setRsbPopupOpenerReportSubscriber,RSB_BROWSER_POPUP_CHANNEL,applyGhostWebviewHardening,+ applyLoginCaptchaWebviewHardening,applyWebviewHardening,+ hardenLoginCaptchaSession,installGhostGuestNavigationHandlers,installBrowserGuestHandlers,installDeferredPopupRouter,+ installLoginCaptchaGuestHandlers,+ isAllowedLoginCaptchaUrl,isGuestShortcutKeyDownType,resolveGuestShortcutAction,+ setLoginCaptchaOriginResolver,setRsbPopupOpenerResolver,} from '../webview-security';@@ -309,6 +318,168 @@ describe('applyGhostWebviewHardening(意识面板 webview)', () => {});});+describe('applyLoginCaptchaWebviewHardening(登录 captcha webview)', () => {+ it('与意识面板同级锁死:保留内存分区、零 preload、零 popup', () => {+ const webPreferences: Record<string, unknown> = {+ nodeIntegration: true,+ nodeIntegrationInSubFrames: true,+ nodeIntegrationInWorker: true,+ contextIsolation: false,+ sandbox: false,+ webviewTag: true,+ webSecurity: false,+ allowRunningInsecureContent: true,+ plugins: true,+ preload: '/tmp/evil-preload.js',+ };+ const params: Record<string, string> = {+ src: 'https://auth.example.com/captcha/turnstile?theme=dark',+ partition: LOGIN_CAPTCHA_PARTITION,+ disablewebsecurity: 'true',+ webpreferences: 'nodeIntegration=1',+ allowpopups: 'true',+ };++ applyLoginCaptchaWebviewHardening(webPreferences, params);++ expect(webPreferences.sandbox).toBe(true);+ expect(webPreferences.nodeIntegration).toBe(false);+ expect(webPreferences.nodeIntegrationInSubFrames).toBe(false);+ expect(webPreferences.nodeIntegrationInWorker).toBe(false);+ expect(webPreferences.contextIsolation).toBe(true);+ expect(webPreferences.webSecurity).toBe(true);+ expect(webPreferences.allowRunningInsecureContent).toBe(false);+ expect(webPreferences.webviewTag).toBe(false);+ expect(webPreferences.plugins).toBe(false);+ expect('preload' in webPreferences).toBe(false);+ expect(params.partition).toBe(LOGIN_CAPTCHA_PARTITION);+ expect('allowpopups' in params).toBe(false);+ expect('disablewebsecurity' in params).toBe(false);+ expect('webpreferences' in params).toBe(false);+ });++ it('对专属 session 的权限与下载都默认拒绝', () => {+ const setPermissionRequestHandler = vi.fn();+ const setPermissionCheckHandler = vi.fn();+ const on = vi.fn();++ hardenLoginCaptchaSession({+ setPermissionRequestHandler,+ setPermissionCheckHandler,+ on,+ } as unknown as Pick<+ Session,+ 'setPermissionRequestHandler' | 'setPermissionCheckHandler' | 'on'+ >);++ expect(setPermissionRequestHandler).toHaveBeenCalledTimes(1);+ expect(setPermissionCheckHandler).toHaveBeenCalledTimes(1);+ expect(on).toHaveBeenCalledWith('will-download', expect.any(Function));++ const callback = vi.fn();+ const requestHandler = setPermissionRequestHandler.mock.calls[0]![0] as (+ webContents: unknown,+ permission: string,+ callback: (allowed: boolean) => void,+ ) => void;+ requestHandler(undefined, 'media', callback);+ expect(callback).toHaveBeenCalledWith(false);++ const checkHandler = setPermissionCheckHandler.mock.calls[0]![0] as () => boolean;+ expect(checkHandler()).toBe(false);++ const preventDefault = vi.fn();+ const downloadHandler = on.mock.calls[0]![1] as (event: {+ preventDefault(): void;+ }) => void;+ downloadHandler({ preventDefault });+ expect(preventDefault).toHaveBeenCalledTimes(1);+ });+});++describe('isAllowedLoginCaptchaUrl(captcha 附加/导航白名单)', () => {+ afterEach(() => setLoginCaptchaOriginResolver(null));++ it('resolver 未注入时 fail-closed', () => {+ expect(isAllowedLoginCaptchaUrl('https://auth.example.com/captcha/turnstile')).toBe(false);+ });++ it('https + origin 命中 + 托管页精确路径才放行', () => {+ setLoginCaptchaOriginResolver(() => ['https://auth.example.com']);+ expect(isAllowedLoginCaptchaUrl('https://auth.example.com/captcha/turnstile')).toBe(true);+ expect(+ isAllowedLoginCaptchaUrl('https://auth.example.com/captcha/turnstile?theme=dark&lang=ja'),+ ).toBe(true);+ // 路径不精确、origin 不命中、协议降级一律拒+ expect(isAllowedLoginCaptchaUrl('https://auth.example.com/captcha/other')).toBe(false);+ expect(isAllowedLoginCaptchaUrl('https://auth.example.com/')).toBe(false);+ expect(isAllowedLoginCaptchaUrl('https://evil.example.com/captcha/turnstile')).toBe(false);+ expect(isAllowedLoginCaptchaUrl('http://auth.example.com/captcha/turnstile')).toBe(false);+ expect(isAllowedLoginCaptchaUrl('not-a-url')).toBe(false);+ expect(isAllowedLoginCaptchaUrl(undefined)).toBe(false);+ });++ it('loopback 上放行 http(本地 dev auth-server),非 loopback http 拒绝', () => {+ setLoginCaptchaOriginResolver(() => [+ 'http://localhost:3344',+ 'http://127.0.0.1:3344',+ 'http://auth.internal:3344',+ ]);+ expect(isAllowedLoginCaptchaUrl('http://localhost:3344/captcha/turnstile')).toBe(true);+ expect(isAllowedLoginCaptchaUrl('http://127.0.0.1:3344/captcha/turnstile')).toBe(true);+ // 即便 resolver 误列了非 loopback 的 http origin,协议闸仍拒+ expect(isAllowedLoginCaptchaUrl('http://auth.internal:3344/captcha/turnstile')).toBe(false);+ });++ it('resolver 抛错时 fail-closed', () => {+ setLoginCaptchaOriginResolver(() => {+ throw new Error('endpoints not ready');+ });+ expect(isAllowedLoginCaptchaUrl('https://auth.example.com/captcha/turnstile')).toBe(false);+ });+});++describe('installLoginCaptchaGuestHandlers(captcha guest 导航闸)', () => {+ afterEach(() => setLoginCaptchaOriginResolver(null));++ it('拒绝 popup,并同时拦截越界普通导航与 HTTP redirect', () => {+ setLoginCaptchaOriginResolver(() => ['https://auth.example.com']);+ const guest = new EventEmitter() as EventEmitter & {+ setWindowOpenHandler: ReturnType<typeof vi.fn>;+ executeJavaScript: ReturnType<typeof vi.fn>;+ };+ guest.setWindowOpenHandler = vi.fn();+ guest.executeJavaScript = vi.fn(async () => undefined);++ installLoginCaptchaGuestHandlers(guest as unknown as WebContents);++ expect(guest.setWindowOpenHandler).toHaveBeenCalledTimes(1);+ expect(guest.setWindowOpenHandler.mock.calls[0]).toEqual({ action: 'deny' });++ const allowed = { preventDefault: vi.fn() };+ guest.emit(+ 'will-redirect',+ allowed,+ 'https://auth.example.com/captcha/turnstile?theme=dark',+ );+ expect(allowed.preventDefault).not.toHaveBeenCalled();++ for (const eventName of ['will-navigate', 'will-redirect']) {+ const blocked = { preventDefault: vi.fn() };+ guest.emit(eventName, blocked, 'https://evil.example.com/captcha/turnstile');+ expect(blocked.preventDefault).toHaveBeenCalledTimes(1);+ }++ const escapeEvent = { preventDefault: vi.fn() };+ guest.emit('before-input-event', escapeEvent, { type: 'keyDown', key: 'Escape' });+ expect(escapeEvent.preventDefault).toHaveBeenCalledTimes(1);+ expect(guest.executeJavaScript).toHaveBeenCalledWith(+ `location.hash = ${JSON.stringify(LOGIN_CAPTCHA_CANCEL_HASH)}`,+ true,+ );+ });+});+describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用导航链)', () => {function makeHarness() {let openHandler: (() => { action: 'deny' }) | null = null;diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 8e1851d89d..c9783e78d4 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -95,6 +95,7 @@ import {type DesktopLoginAction,type DesktopLoginActionResult,} from '../shared/authIpc';+import { LOGIN_CAPTCHA_PAGE_PATH } from '../shared/webviewPartition';import {activeOwnerScopeKey,beginAppSessionBoundary,@@ -1962,6 +1963,15 @@ export function getActiveAuthRealm(): AuthRegion {return activeAuthRealm;}+/**+ * 登录页人机验证托管挑战页地址(不含 query)。邮箱发码固定走构建区域的 auth+ * 部署(与 runLoginAction 的 startsBuildRealmFlow 口径一致),不看 activeAuthRealm。+ * 惰性求值:端点清单可能在 app.ready 后被远程 manifest 回填,不得固化。+ */+export function getLoginCaptchaChallengeUrl(): string {+ return authServerUrl(AUTH_REGION) + LOGIN_CAPTCHA_PAGE_PATH;+}+/** SkillHub v0.2.1: 返回当前登录用户 id(cuid),未登录时返回 null */export function getCurrentUserId(): string | null {return currentUser?.id ?? null;@@ -2989,7 +2999,9 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginAif (action.kind === 'phone' && !providerConfig?.phone) {throw new AuthApiError('PHONE_LOGIN_DISABLED', 400, 'Phone login is disabled');}- await client.requestCode(action.kind, action.identifier);+ await client.requestCode(action.kind, action.identifier, {+ captchaToken: action.captchaToken,+ });loginFlowState = reduceAuthFlow(loginFlowState, {type: 'code-requested',kind: action.kind,diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 2b19f5e307..7f11c0d6f8 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -193,6 +193,7 @@ import { uploadPublicAsset } from './ossPublicUpload';import { removeRefs as removeMediaRefs } from './cindy-media/ledger';import {installWebviewHardener,+ setLoginCaptchaOriginResolver,setRsbPopupHostResolver,setRsbPopupOpenerReportSubscriber,setRsbPopupOpenerResolver,@@ -752,6 +753,7 @@ import {import { isBrowserOpenablePath } from '../shared/browserOpenableExts.js';import {getClientEndpoint,+ getClientEndpointForRealm,initClientEndpoints,registerClientEndpointsIpc,} from './clientEndpointsService.js';@@ -1481,6 +1483,21 @@ if (!app.isPackaged) {// 首次 attach webview 都走 hardener。详见 webview-security.ts。installWebviewHardener();+// 登录 captcha webview 的 auth origin 白名单:hardener 附加/导航闸据此校验+// 挑战页地址。惰性解析(attach 时刻取当前端点清单),两 realm 都收——+// 邮箱发码固定走构建区域,但清单在 dev/远程回填形态下地址可能变化。+setLoginCaptchaOriginResolver(() => {+ const origins = new Set<string>();+ for (const realm of ['cn', 'global'] as const) {+ try {+ origins.add(new URL(getClientEndpointForRealm(realm, 'authApiBaseUrl')).origin);+ } catch {+ // 该 realm 清单不可用(启动早期/异常)时不加入 —— fail-closed。+ }+ }+ return [...origins];+});+// ── RSB browser bridge (browser-backend Phase 2) ────────────────────────// Renderer → main 桥,把 RSB `<webview>` 注册到 main 端 TabRegistry,future// 浏览器自动化 backend(Phase 3+)消费 webContents 句柄。@@ -4535,6 +4552,13 @@ const registerIpcHandlers = () => {return authManager.dispatchLoginAction(action);});+ // 登录 captcha 托管挑战页地址(不含 query)。只返回按构建区域拼出的公开 URL,+ // 无副作用、不含凭证;renderer 的 LoginCaptchaOverlay 用它装载 webview。+ ipcMain.handle('auth:get-captcha-challenge-url', async (event) => {+ assertTrustedAppRendererEvent(event);+ return authManager.getLoginCaptchaChallengeUrl();+ });+ipcMain.handle('auth:logout', async () => {await authManager.logout();});diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.tsindex dddc57c022..aca4e57ea0 100644--- a/apps/desktop/src/main/webview-security.ts+++ b/apps/desktop/src/main/webview-security.ts@@ -24,9 +24,14 @@import path from 'node:path';-import { app, type BrowserWindow, type WebContents } from 'electron';+import { app, session, type BrowserWindow, type Session, type WebContents } from 'electron';-import { BROWSER_PARTITION } from '../shared/webviewPartition';+import {+ BROWSER_PARTITION,+ LOGIN_CAPTCHA_CANCEL_HASH,+ LOGIN_CAPTCHA_PAGE_PATH,+ LOGIN_CAPTCHA_PARTITION,+} from '../shared/webviewPartition';import { GHOST_PARTITION_PREFIX } from '../shared/ghost';import {matchesElectronInput,@@ -160,6 +165,122 @@ export function applyGhostWebviewHardening(delete webPreferences.preload;}+/**+ * 登录页人机验证(Turnstile 托管挑战页)webview 的加固:与意识面板同一套锁死集——+ * 零弹窗、零 preload、保留调用方已验证的专属内存分区。挑战页是我们自己的+ * auth-server 托管页,token 回传只靠 location.hash(did-navigate-in-page),+ * 不需要任何注入面。+ */+export function applyLoginCaptchaWebviewHardening(+ webPreferences: Record<string, unknown>,+ params: Record<string, string>,+): void {+ delete params.disablewebsecurity;+ delete params.webpreferences;+ delete params.allowpopups;+ // 分区不动:调用方(will-attach listener)已验证过 partition ↔ src。++ webPreferences.sandbox = true;+ webPreferences.devTools = true;+ webPreferences.nodeIntegration = false;+ webPreferences.nodeIntegrationInSubFrames = false;+ webPreferences.nodeIntegrationInWorker = false;+ webPreferences.contextIsolation = true;+ webPreferences.webSecurity = true;+ webPreferences.allowRunningInsecureContent = false;+ webPreferences.webviewTag = false;+ webPreferences.plugins = false;+ delete webPreferences.preload;+}++/**+ * CAPTCHA guest 使用独立 session,但 session 默认安全策略不能依赖 Electron+ * 版本的隐式行为。挑战只需要网络、脚本与 iframe,不需要任何设备/系统权限,+ * 也不应向本机写入下载,因此权限与下载通道都显式 fail-closed。+ */+const hardenedLoginCaptchaSessions = new WeakSet<object>();++export function hardenLoginCaptchaSession(+ captchaSession: Pick<+ Session,+ 'setPermissionRequestHandler' | 'setPermissionCheckHandler' | 'on'+ >,+): void {+ // partition session 会跨多次挑战复用;不要为每次 webview attach 累加监听器。+ if (hardenedLoginCaptchaSessions.has(captchaSession)) return;+ captchaSession.setPermissionRequestHandler((_webContents, _permission, callback) => {+ callback(false);+ });+ captchaSession.setPermissionCheckHandler(() => false);+ captchaSession.on('will-download', (event) => {+ event.preventDefault();+ });+ hardenedLoginCaptchaSessions.add(captchaSession);+}++/**+ * 登录 captcha webview 允许加载的 auth 服务端 origin 集合的解析钩子。+ * 与 popupOpenerResolver 同模式注入(保持本模块单向解耦):bootstrap 在 auth+ * 初始化处用 clientEndpointsService 的 authApiBaseUrl(两 realm + dev)接线。+ * 未注入(启动早期 / 单测未接线)时 fail-closed:一律拒附加。+ */+export type LoginCaptchaOriginResolver = () => readonly string[];++let loginCaptchaOriginResolver: LoginCaptchaOriginResolver | null = null;++export function setLoginCaptchaOriginResolver(+ resolver: LoginCaptchaOriginResolver | null,+): void {+ loginCaptchaOriginResolver = resolver;+}++/**+ * captcha webview 的附加与顶层导航白名单:协议(https,或 loopback 上的 http,+ * 兼容本地 dev auth-server)+ origin 命中注入集合 + 路径精确等于托管挑战页。+ * fragment 变更(token 回传通道)不产生导航事件,天然不受本闸约束。+ */+export function isAllowedLoginCaptchaUrl(rawUrl: string | undefined): boolean {+ if (!rawUrl || !loginCaptchaOriginResolver) return false;+ let parsed: URL;+ try {+ parsed = new URL(rawUrl);+ } catch {+ return false;+ }+ const loopback = parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1';+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)) {+ return false;+ }+ if (parsed.pathname !== LOGIN_CAPTCHA_PAGE_PATH) return false;+ let origins: readonly string[];+ try {+ origins = loginCaptchaOriginResolver();+ } catch {+ return false;+ }+ return origins.includes(parsed.origin);+}++/** CAPTCHA guest 的 popup 与顶层导航闸;重定向和普通导航必须走同一白名单。 */+export function installLoginCaptchaGuestHandlers(guestContents: WebContents): void {+ guestContents.setWindowOpenHandler(() => ({ action: 'deny' }));+ const guardTopLevelNavigation = (event: Electron.Event, url: string) => {+ if (isAllowedLoginCaptchaUrl(url)) return;+ event.preventDefault();+ };+ guestContents.on('will-navigate', guardTopLevelNavigation);+ guestContents.on('will-redirect', guardTopLevelNavigation);+ // guest 获得焦点后键盘事件不会冒泡到宿主 Renderer。Main 只拦 Esc,并通过+ // 静态 location.hash 复用既有无日志回传通道,让模态层仍可被键盘取消。+ guestContents.on('before-input-event', (event, input) => {+ if (!isGuestShortcutKeyDownType(input.type) || input.key !== 'Escape') return;+ event.preventDefault();+ void guestContents+ .executeJavaScript(`location.hash = ${JSON.stringify(LOGIN_CAPTCHA_CANCEL_HASH)}`, true)+ .catch(() => undefined);+ });+}+/** Renderer 接收 popup 路由消息的 IPC channel。main → renderer。 */export const RSB_BROWSER_POPUP_CHANNEL = 'rsb:browser-popup';/** Renderer 接收"webview 内按了 Cmd/Ctrl+L"的 IPC channel。main → renderer。@@ -688,10 +809,12 @@ export function installGhostGuestNavigationHandlers(export function installWebviewHardener(): void {app.on('web-contents-created', (_event, contents) => {// will-attach → did-attach 对同一个 guest 同步成对触发;用闭包变量把- // will 阶段的意识判定带给 did 阶段(意识 guest 走独立接线,不装浏览器- // 的 popup 路由与快捷键转发)。+ // will 阶段的意识/captcha 判定带给 did 阶段(这两类 guest 走独立接线,+ // 不装浏览器的 popup 路由与快捷键转发)。let pendingGhostAttach: { id: string } | null = null;+ let pendingCaptchaAttach = false;contents.on('will-attach-webview', (e, webPreferences, params) => {+ pendingCaptchaAttach = false;// 意识面板分支:声明了意识分区的 webview 必须验明正身——// 分区/地址/已装清单三对齐才放行并保留专属分区;验证失败直接拒附加// (绝不回落到浏览器分区,那会让 cindy-ghost:// 内容跑进错误 session)。@@ -707,6 +830,29 @@ export function installWebviewHardener(): void {return;}pendingGhostAttach = null;+ // 登录 captcha 分支:同意识分区一样"验明正身否则拒附加",绝不回落到+ // 浏览器分区(那会把挑战页装进 RSB 持久 session 并注入页面评论 preload)。+ // src 必须命中 auth origin 白名单 + 托管页固定路径(fail-closed)。+ if (params.partition === LOGIN_CAPTCHA_PARTITION) {+ if (!isAllowedLoginCaptchaUrl(params.src)) {+ e.preventDefault();+ return;+ }+ try {+ // 在 guest 获准附加前先锁死专属 session 的权限请求与权限检查;+ // 任一初始化异常都拒绝附加,不能让远程内容落到默认权限策略。+ hardenLoginCaptchaSession(session.fromPartition(LOGIN_CAPTCHA_PARTITION));+ } catch {+ e.preventDefault();+ return;+ }+ applyLoginCaptchaWebviewHardening(+ webPreferences as unknown as Record<string, unknown>,+ params,+ );+ pendingCaptchaAttach = true;+ return;+ }applyWebviewHardening(webPreferences as unknown as Record<string, unknown>,params,@@ -716,6 +862,14 @@ export function installWebviewHardener(): void {);});contents.on('did-attach-webview', (_e, guestContents) => {+ if (pendingCaptchaAttach) {+ pendingCaptchaAttach = false;+ // 挑战页零弹窗;顶层导航只允许停留在托管挑战页白名单内(Turnstile 的+ // 挑战 UI 活在子 iframe 里,顶层不应发生任何跨源导航)。token 回传走+ // location.hash → did-navigate-in-page,不经过 will-navigate。+ installLoginCaptchaGuestHandlers(guestContents);+ return;+ }if (pendingGhostAttach) {const ghostId = pendingGhostAttach.id;pendingGhostAttach = null;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 02d52818b4..882fbda29b 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1767,6 +1767,9 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('auth:get-login-state'),authDispatchLoginAction: (action: DesktopLoginAction): Promise<DesktopLoginActionResult> =>ipcRenderer.invoke('auth:dispatch-login-action', action),+ // 登录 captcha 托管挑战页地址(不含 query);LoginCaptchaOverlay 装载 webview 用。+ authGetCaptchaChallengeUrl: (): Promise<string> =>+ ipcRenderer.invoke('auth:get-captcha-challenge-url'),authLogout: (): Promise<void> => ipcRenderer.invoke('auth:logout'),authEnterLocal: () => ipcRenderer.invoke('auth:enter-local'),authExitLocal: () => ipcRenderer.invoke('auth:exit-local'),diff --git a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts b/apps/desktop/src/renderer/__tests__/authContextRace.test.tsindex 222b5636aa..f33b582591 100644--- a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/authContextRace.test.ts@@ -121,6 +121,19 @@ describe('AuthContext auth-state races', () => {expect(projectWaiting).toBeGreaterThan(-1);expect(autoStart).toBeGreaterThan(projectWaiting);});++ it('gates the sole-email auto request-code behind the login captcha gate', () => {+ // 唯一邮箱自动发码链不经过 LoginPage 的 dispatchRequestCode 闸;这里必须+ // 先问 loginCaptchaGate(global 开启 captcha 后,不过闸会不带 token 发码+ // 直接吃 400),取消(null)则停在 method-choice 不发码。+ expect(source).toContain("from '@/lib/loginCaptchaGate'");+ const gateAt = source.indexOf('getLoginEmailCaptchaGate()');+ const autoRequestAt = source.indexOf("type: 'request-code'");+ expect(gateAt).toBeGreaterThan(-1);+ expect(gateAt).toBeLessThan(autoRequestAt);+ expect(source).toContain('if (captchaToken === null)');+ expect(source).toContain('captchaToken,');+ });});describe('data-owner live push fencing', () => {diff --git a/apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx b/apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsxnew file mode 100644index 0000000000..5dd88cd0ad--- /dev/null+++ b/apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx@@ -0,0 +1,287 @@+import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';+import { useTranslation } from 'react-i18next';+import type { WebviewTag } from 'electron';++import { createLogger } from '@/lib/logger';+import { useIsDarkMode } from '@/components/markdown/useIsDarkMode';++import {+ LOGIN_CAPTCHA_CANCEL_RESULT_CODE,+ LOGIN_CAPTCHA_PARTITION,+} from '../../../shared/webviewPartition';+import { LOGIN_COLORS } from './loginDesignTokens';++const log = createLogger('LoginCaptchaOverlay');++/**+ * 托管挑战页 → 宿主的回传通道(wire 契约,与 auth-server 挑战页内联脚本对齐):+ * 页面把结果写进 location.hash —— fragment 变更不产生网络请求(token 不进任何+ * 访问日志),桌面侧经 <webview> 的 did-navigate-in-page 事件读取。+ * 成功:#cindy-captcha=ok.<encodeURIComponent(token)>+ * 失败:#cindy-captcha=err.<code>+ */+const CAPTCHA_RESULT_HASH_PREFIX = '#cindy-captcha=';+/** Turnstile token 官方上限(与 shared/authIpc 的 IPC 界校验同值)。 */+const MAX_CAPTCHA_TOKEN_LENGTH = 2048;+/** 挑战总时限:超时视为加载失败,转重试态(token 本身 300s 有效,120s 足够)。 */+const CHALLENGE_TIMEOUT_MS = 120_000;++/** 解析挑战页回传结果;非本契约的 URL 返回 null(导出供单测直接断言)。 */+export function parseLoginCaptchaResult(+ rawUrl: string,+ challengeBaseUrl: string,+): { status: 'ok'; token: string } | { status: 'err'; code: string } | null {+ let parsed: URL;+ let expected: URL;+ try {+ parsed = new URL(rawUrl);+ expected = new URL(challengeBaseUrl);+ } catch {+ return null;+ }+ // hash 结果只信任 main 已批准的托管挑战页 origin + path;query 用于主题/语言。+ if (parsed.origin !== expected.origin || parsed.pathname !== expected.pathname) return null;+ const hash = parsed.hash;+ if (!hash.startsWith(CAPTCHA_RESULT_HASH_PREFIX)) return null;+ const payload = hash.slice(CAPTCHA_RESULT_HASH_PREFIX.length);+ if (payload.startsWith('ok.')) {+ let token: string;+ try {+ token = decodeURIComponent(payload.slice('ok.'.length));+ } catch {+ return null;+ }+ if (!token || token.length > MAX_CAPTCHA_TOKEN_LENGTH) return null;+ return { status: 'ok', token };+ }+ if (payload.startsWith('err.')) {+ const code = payload.slice('err.'.length);+ return { status: 'err', code: /^[a-z0-9_-]{1,64}$/i.test(code) ? code : 'unknown' };+ }+ return null;+}++/**+ * LoginCaptchaOverlay — 登录页人机验证模态层。+ *+ * 独立内存分区的 <webview> 装载 auth-server 托管的 Turnstile 挑战页(主窗 CSP+ * 禁止远程脚本/iframe,故挑战跑在隔离 guest 里;分区与地址白名单由 main 的+ * webview hardener 验明正身,这里传什么都以 main 覆盖为准)。模态交互对齐+ * LoginConsentDialog(遮罩不可点穿、Esc = 取消、背景 inert)。+ *+ * 结果经 onResult 一次性回传:token 字符串 = 挑战通过;null = 用户取消。+ * 加载失败/挑战页报错/超时/guest 崩溃 → 卡片内重试态,不自动关闭。+ */+export function LoginCaptchaOverlay({+ challengeBaseUrl,+ onResult,+}: {+ /** 托管挑战页地址(已含业务 action),源地址来自 main。 */+ challengeBaseUrl: string;+ onResult: (token: string | null) => void;+}) {+ const { t, i18n } = useTranslation();+ const isDark = useIsDarkMode();+ const [failed, setFailed] = useState(false);+ const [ready, setReady] = useState(false);+ const [generation, setGeneration] = useState(0);+ const hostRef = useRef<HTMLDivElement | null>(null);+ const containerRef = useRef<HTMLDivElement | null>(null);+ const retryRef = useRef<HTMLButtonElement | null>(null);+ // onResult 进 ref:webview 生命周期 effect 不因回调身份变化重挂载 guest。+ const onResultRef = useRef(onResult);+ onResultRef.current = onResult;+ // 结果只回传一次(ok 与随后的 err/超时互斥)。+ const settledRef = useRef(false);+ const settle = (token: string | null) => {+ if (settledRef.current) return;+ settledRef.current = true;+ onResultRef.current(token);+ };++ const challengeTarget = new URL(challengeBaseUrl);+ challengeTarget.searchParams.set('theme', isDark ? 'dark' : 'light');+ challengeTarget.searchParams.set('lang', i18n.language);+ const challengeUrl = challengeTarget.toString();++ // 模态语义对齐 LoginConsentDialog:背景兄弟节点 inert、关闭归还焦点。+ // 初始焦点由 webview 挂载 effect 交给挑战主交互,绝不默认落在取消动作;+ // guest 内的 Esc 由 Main 转成固定 hash 回传,仍可可靠取消。+ useEffect(() => {+ const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ const rootEl = containerRef.current;+ const inerted: HTMLElement[] = [];+ if (rootEl?.parentElement) {+ for (const child of Array.from(rootEl.parentElement.children)) {+ if (child !== rootEl && child instanceof HTMLElement && !child.inert) {+ child.inert = true;+ inerted.push(child);+ }+ }+ }+ return () => {+ for (const el of inerted) el.inert = false;+ opener?.focus();+ };+ }, []);++ // 挑战失败后,WebView 已卸载;此时重试是弹层内的主要动作。+ useEffect(() => {+ if (failed) retryRef.current?.focus();+ }, [failed]);++ useEffect(() => {+ if (failed) return;+ const host = hostRef.current;+ if (!host) return;+ const webview = document.createElement('webview') as WebviewTag;+ webview.setAttribute('partition', LOGIN_CAPTCHA_PARTITION);+ webview.setAttribute('src', challengeUrl);+ webview.setAttribute('tabindex', '0');+ webview.setAttribute(+ 'style',+ 'display:flex;width:100%;height:100%;opacity:0;transition:opacity 0.12s ease;',+ );+ let disposed = false;+ const timeoutTimer = setTimeout(() => {+ if (!disposed) setFailed(true);+ }, CHALLENGE_TIMEOUT_MS);+ const onDomReady = () => {+ if (disposed) return;+ webview.style.opacity = '1';+ webview.focus();+ setReady(true);+ };+ const onInPageNavigate = (event: Electron.DidNavigateInPageEvent) => {+ if (disposed) return;+ const result = parseLoginCaptchaResult(event.url, challengeBaseUrl);+ if (!result) return;+ if (result.status === 'ok') {+ settle(result.token);+ return;+ }+ if (result.code === LOGIN_CAPTCHA_CANCEL_RESULT_CODE) {+ settle(null);+ return;+ }+ // 挑战页侧 error-callback / expired-callback:转重试态,码只进日志。+ log.warn('captcha challenge reported failure', { code: result.code });+ setFailed(true);+ };+ const onGone = () => {+ if (!disposed) setFailed(true);+ };+ const onFailLoad = (event: Electron.DidFailLoadEvent) => {+ // -3 = ABORTED(导航中断不算失败);子资源失败不判死,交给总时限兜底。+ if (disposed || event.errorCode === -3 || !event.isMainFrame) return;+ setFailed(true);+ };+ webview.addEventListener('dom-ready', onDomReady);+ webview.addEventListener('did-navigate-in-page', onInPageNavigate);+ webview.addEventListener('render-process-gone', onGone);+ webview.addEventListener('did-fail-load', onFailLoad);+ host.appendChild(webview);+ webview.focus();+ return () => {+ disposed = true;+ clearTimeout(timeoutTimer);+ webview.removeEventListener('dom-ready', onDomReady);+ webview.removeEventListener('did-navigate-in-page', onInPageNavigate);+ webview.removeEventListener('render-process-gone', onGone);+ webview.removeEventListener('did-fail-load', onFailLoad);+ webview.remove();+ };+ // challengeUrl 覆盖主题/语言切换;generation 驱动重试重挂载。+ }, [failed, generation, challengeUrl]);++ const retry = () => {+ setReady(false);+ setFailed(false);+ setGeneration((value) => value + 1);+ };++ const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ if (event.key === 'Escape') settle(null);+ };++ return (+ <div+ data-testid="login-captcha-overlay"+ role="dialog"+ aria-modal="true"+ aria-labelledby="login-captcha-title"+ ref={containerRef}+ tabIndex={-1}+ onMouseDown={(event) => {+ // 点遮罩空白把焦点拉回容器,Esc 恒有效(与 LoginConsentDialog 同口径);+ // 遮罩不可点穿:挑战必须显式完成或取消。+ if (event.target === event.currentTarget) event.currentTarget.focus();+ }}+ onKeyDown={handleKeyDown}+ className="fixed inset-0 z-50 grid place-items-center outline-none"+ style={{ background: LOGIN_COLORS.consentOverlay }}+ >+ <div+ className="relative flex flex-col items-center"+ style={{+ width: 400,+ borderRadius: 18,+ background: LOGIN_COLORS.panelBg,+ boxShadow: `inset 0 0 0 1px ${LOGIN_COLORS.panelBorder}`,+ padding: '20px 24px 16px',+ }}+ >+ <p+ id="login-captcha-title"+ className="font-semibold"+ style={{ fontSize: 16, lineHeight: '24px', color: LOGIN_COLORS.titleText }}+ >+ {t('login.captcha.title')}+ </p>+ {failed ? (+ <div+ className="flex flex-col items-center justify-center gap-3"+ style={{ width: 352, height: 240 }}+ >+ <p style={{ fontSize: 13, color: LOGIN_COLORS.errorFg }}>+ {t('login.captcha.failed')}+ </p>+ <button+ type="button"+ ref={retryRef}+ data-testid="login-captcha-retry"+ onClick={retry}+ className="font-medium transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ style={{ fontSize: 13, color: LOGIN_COLORS.linkText }}+ >+ {t('login.captcha.retry')}+ </button>+ </div>+ ) : (+ <div className="relative" style={{ width: 352, height: 240, marginTop: 8 }}>+ {!ready && (+ <p+ className="absolute inset-0 grid place-items-center"+ style={{ fontSize: 13, color: LOGIN_COLORS.secondaryText }}+ >+ {t('login.captcha.loading')}+ </p>+ )}+ {/* webview 由 effect 手动 appendChild 进本容器(GhostSettingsWebview+ 同款生命周期管理),React 只管理占位与提示文案。 */}+ <div ref={hostRef} className="absolute inset-0" />+ </div>+ )}+ <button+ type="button"+ data-testid="login-captcha-cancel"+ onClick={() => settle(null)}+ className="font-medium transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"+ style={{ fontSize: 13, marginTop: 12, color: LOGIN_COLORS.secondaryText }}+ >+ {t('login.captcha.cancel')}+ </button>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsxindex 57e483bc9d..35f17b53cd 100644--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx@@ -9,11 +9,17 @@ import {type ReactNode,} from 'react';import { useTranslation } from 'react-i18next';-import type { AccountDeletionStatus, SocialProvider, VerificationKind } from '@cindy/auth-client';-import { isValidEmail } from '@cindy/auth-client';+import type {+ AccountDeletionStatus,+ CaptchaConfig,+ SocialProvider,+ VerificationKind,+} from '@cindy/auth-client';+import { captchaRequiredActionForVerificationKind, isValidEmail } from '@cindy/auth-client';import { cn } from '@/lib/utils';import { createLogger } from '@/lib/logger';+import { setLoginEmailCaptchaGate } from '@/lib/loginCaptchaGate';import { WindowControls } from '@/components/title-bar/WindowControls';import { useLogin } from '@/hooks/useLogin';import { endLoginFirstLaunchLightGate, loginFirstLaunchLightActive } from '@/hooks/useTheme';@@ -29,6 +35,7 @@ import ssoIcon from '@/assets/login/icons/sso.svg';import ssoIconDark from '@/assets/login/icons/sso-dark.svg';import { LoginStage } from './LoginStage';+import { LoginCaptchaOverlay } from './LoginCaptchaOverlay';import {LoginBackButton,LoginConsentDialog,@@ -110,6 +117,7 @@ export function LoginPage() {getAccountDeletionStatus,clearAccountDeletionReceipt,dispatch,+ dispatchWithResult,clearError,} = useLogin();const { t } = useTranslation();@@ -438,11 +446,126 @@ export function LoginPage() {void dispatch({ type: 'reset' });};+ /* ── 人机验证前置闸(邮箱/短信发码防批量注册)──+ providers.captcha 只随 identifier/realm-confirmation 步的 state 下发,而发码+ 动作发生在后续步骤(method-choice 个人行 / 验证码页重发),进 ref 存续——+ 登录流必经 identifier,ref 必然先就位。cn 构建 / 服务端未开启时字段缺席,+ 整条闸是 no-op;当前服务端只下发邮箱动作,未来下发短信动作即可启用。 */+ const captchaConfigRef = useRef<CaptchaConfig | null>(null);+ useEffect(() => {+ if (loginState?.step === 'identifier' || loginState?.step === 'realm-confirmation') {+ captchaConfigRef.current = loginState.providers.captcha ?? null;+ }+ }, [loginState]);+ const [captchaChallenge, setCaptchaChallenge] = useState<{+ baseUrl: string;+ resolve: (token: string | null) => void;+ } | null>(null);+ // 挑战创建必须单飞:React 提交 overlay 前的快速重复触发不能覆盖 resolver。+ // 后续并发调用按取消处理,避免同一枚单次 token 被两个发码请求重复消费。+ const captchaChallengePendingRef = useRef(false);+ /** 打开挑战 overlay 并等结果:token = 通过;null = 用户取消或挑战页地址不可得。 */+ const obtainCaptchaToken = async (kind: VerificationKind): Promise<string | null> => {+ if (captchaChallengePendingRef.current) return null;+ captchaChallengePendingRef.current = true;+ try {+ let baseUrl: string;+ try {+ baseUrl = await window.electronAPI.authGetCaptchaChallengeUrl();+ const target = new URL(baseUrl);+ target.searchParams.set('action', captchaRequiredActionForVerificationKind(kind));+ baseUrl = target.toString();+ } catch (error) {+ // IPC 面缺失/异常:视同取消(不发码,用户可重试);错误细节只进日志。+ log.error('resolve captcha challenge url failed', error);+ return null;+ }+ return await new Promise((resolve) => {+ setCaptchaChallenge({+ baseUrl,+ resolve: (token) => {+ setCaptchaChallenge(null);+ resolve(token);+ },+ });+ });+ } finally {+ captchaChallengePendingRef.current = false;+ }+ };+ const captchaRequiredFor = (kind: VerificationKind) =>+ captchaConfigRef.current?.requiredFor.includes(+ captchaRequiredActionForVerificationKind(kind),+ ) === true;++ // AuthContext「唯一邮箱方式自动发码」快捷链的前置闸:那条链不经过下面的+ // dispatchRequestCode,借用本组件的挑战 overlay。latest-ref 模式:注册一次,+ // 回调恒取最新一帧的闸函数。+ const captchaGateRef = useRef<() => Promise<string | null | undefined>>(() =>+ Promise.resolve(undefined),+ );+ captchaGateRef.current = () =>+ captchaRequiredFor('email') ? obtainCaptchaToken('email') : Promise.resolve(undefined);+ useEffect(() => {+ setLoginEmailCaptchaGate(() => captchaGateRef.current());+ return () => setLoginEmailCaptchaGate(null);+ }, []);++ /**+ * 邮箱 identifier 提交:discover(AuthContext 可能内联自动发码)+ captcha+ * 错误兜底。providers 缓存旧于服务端开关时,自动链的闸拿不到 captcha 配置、+ * 不带 token 发码吃到 CAPTCHA_REQUIRED——在此出题后带 token 直接重发发码+ * (成功即进输码页,倒计时由 step 沿 effect 起算)。+ */+ const submitEmailDiscover = async (email: string) => {+ const result = await dispatchWithResult({ type: 'discover', email });+ if (+ result.success ||+ (result.code !== 'CAPTCHA_REQUIRED' && result.code !== 'CAPTCHA_INVALID')+ ) {+ return;+ }+ const token = await obtainCaptchaToken('email');+ if (token === null) return;+ await dispatchWithResult({+ type: 'request-code',+ kind: 'email',+ identifier: email,+ captchaToken: token,+ });+ };+// request-code 类动作统一走这里:成功返回时刻 = 倒计时起算点(Step 3a);// 失败(含重发失败)不 arm → 保持当前 deadline。const dispatchRequestCode = async (kind: VerificationKind, value: string) => {- const ok = await dispatch({ type: 'request-code', kind, identifier: value });- if (ok) armResendCountdown();+ let captchaToken: string | undefined;+ if (captchaRequiredFor(kind)) {+ const token = await obtainCaptchaToken(kind);+ if (token === null) return; // 取消:不发码、不 arm、不报错+ captchaToken = token;+ }+ let result = await dispatchWithResult({+ type: 'request-code',+ kind,+ identifier: value,+ captchaToken,+ });+ // 错误驱动兜底(providers 缓存旧于服务端开关,或 token 恰好过期):+ // 重新出题一次后原参重试,仅一次防循环。+ if (+ !result.success &&+ (result.code === 'CAPTCHA_REQUIRED' || result.code === 'CAPTCHA_INVALID')+ ) {+ const retryToken = await obtainCaptchaToken(kind);+ if (retryToken === null) return;+ result = await dispatchWithResult({+ type: 'request-code',+ kind,+ identifier: value,+ captchaToken: retryToken,+ });+ }+ if (result.success) armResendCountdown();};const submitIdentifier = (event: FormEvent) => {@@ -460,7 +583,7 @@ export function LoginPage() {setIdentifierFormatError(null);// 邮箱提交先过协议门(产品拍板 2026-07-24 二次:手机号/邮箱提交一律先弹协议// 弹窗,压过审查侧「discover 纯查询可放行」的建议;显式企业 SSO 入口仍豁免)- requireConsent(() => void dispatch({ type: 'discover', email: value }));+ requireConsent(() => void submitEmailDiscover(value));} else {// 手机号:桌面不做客户端 +86/号段校验(#223 仅移动端做 cnPhone 本地拦截),// 输入原样透传服务端 request-code,由服务端校验号段合法性。@@ -1154,6 +1277,14 @@ export function LoginPage() {onOpenPrivacy={() => undefined}/>)}+ {/* 人机验证挑战层(global 邮箱发码前置闸):独立分区 webview 装载+ auth-server 托管的 Turnstile 页,结果经 resolve 回到 dispatchRequestCode。 */}+ {captchaChallenge && (+ <LoginCaptchaOverlay+ challengeBaseUrl={captchaChallenge.baseUrl}+ onResult={captchaChallenge.resolve}+ />+ )}</div>);}diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.accountDeletionStatus.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.accountDeletionStatus.test.tsxindex 68b012377f..aadac76000 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.accountDeletionStatus.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.accountDeletionStatus.test.tsx@@ -12,6 +12,7 @@ const loginHook = vi.hoisted(() => ({getAccountDeletionStatus: vi.fn(),clearAccountDeletionReceipt: vi.fn(),dispatch: vi.fn(),+ dispatchWithResult: vi.fn(),clearError: vi.fn(),},}));diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsxindex 48ddef72d1..238cde734e 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx@@ -5,11 +5,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const loginHook = vi.hoisted(() => ({dispatch: vi.fn(),+ dispatchWithResult: vi.fn(),value: {isLoading: false,errorCode: null,loginState: { step: 'browser-redirect' as const, label: 'Google' },dispatch: vi.fn(),+ dispatchWithResult: vi.fn(),clearError: vi.fn(),},}));@@ -43,11 +45,13 @@ import { LoginPage } from '../LoginPage';describe('LoginPage browser redirect waiting state', () => {beforeEach(() => {loginHook.dispatch = vi.fn().mockResolvedValue(true);+ loginHook.dispatchWithResult = vi.fn().mockResolvedValue({ success: true, code: null });loginHook.value = {isLoading: false,errorCode: null,loginState: { step: 'browser-redirect', label: 'Google' },dispatch: loginHook.dispatch,+ dispatchWithResult: loginHook.dispatchWithResult,clearError: vi.fn(),};Object.defineProperty(window, 'electronAPI', {diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.captcha.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.captcha.harness.test.tsxnew file mode 100644index 0000000000..62836dbe41--- /dev/null+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.captcha.harness.test.tsx@@ -0,0 +1,417 @@+// @vitest-environment jsdom++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ CindyAuthClient,+ reduceAuthFlow,+ type AuthFlowState,+ type CaptchaRequiredAction,+ type VerificationKind,+} from '@cindy/auth-client';+import { createScenarioFetch } from '@cindy/auth-client/fixtures';++/**+ * 登录人机验证(captcha)harness 测试:+ * - providers:email-captcha 场景驱动「providers 主动触发」路径——重发前+ * overlay 先出现,webview 回传 token 后 dispatch body 才带 captchaToken;+ * - phone_request_code 预接线:服务端未来下发即可启用短信发码闸;+ * - 取消 = 不派发、不报错;+ * - CAPTCHA_REQUIRED 错误驱动兜底(providers 无 captcha 字段时服务端刚开开关)+ * 自动出题一次后原参重试;+ * - parseLoginCaptchaResult 的 hash 契约解析。+ *+ * webview 在 jsdom 中是未知元素:组件经 addEventListener 挂事件,测试直接+ * dispatchEvent 一个带 url 的 did-navigate-in-page 事件模拟挑战页回传。+ */++const loginHook = vi.hoisted(() => ({+ value: {+ isLoading: false,+ errorCode: null as string | null,+ loginState: null as unknown,+ dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null as string | null })),+ clearError: vi.fn(),+ },+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { language: 'zh-CN' },+ }),+}));+vi.mock('@/hooks/useLogin', () => ({ useLogin: () => loginHook.value }));+vi.mock('@/components/title-bar/WindowControls', () => ({ WindowControls: () => null }));+// 重发倒计时置零:本文件测的是发码前的 captcha 闸,identifier → verification-code+// 的 step 迁移会武装 42s 倒计时,把重发链接换成倒计时文案,先掐掉。+vi.mock('../useResendCountdown', () => ({+ useResendCountdown: () => ({ remaining: 0, arm: vi.fn() }),+}));++import { LoginPage } from '../LoginPage';+import { parseLoginCaptchaResult } from '../LoginCaptchaOverlay';+import { getLoginEmailCaptchaGate } from '@/lib/loginCaptchaGate';++const CHALLENGE_BASE = 'https://auth.scenario.invalid/captcha/turnstile';++function scenarioClient(scenario: string) {+ return new CindyAuthClient({+ baseUrl: 'https://auth.scenario.invalid',+ region: 'global',+ deviceId: 'captcha-harness',+ clientType: 'desktop',+ fetch: createScenarioFetch(scenario, { region: 'global' })!,+ });+}++/** identifier(带 captcha providers)→ verification-code:重发链路的现网状态序列。 */+async function statesFor(+ scenario: string,+ kind: VerificationKind = 'email',+ requiredFor?: CaptchaRequiredAction[],+): Promise<{+ identifier: AuthFlowState;+ verification: AuthFlowState;+}> {+ const parsedProviders = await scenarioClient(scenario).getProviders();+ const providers =+ parsedProviders.captcha && requiredFor+ ? {+ ...parsedProviders,+ captcha: { ...parsedProviders.captcha, requiredFor },+ }+ : parsedProviders;+ const identifierValue = kind === 'email' ? '[email protected]' : '+8613800138000';+ const identifier = reduceAuthFlow(null, { type: 'providers-loaded', providers });+ const verification = reduceAuthFlow(identifier, {+ type: 'code-requested',+ kind,+ identifier: identifierValue,+ });+ return { identifier, verification };+}++function mount(state: AuthFlowState) {+ loginHook.value = {+ isLoading: false,+ errorCode: null,+ loginState: state,+ dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null as string | null })),+ clearError: vi.fn(),+ };+ return render(<LoginPage />);+}++function setState(rerender: (ui: React.ReactElement) => void, state: AuthFlowState) {+ loginHook.value = { ...loginHook.value, loginState: state };+ rerender(<LoginPage />);+}++/** 模拟挑战页把结果写进 location.hash(桌面回传通道)。 */+async function emitCaptchaResult(fragment: string) {+ // overlay 先提交、webview 再由 effect append;Windows CI 上两步可能跨 tick。+ const webview = await waitFor(() => {+ const candidate = document.querySelector('webview');+ expect(candidate, 'captcha webview 应已挂载').not.toBeNull();+ return candidate!;+ });+ const event = new Event('did-navigate-in-page');+ Object.defineProperty(event, 'url', { value: `${CHALLENGE_BASE}#${fragment}` });+ webview.dispatchEvent(event);+}++beforeEach(() => {+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'darwin',+ acceptPrivacyConsent: async () => ({ allowed: true }),+ authGetCaptchaChallengeUrl: async () => CHALLENGE_BASE,+ },+ });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('LoginPage captcha 前置闸(providers 主动触发)', () => {+ it('重发前先出题,token 回传后 dispatch body 携带 captchaToken', async () => {+ const { identifier, verification } = await statesFor('providers:email-captcha');+ const { rerender } = mount(identifier); // identifier 步落 captchaConfigRef+ setState(rerender, verification);++ fireEvent.click(screen.getByText('login.resendCode'));+ await screen.findByTestId('login-captcha-overlay');+ // overlay 打开时不应已派发+ expect(loginHook.value.dispatchWithResult).not.toHaveBeenCalled();++ await emitCaptchaResult('cindy-captcha=ok.scenario-captcha-token');+ await waitFor(() =>+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledWith({+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: 'scenario-captcha-token',+ }),+ );+ // 结果回传后 overlay 关闭+ await waitFor(() =>+ expect(screen.queryByTestId('login-captcha-overlay')).toBeNull(),+ );+ });++ it('服务端未来仅下发 phone_request_code 即可启用短信发码闸', async () => {+ const { identifier, verification } = await statesFor('providers:email-captcha', 'phone', [+ 'phone_request_code',+ ]);+ const { rerender } = mount(identifier);+ setState(rerender, verification);++ fireEvent.click(screen.getByText('login.resendCode'));+ await screen.findByTestId('login-captcha-overlay');+ expect(loginHook.value.dispatchWithResult).not.toHaveBeenCalled();+ await waitFor(() => {+ const src = document.querySelector('webview')?.getAttribute('src');+ expect(src).toBeTruthy();+ expect(new URL(src!).searchParams.get('action')).toBe('phone_request_code');+ });++ await emitCaptchaResult('cindy-captcha=ok.phone-captcha-token');+ await waitFor(() =>+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledWith({+ type: 'request-code',+ kind: 'phone',+ identifier: '+8613800138000',+ captchaToken: 'phone-captcha-token',+ }),+ );+ });++ it('挑战打开时聚焦主要 WebView 交互,而不是默认聚焦取消', async () => {+ const { identifier, verification } = await statesFor('providers:email-captcha');+ const { rerender } = mount(identifier);+ setState(rerender, verification);++ fireEvent.click(screen.getByText('login.resendCode'));+ await screen.findByTestId('login-captcha-overlay');++ await waitFor(() => expect(document.activeElement?.tagName).toBe('WEBVIEW'));+ expect(document.activeElement).not.toBe(screen.getByTestId('login-captcha-cancel'));++ fireEvent.click(screen.getByTestId('login-captcha-cancel'));+ });++ it('取消与失败后的重试操作都有键盘可见焦点样式', async () => {+ const { identifier, verification } = await statesFor('providers:email-captcha');+ const { rerender } = mount(identifier);+ setState(rerender, verification);++ fireEvent.click(screen.getByText('login.resendCode'));+ await screen.findByTestId('login-captcha-overlay');+ const cancel = screen.getByTestId('login-captcha-cancel');+ expect(cancel.classList.contains('focus-visible:ring-2')).toBe(true);+ expect(cancel.classList.contains('focus-visible:ring-[var(--focus-ring-soft)]')).toBe(true);++ await emitCaptchaResult('cindy-captcha=err.expired');+ const retry = await screen.findByTestId('login-captcha-retry');+ expect(retry.classList.contains('focus-visible:ring-2')).toBe(true);+ expect(retry.classList.contains('focus-visible:ring-[var(--focus-ring-soft)]')).toBe(true);+ });++ it('guest 内 Esc 的固定取消 hash 会关闭挑战且不派发发码', async () => {+ const { identifier, verification } = await statesFor('providers:email-captcha');+ const { rerender } = mount(identifier);+ setState(rerender, verification);++ fireEvent.click(screen.getByText('login.resendCode'));+ await screen.findByTestId('login-captcha-overlay');+ await emitCaptchaResult('cindy-captcha=err.cancelled');++ await waitFor(() =>+ expect(screen.queryByTestId('login-captcha-overlay')).toBeNull(),+ );+ expect(loginHook.value.dispatchWithResult).not.toHaveBeenCalled();+ });++ it('取消挑战 = 不派发、overlay 关闭、无错误注入', async () => {+ const { identifier, verification } = await statesFor('providers:email-captcha');+ const { rerender } = mount(identifier);+ setState(rerender, verification);++ fireEvent.click(screen.getByText('login.resendCode'));+ await screen.findByTestId('login-captcha-overlay');+ fireEvent.click(screen.getByTestId('login-captcha-cancel'));++ await waitFor(() =>+ expect(screen.queryByTestId('login-captcha-overlay')).toBeNull(),+ );+ expect(loginHook.value.dispatchWithResult).not.toHaveBeenCalled();+ });++ it('providers 无 captcha 时不出题,直接派发(cn/未启用回归)', async () => {+ const { identifier, verification } = await statesFor('providers:email-only');+ const { rerender } = mount(identifier);+ setState(rerender, verification);++ fireEvent.click(screen.getByText('login.resendCode'));+ await waitFor(() =>+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledWith({+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: undefined,+ }),+ );+ expect(screen.queryByTestId('login-captcha-overlay')).toBeNull();+ });++ it('AuthContext 自动发码链的闸(loginCaptchaGate):挂载即注册,需要时出题拿 token', async () => {+ const { identifier } = await statesFor('providers:email-captcha');+ mount(identifier);+ const gate = getLoginEmailCaptchaGate();+ expect(gate, 'LoginPage 挂载后闸必须已注册').not.toBeNull();++ const pending = gate!();+ await screen.findByTestId('login-captcha-overlay');+ await emitCaptchaResult('cindy-captcha=ok.gate-token');+ await expect(pending).resolves.toBe('gate-token');+ });++ it('快速重复触发只保留一个挑战,后续调用取消且不会覆盖首个 resolver', async () => {+ const { identifier } = await statesFor('providers:email-captcha');+ mount(identifier);+ const gate = getLoginEmailCaptchaGate();+ expect(gate).not.toBeNull();++ const first = gate!();+ const duplicate = gate!();+ await expect(duplicate).resolves.toBeNull();+ await screen.findByTestId('login-captcha-overlay');+ expect(document.querySelectorAll('webview')).toHaveLength(1);++ await emitCaptchaResult('cindy-captcha=ok.single-flight-token');+ await expect(first).resolves.toBe('single-flight-token');+ });++ it('AuthContext 自动发码链的闸:providers 无 captcha 时直接放行(undefined)', async () => {+ const { identifier } = await statesFor('providers:email-only');+ mount(identifier);+ const gate = getLoginEmailCaptchaGate();+ expect(gate).not.toBeNull();+ await expect(gate!()).resolves.toBeUndefined();+ expect(screen.queryByTestId('login-captcha-overlay')).toBeNull();+ });++ it('identifier 提交的 discover 兜底:自动链吃到 CAPTCHA_REQUIRED 后出题重发发码', async () => {+ // providers 不带 captcha(providers 缓存旧于服务端开关):自动链不带 token+ // 发码,错误码从 discover 动作冒泡回 submitEmailDiscover。+ const { identifier } = await statesFor('providers:email-only');+ mount(identifier);+ loginHook.value.dispatchWithResult+ .mockResolvedValueOnce({ success: false, code: 'CAPTCHA_REQUIRED' })+ .mockResolvedValueOnce({ success: true, code: null });++ // 先勾协议 radio 再提交(identifier 提交过 requireConsent 门)+ fireEvent.click(screen.getByTestId('login-consent-radio'));+ fireEvent.change(screen.getByTestId('login-input'), {+ target: { value: '[email protected]' },+ });+ fireEvent.click(screen.getByTestId('login-continue-button'));++ await screen.findByTestId('login-captcha-overlay');+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledTimes(1);+ expect(loginHook.value.dispatchWithResult).toHaveBeenNthCalledWith(1, {+ type: 'discover',+ email: '[email protected]',+ });++ await emitCaptchaResult('cindy-captcha=ok.discover-fallback-token');+ await waitFor(() => expect(loginHook.value.dispatchWithResult).toHaveBeenCalledTimes(2));+ expect(loginHook.value.dispatchWithResult).toHaveBeenNthCalledWith(2, {+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: 'discover-fallback-token',+ });+ });++ it('CAPTCHA_REQUIRED 错误驱动兜底:自动出题一次后原参重试', async () => {+ // providers 不带 captcha(模拟服务端刚开开关、客户端 providers 缓存过旧)+ const { identifier, verification } = await statesFor('providers:email-only');+ const { rerender } = mount(identifier);+ setState(rerender, verification);+ loginHook.value.dispatchWithResult+ .mockResolvedValueOnce({ success: false, code: 'CAPTCHA_REQUIRED' })+ .mockResolvedValueOnce({ success: true, code: null });++ fireEvent.click(screen.getByText('login.resendCode'));+ await screen.findByTestId('login-captcha-overlay');+ await emitCaptchaResult('cindy-captcha=ok.fallback-token');++ await waitFor(() => expect(loginHook.value.dispatchWithResult).toHaveBeenCalledTimes(2));+ expect(loginHook.value.dispatchWithResult).toHaveBeenNthCalledWith(2, {+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: 'fallback-token',+ });+ });+});++describe('parseLoginCaptchaResult(挑战页 hash 回传契约)', () => {+ it('解析 ok/err,拒绝越界与非本契约 URL', () => {+ expect(+ parseLoginCaptchaResult(+ `${CHALLENGE_BASE}#cindy-captcha=ok.abc%2B123`,+ CHALLENGE_BASE,+ ),+ ).toEqual({ status: 'ok', token: 'abc+123' });+ expect(+ parseLoginCaptchaResult(+ `${CHALLENGE_BASE}#cindy-captcha=err.expired`,+ CHALLENGE_BASE,+ ),+ ).toEqual({+ status: 'err',+ code: 'expired',+ });+ // 越界 token(>2048)拒+ expect(+ parseLoginCaptchaResult(+ `${CHALLENGE_BASE}#cindy-captcha=ok.${'a'.repeat(2049)}`,+ CHALLENGE_BASE,+ ),+ ).toBeNull();+ // 空 token / 非法编码 / 无关 hash / 非 URL+ expect(+ parseLoginCaptchaResult(`${CHALLENGE_BASE}#cindy-captcha=ok.`, CHALLENGE_BASE),+ ).toBeNull();+ expect(+ parseLoginCaptchaResult(`${CHALLENGE_BASE}#cindy-captcha=ok.%E0%A4%A`, CHALLENGE_BASE),+ ).toBeNull();+ expect(parseLoginCaptchaResult(`${CHALLENGE_BASE}#other`, CHALLENGE_BASE)).toBeNull();+ expect(parseLoginCaptchaResult('not-a-url', CHALLENGE_BASE)).toBeNull();+ expect(+ parseLoginCaptchaResult(+ 'https://evil.example.com/captcha/turnstile#cindy-captcha=ok.forged',+ CHALLENGE_BASE,+ ),+ ).toBeNull();+ expect(+ parseLoginCaptchaResult(+ 'https://auth.scenario.invalid/redirected#cindy-captcha=ok.forged',+ CHALLENGE_BASE,+ ),+ ).toBeNull();+ // 异常错误码收敛为 unknown+ expect(+ parseLoginCaptchaResult(`${CHALLENGE_BASE}#cindy-captcha=err.<script>`, CHALLENGE_BASE),+ ).toEqual({ status: 'err', code: 'unknown' });+ });+});diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsxindex ed00c3b4a6..8be08c8f89 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.consent.test.tsx@@ -20,6 +20,7 @@ const loginHook = vi.hoisted(() => ({errorCode: null as string | null,loginState: null as unknown,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),},}));@@ -66,6 +67,7 @@ function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.valerrorCode: null,loginState: state,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),...extra,};@@ -226,14 +228,16 @@ describe('consent guard(未勾选拦截个人登录链路)', () => {fireEvent.change(screen.getByTestId('login-input'), { target: { value: '13800138000' } });fireEvent.click(screen.getByTestId('login-continue-button'));expect(screen.getByTestId('login-consent-dialog')).toBeTruthy();- expect(loginHook.value.dispatch).not.toHaveBeenCalled();+ expect(loginHook.value.dispatchWithResult).not.toHaveBeenCalled();await act(async () => {fireEvent.click(screen.getByTestId('login-consent-agree'));});- expect(loginHook.value.dispatch).toHaveBeenCalledWith({+ // request-code 走 dispatchWithResult(captcha 兜底需要读失败码)+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledWith({type: 'request-code',kind: 'phone',identifier: '13800138000',+ captchaToken: undefined,});});diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsxindex a11ca5a6df..54aa81707d 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.errorCopy.harness.test.tsx@@ -26,6 +26,7 @@ const loginHook = vi.hoisted(() => ({errorCode: null as string | null,loginState: null as unknown,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),},}));@@ -44,6 +45,9 @@ const NAMED_CODES = ['INVALID_CODE','CODE_ATTEMPTS_EXCEEDED','RATE_LIMITED',+ 'CAPTCHA_REQUIRED',+ 'CAPTCHA_INVALID',+ 'CAPTCHA_UNAVAILABLE','SSO_LOGIN_REQUIRED','ORG_SSO_NOT_FOUND','SOCIAL_TOKEN_INVALID',@@ -115,6 +119,7 @@ function mountWithError(code: string) {errorCode: code,loginState: identifierState,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),};return render(<LoginPage />);diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsxindex 6ad8252af9..03614d191c 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx@@ -27,6 +27,7 @@ const loginHook = vi.hoisted(() => ({errorCode: null as string | null,loginState: null as unknown,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),},}));@@ -96,6 +97,7 @@ function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.valerrorCode: null,loginState: state,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),...extra,};diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.identifierFormat.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.identifierFormat.harness.test.tsxindex fcfdedf9ee..10b5c28b88 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.identifierFormat.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.identifierFormat.harness.test.tsx@@ -24,6 +24,7 @@ const loginHook = vi.hoisted(() => ({errorCode: null as string | null,loginState: null as unknown,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),},}));@@ -87,6 +88,7 @@ function mount(state: AuthFlowState) {errorCode: null,loginState: state,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),};return render(<LoginPage />);@@ -116,7 +118,8 @@ describe('identifier 本地格式校验错误态(设计稿 347:1727)', () => {target: { value: '[email protected]' },});fireEvent.click(screen.getByTestId('login-continue-button'));- expect(loginHook.value.dispatch).toHaveBeenCalledWith({+ // 邮箱 discover 走 dispatchWithResult(captcha 兜底需要读失败码)+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledWith({type: 'discover',email: '[email protected]',});@@ -132,10 +135,12 @@ describe('identifier 本地格式校验错误态(设计稿 347:1727)', () => {});fireEvent.click(screen.getByTestId('login-continue-button'));// 桌面不再做 cnPhone 本地拦截:任意输入原样透传服务端,无红边红字- expect(loginHook.value.dispatch).toHaveBeenCalledWith({+ // (request-code 走 dispatchWithResult,captcha 兜底需要读失败码)+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledWith({type: 'request-code',kind: 'phone',identifier: '12345',+ captchaToken: undefined,});expect(screen.queryByTestId('login-error-text')).toBeNull();});diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.pr2a.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.pr2a.harness.test.tsxindex f12dc7f6f9..57709b0e69 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.pr2a.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.pr2a.harness.test.tsx@@ -29,6 +29,7 @@ const loginHook = vi.hoisted(() => ({errorCode: null as string | null,loginState: null as unknown,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),},}));@@ -97,6 +98,7 @@ function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.valerrorCode: null,loginState: state,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),...extra,};@@ -257,13 +259,15 @@ describe('verification-code', () => {it('重发成功重置 / 失败保持(dispatch 返回值驱动 arm)', async () => {vi.useFakeTimers();- const dispatch = vi.fn(async () => true);- mount(await verificationState(), { dispatch });+ // request-code 走 dispatchWithResult(captcha 兜底需要读失败码),arm 由其+ // success 驱动+ const dispatchWithResult = vi.fn(async () => ({ success: true, code: null as string | null }));+ mount(await verificationState(), { dispatchWithResult });// 初始无倒计时(直接注入态未经历 request-code) → 链接可点await act(async () => {fireEvent.click(screen.getByTestId('login-resend-link'));});- expect(dispatch).toHaveBeenCalledWith(+ expect(dispatchWithResult).toHaveBeenCalledWith(expect.objectContaining({ type: 'request-code', kind: 'email' }),);expect(screen.getByTestId('login-resend-countdown').textContent).toBe(@@ -271,7 +275,7 @@ describe('verification-code', () => {);// 走到 0 → 再点一次但失败:不 arm,链接保持act(() => vi.advanceTimersByTime(42_000));- dispatch.mockResolvedValueOnce(false);+ dispatchWithResult.mockResolvedValueOnce({ success: false, code: 'RATE_LIMITED' });await act(async () => {fireEvent.click(screen.getByTestId('login-resend-link'));});diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.region.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.region.harness.test.tsxindex b4b4d88e9e..ccdcd359f2 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.region.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.region.harness.test.tsx@@ -25,6 +25,7 @@ const loginHook = vi.hoisted(() => ({errorCode: null as string | null,loginState: null as unknown,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),},}));@@ -69,6 +70,7 @@ function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.valerrorCode: null,loginState: state,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),...extra,};diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.regionPill.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.regionPill.test.tsxindex b3192d8eb4..403881f64c 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.regionPill.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.regionPill.test.tsx@@ -26,6 +26,7 @@ const loginHook = vi.hoisted(() => ({errorCode: null as string | null,loginState: null as unknown,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),},}));@@ -69,6 +70,7 @@ function mount(state: AuthFlowState) {errorCode: null,loginState: state,dispatch: vi.fn(async () => true),+ dispatchWithResult: vi.fn(async () => ({ success: true, code: null })),clearError: vi.fn(),};return render(<LoginPage />);diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex d6ce9fb2a0..4a819d765f 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -15,6 +15,7 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { clearWorkersCache } from '@/features/cc-agent/hooks/useWorkers';import { setSelectedMachineOwner } from '@/features/device-link/selectedMachineStore';import { createLogger } from '@/lib/logger';+import { getLoginEmailCaptchaGate } from '@/lib/loginCaptchaGate';import { toast } from '@/lib/toast';import {createAuthService,@@ -356,10 +357,21 @@ export function AuthProvider({});}if (sole?.type === 'email_code' && result.state.email) {+ // 自动发码同样要先过人机验证闸(LoginPage 注册的挑战 overlay):+ // 这条快捷链不经过 LoginPage 的 dispatchRequestCode,不过闸会在+ // global 开启 captcha 后不带 token 发码直接吃 400。+ const captchaGate = getLoginEmailCaptchaGate();+ const captchaToken = captchaGate ? await captchaGate() : undefined;+ if (captchaToken === null) {+ // 用户取消挑战:停在 method-choice,个人行可再次发起(会重新过闸)+ setLoginState(result.state);+ return result;+ }return dispatchLoginAction({type: 'request-code',kind: 'email',identifier: result.state.email,+ captchaToken,});}}diff --git a/apps/desktop/src/renderer/hooks/useLogin.ts b/apps/desktop/src/renderer/hooks/useLogin.tsindex c8234c9cff..8088cefeb9 100644--- a/apps/desktop/src/renderer/hooks/useLogin.ts+++ b/apps/desktop/src/renderer/hooks/useLogin.ts@@ -11,6 +11,15 @@ interface UseLoginReturn {getAccountDeletionStatus: ReturnType<typeof useAuth>['getAccountDeletionStatus'];clearAccountDeletionReceipt: ReturnType<typeof useAuth>['clearAccountDeletionReceipt'];dispatch: (action: DesktopLoginAction) => Promise<boolean>;+ /**+ * 与 dispatch 同一条链路,但把失败码返回给调用方——captcha 兜底重试需要在+ * 调用点区分 CAPTCHA_REQUIRED/CAPTCHA_INVALID 与其他失败(errorCode state+ * 在同一 tick 内读不到新值)。busy 短路时 code 为 null(与 dispatch 静默+ * 返回 false 同口径,不产生可展示错误)。+ */+ dispatchWithResult: (+ action: DesktopLoginAction,+ ) => Promise<{ success: boolean; code: string | null }>;clearError: () => void;}@@ -43,9 +52,11 @@ export function useLogin(): UseLoginReturn {});}, [loadLoginState, loginState]);- const dispatch = useCallback(- async (action: DesktopLoginAction): Promise<boolean> => {- if (loadingRef.current && action.type !== 'cancel-browser') return false;+ const dispatchWithResult = useCallback(+ async (action: DesktopLoginAction): Promise<{ success: boolean; code: string | null }> => {+ if (loadingRef.current && action.type !== 'cancel-browser') {+ return { success: false, code: null };+ }loadingRef.current = true;setIsLoading(true);setErrorCode(null);@@ -53,12 +64,12 @@ export function useLogin(): UseLoginReturn {const result = await dispatchLoginAction(action);if (!result.success) {setErrorCode(result.code === 'USER_CANCELLED' ? null : result.code);- return false;+ return { success: false, code: result.code };}- return true;+ return { success: true, code: null };} catch {setErrorCode('AUTH_REQUEST_FAILED');- return false;+ return { success: false, code: 'AUTH_REQUEST_FAILED' };} finally {loadingRef.current = false;setIsLoading(false);@@ -67,6 +78,12 @@ export function useLogin(): UseLoginReturn {[dispatchLoginAction],);+ const dispatch = useCallback(+ async (action: DesktopLoginAction): Promise<boolean> =>+ (await dispatchWithResult(action)).success,+ [dispatchWithResult],+ );+return {isLoading,errorCode,@@ -75,6 +92,7 @@ export function useLogin(): UseLoginReturn {getAccountDeletionStatus,clearAccountDeletionReceipt,dispatch,+ dispatchWithResult,clearError: () => setErrorCode(null),};}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex dcaeb4bede..c8e84d82fe 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4708,6 +4708,13 @@"cn": "CN","dev": "Dev"},+ "captcha": {+ "title": "Security check",+ "loading": "Loading security check…",+ "failed": "Failed to load the security check.",+ "retry": "Retry",+ "cancel": "Cancel"+ },"errors": {"fallback": "Sign-in failed. Please try again.","AUTH_SERVICE_UNAVAILABLE": "The sign-in service is temporarily unavailable.",@@ -4718,6 +4725,9 @@"INVALID_CODE": "The verification code is incorrect or expired.","CODE_ATTEMPTS_EXCEEDED": "Too many incorrect attempts. Request a new code.","RATE_LIMITED": "Too many attempts. Please wait and try again.",+ "CAPTCHA_REQUIRED": "Please complete the security check first.",+ "CAPTCHA_INVALID": "Security check failed. Please try again.",+ "CAPTCHA_UNAVAILABLE": "The security check is temporarily unavailable. Please try again later.","SSO_LOGIN_REQUIRED": "This organization requires SSO sign-in.","ORG_SSO_NOT_FOUND": "Company not found, or it has no SSO connection enabled","ORG_REALM_AMBIGUOUS": "This enterprise identifier exists in both regions. Contact your administrator.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 9441ad2fc5..ca12c29602 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4733,6 +4733,13 @@"cn": "CN","dev": "Dev"},+ "captcha": {+ "title": "セキュリティチェック",+ "loading": "セキュリティチェックを読み込んでいます…",+ "failed": "セキュリティチェックを読み込めませんでした。",+ "retry": "再試行",+ "cancel": "キャンセル"+ },"errors": {"fallback": "ログインに失敗しました。再試行してください。","AUTH_SERVICE_UNAVAILABLE": "ログインサービスは一時的に利用できません。",@@ -4743,6 +4750,9 @@"INVALID_CODE": "認証コードが間違っているか期限切れです。","CODE_ATTEMPTS_EXCEEDED": "試行回数を超えました。新しいコードを取得してください。","RATE_LIMITED": "試行が多すぎます。少し待ってから再試行してください。",+ "CAPTCHA_REQUIRED": "先にセキュリティチェックを完了してください。",+ "CAPTCHA_INVALID": "セキュリティチェックに失敗しました。もう一度お試しください。",+ "CAPTCHA_UNAVAILABLE": "セキュリティチェックは一時的に利用できません。しばらくしてから再試行してください。","SSO_LOGIN_REQUIRED": "この組織は SSO ログインが必要です。","ORG_SSO_NOT_FOUND": "該当する企業が見つからないか、SSO サインインが有効になっていません","ORG_REALM_AMBIGUOUS": "この企業識別子は両方の地域に存在します。管理者にお問い合わせください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 11c9574b72..be1dc1a5cb 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4733,6 +4733,13 @@"cn": "CN","dev": "Dev"},+ "captcha": {+ "title": "보안 확인",+ "loading": "보안 확인을 불러오는 중…",+ "failed": "보안 확인을 불러오지 못했습니다.",+ "retry": "다시 시도",+ "cancel": "취소"+ },"errors": {"fallback": "로그인에 실패했습니다. 다시 시도하세요.","AUTH_SERVICE_UNAVAILABLE": "로그인 서비스를 일시적으로 사용할 수 없습니다.",@@ -4743,6 +4750,9 @@"INVALID_CODE": "인증 코드가 잘못되었거나 만료되었습니다.","CODE_ATTEMPTS_EXCEEDED": "시도 횟수를 초과했습니다. 새 코드를 요청하세요.","RATE_LIMITED": "시도가 너무 많습니다. 잠시 후 다시 시도하세요.",+ "CAPTCHA_REQUIRED": "먼저 보안 확인을 완료하세요.",+ "CAPTCHA_INVALID": "보안 확인에 실패했습니다. 다시 시도하세요.",+ "CAPTCHA_UNAVAILABLE": "보안 확인 서비스를 일시적으로 사용할 수 없습니다. 잠시 후 다시 시도하세요.","SSO_LOGIN_REQUIRED": "이 조직은 SSO 로그인이 필요합니다.","ORG_SSO_NOT_FOUND": "해당 기업을 찾을 수 없거나 SSO 로그인이 활성화되어 있지 않습니다","ORG_REALM_AMBIGUOUS": "이 기업 식별자가 두 지역에 모두 존재합니다. 관리자에게 문의하세요.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 2bb79a96cb..f0dca0c071 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4706,6 +4706,13 @@"cn": "CN","dev": "Dev"},+ "captcha": {+ "title": "安全验证",+ "loading": "正在加载安全验证…",+ "failed": "安全验证加载失败",+ "retry": "重试",+ "cancel": "取消"+ },"errors": {"fallback": "登录失败,请稍后重试","AUTH_SERVICE_UNAVAILABLE": "登录服务暂不可用",@@ -4716,6 +4723,9 @@"INVALID_CODE": "验证码错误或已过期","CODE_ATTEMPTS_EXCEEDED": "验证码错误次数过多,请重新获取","RATE_LIMITED": "操作过于频繁,请稍后再试",+ "CAPTCHA_REQUIRED": "请先完成安全验证",+ "CAPTCHA_INVALID": "安全验证未通过,请重试",+ "CAPTCHA_UNAVAILABLE": "安全验证服务暂不可用,请稍后再试","SSO_LOGIN_REQUIRED": "该邮箱所属企业要求通过 SSO 登录","ORG_SSO_NOT_FOUND": "未找到该企业,或该企业未启用 SSO 登录","ORG_REALM_AMBIGUOUS": "该企业标识同时存在于两个区域,请联系企业管理员处理",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 4383b83568..ddc6b3f2fb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4733,6 +4733,13 @@"cn": "CN","dev": "Dev"},+ "captcha": {+ "title": "安全驗證",+ "loading": "正在載入安全驗證…",+ "failed": "安全驗證載入失敗",+ "retry": "重試",+ "cancel": "取消"+ },"errors": {"fallback": "登入失敗,請稍後重試","AUTH_SERVICE_UNAVAILABLE": "登入服務暫不可用",@@ -4743,6 +4750,9 @@"INVALID_CODE": "驗證碼錯誤或已過期","CODE_ATTEMPTS_EXCEEDED": "驗證碼錯誤次數過多,請重新獲取","RATE_LIMITED": "操作過於頻繁,請稍後再試",+ "CAPTCHA_REQUIRED": "請先完成安全驗證",+ "CAPTCHA_INVALID": "安全驗證未通過,請重試",+ "CAPTCHA_UNAVAILABLE": "安全驗證服務暫時無法使用,請稍後再試","SSO_LOGIN_REQUIRED": "該電子郵件所屬企業要求透過 SSO 登入","ORG_SSO_NOT_FOUND": "未找到該企業,或該企業未啟用 SSO 登入","ORG_REALM_AMBIGUOUS": "該企業標識同時存在於兩個區域,請聯絡企業管理員處理",diff --git a/apps/desktop/src/renderer/lib/loginCaptchaGate.ts b/apps/desktop/src/renderer/lib/loginCaptchaGate.tsnew file mode 100644index 0000000000..2aafa72718--- /dev/null+++ b/apps/desktop/src/renderer/lib/loginCaptchaGate.ts@@ -0,0 +1,25 @@+/**+ * loginCaptchaGate — 登录邮箱发码人机验证闸的注册点。+ *+ * AuthContext.dispatchLoginAction 的「唯一邮箱方式自动发码」快捷链(discover+ * 返回 sole email_code 时内联派发 request-code)不经过 LoginPage 的+ * dispatchRequestCode,若不在此处过闸,global 开启 captcha 后这条链会不带+ * token 发码直接吃 400。挑战 overlay 属于 LoginPage 的视图层,经本模块注册+ * 回调借用——独立小模块而非放进 AuthContext,是为了 LoginPage 不必 import+ * 重量级的 AuthContext 模块图(单测下会拖入全部 store 依赖)。+ *+ * 返回语义:undefined = 本部署不需要人机验证,直接发码;string = 已取得+ * token;null = 用户取消挑战(调用方不发码,停在当前步)。+ */+export type LoginEmailCaptchaGate = () => Promise<string | null | undefined>;++let gate: LoginEmailCaptchaGate | null = null;++/** LoginPage 挂载时注册、卸载时置 null。 */+export function setLoginEmailCaptchaGate(value: LoginEmailCaptchaGate | null): void {+ gate = value;+}++export function getLoginEmailCaptchaGate(): LoginEmailCaptchaGate | null {+ return gate;+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8efcb81405..fa875f29ff 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2001,6 +2001,8 @@ interface ElectronAPI {}>;authGetLoginState: () => Promise<DesktopLoginActionResult>;authDispatchLoginAction: (action: DesktopLoginAction) => Promise<DesktopLoginActionResult>;+ /** 登录 captcha 托管挑战页地址(不含 query);LoginCaptchaOverlay 装载 webview 用。 */+ authGetCaptchaChallengeUrl: () => Promise<string>;authLogout: () => Promise<void>;authEnterLocal: () => Promise<AuthStateChangePayload>;authExitLocal: () => Promise<AuthStateChangePayload>;diff --git a/apps/desktop/src/shared/__tests__/authIpc.test.ts b/apps/desktop/src/shared/__tests__/authIpc.test.tsindex 78b732ea03..862a28d8be 100644--- a/apps/desktop/src/shared/__tests__/authIpc.test.ts+++ b/apps/desktop/src/shared/__tests__/authIpc.test.ts@@ -20,6 +20,50 @@ describe('desktop auth IPC validation', () => {});});+ it('accepts request-code with and without a bounded captchaToken', () => {+ expect(+ parseDesktopLoginAction({ type: 'request-code', kind: 'email', identifier: '[email protected]' }),+ ).toEqual({ type: 'request-code', kind: 'email', identifier: '[email protected]' });+ expect(+ parseDesktopLoginAction({+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: 'tok',+ }),+ ).toEqual({+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: 'tok',+ });+ // 携带即校验:超界/空/非字符串一律整条拒绝,不做静默剥离+ expect(+ parseDesktopLoginAction({+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: 'a'.repeat(2049),+ }),+ ).toBeNull();+ expect(+ parseDesktopLoginAction({+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: '',+ }),+ ).toBeNull();+ expect(+ parseDesktopLoginAction({+ type: 'request-code',+ kind: 'email',+ identifier: '[email protected]',+ captchaToken: 42,+ }),+ ).toBeNull();+ });+it('rejects unknown, incomplete, and oversized actions', () => {expect(parseDesktopLoginAction(null)).toBeNull();expect(parseDesktopLoginAction({ type: 'unknown' })).toBeNull();diff --git a/apps/desktop/src/shared/authIpc.ts b/apps/desktop/src/shared/authIpc.tsindex 7c775c9162..e6b8a4edbe 100644--- a/apps/desktop/src/shared/authIpc.ts+++ b/apps/desktop/src/shared/authIpc.ts@@ -13,7 +13,7 @@ export type DesktopLoginAction =| { type: 'discover-sso-org'; org: string }| { type: 'confirm-sso-realm' }| { type: 'cancel-sso-realm' }- | { type: 'request-code'; kind: VerificationKind; identifier: string }+ | { type: 'request-code'; kind: VerificationKind; identifier: string; captchaToken?: string }| { type: 'verify-code'; kind: VerificationKind; identifier: string; code: string }| {type: 'start-browser';@@ -60,6 +60,8 @@ export type DesktopAccountDeletionStatusResult =const MAX_IDENTIFIER_LENGTH = 320;const MAX_OPAQUE_ID_LENGTH = 256;const MAX_CODE_LENGTH = 32;+// Turnstile token 官方上限 2048 字符(服务端 schema 同值)。+const MAX_CAPTCHA_TOKEN_LENGTH = 2048;// 与 auth-server 的企业 ID / slug / 已验证域名统一上限对齐。const MAX_ORG_IDENTIFIER_LENGTH = 253;@@ -99,11 +101,27 @@ export function parseDesktopLoginAction(value: unknown): DesktopLoginAction | nureturn { type: 'confirm-sso-realm' };case 'cancel-sso-realm':return { type: 'cancel-sso-realm' };- case 'request-code':- return isVerificationKind(value.kind) &&- isBoundedString(value.identifier, MAX_IDENTIFIER_LENGTH)- ? { type: 'request-code', kind: value.kind, identifier: value.identifier }+ case 'request-code': {+ if (+ !isVerificationKind(value.kind) ||+ !isBoundedString(value.identifier, MAX_IDENTIFIER_LENGTH)+ ) {+ return null;+ }+ // captchaToken 缺省合法(cn 构建 / captcha 未启用);一旦携带必须过界校验,+ // 非法则整条 action 拒绝,不做静默剥离。+ if (value.captchaToken === undefined) {+ return { type: 'request-code', kind: value.kind, identifier: value.identifier };+ }+ return isBoundedString(value.captchaToken, MAX_CAPTCHA_TOKEN_LENGTH)+ ? {+ type: 'request-code',+ kind: value.kind,+ identifier: value.identifier,+ captchaToken: value.captchaToken,+ }: null;+ }case 'verify-code':return isVerificationKind(value.kind) &&isBoundedString(value.identifier, MAX_IDENTIFIER_LENGTH) &&diff --git a/apps/desktop/src/shared/webviewPartition.ts b/apps/desktop/src/shared/webviewPartition.tsindex 49d95cade7..78d031bd5b 100644--- a/apps/desktop/src/shared/webviewPartition.ts+++ b/apps/desktop/src/shared/webviewPartition.ts@@ -16,3 +16,26 @@* 同时跨 main / renderer 共用,放到 shared/ 保持单一来源。*/export const BROWSER_PARTITION = 'persist:xdmaker-browser-app';++/**+ * LOGIN_CAPTCHA_PARTITION — 登录页人机验证(Turnstile 托管挑战页)webview 的专用+ * 分区。不带 `persist:` 前缀 = 纯内存 session,关闭 overlay 即弃,不与 RSB 浏览器+ * 或主窗共享任何 cookie / 存储。主进程 webview hardener 对该分区做显式白名单:+ * 只允许加载 auth-server 的 /captcha/ 托管页(来源与路径校验见 webview-security.ts),+ * 其余一律拒附加。+ */+export const LOGIN_CAPTCHA_PARTITION = 'login-captcha';++/** guest 获得焦点时,Main 用这个静态 hash 把 Esc 取消意图送回宿主 Renderer。 */+export const LOGIN_CAPTCHA_CANCEL_RESULT_CODE = 'cancelled';+export const LOGIN_CAPTCHA_CANCEL_HASH =+ `#cindy-captcha=err.${LOGIN_CAPTCHA_CANCEL_RESULT_CODE}`;++import { CAPTCHA_CHALLENGE_PAGE_PATH } from '@cindy/auth-client';++/**+ * auth-server 托管挑战页的固定路径(wire 契约单一来源在 @cindy/auth-client,+ * 双端共用)。完整 URL = authApiBaseUrl + 本路径 + query,由 main 惰性拼出;+ * webview hardener 也用它做附加/导航的路径白名单。+ */+export const LOGIN_CAPTCHA_PAGE_PATH = CAPTCHA_CHALLENGE_PAGE_PATH;diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsxindex bc7fc6e40e..e2d90dab38 100644--- a/apps/mobile/app/(auth)/login.tsx+++ b/apps/mobile/app/(auth)/login.tsx@@ -6,6 +6,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context';import type { AccountDeletionStatus, SocialProvider, VerificationKind } from '@cindy/auth-client';import { useAuth } from '@/auth/AuthContext';+import { LoginCaptchaWebView } from '@/auth/LoginCaptchaWebView';import { useLoginFirstLaunchLight } from '@/auth/loginFirstLaunchGate';import { resolveStartupSplashHandoff } from '@/auth/startupSplashContinuity';import {@@ -1187,8 +1188,9 @@ export default function LoginScreen() {// 只管渲染与命中,读屏仍会念出不可见的注销状态)。iOS 走 accessibilityElementsHidden、// Android 走 importantForAccessibility,两端都要给(PR #464 codex)。const realmConsentOpen = realmConfirmation !== null;+ const captchaChallengeOpen = auth.captchaChallenge !== null;const deletionBubbleA11yHidden =- consentDialogOpen || realmConsentOpen || handoffPhase !== 'done';+ consentDialogOpen || realmConsentOpen || captchaChallengeOpen || handoffPhase !== 'done';return (<MobileLoginHandoffStage@@ -1210,7 +1212,9 @@ export default function LoginScreen() {// Android 读屏:弹窗打开时隐藏背景登录组(accessibilityViewIsModal 仅 iOS// 生效;codex 审查 P2)。iOS 忽略此属性,无副作用。importantForAccessibility={- consentDialogOpen || realmConsentOpen ? 'no-hide-descendants' : 'auto'+ consentDialogOpen || realmConsentOpen || captchaChallengeOpen+ ? 'no-hide-descendants'+ : 'auto'}onLayout={measureBaseline}ref={outerGroupRef}@@ -1315,6 +1319,14 @@ export default function LoginScreen() {onOpenPrivacy={() => undefined}/>) : null}+ {/* 人机验证挑战层(global 邮箱发码前置闸):incognito WebView 装载+ auth-server 托管的 Turnstile 页,结果回 AuthContext 挂起的发码动作。 */}+ {auth.captchaChallenge ? (+ <LoginCaptchaWebView+ url={auth.captchaChallenge.url}+ onResult={auth.resolveCaptchaChallenge}+ />+ ) : null}</MobileLoginHandoffStage>);}diff --git a/apps/mobile/src/__tests__/accountDeletion.test.ts b/apps/mobile/src/__tests__/accountDeletion.test.tsindex 51355b3cf1..442222cb98 100644--- a/apps/mobile/src/__tests__/accountDeletion.test.ts+++ b/apps/mobile/src/__tests__/accountDeletion.test.ts@@ -321,7 +321,7 @@ describe("mobile account deletion", () => {"const realmConsentOpen = realmConfirmation !== null;",);expect(login).toContain(- "const deletionBubbleA11yHidden =\n consentDialogOpen || realmConsentOpen || handoffPhase !== 'done';",+ "const deletionBubbleA11yHidden =\n consentDialogOpen || realmConsentOpen || captchaChallengeOpen || handoffPhase !== 'done';",);expect(gate).toContain("accessibilityElementsHidden={deletionBubbleA11yHidden}",@@ -331,7 +331,7 @@ describe("mobile account deletion", () => {);// 登录组那层仍按弹窗条件隐藏(它本身在入场动画容器内,不需要入场条件)。expect(login).toContain(- "consentDialogOpen || realmConsentOpen ? 'no-hide-descendants' : 'auto'",+ "consentDialogOpen || realmConsentOpen || captchaChallengeOpen\n ? 'no-hide-descendants'\n : 'auto'",);});});diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex a938f78bd3..622ca0d619 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -10,10 +10,12 @@ import {useState,type ReactNode,} from 'react';-import { AppState, Linking, Platform } from 'react-native';+import { AppState, Keyboard, Linking, Platform } from 'react-native';import {AuthApiError,+ CAPTCHA_CHALLENGE_PAGE_PATH,CindyAuthClient,+ captchaRequiredActionForVerificationKind,discoverSsoOrgRealm,parseAccountDeletionReceiptRecord,parseAuthSessionRecord,@@ -30,6 +32,7 @@ import {type AccountDeletionAvailability,type AccountDeletionChallenge,type AccountDeletionStatus,+ type CaptchaConfig,type LoginOutcome,type SocialProvider,type SsoOrgDiscovery,@@ -62,7 +65,7 @@ import { syncCanaryChannelAfterAuth } from '@/auth/canaryChannelSync';import { ensureDeviceId, hasStoredDeviceId } from '@/auth/deviceId';import { decodeJwtOrgSlug, isAccessTokenExpiring } from '@/auth/jwt';import { maybeEnableXdOrgBetaDefault } from '@/auth/xdOrgBetaDefault';-import { getAuthLocale } from '@/auth/loginMessages';+import { getAuthLocale, getLoginLanguage } from '@/auth/loginMessages';import { acquireNativeSocialCredential } from '@/auth/nativeSocial';import {matchesOAuthCallbackUrl,@@ -186,6 +189,13 @@ export interface AuthContextValue {clearAuthError(): void;consumeAccountDeletionRestored(): void;dispatchLoginAction(action: MobileLoginAction): Promise<boolean>;+ /**+ * 登录人机验证挑战(global 邮箱发码前置闸):非空时登录页渲染 WebView Modal+ * 装载该托管挑战页;结果经 resolveCaptchaChallenge 回到挂起的发码动作+ * (token = 通过,null = 用户取消/挑战失败)。+ */+ captchaChallenge: { url: string } | null;+ resolveCaptchaChallenge(token: string | null): void;completeOAuthCallback(callbackUrl: string): Promise<void>;logout(): Promise<void>;/** 认证服务已明确拒绝当前会话时,单飞执行完整本地退登。 */@@ -222,6 +232,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {clearAuthError: () => undefined,consumeAccountDeletionRestored: () => undefined,dispatchLoginAction: async () => true,+ captchaChallenge: null,+ resolveCaptchaChallenge: () => undefined,completeOAuthCallback: async () => undefined,logout: async () => undefined,terminateSession: async () => undefined,@@ -457,11 +469,106 @@ export function AuthProvider({ children }: { children: ReactNode }) {[],);+ /* ── 登录人机验证(Turnstile 托管挑战页,按 requiredFor 控制邮箱/短信发码)── */+ const captchaConfigRef = useRef<CaptchaConfig | null>(null);+ const [captchaChallenge, setCaptchaChallenge] = useState<{ url: string } | null>(null);+ const captchaResolveRef = useRef<((token: string | null) => void) | null>(null);+const updateLoginState = useCallback((next: AuthFlowState | null) => {+ // providers.captcha 只随 identifier/realm-confirmation 步下发,发码动作发生在+ // 后续步骤,进 ref 存续(登录流必经 identifier,ref 必然先就位);cn 构建 /+ // 服务端未开启时字段缺席,captcha 闸整体 no-op。+ if (next?.step === 'identifier' || next?.step === 'realm-confirmation') {+ captchaConfigRef.current = next.providers.captcha ?? null;+ }loginStateRef.current = next;setLoginState(next);}, []);+ /** 登录页 WebView Modal 的结果回传口(token = 通过,null = 取消/失败)。 */+ const resolveCaptchaChallenge = useCallback((token: string | null) => {+ const resolve = captchaResolveRef.current;+ captchaResolveRef.current = null;+ setCaptchaChallenge(null);+ resolve?.(token);+ }, []);++ /** 出题并等结果。有效登录主题由 ThemeOverrideProvider 内的 WebView 补入 URL。 */+ const runCaptchaChallenge = useCallback((kind: VerificationKind): Promise<string | null> => {+ let base = getMobileEndpointForRealm(BUILD_AUTH_REGION, 'authApiBaseUrl');+ while (base.endsWith('/')) base = base.slice(0, -1);+ const action = captchaRequiredActionForVerificationKind(kind);+ const url = `${base}${CAPTCHA_CHALLENGE_PAGE_PATH}?action=${encodeURIComponent(action)}&lang=${encodeURIComponent(getLoginLanguage())}`;+ return new Promise<string | null>((resolve) => {+ // 单飞:dispatchLoginAction 本身串行,这里不会出现并发挑战。+ captchaResolveRef.current = resolve;+ // 验证码浮层不是原生 Modal,也不做键盘避让;先收键盘,避免 iOS 小屏上+ // 挑战内容与取消动作被仍聚焦的 identifier 输入框键盘遮挡。+ Keyboard.dismiss();+ setCaptchaChallenge({ url });+ });+ }, []);++ /** 按发码类型执行前置闸:未启用 → 放行;启用 → 出题;取消 → 不发码。 */+ const ensureCaptchaGate = useCallback(+ async (+ kind: VerificationKind,+ ): Promise<+ { proceed: true; captchaToken?: string } | { proceed: false }+ > => {+ if (+ captchaConfigRef.current?.requiredFor.includes(+ captchaRequiredActionForVerificationKind(kind),+ ) !== true+ ) {+ return { proceed: true };+ }+ const token = await runCaptchaChallenge(kind);+ return token === null+ ? { proceed: false }+ : { proceed: true, captchaToken: token };+ },+ [runCaptchaChallenge],+ );++ /**+ * 发验证码 + 错误驱动兜底:服务端返回 CAPTCHA_REQUIRED/CAPTCHA_INVALID+ * (providers 缓存旧于服务端开关,或 token 恰好过期)时重新出题一次后重试,+ * 仅一次防循环;重试被取消或再失败则抛原错误走统一错误链路。+ */+ const requestCodeWithCaptchaFallback = useCallback(+ async (+ did: string,+ kind: VerificationKind,+ identifier: string,+ captchaToken: string | undefined,+ ): Promise<void> => {+ try {+ await authClientFor(did, BUILD_AUTH_REGION).requestCode(+ kind,+ identifier,+ {+ captchaToken,+ },+ );+ } catch (error) {+ const code = authErrorCode(error);+ if (code !== 'CAPTCHA_REQUIRED' && code !== 'CAPTCHA_INVALID')+ throw error;+ const retryToken = await runCaptchaChallenge(kind);+ if (retryToken === null) throw error;+ await authClientFor(did, BUILD_AUTH_REGION).requestCode(+ kind,+ identifier,+ {+ captchaToken: retryToken,+ },+ );+ }+ },+ [runCaptchaChallenge],+ );+const setToken = useCallback((token: string | null) => {accessTokenRef.current = token;setAccessToken(token);@@ -1154,9 +1261,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {});}if (sole?.type === 'email_code') {- await authClientFor(did, BUILD_AUTH_REGION).requestCode(+ // 人机验证前置闸(覆盖 discovery→发码的自动串发路径):取消则不+ // 串发,落 method-choice,用户可从个人行再次发起(会重新过闸)。+ const gate = await ensureCaptchaGate('email');+ if (!gate.proceed) {+ updateLoginState(+ reduceAuthFlow(currentState, {+ type: 'discovery-loaded',+ email,+ methods,+ }),+ );+ return true;+ }+ await requestCodeWithCaptchaFallback(+ did,'email',email,+ gate.captchaToken,);updateLoginState(reduceAuthFlow(currentState, {@@ -1250,9 +1372,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {}if (action.type === 'request-code') {const identifier = action.identifier.trim();- await authClientFor(did, BUILD_AUTH_REGION).requestCode(+ const gate = await ensureCaptchaGate(action.kind);+ // 取消:不发码、不改状态、不报错(用户可再点发送/重发)。+ if (!gate.proceed) return false;+ await requestCodeWithCaptchaFallback(+ did,action.kind,identifier,+ gate.captchaToken,);updateLoginState(reduceAuthFlow(loginStateRef.current, {@@ -1433,6 +1560,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {[acceptOutcome,completeOAuthCallback,+ ensureCaptchaGate,+ requestCodeWithCaptchaFallback,prepareBetaChannelForCurrentDevice,suspendSessionRecoveryForLogin,updateLoginState,@@ -1727,6 +1856,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {clearAuthError,consumeAccountDeletionRestored,dispatchLoginAction,+ captchaChallenge,+ resolveCaptchaChallenge,completeOAuthCallback,logout,terminateSession,@@ -1744,6 +1875,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {accountDeletionReceipt,accountDeletionRestored,authError,+ captchaChallenge,clearAccountDeletionReceipt,clearAuthError,completeOAuthCallback,@@ -1760,6 +1892,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {loginState,logout,requestAccountDeletionChallenge,+ resolveCaptchaChallenge,terminateSession,user,],diff --git a/apps/mobile/src/auth/LoginCaptchaWebView.tsx b/apps/mobile/src/auth/LoginCaptchaWebView.tsxnew file mode 100644index 0000000000..e9ff027c92--- /dev/null+++ b/apps/mobile/src/auth/LoginCaptchaWebView.tsx@@ -0,0 +1,202 @@+import { useEffect, useMemo, useState } from 'react';+import { ActivityIndicator, BackHandler, Pressable, StyleSheet, View } from 'react-native';+import { WebView } from 'react-native-webview';++import { parseCaptchaWebViewMessage } from '@/auth/loginCaptchaMessage';+import {+ isAllowedLoginCaptchaNavigation,+ withLoginCaptchaTheme,+} from '@/auth/loginCaptchaUrl';+import { loginText } from '@/auth/loginMessages';+import { Text } from '@/components/AppText';+import { useTheme } from '@/theme';+import { fontWeight, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';++/** 挑战总时限:网络半通或 iframe 卡死时转入弹窗内重试态。 */+const CHALLENGE_TIMEOUT_MS = 120_000;++/**+ * LoginCaptchaWebView — 登录人机验证模态层(global 邮箱发码前置闸)。+ *+ * 内嵌 WebView 装载 auth-server 托管的 Turnstile 挑战页;导航白名单只放行+ * 托管页同源与 Turnstile 挑战 iframe,其余一律拒。结果经 onResult 一次性回传:+ * token = 通过,null = 用户取消。加载失败/挑战页报错 → 卡片内重试态。+ * 遮罩与 Android 返回键语义对齐 LoginConsentDialog(遮罩不可点穿、返回 = 取消)。+ */+export function LoginCaptchaWebView({+ url,+ onResult,+}: {+ /** 托管挑战页完整地址(AuthContext 按构建区域 authApiBaseUrl 拼出)。 */+ url: string;+ onResult: (token: string | null) => void;+}) {+ const { colors, mode } = useTheme();+ const login = colors.login;+ const [failed, setFailed] = useState(false);+ const [ready, setReady] = useState(false);+ const [generation, setGeneration] = useState(0);++ // Android 硬件返回键 = 取消(非原生 Modal 需自行拦截,同 LoginConsentDialog)。+ useEffect(() => {+ const sub = BackHandler.addEventListener('hardwareBackPress', () => {+ onResult(null);+ return true;+ });+ return () => sub.remove();+ }, [onResult]);++ // 此组件位于 MobileLoginHandoffStage 的 ThemeOverrideProvider 内,mode 是登录+ // 子树真正显示的主题(首次启动固定 light,之后才跟随系统)。+ const themedUrl = useMemo(() => withLoginCaptchaTheme(url, mode), [mode, url]);++ // WebView 主文档成功不代表 Cloudflare iframe 一定能完成;为加载、挑战与回传+ // 设置同桌面端一致的总时限。成功/取消会卸载组件,失败与重试会重跑 effect,+ // cleanup 因而覆盖完成、重试和卸载三条清理路径。+ useEffect(() => {+ if (failed) return;+ const timeoutTimer = setTimeout(() => {+ setReady(false);+ setFailed(true);+ }, CHALLENGE_TIMEOUT_MS);+ return () => clearTimeout(timeoutTimer);+ }, [failed, generation, themedUrl]);++ const retry = () => {+ setReady(false);+ setFailed(false);+ setGeneration((value) => value + 1);+ };++ return (+ <View+ accessibilityViewIsModal+ style={[+ StyleSheet.absoluteFill,+ {+ alignItems: 'center',+ backgroundColor: login.consentOverlay,+ justifyContent: 'center',+ paddingHorizontal: spacing.lg,+ zIndex: 100,+ },+ ]}+ testID="login.captcha"+ >+ <View+ style={{+ alignItems: 'center',+ backgroundColor: login.panelBg,+ borderColor: login.panelBorder,+ borderRadius: radius.container,+ borderWidth: 1,+ paddingBottom: 12,+ paddingHorizontal: 16,+ paddingTop: 16,+ maxWidth: 340,+ width: '100%',+ }}+ >+ <Text+ style={{+ color: login.titleText,+ fontSize: typeScale.body,+ fontWeight: fontWeight.bold,+ lineHeight: lineHeight.bodyRelaxed,+ }}+ >+ {loginText('captchaTitle')}+ </Text>+ {failed ? (+ <View+ style={{+ alignItems: 'center',+ alignSelf: 'stretch',+ height: 220,+ justifyContent: 'center',+ }}+ >+ <Text style={{ color: login.loginError, fontSize: typeScale.footnote, textAlign: 'center' }}>+ {loginText('captchaFailed')}+ </Text>+ <Pressable+ accessibilityRole="button"+ onPress={retry}+ style={{+ alignItems: 'center',+ justifyContent: 'center',+ marginTop: spacing.md,+ minHeight: 44,+ minWidth: 44,+ }}+ testID="login.captcha.retry"+ >+ <Text style={{ color: login.linkText, fontSize: typeScale.footnote }}>+ {loginText('captchaRetry')}+ </Text>+ </Pressable>+ </View>+ ) : (+ <View style={{ alignSelf: 'stretch', height: 220, marginTop: 8 }}>+ <WebView+ key={generation}+ source={{ uri: themedUrl }}+ // react-native-webview 会把 originWhitelist 未命中的 URL 主动交给+ // Linking.openURL。因此这里只负责让导航进入下方回调;真正的同源+ // 白名单由回调精确判定,其余(含任意跳转/唤起外部)一律拒绝。+ originWhitelist={['*']}+ // Android 的 window.open/target=_blank 默认走 onCreateWindow,可能+ // 绕过导航回调并唤起外部浏览器;禁用多窗口后统一落回本 WebView 闸。+ setSupportMultipleWindows={false}+ onShouldStartLoadWithRequest={(request) =>+ isAllowedLoginCaptchaNavigation(request, themedUrl)+ }+ onMessage={(event) => {+ // 客户端不是认证边界:Android WebMessageListener 只上报 source origin,+ // 不保证带托管页 pathname。这里只校验 wire 契约;token 的真实性、action、+ // hostname、时效与一次性均由 auth-server Siteverify 最终裁决。+ const result = parseCaptchaWebViewMessage(event.nativeEvent.data);+ if (!result) return;+ if (result.ok) {+ onResult(result.token);+ return;+ }+ setFailed(true);+ }}+ onLoadEnd={() => setReady(true)}+ onError={() => setFailed(true)}+ onHttpError={() => setFailed(true)}+ onContentProcessDidTerminate={() => setFailed(true)}+ onRenderProcessGone={() => setFailed(true)}+ style={{ backgroundColor: 'transparent', flex: 1 }}+ />+ {!ready ? (+ <View+ pointerEvents="none"+ style={[StyleSheet.absoluteFill, { alignItems: 'center', justifyContent: 'center' }]}+ >+ <ActivityIndicator color={login.secondaryText} />+ </View>+ ) : null}+ </View>+ )}+ <Pressable+ accessibilityRole="button"+ onPress={() => onResult(null)}+ style={{+ alignItems: 'center',+ justifyContent: 'center',+ marginTop: spacing.sm,+ minHeight: 44,+ minWidth: 44,+ }}+ testID="login.captcha.cancel"+ >+ <Text style={{ color: login.secondaryText, fontSize: typeScale.footnote }}>+ {loginText('captchaCancel')}+ </Text>+ </Pressable>+ </View>+ </View>+ );+}diff --git a/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts b/apps/mobile/src/auth/__tests__/loginCaptcha.test.tsnew file mode 100644index 0000000000..67caee9261--- /dev/null+++ b/apps/mobile/src/auth/__tests__/loginCaptcha.test.ts@@ -0,0 +1,278 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++import { parseCaptchaWebViewMessage } from '@/auth/loginCaptchaMessage';+import {+ isAllowedLoginCaptchaNavigation,+ isAllowedLoginCaptchaPageUrl,+ withLoginCaptchaTheme,+} from '@/auth/loginCaptchaUrl';++/**+ * 登录人机验证(captcha)移动端测试:+ * - parseCaptchaWebViewMessage 纯函数(WebView postMessage 回传契约);+ * - AuthContext 发码前置闸接线(静态源码断言——AuthContext.tsx 整模块依赖+ * expo/RN 运行时,node vitest 不宜加载,与 loginScenarioHarness 同款模式)。+ */++describe('parseCaptchaWebViewMessage(挑战页 postMessage 回传契约)', () => {+ it('解析 ok/err,拒绝越界与非本契约消息', () => {+ expect(+ parseCaptchaWebViewMessage(+ JSON.stringify({ type: 'cindy-captcha', ok: true, token: 'tok-1' }),+ ),+ ).toEqual({ ok: true, token: 'tok-1' });+ expect(+ parseCaptchaWebViewMessage(+ JSON.stringify({ type: 'cindy-captcha', ok: false, code: 'expired' }),+ ),+ ).toEqual({ ok: false, code: 'expired' });+ // 越界 token(>2048)/ 空 token 拒+ expect(+ parseCaptchaWebViewMessage(+ JSON.stringify({ type: 'cindy-captcha', ok: true, token: 'a'.repeat(2049) }),+ ),+ ).toBeNull();+ expect(+ parseCaptchaWebViewMessage(JSON.stringify({ type: 'cindy-captcha', ok: true, token: '' })),+ ).toBeNull();+ // 非本契约 type / 非 JSON / 缺 ok+ expect(+ parseCaptchaWebViewMessage(JSON.stringify({ type: 'other', ok: true, token: 't' })),+ ).toBeNull();+ expect(parseCaptchaWebViewMessage('not-json')).toBeNull();+ expect(parseCaptchaWebViewMessage(JSON.stringify({ type: 'cindy-captcha' }))).toBeNull();+ // 失败缺 code → 收敛 unknown+ expect(+ parseCaptchaWebViewMessage(JSON.stringify({ type: 'cindy-captcha', ok: false })),+ ).toEqual({ ok: false, code: 'unknown' });+ });+});++describe('withLoginCaptchaTheme(挑战页有效登录主题)', () => {+ it('保留既有参数并写入 light/dark,覆盖陈旧 theme', () => {+ expect(+ withLoginCaptchaTheme('https://auth.example.com/captcha/turnstile?lang=ja', 'light'),+ ).toBe('https://auth.example.com/captcha/turnstile?lang=ja&theme=light');+ expect(+ withLoginCaptchaTheme(+ 'https://auth.example.com/captcha/turnstile?theme=light&lang=ko',+ 'dark',+ ),+ ).toBe('https://auth.example.com/captcha/turnstile?theme=dark&lang=ko');+ });++ it('非法 URL 保留原值,由 WebView 加载失败路径收敛', () => {+ expect(withLoginCaptchaTheme('not-a-url', 'light')).toBe('not-a-url');+ });+});++describe('mobile captcha WebView 导航与消息契约边界', () => {+ const expected =+ 'https://auth.example.com/captcha/turnstile?action=email_request_code&theme=dark';++ it('顶层只允许预期协议、origin 与精确托管路径', () => {+ expect(+ isAllowedLoginCaptchaNavigation({ url: expected, isTopFrame: true }, expected),+ ).toBe(true);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'https://auth.example.com/captcha/other', isTopFrame: true },+ expected,+ ),+ ).toBe(false);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'blob:https://auth.example.com/opaque-id', isTopFrame: true },+ expected,+ ),+ ).toBe(false);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'https://challenges.cloudflare.com/widget', isTopFrame: true },+ expected,+ ),+ ).toBe(false);+ });++ it('Turnstile 子 frame 放行 Cloudflare HTTPS 与其必需的本地空文档', () => {+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'https://challenges.cloudflare.com/turnstile/widget', isTopFrame: false },+ expected,+ ),+ ).toBe(true);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'about:blank', isTopFrame: false },+ expected,+ ),+ ).toBe(true);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'about:srcdoc', isTopFrame: false },+ expected,+ ),+ ).toBe(true);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'about:config', isTopFrame: false },+ expected,+ ),+ ).toBe(false);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'blob:https://challenges.cloudflare.com/opaque-id', isTopFrame: false },+ expected,+ ),+ ).toBe(false);+ expect(+ isAllowedLoginCaptchaNavigation(+ { url: 'https://evil.example.com/widget', isTopFrame: false },+ expected,+ ),+ ).toBe(false);+ });++ it('托管顶层页只接受预期地址,并允许 loopback HTTP 本地开发', () => {+ expect(isAllowedLoginCaptchaPageUrl(expected, expected)).toBe(true);+ expect(+ isAllowedLoginCaptchaPageUrl('https://auth.example.com/captcha/other', expected),+ ).toBe(false);+ expect(+ isAllowedLoginCaptchaPageUrl(+ 'http://localhost:3344/captcha/turnstile',+ 'http://localhost:3344/captcha/turnstile?action=email_request_code',+ ),+ ).toBe(true);+ expect(+ isAllowedLoginCaptchaPageUrl(+ 'http://auth.example.com/captcha/turnstile',+ 'http://auth.example.com/captcha/turnstile',+ ),+ ).toBe(false);+ });+});++describe('AuthContext captcha 闸接线(静态源码断言)', () => {+ const authContextSource = readFileSync(+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),+ 'utf8',+ );+ const loginSource = readFileSync(resolve(process.cwd(), 'app/(auth)/login.tsx'), 'utf8');+ const captchaWebViewSource = readFileSync(+ resolve(process.cwd(), 'src/auth/LoginCaptchaWebView.tsx'),+ 'utf8',+ );++ it('discover 的 sole email_code 自动串发路径先过 ensureCaptchaGate', () => {+ const soleBranch = authContextSource.slice(+ authContextSource.indexOf("sole?.type === 'email_code'"),+ authContextSource.indexOf("updateLoginState(\n reduceAuthFlow(currentState, {\n type: 'code-requested'"),+ );+ expect(soleBranch).toContain("ensureCaptchaGate('email')");+ expect(soleBranch).toContain('requestCodeWithCaptchaFallback');+ });++ it('request-code 的 email/phone 都按 requiredFor 动作过闸,取消不派发', () => {+ const branch = authContextSource.slice(+ authContextSource.indexOf("if (action.type === 'request-code')"),+ authContextSource.indexOf("if (action.type === 'verify-code')"),+ );+ expect(branch).toContain('ensureCaptchaGate(action.kind)');+ expect(branch).toContain('if (!gate.proceed) return false;');+ expect(branch).toContain('requestCodeWithCaptchaFallback');+ expect(authContextSource).toContain('captchaRequiredActionForVerificationKind(kind)');+ expect(authContextSource).toContain('?action=${encodeURIComponent(action)}&lang=');+ });++ it('挑战页地址由构建区域 authApiBaseUrl + 共享路径常量拼出', () => {+ expect(authContextSource).toContain('CAPTCHA_CHALLENGE_PAGE_PATH');+ expect(authContextSource).toContain(+ "getMobileEndpointForRealm(BUILD_AUTH_REGION, 'authApiBaseUrl')",+ );+ });++ it('显示 captcha WebView 前先收起软键盘', () => {+ const challengeBranch = authContextSource.slice(+ authContextSource.indexOf('const runCaptchaChallenge'),+ authContextSource.indexOf('const ensureCaptchaGate'),+ );+ expect(authContextSource).toMatch(+ /import \{[^}]*\bKeyboard\b[^}]*\} from 'react-native';/,+ );+ expect(challengeBranch.indexOf('Keyboard.dismiss();')).toBeGreaterThan(-1);+ expect(challengeBranch.indexOf('Keyboard.dismiss();')).toBeLessThan(+ challengeBranch.indexOf('setCaptchaChallenge({ url });'),+ );+ });++ it('login.tsx 渲染 captcha WebView 模态并接回 resolveCaptchaChallenge', () => {+ expect(loginSource).toContain('auth.captchaChallenge');+ expect(loginSource).toContain('LoginCaptchaWebView');+ expect(loginSource).toContain('auth.resolveCaptchaChallenge');+ });++ it('captcha WebView 限制导航但不把客户端消息来源当作认证边界', () => {+ expect(captchaWebViewSource).toContain("originWhitelist={['*']}");+ expect(captchaWebViewSource).toContain('setSupportMultipleWindows={false}');+ expect(captchaWebViewSource).toContain('isAllowedLoginCaptchaNavigation(request, themedUrl)');+ expect(captchaWebViewSource).not.toContain('event.nativeEvent.url');+ expect(captchaWebViewSource).not.toMatch(/^\s*incognito(?:\s|=)/m);+ expect(captchaWebViewSource).toContain(+ 'parseCaptchaWebViewMessage(event.nativeEvent.data)',+ );+ expect(captchaWebViewSource).not.toContain('`${pageOrigin}/*`');+ });++ it('captcha WebView 使用 ThemeOverrideProvider 内的有效登录主题', () => {+ expect(captchaWebViewSource).toContain('const { colors, mode } = useTheme()');+ expect(captchaWebViewSource).toContain('withLoginCaptchaTheme(url, mode)');+ expect(captchaWebViewSource).toContain('source={{ uri: themedUrl }}');+ });++ it('captcha WebView 的 iOS/Android 渲染进程异常都进入失败重试态', () => {+ expect(captchaWebViewSource).toContain('onContentProcessDidTerminate={() => setFailed(true)}');+ expect(captchaWebViewSource).toContain('onRenderProcessGone={() => setFailed(true)}');+ });++ it('captcha WebView 超时后进入重试态,并在完成、重试或卸载时清理计时器', () => {+ expect(captchaWebViewSource).toContain('const CHALLENGE_TIMEOUT_MS = 120_000;');+ expect(captchaWebViewSource).toContain('const timeoutTimer = setTimeout(() => {');+ expect(captchaWebViewSource).toContain('return () => clearTimeout(timeoutTimer);');+ expect(captchaWebViewSource).toContain('}, [failed, generation, themedUrl]);');+ });++ it('captcha 重试与取消动作都提供至少 44×44 的触控目标', () => {+ for (const testId of ['login.captcha.retry', 'login.captcha.cancel']) {+ const marker = `testID="${testId}"`;+ const markerIndex = captchaWebViewSource.indexOf(marker);+ const actionStart = captchaWebViewSource.lastIndexOf('<Pressable', markerIndex);+ const actionSource = captchaWebViewSource.slice(actionStart, markerIndex);+ expect(markerIndex).toBeGreaterThan(-1);+ expect(actionStart).toBeGreaterThan(-1);+ expect(actionSource).toContain('minHeight: 44');+ expect(actionSource).toContain('minWidth: 44');+ }+ });++ it('captcha 卡片和挑战内容在窄屏内按安全边距收缩', () => {+ expect(captchaWebViewSource).toContain('paddingHorizontal: spacing.lg');+ expect(captchaWebViewSource).toContain('maxWidth: 340');+ expect(captchaWebViewSource).toContain("width: '100%'");+ expect(captchaWebViewSource.match(/alignSelf: 'stretch'/g)).toHaveLength(2);+ expect(captchaWebViewSource).not.toContain('width: 340');+ expect(captchaWebViewSource).not.toContain('width: 308');+ });++ it('captcha 打开时从 Android TalkBack 隐藏背景登录组与注销气泡', () => {+ expect(loginSource).toContain('const captchaChallengeOpen = auth.captchaChallenge !== null');+ expect(loginSource).toContain(+ 'consentDialogOpen || realmConsentOpen || captchaChallengeOpen || handoffPhase',+ );+ expect(loginSource).toContain(+ 'consentDialogOpen || realmConsentOpen || captchaChallengeOpen',+ );+ });+});diff --git a/apps/mobile/src/auth/__tests__/loginSkinErrorCopy.test.ts b/apps/mobile/src/auth/__tests__/loginSkinErrorCopy.test.tsindex f1baae266d..b6a2f5f880 100644--- a/apps/mobile/src/auth/__tests__/loginSkinErrorCopy.test.ts+++ b/apps/mobile/src/auth/__tests__/loginSkinErrorCopy.test.ts@@ -66,6 +66,27 @@ describe("loginSkin 错误文案 5 语(catalog verbatim 路由)", () => {);});+ it("CAPTCHA_REQUIRED:5 语 catalog verbatim 路由", () => {+ expectCodeRoutedVerbatim("CAPTCHA_REQUIRED");+ expect(authErrorMessages.CAPTCHA_REQUIRED["zh-CN"]).toBe(+ "请先完成安全验证。",+ );+ });++ it("CAPTCHA_INVALID:5 语 catalog verbatim 路由", () => {+ expectCodeRoutedVerbatim("CAPTCHA_INVALID");+ expect(authErrorMessages.CAPTCHA_INVALID["zh-CN"]).toBe(+ "安全验证未通过,请重试。",+ );+ });++ it("CAPTCHA_UNAVAILABLE:5 语 catalog verbatim 路由", () => {+ expectCodeRoutedVerbatim("CAPTCHA_UNAVAILABLE");+ expect(authErrorMessages.CAPTCHA_UNAVAILABLE["zh-CN"]).toBe(+ "安全验证服务暂不可用,请稍后再试。",+ );+ });+it("INVALID_AUTH_CODE:5 语 catalog verbatim 路由", () => {expectCodeRoutedVerbatim("INVALID_AUTH_CODE");expect(authErrorMessages.INVALID_AUTH_CODE["zh-CN"]).toBe(diff --git a/apps/mobile/src/auth/loginCaptchaMessage.ts b/apps/mobile/src/auth/loginCaptchaMessage.tsnew file mode 100644index 0000000000..4b257dfa6c--- /dev/null+++ b/apps/mobile/src/auth/loginCaptchaMessage.ts@@ -0,0 +1,32 @@+/** Turnstile token 官方上限(与桌面 IPC 界校验、服务端 schema 同值)。 */+const MAX_CAPTCHA_TOKEN_LENGTH = 2048;++/**+ * 挑战页 postMessage 回传 payload 解析(wire 契约,与 auth-server 托管页内联+ * 脚本对齐;桌面宿主走 location.hash 通道,见 desktop LoginCaptchaOverlay)。+ * 纯函数、零 RN 依赖:node vitest 直接单测(LoginCaptchaWebView 组件本体因+ * react-native 依赖链不宜在 node 环境加载)。+ */+export function parseCaptchaWebViewMessage(+ raw: string,+): { ok: true; token: string } | { ok: false; code: string } | null {+ let data: { type?: unknown; ok?: unknown; token?: unknown; code?: unknown };+ try {+ data = JSON.parse(raw) as typeof data;+ } catch {+ return null;+ }+ if (data.type !== 'cindy-captcha') return null;+ if (+ data.ok === true &&+ typeof data.token === 'string' &&+ data.token.length > 0 &&+ data.token.length <= MAX_CAPTCHA_TOKEN_LENGTH+ ) {+ return { ok: true, token: data.token };+ }+ if (data.ok === false) {+ return { ok: false, code: typeof data.code === 'string' ? data.code : 'unknown' };+ }+ return null;+}diff --git a/apps/mobile/src/auth/loginCaptchaUrl.ts b/apps/mobile/src/auth/loginCaptchaUrl.tsnew file mode 100644index 0000000000..fc86378623--- /dev/null+++ b/apps/mobile/src/auth/loginCaptchaUrl.ts@@ -0,0 +1,67 @@+import { CAPTCHA_CHALLENGE_PAGE_PATH } from '@cindy/auth-client';++const TURNSTILE_ORIGIN = 'https://challenges.cloudflare.com';+const TURNSTILE_LOCAL_DOCUMENT_URLS = new Set(['about:blank', 'about:srcdoc']);++function isHttpsOrLoopbackHttp(url: URL): boolean {+ const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1';+ return url.protocol === 'https:' || (url.protocol === 'http:' && loopback);+}++/**+ * 托管挑战页的顶层文档边界:协议必须为 HTTPS(本地开发仅放行 loopback HTTP),+ * origin 与共享挑战路径都必须和预期地址一致。显式检查 protocol,避免 blob URL+ * 继承 auth origin 后绕过只比较 origin 的判定。+ */+export function isAllowedLoginCaptchaPageUrl(rawUrl: string, expectedUrl: string): boolean {+ let target: URL;+ let expected: URL;+ try {+ target = new URL(rawUrl);+ expected = new URL(expectedUrl);+ } catch {+ return false;+ }+ if (!isHttpsOrLoopbackHttp(target) || !isHttpsOrLoopbackHttp(expected)) return false;+ return (+ target.protocol === expected.protocol &&+ target.origin === expected.origin &&+ target.pathname === CAPTCHA_CHALLENGE_PAGE_PATH &&+ expected.pathname === CAPTCHA_CHALLENGE_PAGE_PATH+ );+}++/**+ * Mobile WebView 导航闸:auth 托管页只能是顶层;Turnstile 子 frame 放行其+ * HTTPS origin,以及 Cloudflare WebView 集成明确依赖的 about:blank/srcdoc。+ */+export function isAllowedLoginCaptchaNavigation(+ request: { url: string; isTopFrame: boolean },+ expectedUrl: string,+): boolean {+ if (request.isTopFrame) return isAllowedLoginCaptchaPageUrl(request.url, expectedUrl);+ if (TURNSTILE_LOCAL_DOCUMENT_URLS.has(request.url)) return true;+ try {+ const target = new URL(request.url);+ return target.protocol === 'https:' && target.origin === TURNSTILE_ORIGIN;+ } catch {+ return false;+ }+}++/**+ * 将登录子树最终生效的 light/dark 模式写入托管挑战页 URL。+ *+ * URL 在 AuthContext 中创建,但首次启动的亮色覆盖只存在于+ * MobileLoginHandoffStage 子树内,因此必须由该子树里的 WebView 补入主题。+ */+export function withLoginCaptchaTheme(url: string, theme: 'light' | 'dark'): string {+ try {+ const themedUrl = new URL(url);+ themedUrl.searchParams.set('theme', theme);+ return themedUrl.toString();+ } catch {+ // 保留既有加载失败路径,由 WebView 的 onError 收敛到卡片内重试态。+ return url;+ }+}diff --git a/apps/mobile/src/auth/loginMessages.ts b/apps/mobile/src/auth/loginMessages.tsindex 35c2d52937..988c15aa77 100644--- a/apps/mobile/src/auth/loginMessages.ts+++ b/apps/mobile/src/auth/loginMessages.ts@@ -58,6 +58,10 @@ const messages = {codePlaceholder: "6 位驗證碼",signIn: "登入",resendCode: "重新發送驗證碼",+ captchaTitle: "安全驗證",+ captchaFailed: "安全驗證載入失敗",+ captchaRetry: "重試",+ captchaCancel: "取消",resendCountdown: "{n} 秒後可重新發送",chooseAccount: "選擇身分",chooseAccountSubtitle: "選擇本次要進入的個人或組織身分。",@@ -168,6 +172,10 @@ const messages = {codePlaceholder: "6 位验证码",signIn: "登录",resendCode: "重新发送验证码",+ captchaTitle: "安全验证",+ captchaFailed: "安全验证加载失败",+ captchaRetry: "重试",+ captchaCancel: "取消",resendCountdown: "{n} 秒后可重新发送",chooseAccount: "选择身份",chooseAccountSubtitle: "选择本次要进入的个人或组织身份。",@@ -280,6 +288,10 @@ const messages = {codePlaceholder: "6-digit code",signIn: "Sign in",resendCode: "Resend code",+ captchaTitle: "Security check",+ captchaFailed: "Failed to load the security check.",+ captchaRetry: "Retry",+ captchaCancel: "Cancel",resendCountdown: "Resend available in {n}s",chooseAccount: "Choose an account",chooseAccountSubtitle:@@ -404,6 +416,10 @@ const messages = {codePlaceholder: "6桁の認証コード",signIn: "ログイン",resendCode: "認証コードを再送信",+ captchaTitle: "セキュリティチェック",+ captchaFailed: "セキュリティチェックを読み込めませんでした。",+ captchaRetry: "再試行",+ captchaCancel: "キャンセル",resendCountdown: "{n} 秒後に再送信できます",chooseAccount: "アカウントを選択",chooseAccountSubtitle:@@ -526,6 +542,10 @@ const messages = {codePlaceholder: "6자리 인증 코드",signIn: "로그인",resendCode: "인증 코드 재전송",+ captchaTitle: "보안 확인",+ captchaFailed: "보안 확인을 불러오지 못했습니다.",+ captchaRetry: "다시 시도",+ captchaCancel: "취소",resendCountdown: "{n}초 후 재전송 가능",chooseAccount: "계정 선택",chooseAccountSubtitle: "사용할 개인 또는 조직 계정을 선택하세요.",@@ -670,6 +690,27 @@ export const authErrorMessages: Record<string, Record<LoginLocale, string>> = {ja: "入力内容の形式が正しくありません。",ko: "입력한 내용의 형식이 올바르지 않습니다.",},+ CAPTCHA_REQUIRED: {+ "zh-CN": "请先完成安全验证。",+ "zh-TW": "請先完成安全驗證。",+ en: "Please complete the security check first.",+ ja: "先にセキュリティチェックを完了してください。",+ ko: "먼저 보안 확인을 완료해 주세요.",+ },+ CAPTCHA_INVALID: {+ "zh-CN": "安全验证未通过,请重试。",+ "zh-TW": "安全驗證未通過,請重試。",+ en: "Security check failed. Please try again.",+ ja: "セキュリティチェックに失敗しました。もう一度お試しください。",+ ko: "보안 확인에 실패했습니다. 다시 시도해 주세요.",+ },+ CAPTCHA_UNAVAILABLE: {+ "zh-CN": "安全验证服务暂不可用,请稍后再试。",+ "zh-TW": "安全驗證服務暫時無法使用,請稍後再試。",+ en: "The security check is temporarily unavailable. Please try again later.",+ ja: "セキュリティチェックは一時的に利用できません。しばらくしてから再試行してください。",+ ko: "보안 확인 서비스를 일시적으로 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.",+ },INVALID_AUTH_CODE: {"zh-CN": "登录授权已过期,请重新发起。","zh-TW": "登入授權已過期,請重新發起。",diff --git a/docs/dev-rules/electron-security-and-process-boundaries.md b/docs/dev-rules/electron-security-and-process-boundaries.mdindex d8e2f13b4c..b6e7147b54 100644--- a/docs/dev-rules/electron-security-and-process-boundaries.md+++ b/docs/dev-rules/electron-security-and-process-boundaries.md@@ -128,6 +128,19 @@ webview)——所有例外都必须继续由 `webview-security.ts` 在 `will-a不得自行添加 `allowpopups`。Ghost 面板更严格:专属 partition、无 Node、无通用 preload,身份由 Main 根据真实 `webContents` 反查。+登录人机验证(captcha)webview 是 hardener 中与 ghost 同级的第三类受控分支+(`LOGIN_CAPTCHA_PARTITION`,非 persist 内存分区):`will-attach-webview` 阶段按+`isAllowedLoginCaptchaUrl` 验明正身——协议(https,或 loopback http 兼容本地 dev+auth-server)+ origin 命中 `setLoginCaptchaOriginResolver` 注入的 auth 端点集合 ++路径精确等于托管挑战页(`@cindy/auth-client` 的 `CAPTCHA_CHALLENGE_PAGE_PATH`),+验不过直接拒附加,绝不回落浏览器分区;attach 后零 preload、零弹窗,顶层导航仅放行+同一白名单。挑战结果(Turnstile token)经托管页 `location.hash` 写入、宿主 renderer+监听 `did-navigate-in-page` 读取——fragment 变更不产生网络请求,token 不进任何日志,+也不需要新增 preload / IPC 注入面。主窗 CSP 保持不动:挑战页是独立 origin 的 guest+文档,`installContentSecurityPolicy` 只注入 app 自有文档,`frame-src 'none'` 也不约束+`<webview>`。回归用例钉在 `main/__tests__/webview-security.test.ts` 的 captcha 分区+测试组。+## 4.preload 与 Context Bridge- 只通过 `contextBridge.exposeInMainWorld` 暴露按用途命名的最小方法。diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex aa98ebbe20..65213de02d 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -175,6 +175,10 @@ Anthropic Messages API / wire protocol 的用户可见名称。四语统一保Cindy 在 X 上发出的那条公开回复。zh-CN 取「回帖」以强调它是**一条公开帖子**而不是私聊消息——这正是 X 与 Slack / Telegram 的性质差异, 也是风险告知的核心。与「消息」区分开: 后者按 task-and-conversation-naming 只用于任务内的单条往来。proposed 同上。+### Security check++登录邮箱发码前的 CAPTCHA(Cloudflare Turnstile)挑战。中文用「安全验证」(腾讯/阿里系产品的通行叫法,2026-08-19 用户反馈弃用「人机验证」;与「验证码」= verification code 消歧——后者已被 login.codePlaceholder 占用指 6 位数字码);en 用 Security check 而非品牌词 Turnstile 或缩写 CAPTCHA。消费处:login.captcha.* 与 login.errors.CAPTCHA_*(desktop 五语 + mobile 影子 catalog)。+### China模型目录中由服务端显式 group:"china" 标记的来源分组。它描述模型或供应商来自中国,不表示相对于当前用户或发行区域的‘国内’;英文词条保持自然大小写 China,设置页分组头由统一 uppercase 样式显示为 CHINA。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 77fe3ce98a..eb47b9d178 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -68,6 +68,18 @@},"note": "远端主机上由 Cindy 管理的 Codex 凭证目录(~/.xdt-server/v1/codex-home/),与用户本机 ~/.codex 相区分。四语统一保留英文原词(home 小写),避免各语言自造「Codex 主目录」等不同说法;syncAuth 与 codexAuthMissing 等远端登录态文案使用。"},+ {+ "id": "captcha",+ "status": "proposed",+ "en": "Security check",+ "translations": {+ "zh-CN": "安全验证",+ "zh-TW": "安全驗證",+ "ja": "セキュリティチェック",+ "ko": "보안 확인"+ },+ "note": "登录邮箱发码前的 CAPTCHA(Cloudflare Turnstile)挑战。中文用「安全验证」(腾讯/阿里系产品的通行叫法,2026-08-19 用户反馈弃用「人机验证」;与「验证码」= verification code 消歧——后者已被 login.codePlaceholder 占用指 6 位数字码);en 用 Security check 而非品牌词 Turnstile 或缩写 CAPTCHA。消费处:login.captcha.* 与 login.errors.CAPTCHA_*(desktop 五语 + mobile 影子 catalog)。"+ },{"id": "passkey","status": "proposed",diff --git a/packages/auth-client/fixtures/loginScenarios.ts b/packages/auth-client/fixtures/loginScenarios.tsindex 4efd4e2932..0edddef077 100644--- a/packages/auth-client/fixtures/loginScenarios.ts+++ b/packages/auth-client/fixtures/loginScenarios.ts@@ -34,6 +34,7 @@ export const LOGIN_SCENARIO_TOKENS = Object.freeze(["providers:both","providers:cn-social","providers:global-social",+ "providers:email-captcha","sso:single","sso:multi","sso:required",@@ -71,6 +72,9 @@ export const LOGIN_SCENARIO_ERROR_CODES = Object.freeze(["INVALID_CODE","CODE_ATTEMPTS_EXCEEDED","RATE_LIMITED",+ "CAPTCHA_REQUIRED",+ "CAPTCHA_INVALID",+ "CAPTCHA_UNAVAILABLE","SSO_LOGIN_REQUIRED","ORG_SSO_NOT_FOUND","SOCIAL_TOKEN_INVALID",@@ -217,6 +221,20 @@ function providersFor(return { region, attribution: "phone", email: false, phone: true, social: [] };case "email-only":return { region, attribution: "email", email: true, phone: false, social: [] };+ case "email-captcha":+ // global 邮箱发码前必须过人机验证(captcha 字段驱动客户端 overlay 触发路径)+ return {+ region,+ attribution: "email",+ email: true,+ phone: false,+ social: [],+ captcha: {+ provider: "turnstile",+ siteKey: fakeValue("captcha-sitekey"),+ requiredFor: ["email_request_code"],+ },+ };case "both":return { ...defaults, social: [] };case "cn-social":diff --git a/packages/auth-client/src/__tests__/client.test.ts b/packages/auth-client/src/__tests__/client.test.tsindex 0a5a5c08e7..2171426ba4 100644--- a/packages/auth-client/src/__tests__/client.test.ts+++ b/packages/auth-client/src/__tests__/client.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";import {AuthApiError,+ captchaRequiredActionForVerificationKind,CindyAuthClient,discoverSsoOrgRealm,parseAccountDeletionReceiptRecord,@@ -66,6 +67,90 @@ describe("CindyAuthClient", () => {});});+ it("parses the optional captcha config from providers", async () => {+ const fetch = vi.fn(async () =>+ response(200, {+ region: "cn",+ attribution: "phone",+ email: true,+ phone: true,+ social: [],+ captcha: {+ provider: "turnstile",+ siteKey: "scenario-captcha-sitekey",+ requiredFor: ["email_request_code"],+ },+ }),+ );+ await expect(client(fetch).getProviders()).resolves.toMatchObject({+ captcha: { provider: "turnstile", requiredFor: ["email_request_code"] },+ });+ // 客户端预认短信发码动作;服务端以后仅需下发该值即可启用,无需客户端发版。+ // 其他 append-only 未知动作仍忽略,不让整份 providers 解析失败。+ const extendedFetch = vi.fn(async () =>+ response(200, {+ region: "cn",+ attribution: "phone",+ email: true,+ phone: true,+ social: [],+ captcha: {+ provider: "turnstile",+ siteKey: "scenario-captcha-sitekey",+ requiredFor: [+ "email_request_code",+ "phone_request_code",+ "future_request_code",+ ],+ },+ }),+ );+ const extended = await client(extendedFetch).getProviders();+ expect(extended.captcha?.requiredFor).toEqual([+ "email_request_code",+ "phone_request_code",+ ]);+ expect(captchaRequiredActionForVerificationKind("email")).toBe(+ "email_request_code",+ );+ expect(captchaRequiredActionForVerificationKind("phone")).toBe(+ "phone_request_code",+ );+ // 旧 server 缺字段 → undefined(可选字段,不整份拒绝)+ const legacyFetch = vi.fn(async () =>+ response(200, {+ region: "cn",+ attribution: "phone",+ email: true,+ phone: true,+ social: [],+ }),+ );+ const legacy = await client(legacyFetch).getProviders();+ expect(legacy.captcha).toBeUndefined();+ });++ it("carries captchaToken in the email request-code body only when provided", async () => {+ const fetch = vi.fn(async () => response(200, { status: "sent" }));+ await client(fetch).requestCode("email", "[email protected]");+ const bare = JSON.parse((fetch.mock.calls[0]?.[1] as { body: string }).body) as Record<+ string,+ unknown+ >;+ expect(bare).toEqual({ email: "[email protected]", locale: "zh-CN" });+ await client(fetch).requestCode("email", "[email protected]", {+ captchaToken: "captcha-token-1",+ });+ const withToken = JSON.parse(+ (fetch.mock.calls[1]?.[1] as { body: string }).body,+ ) as Record<string, unknown>;+ expect(withToken).toEqual({+ email: "[email protected]",+ locale: "zh-CN",+ captchaToken: "captcha-token-1",+ });+ });+it("parses all auth-server outcome states", async () => {const outcomes = [{ status: "binding_required", bindType: "phone", bindTicket: "bind-1" },diff --git a/packages/auth-client/src/client.ts b/packages/auth-client/src/client.tsindex 7307bac35a..d5cff74ebf 100644--- a/packages/auth-client/src/client.ts+++ b/packages/auth-client/src/client.ts@@ -148,11 +148,17 @@ export class CindyAuthClient {return discovery;}- async requestCode(kind: VerificationKind, identifier: string): Promise<void> {- const body =- kind === "email"- ? { email: identifier, locale: this.options.locale }- : { phone: identifier, locale: this.options.locale };+ async requestCode(+ kind: VerificationKind,+ identifier: string,+ options: { captchaToken?: string } = {},+ ): Promise<void> {+ const body = {+ ...(kind === "email" ? { email: identifier } : { phone: identifier }),+ locale: this.options.locale,+ // 仅有值时携带:旧 auth-server 的 zod 会忽略未知字段,但保持最小请求面。+ ...(options.captchaToken ? { captchaToken: options.captchaToken } : {}),+ };await this.request(`/api/auth/${kind}/request-code`,z.object({ status: z.literal("sent") }),diff --git a/packages/auth-client/src/index.ts b/packages/auth-client/src/index.tsindex 84e29e37db..9fec35cef9 100644--- a/packages/auth-client/src/index.ts+++ b/packages/auth-client/src/index.ts@@ -29,6 +29,10 @@ export {accountDeletionStatusSchema,accountMembershipSchema,authRegionSchema,+ CAPTCHA_CHALLENGE_PAGE_PATH,+ captchaConfigSchema,+ captchaRequiredActionForVerificationKind,+ captchaRequiredActionSchema,desktopAuthorizationPollSchema,loginMethodSchema,loginOutcomeSchema,@@ -52,6 +56,8 @@ export type {AuthClientType,AuthFlowAction,AuthFlowState,+ CaptchaConfig,+ CaptchaRequiredAction,AuthMe,AuthMembership,AuthRegion,diff --git a/packages/auth-client/src/types.ts b/packages/auth-client/src/types.tsindex 900e725ef4..4bb5d397f1 100644--- a/packages/auth-client/src/types.ts+++ b/packages/auth-client/src/types.ts@@ -24,12 +24,52 @@ export const membershipSchema = z.object({});export type AuthMembership = z.infer<typeof membershipSchema>;+/**+ * 人机验证(CAPTCHA)配置:auth-server 开启时经 GET /api/auth/providers 下发。+ * requiredFor 声明哪些动作发起前必须先完成挑战。+ * 客户端预认邮箱与短信发码;服务端当前可只下发邮箱动作,后续下发短信动作+ * 即可启用既有客户端闸门,无需变更 wire 结构。+ * 关闭时服务端整字段省略 → undefined = 不需要人机验证。+ */+export const captchaRequiredActionSchema = z.enum([+ "email_request_code",+ "phone_request_code",+]);+export type CaptchaRequiredAction = z.infer<typeof captchaRequiredActionSchema>;++export const captchaConfigSchema = z.object({+ provider: z.literal("turnstile"),+ siteKey: z.string().min(1),+ // 服务端可 append-only 扩展动作;当前客户端预认邮箱与短信发码,其他未知+ // 动作忽略,避免一个未来动作让整份 providers 响应解析失败。+ requiredFor: z+ .array(z.string())+ .transform((actions) =>+ actions.filter(+ (action): action is CaptchaRequiredAction =>+ captchaRequiredActionSchema.safeParse(action).success,+ ),+ ),+});+export type CaptchaConfig = z.infer<typeof captchaConfigSchema>;++/**+ * auth-server 托管 Turnstile 挑战页的固定路径(wire 契约)。+ * 完整地址 = authApiBaseUrl + 本路径 ++ * `?action=<email_request_code|phone_request_code>&theme=<light|dark>&lang=<BCP-47>`;+ * 页面把结果写进 location.hash(`cindy-captcha=ok.<token>` / `err.<code>`)+ * 或经 ReactNativeWebView.postMessage 回传(双宿主同页兼容)。+ */+export const CAPTCHA_CHALLENGE_PAGE_PATH = "/captcha/turnstile";+export const providerConfigSchema = z.object({region: authRegionSchema,attribution: z.enum(["phone", "email"]),email: z.boolean(),phone: z.boolean(),social: z.array(socialProviderSchema),+ // optional 兼容尚未升级的旧 auth-server 响应(缺字段不整份拒绝)。+ captcha: captchaConfigSchema.optional(),});export type ProviderConfig = z.infer<typeof providerConfigSchema>;@@ -237,6 +277,13 @@ export type AuthClientType = "desktop" | "mobile" | "web";export type VerificationKind = "email" | "phone";export type SsoVerificationChannel = "email" | "sms";+/** 发码类型到 providers.captcha.requiredFor wire action 的唯一映射。 */+export function captchaRequiredActionForVerificationKind(+ kind: VerificationKind,+): CaptchaRequiredAction {+ return kind === "email" ? "email_request_code" : "phone_request_code";+}+export type AuthFlowState =| { step: "identifier"; providers: ProviderConfig }| {