Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(auth): discover enterprise regions from email logins
xd-bobob369f53df7dd
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex a445b5c425..4fa12ced2f 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -42,6 +42,34 @@ describe('auth login-flow reset', () => {expect(clearBody).toContain('canaryFlagStore.clear();');});+ it('keeps successful personal credentials private until the region choice and excludes saved-account activation', () => {+ const start = source.indexOf('async function finishFreshLogin(');+ const finish = source.slice(start, source.indexOf('async function runLoginAction(', start));+ expect(finish).toContain('discoverPersonalLoginOrganization(outcome.membership');+ expect(finish.indexOf('assertLoginFlowCurrent(expectedLoginFlowEpoch)')).toBeGreaterThan(finish.indexOf('await discoverPersonalLoginOrganization'));+ expect(finish).toContain('pendingPersonalLogin = { outcome, realm: personalRealm }');+ expect(finish).toContain('personalLoginAvailable: true');+ expect(finish).not.toContain('pendingAuthRealm = discovery.region');+ expect(finish).toContain('return completeLogin(outcome, expectedLoginFlowEpoch)');+ const lookupStart = source.indexOf('async function lookupOrganizationRealm(');+ const lookup = source.slice(lookupStart, source.indexOf('async function completeLogin(', lookupStart));+ expect(lookup).not.toContain('pendingAuthRealm =');+ const continueStart = source.indexOf("if (action.type === 'cancel-sso-realm')");+ const continueBody = source.slice(continueStart, source.indexOf('if (!providerConfig)', continueStart));+ expect(continueBody).toContain('pendingAuthRealm = personal.realm');+ expect(continueBody).toContain('await completeLogin(personal.outcome, actionLoginFlowEpoch)');+ expect(continueBody).not.toContain('finishFreshLogin(');+ const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm')");+ const confirmBody = source.slice(confirmStart, continueStart);+ expect(confirmBody.indexOf('pendingPersonalLogin = null')).toBeLessThan(confirmBody.indexOf('pendingAuthRealm = confirmation.targetRegion'));+ expect(confirmBody).toContain('pendingAccountRefreshToken = null');+ expect(source.slice(0, source.indexOf('async function acceptLoginOutcome('))).not.toContain('await finishFreshLogin(');+ expect(source).toContain("await finishFreshLogin({ status: 'ok', ...pair }, actionLoginFlowEpoch)");+ const reset = source.slice(source.indexOf('function resetLoginFlowState()'), source.indexOf('function clearAuth('));+ expect(reset).toContain('pendingPersonalLogin = null');+ expect(reset).toContain('handledLoginEmail = null');+ });+it('keeps the login-epoch guard and does not resurrect the legacy feishu token chain', () => {const completeStart = source.indexOf('async function completeLogin(');const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);@@ -109,10 +137,27 @@ describe('auth login-flow reset', () => {source.indexOf("if (action.type === 'discover')", actionStart),);expect(personalActionSetup).toContain(- 'if (startsBuildRealmFlow) pendingAuthRealm = loginRealm;',+ "if (startsBuildRealmFlow && action.type !== 'request-code') pendingAuthRealm = loginRealm;",);});+ it('keeps cross-region email choices gated and preserves SSO after failed personal code sending', () => {+ const discover = source.slice(+ source.indexOf("if (action.type === 'discover') {"),+ source.indexOf("if (action.type === 'discover-sso-org') {"),+ );+ expect(discover).toContain('discoverEmailLogin(action.email');+ expect(discover.indexOf('discoveredMethods = [];')).toBeLessThan(discover.indexOf('await discoverEmailLogin'));+ expect(discover).toContain('discoverOrganizationRealm(domain, actionLoginFlowEpoch)');+ expect(discover).toContain('pendingAuthRealm = region;');+ expect(discover.indexOf("type: 'realm-switch-required'")).toBeLessThan(discover.indexOf('discoveredMethods = methods;'));+ expect(source).toContain("email: confirmation.email ?? ''");+ const requestStart = source.indexOf("if (action.type === 'request-code') {");+ const request = source.slice(requestStart, source.indexOf("if (action.type === 'verify-code') {", requestStart));+ expect(request.indexOf('pendingAuthRealm = AUTH_REGION;')).toBeGreaterThan(request.indexOf('await client.requestCode('));+ expect(request).toContain('discoveredMethods = [];');+ });+it('does not leave expired private tickets on a screen that can only reuse them', () => {expect(source).toContain("'INVALID_LOGIN_TICKET',");expect(source).toContain("'INVALID_BIND_TICKET',");diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex b2f3957117..c117de257e 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -23,6 +23,8 @@ import { machineIdSync } from 'node-machine-id';import {AuthApiError,CindyAuthClient,+ discoverEmailLogin,+ discoverPersonalLoginOrganization,discoverSsoOrgRealm,parseAccountDeletionReceiptRecord,parseAuthSessionRecord,@@ -401,6 +403,12 @@ const deviceId = process.env.XDT_DEVICE_ID_OVERRIDE?.trim() || machineIdSync();let loginFlowState: AuthFlowState | null = null;let providerConfig: ProviderConfig | null = null;let discoveredMethods: LoginMethod[] = [];+// These live only within the current fresh-login flow; no credentials reach Renderer.+let handledLoginEmail: string | null = null;+let pendingPersonalLogin: {+ outcome: Extract<LoginOutcome, { status: 'ok' }>;+ realm: AuthRegion;+} | null = null;// Account token 仅在一次登录的 Membership 选择阶段存活;兑换 resource token// 后立即清空,不持久化、不续期,也不参与业务请求或正常登出。let pendingAccountToken: string | null = null;@@ -3471,6 +3479,8 @@ function clearPerAccountIntegrationsInBackground(): void {/** Clear renderer-safe login progress and all main-only login tickets. */function resetLoginFlowState(): void {+ handledLoginEmail = null;+ pendingPersonalLogin = null;loginFlowState = null;providerConfig = null;discoveredMethods = [];@@ -4851,6 +4861,8 @@ async function runColdStartRefreshFlow(}async function loadLoginProviders(expectedLoginFlowEpoch = loginFlowEpoch): Promise<AuthFlowState> {+ handledLoginEmail = null;+ pendingPersonalLogin = null;discoveredMethods = [];pendingAccountToken = null;pendingAccountRefreshToken = null;@@ -4878,11 +4890,18 @@ async function loadLoginProviders(expectedLoginFlowEpoch = loginFlowEpoch): Promasync function discoverOrganizationRealm(org: string, expectedLoginFlowEpoch = loginFlowEpoch) {// 新的一次组织发现不得复用上一轮成功结果;只有本轮双区判定成功后才重新冻结。pendingAuthRealm = null;+ const discovery = await lookupOrganizationRealm(org, expectedLoginFlowEpoch);+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ pendingAuthRealm = discovery.region;+ return discovery;+}++/** Read-only realm lookup also serves optional hints after successful personal authentication. */+async function lookupOrganizationRealm(org: string, expectedLoginFlowEpoch: number) {const realmConfig = getClientEndpointRealmConfig();if (!realmConfig.crossRealmOrgLoginEnabled || !realmConfig.realmManifestBaseUrls) {const discovery = await createAuthClient(AUTH_REGION).discoverSsoOrg(org);assertLoginFlowCurrent(expectedLoginFlowEpoch);- pendingAuthRealm = AUTH_REGION;return discovery;}@@ -4904,7 +4923,6 @@ async function discoverOrganizationRealm(org: string, expectedLoginFlowEpoch = lglobal: createAuthClient('global'),});assertLoginFlowCurrent(expectedLoginFlowEpoch);- pendingAuthRealm = selected.region;return selected.discovery;}@@ -5069,6 +5087,8 @@ async function completeLogin(pendingLoginTicket = null;pendingBindTicket = null;pendingSsoVerificationTicket = null;+ pendingPersonalLogin = null;+ handledLoginEmail = null;loginFlowState = reduceAuthFlow(loginFlowState, { type: 'outcome', outcome });notifyRenderer();notifyAuthListeners();@@ -5101,7 +5121,7 @@ async function acceptLoginOutcome(? [outcome.membership]: [];- if (outcome.status === 'ok') return completeLogin(outcome, expectedLoginFlowEpoch);+ if (outcome.status === 'ok') return finishFreshLogin(outcome, expectedLoginFlowEpoch);if (outcome.status === 'select_account') {pendingLoginTicket = outcome.loginTicket;pendingBindTicket = null;@@ -5119,6 +5139,32 @@ async function acceptLoginOutcome(return loginFlowState;}+/** Offer enterprise login before committing a fresh personal identity, never during refresh/switch. */+async function finishFreshLogin(+ outcome: Extract<LoginOutcome, { status: 'ok' }>,+ expectedLoginFlowEpoch: number,+): Promise<AuthFlowState> {+ const personalRealm = pendingAuthRealm ?? AUTH_REGION;+ const discovery = await discoverPersonalLoginOrganization(outcome.membership, {+ handledEmail: handledLoginEmail,+ discoverOrganization: (domain) => lookupOrganizationRealm(domain, expectedLoginFlowEpoch),+ });+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ if (discovery && providerConfig) {+ pendingPersonalLogin = { outcome, realm: personalRealm };+ discoveredMethods = [];+ loginFlowState = reduceAuthFlow(loginFlowState, {+ type: 'realm-switch-required',+ targetRegion: discovery.region,+ personalLoginAvailable: true,+ providers: providerConfig,+ methods: ssoOrgDiscoveryToMethods(discovery),+ });+ return loginFlowState;+ }+ return completeLogin(outcome, expectedLoginFlowEpoch);+}+async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginActionResult> {const actionLoginFlowEpoch = loginFlowEpoch;const startsBuildRealmFlow =@@ -5142,7 +5188,9 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginAconst confirmation = loginFlowState;if (confirmation?.step !== 'realm-confirmation' ||- pendingAuthRealm !== confirmation.targetRegion+ (confirmation.personalLoginAvailable+ ? !pendingPersonalLogin+ : pendingAuthRealm !== confirmation.targetRegion)) {throw new AuthApiError('INVALID_AUTH_ACTION',@@ -5150,10 +5198,22 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA'No enterprise region switch is waiting for confirmation',);}+ if (confirmation.personalLoginAvailable) {+ // The user chose a fresh enterprise authentication, not reuse of the personal token.+ pendingPersonalLogin = null;+ pendingAccountToken = null;+ pendingAccountRefreshToken = null;+ pendingAccountMemberships = [];+ pendingLoginTicket = null;+ pendingBindTicket = null;+ pendingSsoVerificationTicket = null;+ pendingAccountDeletionRestored = false;+ pendingAuthRealm = confirmation.targetRegion;+ }discoveredMethods = confirmation.methods;loginFlowState = reduceAuthFlow(loginFlowState, {type: 'discovery-loaded',- email: '',+ email: confirmation.email ?? '',methods: confirmation.methods,});return { success: true, state: loginFlowState };@@ -5167,6 +5227,14 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA'No enterprise region switch is waiting for cancellation',);}+ if (confirmation.personalLoginAvailable) {+ const personal = pendingPersonalLogin;+ if (!personal) throw new AuthApiError('INVALID_AUTH_ACTION', 400, 'Personal login unavailable');+ pendingAuthRealm = personal.realm;+ const state = await completeLogin(personal.outcome, actionLoginFlowEpoch);+ pendingPersonalLogin = null;+ return { success: true, state };+ }pendingAuthRealm = null;discoveredMethods = [];loginFlowState = reduceAuthFlow(loginFlowState, {@@ -5179,12 +5247,33 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA// loadLoginProviders clears transient login state. Pin a new personal login// afterwards so account selection and binding cannot inherit the active// organization's realm. The active account remains untouched until commit.- if (startsBuildRealmFlow) pendingAuthRealm = loginRealm;+ // Keep the confirmed SSO realm if a personal code request fails and returns to method choice.+ if (startsBuildRealmFlow && action.type !== 'request-code') pendingAuthRealm = loginRealm;+ if (action.type === 'start-browser' && action.kind === 'social') handledLoginEmail = null;if (action.type === 'discover') {- const email = action.email.trim().toLowerCase();- const methods = await client.discover(email);+ discoveredMethods = [];+ const { email, methods, region } = await discoverEmailLogin(action.email, {+ buildRegion: AUTH_REGION,+ discoverOrganization: (domain) => discoverOrganizationRealm(domain, actionLoginFlowEpoch),+ discoverPersonal: (email) => client.discover(email),+ });assertLoginFlowCurrent(actionLoginFlowEpoch);+ handledLoginEmail = email;+ pendingAuthRealm = region;+ if (region !== AUTH_REGION) {+ if (!providerConfig) {+ throw new AuthApiError('AUTH_SERVICE_UNAVAILABLE', 503, 'Login providers unavailable');+ }+ loginFlowState = reduceAuthFlow(loginFlowState, {+ type: 'realm-switch-required',+ targetRegion: region,+ email,+ providers: providerConfig,+ methods,+ });+ return { success: true, state: loginFlowState };+ }discoveredMethods = methods;loginFlowState = reduceAuthFlow(loginFlowState, {type: 'discovery-loaded',@@ -5238,6 +5327,8 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginAcaptchaToken: action.captchaToken,});assertLoginFlowCurrent(actionLoginFlowEpoch);+ pendingAuthRealm = AUTH_REGION;+ discoveredMethods = [];loginFlowState = reduceAuthFlow(loginFlowState, {type: 'code-requested',kind: action.kind,@@ -5326,7 +5417,7 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginApendingAccountToken = null;return {success: true,- state: await completeLogin({ status: 'ok', ...pair }, actionLoginFlowEpoch),+ state: await finishFreshLogin({ status: 'ok', ...pair }, actionLoginFlowEpoch),};}// 纯社交/SSO 等没有 account 会话的历史路径仍用一次性 loginTicket。@@ -5423,6 +5514,8 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA'USER_CANCELLED',].includes(code);if (flowCannotRetry) {+ pendingPersonalLogin = null;+ handledLoginEmail = null;pendingAccountToken = null;pendingLoginTicket = null;pendingBindTicket = null;diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsxindex 0f8d2dc911..a1045168f4 100644--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx@@ -1485,14 +1485,19 @@ export function LoginPage({)}{realmConfirmation && (<LoginConsentDialog- title={t('login.realmConsent.title')}+ title={t(realmConfirmation.personalLoginAvailable+ ? 'login.realmConsent.personalTitle' : 'login.realmConsent.title')}body={t(- realmConfirmation.targetRegion === 'cn'- ? 'login.realmConsent.bodyCn'- : 'login.realmConsent.bodyGlobal',+ realmConfirmation.personalLoginAvailable+ ? (realmConfirmation.targetRegion === 'cn'+ ? 'login.realmConsent.personalBodyCn' : 'login.realmConsent.personalBodyGlobal')+ : (realmConfirmation.targetRegion === 'cn'+ ? 'login.realmConsent.bodyCn' : 'login.realmConsent.bodyGlobal'),)}- agreeLabel={t('login.realmConsent.agree')}- disagreeLabel={t('login.realmConsent.disagree')}+ agreeLabel={t(realmConfirmation.personalLoginAvailable+ ? 'login.realmConsent.enterpriseLogin' : 'login.realmConsent.agree')}+ disagreeLabel={t(realmConfirmation.personalLoginAvailable+ ? 'login.realmConsent.continuePersonal' : 'login.realmConsent.disagree')}onAgree={() => void dispatch({ type: 'confirm-sso-realm' })}onDisagree={() => void dispatch({ type: 'cancel-sso-realm' })}onOpenTerms={() => undefined}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 a3822eeaf6..90ef536080 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@@ -3,7 +3,7 @@import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { CindyAuthClient, reduceAuthFlow, type AuthFlowState } from '@cindy/auth-client';+import { CindyAuthClient, discoverEmailLogin, reduceAuthFlow, type AuthFlowState } from '@cindy/auth-client';import { createScenarioFetch } from '@cindy/auth-client/fixtures';/**@@ -38,7 +38,10 @@ const CONSENT_TEXT: Record<string, string> = {};vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => CONSENT_TEXT[key] ?? key }),+ useTranslation: () => ({+ t: (key: string, params?: { org?: string; email?: string; name?: string }) =>+ params ? [key, ...Object.values(params)].join('#') : (CONSENT_TEXT[key] ?? key),+ }),}));// 构建区域 = global(LEGAL_LINKS 亦随之解析为 protocol.xd.com 系)vi.mock('../../../../shared/brandRegion', () => ({@@ -178,3 +181,76 @@ describe('Global 构建变体:登录改版四件事同样生效', () => {expect(loginHook.value.dispatch).not.toHaveBeenCalled();});});+++describe('email enterprise region confirmation', () => {+ it('shows the existing region confirmation, then offers SSO and the original mailbox', async () => {+ const result = await discoverEmailLogin('[email protected]', {+ buildRegion: 'global',+ discoverOrganization: async () => ({+ region: 'cn', orgName: 'Example Enterprise',+ connections: [{ connectionId: 'cn-sso', protocol: 'oidc', connectionName: 'Work SSO' }],+ }),+ discoverPersonal: vi.fn(),+ });+ const identifier = await globalIdentifierState();+ if (identifier.step !== 'identifier') throw new Error('Expected identifier');+ const confirmation = reduceAuthFlow(identifier, {+ type: 'realm-switch-required', targetRegion: result.region,+ email: result.email, methods: result.methods, providers: identifier.providers,+ });+ const view = mount(confirmation);+ expect(screen.getByText('login.realmConsent.bodyCn')).toBeTruthy();+ expect(loginHook.value.dispatch).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId('login-consent-disagree'));+ expect(loginHook.value.dispatch).toHaveBeenLastCalledWith({ type: 'cancel-sso-realm' });+ fireEvent.click(screen.getByTestId('login-consent-agree'));+ expect(loginHook.value.dispatch).toHaveBeenLastCalledWith({ type: 'confirm-sso-realm' });++ loginHook.value.loginState = reduceAuthFlow(confirmation, {+ type: 'discovery-loaded', email: result.email, methods: result.methods,+ });+ view.rerender(<LoginPage />);+ expect(screen.queryByTestId('login-consent-dialog')).toBeNull();+ const rows = screen.getAllByTestId(/^login-method-/);+ expect(rows).toHaveLength(2);+ expect(screen.getByText('login.orgDetected#[email protected]#Example Enterprise')).toBeTruthy();+ expect(screen.getByTestId('login-method-sso-cn-sso').textContent).toContain('Work SSO');+ expect(screen.getByTestId('login-method-personal')).toBeTruthy();+ fireEvent.click(screen.getByTestId('login-method-sso-cn-sso'));+ expect(loginHook.value.dispatch).toHaveBeenLastCalledWith({+ type: 'start-browser', kind: 'sso', providerOrConnectionId: 'cn-sso', label: 'Work SSO',+ });+ });+});+++describe('fresh personal login enterprise suggestion', () => {+ it.each(['cn', 'global'] as const)('offers enterprise SSO or the successful personal login for %s', async (targetRegion) => {+ const identifier = await globalIdentifierState();+ if (identifier.step !== 'identifier') throw new Error('Expected identifier');+ mount(reduceAuthFlow(identifier, {+ type: 'realm-switch-required', targetRegion, personalLoginAvailable: true,+ providers: identifier.providers,+ methods: [{ type: 'sso', connectionId: 'enterprise-sso', protocol: 'oidc', orgName: 'Enterprise', connectionName: 'Work SSO', ssoRequired: false }],+ }));+ expect(screen.getByText('login.realmConsent.personalTitle')).toBeTruthy();+ expect(screen.getByText(targetRegion === 'cn'+ ? 'login.realmConsent.personalBodyCn' : 'login.realmConsent.personalBodyGlobal')).toBeTruthy();+ expect(screen.getByTestId('login-consent-agree').textContent).toContain('login.realmConsent.enterpriseLogin');+ expect(screen.getByTestId('login-consent-disagree').textContent).toContain('login.realmConsent.continuePersonal');+ expect(loginHook.value.dispatch).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId('login-consent-disagree'));+ expect(loginHook.value.dispatch).toHaveBeenLastCalledWith({ type: 'cancel-sso-realm' });+ fireEvent.click(screen.getByTestId('login-consent-agree'));+ expect(loginHook.value.dispatch).toHaveBeenLastCalledWith({ type: 'confirm-sso-realm' });+ });++ it('submits the full email address from the email field', async () => {+ mount(await globalIdentifierState());+ fireEvent.change(screen.getByTestId('login-input'), { target: { value: '[email protected]' } });+ await act(async () => { fireEvent.click(screen.getByTestId('login-consent-radio')); });+ await act(async () => { fireEvent.click(screen.getByTestId('login-continue-button')); });+ expect(loginHook.value.dispatchWithResult).toHaveBeenCalledWith({ type: 'discover', email: '[email protected]' });+ });+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex fbce8a009e..69f4df4208 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -5849,6 +5849,11 @@"ssoOrgHint": "Don't know your enterprise sign-in identifier? Ask your admin","ssoOrgDetected": "Choose a single sign-on connection for \"{{org}}\"","realmConsent": {+ "personalTitle": "Enterprise sign-in available",+ "personalBodyCn": "Enterprise found in Mainland China.\nUse SSO or continue with your account.",+ "personalBodyGlobal": "Enterprise found in the Global region.\nUse SSO or continue with your account.",+ "enterpriseLogin": "Enterprise SSO",+ "continuePersonal": "Continue personal","title": "Connect to your enterprise region","bodyCn": "Your enterprise is in Mainland China.\nContinue to connect Cindy to this region.","bodyGlobal": "Your enterprise is in the Global region.\nContinue to connect Cindy to this region.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2244e12282..fbad129e39 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -5847,6 +5847,11 @@"ssoOrgHint": "企業のログイン識別子が不明な場合は、管理者にお問い合わせください","ssoOrgDetected": "「{{org}}」のシングルサインオン方法を選択してください","realmConsent": {+ "personalTitle": "企業ログインが見つかりました",+ "personalBodyCn": "メールに対応する企業は中国本土です。\n企業 SSO または個人ログインを選べます。",+ "personalBodyGlobal": "メールに対応する企業は国際地域です。\n企業 SSO または個人ログインを選べます。",+ "enterpriseLogin": "企業 SSO",+ "continuePersonal": "個人で続ける","title": "企業のリージョンに接続","bodyCn": "この企業は中国本土リージョンにあります。\n続行すると Cindy はこの地域に接続します。","bodyGlobal": "この企業はグローバルリージョンにあります。\n続行すると Cindy はこの地域に接続します。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b658969371..8f65cbc830 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -5847,6 +5847,11 @@"ssoOrgHint": "기업 로그인 식별자를 모르시나요? 관리자에게 문의하세요","ssoOrgDetected": "\"{{org}}\"의 통합 로그인 방식을 선택하세요","realmConsent": {+ "personalTitle": "기업 로그인 발견",+ "personalBodyCn": "중국 본토의 기업을 찾았습니다.\n기업 SSO 또는 개인 로그인을 선택하세요.",+ "personalBodyGlobal": "글로벌 지역의 기업을 찾았습니다.\n기업 SSO 또는 개인 로그인을 선택하세요.",+ "enterpriseLogin": "기업 SSO",+ "continuePersonal": "개인 로그인 계속","title": "기업 지역에 연결","bodyCn": "이 기업은 중국 본토 지역에 있습니다.\n계속하면 Cindy가 해당 지역에 연결됩니다.","bodyGlobal": "이 기업은 글로벌 지역에 있습니다.\n계속하면 Cindy가 해당 지역에 연결됩니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 1792a08da9..de9db36086 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -5843,6 +5843,11 @@"ssoOrgHint": "不知道企业登录标识?请联系企业管理员","ssoOrgDetected": "选择企业「{{org}}」的单点登录方式","realmConsent": {+ "personalTitle": "发现企业登录",+ "personalBodyCn": "邮箱对应企业位于中国大陆区。\n可使用企业 SSO,或继续个人登录。",+ "personalBodyGlobal": "邮箱对应企业位于国际区。\n可使用企业 SSO,或继续个人登录。",+ "enterpriseLogin": "企业 SSO",+ "continuePersonal": "继续个人登录","title": "连接企业所在区域","bodyCn": "你的企业位于中国大陆区。\n继续后,Cindy 会连接该区域。","bodyGlobal": "你的企业位于国际区。\n继续后,Cindy 会连接该区域。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5391418f79..31b3e19a58 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -5843,6 +5843,11 @@"ssoOrgHint": "不知道企業登入標識?請聯絡企業管理員","ssoOrgDetected": "選擇企業「{{org}}」的單點登入方式","realmConsent": {+ "personalTitle": "發現企業登入",+ "personalBodyCn": "信箱對應企業位於中國大陸區。\n可使用企業 SSO,或繼續個人登入。",+ "personalBodyGlobal": "信箱對應企業位於國際區。\n可使用企業 SSO,或繼續個人登入。",+ "enterpriseLogin": "企業 SSO",+ "continuePersonal": "繼續個人登入","title": "連線企業所在區域","bodyCn": "你的企業位於中國大陸區。\n繼續後,Cindy 會連線該區域。","bodyGlobal": "你的企業位於國際區。\n繼續後,Cindy 會連線該區域。",diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsxindex a6ab74cd1a..4e31356e3a 100644--- a/apps/mobile/app/(auth)/login.tsx+++ b/apps/mobile/app/(auth)/login.tsx@@ -1496,14 +1496,19 @@ export function LoginScreen({{realmConfirmation ? (<LoginConsentDialogscale={groupScale}- title={loginText('realmConsentTitle')}+ title={loginText(realmConfirmation.personalLoginAvailable+ ? 'realmConsentPersonalTitle' : 'realmConsentTitle')}body={loginText(- realmConfirmation.targetRegion === 'cn'- ? 'realmConsentBodyCn'- : 'realmConsentBodyGlobal',+ realmConfirmation.personalLoginAvailable+ ? (realmConfirmation.targetRegion === 'cn'+ ? 'realmConsentPersonalBodyCn' : 'realmConsentPersonalBodyGlobal')+ : (realmConfirmation.targetRegion === 'cn'+ ? 'realmConsentBodyCn' : 'realmConsentBodyGlobal'),)}- agreeLabel={loginText('realmConsentAgree')}- disagreeLabel={loginText('realmConsentDisagree')}+ agreeLabel={loginText(realmConfirmation.personalLoginAvailable+ ? 'realmConsentEnterpriseLogin' : 'realmConsentAgree')}+ disagreeLabel={loginText(realmConfirmation.personalLoginAvailable+ ? 'realmConsentContinuePersonal' : 'realmConsentDisagree')}onAgree={() =>void auth.dispatchLoginAction({ type: 'confirm-sso-realm' })}diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.tsindex 09d4ebf915..7c22fe4de5 100644--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts@@ -173,16 +173,16 @@ describe('mobile auth-server login', () => {expect(authSource).toContain("action.type === 'start-social-browser' ||");expect(authSource).toContain("action.type === 'native-social'");expect(authSource).toContain(- 'if (startsBuildRealmFlow) {\n pendingAuthRealmRef.current = null;',+ "if (startsBuildRealmFlow && action.type !== 'request-code') {\n pendingAuthRealmRef.current = null;",);const discoveryStart = authSource.indexOf(- "if (action.type === 'discover-sso-org') {",+ 'const discoverOrganization = async (',);const discoveryBody = authSource.slice(discoveryStart,authSource.indexOf(- 'const realmConfig = getMobileEndpointRealmConfig();',+ "if (action.type === 'reset')",discoveryStart,),);@@ -216,6 +216,20 @@ describe('mobile auth-server login', () => {expect(authSource).toContain("sole?.type === 'email_code'");});+ it('shares email-domain discovery and keeps the enterprise realm until personal code sending succeeds', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'), 'utf8');+ const discoverStart = source.indexOf("if (action.type === 'discover') {");+ const discover = source.slice(discoverStart, source.indexOf("if (action.type === 'discover-sso-org') {", discoverStart));+ expect(discover).toContain('discoverEmailLogin(action.email');+ expect(discover).toContain('discoverOrganization,');+ expect(discover).toContain('pendingAuthRealmRef.current = region;');+ expect(discover.indexOf("type: 'realm-switch-required'")).toBeLessThan(discover.indexOf("await ensureCaptchaGate('email')"));+ expect(source).toContain("email: confirmation.email ?? ''");+ const requestStart = source.indexOf("if (action.type === 'request-code') {");+ const request = source.slice(requestStart, source.indexOf("if (action.type === 'verify-code') {", requestStart));+ expect(request.indexOf('pendingAuthRealmRef.current = BUILD_AUTH_REGION;')).toBeGreaterThan(request.indexOf('await requestCodeWithCaptchaFallback('));+ });+it('remembers successful organization discovery before sole-SSO browser auth starts', () => {const authSource = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'),@@ -790,3 +804,39 @@ describe('mobile auth-server login', () => {expect(loginSource).toContain("type: 'discover-sso-org'");});});+++describe('fresh personal login enterprise suggestion boundaries', () => {+ const source = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'), 'utf8');+ it('guards late discovery before prompting and preserves the original region until the choice', () => {+ const start = source.indexOf('const acceptOutcome = useCallback');+ const body = source.slice(start, source.indexOf('const refresh = useCallback', start));+ const discovery = body.indexOf('await discoverPersonalLoginOrganization');+ const guard = body.indexOf('assertLoginFlowCurrent(expectedLoginFlowEpoch)', discovery);+ const prompt = body.indexOf('pendingPersonalLoginRef.current = { outcome, realm: personalRealm }');+ expect(discovery).toBeGreaterThan(-1);+ expect(guard).toBeGreaterThan(discovery);+ expect(prompt).toBeGreaterThan(guard);+ expect(body.slice(discovery, prompt)).not.toContain('pendingAuthRealmRef.current =');+ expect(body).toContain('personalLoginAvailable: true');+ expect(body).toContain('pendingPersonalLoginRef.current = null');+ const lookupStart = source.indexOf('const lookupOrganizationRealm = useCallback');+ expect(source.slice(lookupStart, start)).not.toContain('pendingAuthRealmRef.current =');+ });+ it('continues personal login without rediscovery or starts SSO with a freshly selected realm', () => {+ const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm')");+ const cancelStart = source.indexOf("if (action.type === 'cancel-sso-realm')");+ const confirm = source.slice(confirmStart, cancelStart);+ expect(confirm.indexOf('pendingAccountRefreshTokenRef.current = null')).toBeLessThan(confirm.indexOf('pendingAuthRealmRef.current = confirmation.targetRegion'));+ const cancel = source.slice(cancelStart, source.indexOf("if (action.type === 'discover')", cancelStart));+ expect(cancel).toContain('pendingAuthRealmRef.current = personal.realm');+ expect(cancel).toContain('acceptOutcome(personal.outcome, did, expectedLoginFlowEpoch');+ expect(cancel).toContain('skipOrganizationDiscovery: true');+ const browserStart = source.indexOf('const startBrowserAuthorization = async');+ const browser = source.slice(browserStart, source.indexOf('const discoverOrganization = async', browserStart));+ expect(browser).toContain('authClientFor(did, authorizationRealm)');+ expect(browser).toContain('realm: authorizationRealm');+ expect(browser).toContain('authorizationClient.buildAuthorizeUrl');+ expect(browser).not.toContain('realm: loginRealm');+ });+});diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex e46f5f3cd5..916d5e5e43 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -19,6 +19,8 @@ import {passportVaultKey,captchaRequiredActionForVerificationKind,discoverSsoOrgRealm,+ discoverEmailLogin,+ discoverPersonalLoginOrganization,parseAccountDeletionReceiptRecord,parseAuthSessionRecord,reduceAuthFlow,@@ -36,6 +38,7 @@ import {type AccountDeletionStatus,type CaptchaConfig,type LoginOutcome,+ type ProviderConfig,type SocialProvider,type SsoOrgDiscovery,type VerificationKind,@@ -417,6 +420,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {const pendingSsoVerificationTicketRef = useRef<string | null>(null);const activeAuthRealmRef = useRef<AuthRegion>(BUILD_AUTH_REGION);const pendingAuthRealmRef = useRef<AuthRegion | null>(null);+ const handledLoginEmailRef = useRef<string | null>(null);+ const pendingPersonalLoginRef = useRef<{+ outcome: Extract<LoginOutcome, { status: 'ok' }>;+ realm: AuthRegion;+ } | null>(null);const accountDeletionReceiptRealmRef = useRef<AuthRegion | null>(null);const pendingAccountDeletionRestoredRef = useRef(false);const loginActionInFlightRef = useRef<Promise<boolean> | null>(null);@@ -708,6 +716,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {/* ── 登录人机验证(Turnstile 托管挑战页,按 requiredFor 控制邮箱/短信发码)── */const captchaConfigRef = useRef<CaptchaConfig | null>(null);+ const loginProvidersRef = useRef<ProviderConfig | null>(null);const [captchaChallenge, setCaptchaChallenge] = useState<{ url: string } | null>(null);const captchaResolveRef = useRef<((token: string | null) => void) | null>(null);@@ -717,6 +726,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {// 服务端未开启时字段缺席,captcha 闸整体 no-op。if (next?.step === 'identifier' || next?.step === 'realm-confirmation') {captchaConfigRef.current = next.providers.captcha ?? null;+ loginProvidersRef.current = next.providers;}loginStateRef.current = next;setLoginState(next);@@ -906,11 +916,53 @@ export function AuthProvider({ children }: { children: ReactNode }) {[applyUser, refreshSavedAccountsSnapshot],);+ // Optional post-login discovery must not mutate the realm that issued the personal tokens.+ const lookupOrganizationRealm = useCallback(async (+ org: string,+ did: string,+ expectedLoginFlowEpoch: number,+ ): Promise<SsoOrgDiscovery> => {+ const realmConfig = getMobileEndpointRealmConfig();+ let discovery: SsoOrgDiscovery;+ if (+ realmConfig.crossRealmOrgLoginEnabled &&+ realmConfig.realmManifestBaseUrls+ ) {+ try {+ await Promise.all([+ loadMobileEndpointsForRealm('cn'),+ loadMobileEndpointsForRealm('global'),+ ]);+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ } catch {+ throw new AuthApiError(+ 'ORG_REALM_UNAVAILABLE',+ 503,+ 'Unable to load both enterprise auth region manifests',+ );+ }+ const selected = await discoverSsoOrgRealm(org, {+ cn: authClientFor(did, 'cn'),+ global: authClientFor(did, 'global'),+ });+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ discovery = selected.discovery;+ } else {+ discovery = await authClientFor(+ did,+ BUILD_AUTH_REGION,+ ).discoverSsoOrg(org);+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ }+ return discovery;+ }, [assertLoginFlowCurrent]);+const acceptOutcome = useCallback(async (outcome: LoginOutcome,did: string,expectedLoginFlowEpoch = loginFlowEpochRef.current,+ options: { skipOrganizationDiscovery?: boolean } = {},): Promise<void> => {await deleteSecureItem(PENDING_OAUTH_KEY).catch(() => undefined);assertLoginFlowCurrent(expectedLoginFlowEpoch);@@ -961,6 +1013,32 @@ export function AuthProvider({ children }: { children: ReactNode }) {return;}+ if (!options.skipOrganizationDiscovery) {+ const personalRealm = pendingAuthRealmRef.current ?? BUILD_AUTH_REGION;+ const discovery = await discoverPersonalLoginOrganization(outcome.membership, {+ handledEmail: handledLoginEmailRef.current,+ discoverOrganization: (domain) => lookupOrganizationRealm(domain, did, expectedLoginFlowEpoch),+ });+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ // A cold OAuth callback can arrive before the login screen loads providers.+ const providers = discovery+ ? (loginProvidersRef.current ?? await authClientFor(did, BUILD_AUTH_REGION)+ .getProviders().catch(() => null))+ : null;+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ if (discovery && providers) {+ pendingPersonalLoginRef.current = { outcome, realm: personalRealm };+ updateLoginState(reduceAuthFlow(loginStateRef.current, {+ type: 'realm-switch-required',+ targetRegion: discovery.region,+ personalLoginAvailable: true,+ providers,+ methods: ssoOrgDiscoveryToMethods(discovery),+ }));+ return;+ }+ }+const deletionWasRestored =outcome.accountDeletionRestored === true ||pendingAccountDeletionRestoredRef.current;@@ -1039,6 +1117,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {pendingAccountTokenRef.current = null;pendingAccountRefreshTokenRef.current = null;pendingAccountMembershipsRef.current = [];+ pendingPersonalLoginRef.current = null;+ handledLoginEmailRef.current = null;pendingBindTicketRef.current = null;pendingSsoVerificationTicketRef.current = null;pendingAuthRealmRef.current = null;@@ -1097,6 +1177,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {clearAccountScopedRuntimeForSwitch,commitWithClearedAccountDeletionReceipt,loadMe,+ lookupOrganizationRealm,scheduleCanaryChannelSync,scheduleXdOrgBetaDefault,refreshSavedAccountsSnapshotBestEffort,@@ -1734,10 +1815,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {action.type === 'verify-code' ||action.type === 'start-social-browser' ||action.type === 'native-social';- if (startsBuildRealmFlow) {+ if (startsBuildRealmFlow && action.type !== 'request-code') {pendingAuthRealmRef.current = null;if (!additionalLoginRef.current) resetMobileSessionRealm();}+ if (action.type === 'start-social-browser' || action.type === 'native-social') {+ handledLoginEmailRef.current = null;+ }const loginRealm = pendingAuthRealmRef.current ?? BUILD_AUTH_REGION;const client = authClientFor(did, loginRealm);const startBrowserAuthorization = async (input: {@@ -1746,6 +1830,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {providerOrConnectionId: string;label: string;}): Promise<boolean> => {+ const authorizationRealm = pendingAuthRealmRef.current ?? BUILD_AUTH_REGION;+ const authorizationClient = authClientFor(did, authorizationRealm);const { codeVerifier, codeChallenge } = await createPkcePair();assertLoginFlowCurrent(expectedLoginFlowEpoch);const state = createState();@@ -1757,7 +1843,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {state,createdAt: Date.now(),label: input.label,- realm: loginRealm,+ realm: authorizationRealm,} satisfies PendingOAuth),);assertLoginFlowCurrent(expectedLoginFlowEpoch);@@ -1767,7 +1853,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {label: input.label,}),);- const authUrl = client.buildAuthorizeUrl({+ const authUrl = authorizationClient.buildAuthorizeUrl({kind: input.kind,providerOrConnectionId: input.providerOrConnectionId,redirectUri: MOBILE_REDIRECT_URL,@@ -1790,10 +1876,19 @@ export function AuthProvider({ children }: { children: ReactNode }) {throw authCodeError('USER_CANCELLED');};+ const discoverOrganization = async (org: string): Promise<SsoOrgDiscovery> => {+ pendingAuthRealmRef.current = null;+ const discovery = await lookupOrganizationRealm(org, did, expectedLoginFlowEpoch);+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ pendingAuthRealmRef.current = discovery.region;+ return discovery;+ };if (action.type === 'reset') {pendingAccountTokenRef.current = null;pendingAccountRefreshTokenRef.current = null;pendingAccountMembershipsRef.current = [];+ pendingPersonalLoginRef.current = null;+ handledLoginEmailRef.current = null;pendingLoginTicketRef.current = null;pendingBindTicketRef.current = null;pendingSsoVerificationTicketRef.current = null;@@ -1820,10 +1915,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {const confirmation = loginStateRef.current;if (confirmation?.step !== 'realm-confirmation' ||- pendingAuthRealmRef.current !== confirmation.targetRegion+ (confirmation.personalLoginAvailable+ ? !pendingPersonalLoginRef.current+ : pendingAuthRealmRef.current !== confirmation.targetRegion)) {throw authCodeError('INVALID_AUTH_ACTION');}+ if (confirmation.personalLoginAvailable) {+ pendingAccountTokenRef.current = null;+ pendingAccountRefreshTokenRef.current = null;+ pendingAccountMembershipsRef.current = [];+ pendingPersonalLoginRef.current = null;+ handledLoginEmailRef.current = null;+ pendingLoginTicketRef.current = null;+ pendingBindTicketRef.current = null;+ pendingSsoVerificationTicketRef.current = null;+ pendingAccountDeletionRestoredRef.current = false;+ pendingAuthRealmRef.current = confirmation.targetRegion;+ }const sole = soleAutoStartSsoMethod(confirmation.methods);if (sole) {return startBrowserAuthorization({@@ -1836,7 +1945,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {updateLoginState(reduceAuthFlow(confirmation, {type: 'discovery-loaded',- email: '',+ email: confirmation.email ?? '',methods: confirmation.methods,}),);@@ -1847,6 +1956,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {if (confirmation?.step !== 'realm-confirmation') {throw authCodeError('INVALID_AUTH_ACTION');}+ if (confirmation.personalLoginAvailable) {+ const personal = pendingPersonalLoginRef.current;+ if (!personal) throw authCodeError('INVALID_AUTH_ACTION');+ pendingAuthRealmRef.current = personal.realm;+ await acceptOutcome(personal.outcome, did, expectedLoginFlowEpoch, {+ skipOrganizationDiscovery: true,+ });+ return true;+ }pendingAuthRealmRef.current = null;if (!additionalLoginRef.current) resetMobileSessionRealm();updateLoginState(@@ -1858,13 +1976,30 @@ export function AuthProvider({ children }: { children: ReactNode }) {return true;}if (action.type === 'discover') {- const email = action.email.trim().toLowerCase();- const methods = await authClientFor(- did,- BUILD_AUTH_REGION,- ).discover(email);+ const { email, methods, region } = await discoverEmailLogin(action.email, {+ buildRegion: BUILD_AUTH_REGION,+ discoverOrganization,+ discoverPersonal: (email) => authClientFor(did, BUILD_AUTH_REGION).discover(email),+ });assertLoginFlowCurrent(expectedLoginFlowEpoch);+ handledLoginEmailRef.current = email;+ pendingAuthRealmRef.current = region;const currentState = loginStateRef.current;+ if (region !== BUILD_AUTH_REGION) {+ if (currentState?.step !== 'identifier') {+ throw authCodeError('INVALID_AUTH_ACTION');+ }+ updateLoginState(+ reduceAuthFlow(currentState, {+ type: 'realm-switch-required',+ targetRegion: region,+ email,+ providers: currentState.providers,+ methods,+ }),+ );+ return true;+ }const sole = soleLoginMethod(methods);if (sole?.type === 'sso' && currentState) {return startBrowserAuthorization({@@ -1918,43 +2053,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {// 多连接才映射进 method-choice,复用连接选择 UI 与 start-sso 流程。if (action.type === 'discover-sso-org') {const org = action.org.trim().toLowerCase();- // 新的一次组织发现不得复用上一轮成功结果;只有本轮双区判定成功后- // 才重新冻结 pending realm。- pendingAuthRealmRef.current = null;- const realmConfig = getMobileEndpointRealmConfig();- let discovery: SsoOrgDiscovery;- if (- realmConfig.crossRealmOrgLoginEnabled &&- realmConfig.realmManifestBaseUrls- ) {- try {- await Promise.all([- loadMobileEndpointsForRealm('cn'),- loadMobileEndpointsForRealm('global'),- ]);- assertLoginFlowCurrent(expectedLoginFlowEpoch);- } catch {- throw new AuthApiError(- 'ORG_REALM_UNAVAILABLE',- 503,- 'Unable to load both enterprise auth region manifests',- );- }- const selected = await discoverSsoOrgRealm(org, {- cn: authClientFor(did, 'cn'),- global: authClientFor(did, 'global'),- });- assertLoginFlowCurrent(expectedLoginFlowEpoch);- pendingAuthRealmRef.current = selected.region;- discovery = selected.discovery;- } else {- pendingAuthRealmRef.current = BUILD_AUTH_REGION;- discovery = await authClientFor(- did,- BUILD_AUTH_REGION,- ).discoverSsoOrg(org);- assertLoginFlowCurrent(expectedLoginFlowEpoch);- }+ const discovery = await discoverOrganization(org);const methods = ssoOrgDiscoveryToMethods(discovery);// A sole same-region connection auto-starts browser authorization// below. Persist the successful discovery first so cancel/timeout@@ -2007,6 +2106,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {gate.captchaToken,);assertLoginFlowCurrent(expectedLoginFlowEpoch);+ // Commit the personal realm only after sending; a failed attempt leaves SSO usable.+ pendingAuthRealmRef.current = BUILD_AUTH_REGION;+ if (!additionalLoginRef.current) resetMobileSessionRealm();updateLoginState(reduceAuthFlow(loginStateRef.current, {type: 'code-requested',@@ -2181,6 +2283,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {pendingAccountTokenRef.current = null;pendingAccountRefreshTokenRef.current = null;pendingAccountMembershipsRef.current = [];+ pendingPersonalLoginRef.current = null;+ handledLoginEmailRef.current = null;pendingLoginTicketRef.current = null;pendingBindTicketRef.current = null;pendingSsoVerificationTicketRef.current = null;@@ -2206,6 +2310,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {acceptOutcome,assertLoginFlowCurrent,completeOAuthCallback,+ lookupOrganizationRealm,ensureCaptchaGate,requestCodeWithCaptchaFallback,prepareBetaChannelForCurrentDevice,@@ -2530,6 +2635,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {pendingAccountTokenRef.current = null;pendingAccountRefreshTokenRef.current = null;pendingAccountMembershipsRef.current = [];+ pendingPersonalLoginRef.current = null;+ handledLoginEmailRef.current = null;pendingLoginTicketRef.current = null;pendingBindTicketRef.current = null;pendingSsoVerificationTicketRef.current = null;@@ -2557,6 +2664,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {// 同步失效认证代次,必须早于第一个 await。否则推送 token 注销的网络等待窗口内,// 迟到的 canary / XD beta 探测仍会把旧账号结果写回本地。authGenerationRef.current += 1;+ loginFlowEpochRef.current += 1;refreshInFlightRef.current = null;await unregisterPushTokenBestEffort(accessTokenRef.current,@@ -2569,6 +2677,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {pendingAccountTokenRef.current = null;pendingAccountRefreshTokenRef.current = null;pendingAccountMembershipsRef.current = [];+ pendingPersonalLoginRef.current = null;+ handledLoginEmailRef.current = null;additionalLoginRef.current = false;pendingLoginTicketRef.current = null;pendingBindTicketRef.current = null;diff --git a/apps/mobile/src/auth/__tests__/loginMessages.test.ts b/apps/mobile/src/auth/__tests__/loginMessages.test.tsindex 6156c567d1..d9136c1153 100644--- a/apps/mobile/src/auth/__tests__/loginMessages.test.ts+++ b/apps/mobile/src/auth/__tests__/loginMessages.test.ts@@ -91,6 +91,8 @@ describe("loginMessages 5 语 catalog", () => {for (const body of [messages.realmConsentBodyCn,messages.realmConsentBodyGlobal,+ messages.realmConsentPersonalBodyCn,+ messages.realmConsentPersonalBodyGlobal,]) {const lines = body.split("\n");expect(lines, `locale=${locale}: ${body}`).toHaveLength(2);diff --git a/apps/mobile/src/auth/loginMessages.ts b/apps/mobile/src/auth/loginMessages.tsindex ce5329ff17..f032afc787 100644--- a/apps/mobile/src/auth/loginMessages.ts+++ b/apps/mobile/src/auth/loginMessages.ts@@ -44,6 +44,11 @@ const messages = {ssoOrgHint: "不知道企業登入標識?請聯絡企業管理員。",ssoOrgDetected: "選擇企業「{org}」的單點登入方式",realmConsentTitle: "連線企業所在區域",+ realmConsentPersonalTitle: "發現企業登入",+ realmConsentPersonalBodyCn: "信箱對應企業位於中國大陸區。\n可使用企業 SSO,或繼續個人登入。",+ realmConsentPersonalBodyGlobal: "信箱對應企業位於國際區。\n可使用企業 SSO,或繼續個人登入。",+ realmConsentEnterpriseLogin: "企業 SSO",+ realmConsentContinuePersonal: "繼續個人登入",realmConsentBodyCn:"你的企業位於中國大陸區。\n繼續後,Cindy 會連線該區域。",realmConsentBodyGlobal:@@ -159,6 +164,11 @@ const messages = {ssoOrgHint: "不知道企业登录标识?请联系企业管理员。",ssoOrgDetected: "选择企业「{org}」的单点登录方式",realmConsentTitle: "连接企业所在区域",+ realmConsentPersonalTitle: "发现企业登录",+ realmConsentPersonalBodyCn: "邮箱对应企业位于中国大陆区。\n可使用企业 SSO,或继续个人登录。",+ realmConsentPersonalBodyGlobal: "邮箱对应企业位于国际区。\n可使用企业 SSO,或继续个人登录。",+ realmConsentEnterpriseLogin: "企业 SSO",+ realmConsentContinuePersonal: "继续个人登录",realmConsentBodyCn:"你的企业位于中国大陆区。\n继续后,Cindy 会连接该区域。",realmConsentBodyGlobal:@@ -276,6 +286,11 @@ const messages = {"Don't know your enterprise sign-in identifier? Ask your admin.",ssoOrgDetected: 'Choose a single sign-on connection for "{org}"',realmConsentTitle: "Connect to your enterprise region",+ realmConsentPersonalTitle: "Enterprise sign-in available",+ realmConsentPersonalBodyCn: "Enterprise found in Mainland China.\nUse SSO or continue with your account.",+ realmConsentPersonalBodyGlobal: "Enterprise found in the Global region.\nUse SSO or continue with your account.",+ realmConsentEnterpriseLogin: "Enterprise SSO",+ realmConsentContinuePersonal: "Continue personal",realmConsentBodyCn:"Your enterprise is in Mainland China.\nContinue to connect Cindy to this region.",realmConsentBodyGlobal:@@ -405,6 +420,11 @@ const messages = {"企業のログイン識別子が不明な場合は、管理者にお問い合わせください。",ssoOrgDetected: "組織「{org}」のシングルサインオン方法を選択",realmConsentTitle: "企業のリージョンに接続",+ realmConsentPersonalTitle: "企業ログインが見つかりました",+ realmConsentPersonalBodyCn: "メールに対応する企業は中国本土です。\n企業 SSO または個人ログインを選べます。",+ realmConsentPersonalBodyGlobal: "メールに対応する企業は国際地域です。\n企業 SSO または個人ログインを選べます。",+ realmConsentEnterpriseLogin: "企業 SSO",+ realmConsentContinuePersonal: "個人で続ける",realmConsentBodyCn:"この企業は中国本土リージョンにあります。\n続行すると Cindy はこの地域に接続します。",realmConsentBodyGlobal:@@ -532,6 +552,11 @@ const messages = {ssoOrgHint: "기업 로그인 식별자를 모르시나요? 관리자에게 문의하세요.",ssoOrgDetected: '"{org}" 조직의 SSO 연결을 선택하세요',realmConsentTitle: "기업 지역에 연결",+ realmConsentPersonalTitle: "기업 로그인 발견",+ realmConsentPersonalBodyCn: "중국 본토의 기업을 찾았습니다.\n기업 SSO 또는 개인 로그인을 선택하세요.",+ realmConsentPersonalBodyGlobal: "글로벌 지역의 기업을 찾았습니다.\n기업 SSO 또는 개인 로그인을 선택하세요.",+ realmConsentEnterpriseLogin: "기업 SSO",+ realmConsentContinuePersonal: "개인 로그인 계속",realmConsentBodyCn:"이 기업은 중국 본토 지역에 있습니다.\n계속하면 Cindy가 해당 지역에 연결됩니다.",realmConsentBodyGlobal:diff --git a/docs/auth-realm-routing.md b/docs/auth-realm-routing.mdindex 46c4c39b74..71e5ff2bb6 100644--- a/docs/auth-realm-routing.md+++ b/docs/auth-realm-routing.md@@ -49,6 +49,34 @@ Cindy 的中国大陆版与国际版仍是两个独立的安装包和更新通`buildRegion` 固定,无需在确认文案中重复说明。选中的临时区域用于本次 SSOauthorize、callback、授权码兑换、联系方式验证与身份选择。+邮箱入口在用户提交完整邮箱后,也会提取并小写化域名,复用上述双区组织发现;不会在+逐字输入时请求,也不会向对端发送完整邮箱。跨区命中时,复用现有目标区域确认文案,+确认后提供该企业的 SSO 连接,同时保留个人邮箱验证码选项。个人验证码始终走安装包+区域;确认企业区域不会把个人账号、验证码或社交登录迁往另一地区。++同区企业继续使用原有邮箱 discovery 的登录方式列表;两区都明确未找到时继续普通+邮箱登录。歧义、网络故障和非法响应仍遵守上面的失败规则,不当作未找到而自动发码。+服务端现有 `POST /api/auth/sso/discovery` 已支持已验证域名、企业名称、区域和启用的+SSO 连接,无需改接口。未验证域名、未启用 SSO 的企业不在本次发现范围内。+实现见 `packages/auth-client/src/emailLoginDiscovery.ts`,回归见同目录+`__tests__/emailLoginDiscovery.test.ts`。++## 本次个人登录后的企业提示++Google、Apple、邮箱/手机验证码、补绑和身份选择等新登录,统一在收到最终个人+membership 后检查邮箱域名(Desktop `finishFreshLogin`、Mobile `acceptOutcome`)。+只使用服务端返回的邮箱;已通过邮箱入口完成发现的同一邮箱不重复提示。已是企业身份、+没有有效邮箱、冷启动恢复、刷新 token 和切换已保存账号不触发此提示。++发现可用企业时,同区和跨区均显示区域及两个选择:使用企业 SSO,或继续刚完成的个人+登录。个人登录结果仅暂存在 main / AuthContext 内存,UI 状态只有发现信息和可继续标记。+继续个人登录直接提交原结果和原区域;选择企业 SSO 则丢弃临时个人结果,并在企业区域+重新授权。不会把个人 token、Google/Apple 凭据或两区 passport 互相转移。++此阶段的发现属于可选提示:未找到、歧义、限流或网络失败都保留原个人登录,不猜测+企业区域。取消本次登录或开始新流程后,迟到发现结果不能恢复旧登录。此规则只适用于+已经成功的个人认证;用户主动提交邮箱或企业标识时仍执行前述严格发现规则。+## 会话持久化与恢复Desktop safeStorage 和 Mobile SecureStore 都只保存一个加密的原子记录:@@ -66,7 +94,8 @@ session 被拒绝时,Desktop 仍把轮换后的 refresh token 写回原 realm`sessionRealm`,业务端点恢复安装包区域。Mobile 的 Pending OAuth 同时保存 `realm`,但 redirect scheme 始终使用当前安装包的-scheme。个人验证码和社交登录不做跨区域发现,也不合并两区 passport。+scheme。个人验证码和社交登录固定使用安装包区域,也不合并两区 passport;邮箱提交时+新增的域名发现只为引导企业 SSO。## 模型访问与媒体目录边界diff --git a/packages/auth-client/src/__tests__/client.test.ts b/packages/auth-client/src/__tests__/client.test.tsindex d2192e82c7..09f1bcb8df 100644--- a/packages/auth-client/src/__tests__/client.test.ts+++ b/packages/auth-client/src/__tests__/client.test.ts@@ -21,7 +21,7 @@ function response(status: number, data: unknown): AuthFetchResponse {return { ok: status >= 200 && status < 300, status, json: async () => data };}-function client(fetch = vi.fn(async () => response(200, {}))) {+function client(fetch: AuthFetch = vi.fn(async () => response(200, {}))) {return new CindyAuthClient({baseUrl: "https://auth.example.com/",region: "cn",@@ -151,7 +151,7 @@ describe("CindyAuthClient", () => {});it("carries captchaToken in the email request-code body only when provided", async () => {- const fetch = vi.fn(async () => response(200, { status: "sent" }));+ const fetch = vi.fn<AuthFetch>(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,diff --git a/packages/auth-client/src/__tests__/emailLoginDiscovery.test.ts b/packages/auth-client/src/__tests__/emailLoginDiscovery.test.tsnew file mode 100644index 0000000000..686fdcb7e8--- /dev/null+++ b/packages/auth-client/src/__tests__/emailLoginDiscovery.test.ts@@ -0,0 +1,265 @@+import { describe, expect, it, vi } from "vitest";+import {+ AuthApiError,+ CindyAuthClient,+ discoverEmailLogin,+ discoverPersonalLoginOrganization,+ type AuthMembership,+ discoverSsoOrgRealm,+ reduceAuthFlow,+ type AuthRegion,+ type LoginMethod,+ type SsoOrgDiscovery,+} from "../index.js";++const organization = (region: AuthRegion): SsoOrgDiscovery => ({+ region,+ orgName: "Example Enterprise",+ connections: [+ {+ connectionId: `${region}-sso`,+ protocol: "oidc",+ connectionName: "Work SSO",+ },+ ],+});++describe("email enterprise discovery", () => {+ it.each(["cn", "global"] as const)(+ "discovers a %s enterprise without sharing the mailbox",+ async (region) => {+ const requests: { region: AuthRegion; body: unknown }[] = [];+ const makeClient = (target: AuthRegion) =>+ new CindyAuthClient({+ baseUrl: `https://${target}.example.invalid`,+ region: target,+ clientType: "desktop",+ deviceId: "test-device",+ fetch: async (_url, init) => {+ requests.push({+ region: target,+ body: JSON.parse(init?.body as string),+ });+ return new Response(+ JSON.stringify(+ target === region+ ? organization(region)+ : {+ error: {+ code: "ORG_SSO_NOT_FOUND",+ message: "not found",+ },+ },+ ),+ { status: target === region ? 200 : 404 },+ );+ },+ });+ const discoverPersonal = vi.fn();+ const result = await discoverEmailLogin(" [email protected] ", {+ buildRegion: region === "cn" ? "global" : "cn",+ discoverPersonal,+ discoverOrganization: async (domain) =>+ (+ await discoverSsoOrgRealm(domain, {+ cn: makeClient("cn"),+ global: makeClient("global"),+ })+ ).discovery,+ });+ expect(requests).toEqual([+ { region: "cn", body: { org: "example.com" } },+ { region: "global", body: { org: "example.com" } },+ ]);+ expect(result).toMatchObject({ email: "[email protected]", region });+ expect(result.methods).toEqual([+ {+ type: "sso",+ connectionId: `${region}-sso`,+ protocol: "oidc",+ orgName: "Example Enterprise",+ connectionName: "Work SSO",+ ssoRequired: false,+ },+ { type: "email_code" },+ ]);+ expect(discoverPersonal).not.toHaveBeenCalled();+ },+ );++ it("preserves local email discovery and SSO preferences for a same-region enterprise", async () => {+ const methods: LoginMethod[] = [+ { type: "email_code" },+ {+ type: "sso",+ connectionId: "global-sso",+ protocol: "oidc",+ orgName: "Example Enterprise",+ connectionName: "Work SSO",+ ssoRequired: true,+ },+ ];+ const discoverPersonal = vi.fn(async () => methods);+ const result = await discoverEmailLogin("[email protected]", {+ buildRegion: "global",+ discoverPersonal,+ discoverOrganization: async () => organization("global"),+ });+ expect(result).toEqual({+ email: "[email protected]",+ region: "global",+ methods,+ });+ expect(discoverPersonal).toHaveBeenCalledWith("[email protected]");+ });++ it("continues ordinary email login when neither region has enabled enterprise SSO", async () => {+ const result = await discoverEmailLogin("[email protected]", {+ buildRegion: "global",+ discoverOrganization: async () => {+ throw new AuthApiError("ORG_SSO_NOT_FOUND", 404, "not found");+ },+ discoverPersonal: async () => [{ type: "email_code" }],+ });+ expect(result).toEqual({+ email: "[email protected]",+ region: "global",+ methods: [{ type: "email_code" }],+ });+ });++ it.each([+ "ORG_REALM_AMBIGUOUS",+ "ORG_REALM_UNAVAILABLE",+ "REGION_MISMATCH",+ "INVALID_RESPONSE",+ "RATE_LIMITED",+ ])("does not mistake %s for an absent enterprise", async (code) => {+ const discoverPersonal = vi.fn();+ await expect(+ discoverEmailLogin("[email protected]", {+ buildRegion: "global",+ discoverPersonal,+ discoverOrganization: async () => {+ throw new AuthApiError(code, 503, "failure");+ },+ }),+ ).rejects.toMatchObject({ code });+ expect(discoverPersonal).not.toHaveBeenCalled();+ });++ it.each([+ "",+ "user@",+ "user@@example.com",+ "example.com",+ `${"a".repeat(255)}@example.com`,+ ])("rejects invalid email before discovery", async (email) => {+ const discoverOrganization = vi.fn();+ const discoverPersonal = vi.fn();+ await expect(+ discoverEmailLogin(email, {+ buildRegion: "global",+ discoverOrganization,+ discoverPersonal,+ }),+ ).rejects.toMatchObject({ code: "INVALID_PARAMS" });+ expect(discoverOrganization).not.toHaveBeenCalled();+ expect(discoverPersonal).not.toHaveBeenCalled();+ });++ it("retains the mailbox through region confirmation for the personal email option", async () => {+ const result = await discoverEmailLogin("[email protected]", {+ buildRegion: "global",+ discoverPersonal: vi.fn(),+ discoverOrganization: async () => organization("cn"),+ });+ const state = reduceAuthFlow(null, {+ type: "realm-switch-required",+ targetRegion: result.region,+ email: result.email,+ methods: result.methods,+ providers: {+ region: "global",+ attribution: "email",+ email: true,+ phone: false,+ social: [],+ },+ });+ expect(state).toMatchObject({+ step: "realm-confirmation",+ email: "[email protected]",+ targetRegion: "cn",+ });+ if (state.step !== "realm-confirmation")+ throw new Error("Expected confirmation");+ expect(+ reduceAuthFlow(state, {+ type: "discovery-loaded",+ email: state.email ?? "",+ methods: state.methods,+ }),+ ).toMatchObject({+ step: "method-choice",+ email: "[email protected]",+ methods: result.methods,+ });+ });+});+++describe("successful personal login enterprise discovery", () => {+ const membership = (email: string | null = " [email protected] "): AuthMembership => ({+ id: "personal-account", kind: "personal", role: "owner", displayName: "Person",+ email, orgId: null, orgName: null,+ });++ it.each(["cn", "global"] as const)("offers the %s enterprise using only the normalized email domain", async (region) => {+ const discoverOrganization = vi.fn(async () => organization(region));+ expect(await discoverPersonalLoginOrganization(membership(), {+ handledEmail: null, discoverOrganization,+ })).toEqual(organization(region));+ expect(discoverOrganization).toHaveBeenCalledExactlyOnceWith("xd.com");+ });++ it.each([null, "", "xd.com", "invalid@@xd.com", `${"x".repeat(250)}@xd.com`])(+ "leaves login unchanged when no usable email is available: %s", async (email) => {+ const discoverOrganization = vi.fn();+ expect(await discoverPersonalLoginOrganization(membership(email), {+ handledEmail: null, discoverOrganization,+ })).toBeNull();+ expect(discoverOrganization).not.toHaveBeenCalled();+ },+ );++ it("does not rediscover an organization identity or a mailbox already handled by email login", async () => {+ const discoverOrganization = vi.fn();+ expect(await discoverPersonalLoginOrganization({ ...membership(), kind: "org" }, {+ handledEmail: null, discoverOrganization,+ })).toBeNull();+ expect(await discoverPersonalLoginOrganization(membership(), {+ handledEmail: "[email protected]", discoverOrganization,+ })).toBeNull();+ expect(discoverOrganization).not.toHaveBeenCalled();+ });++ it.each(["ORG_SSO_NOT_FOUND", "ORG_REALM_AMBIGUOUS", "ORG_REALM_UNAVAILABLE", "RATE_LIMITED"])(+ "keeps successful login available on %s without suggesting a guessed region", async (code) => {+ expect(await discoverPersonalLoginOrganization(membership(), {+ handledEmail: null,+ discoverOrganization: async () => { throw new AuthApiError(code, 503, "discovery failed"); },+ })).toBeNull();+ },+ );++ it("carries only display metadata into confirmation, never the successful login tokens", () => {+ const state = reduceAuthFlow(null, {+ type: "realm-switch-required", targetRegion: "cn", personalLoginAvailable: true,+ providers: { region: "global", attribution: "email", email: true, phone: false, social: ["google"] },+ methods: [{ type: "sso", connectionId: "cn-sso", protocol: "oidc", orgName: "Enterprise", connectionName: "Work SSO", ssoRequired: false }],+ });+ expect(state).toMatchObject({ step: "realm-confirmation", personalLoginAvailable: true, targetRegion: "cn" });+ expect(Object.keys(state).sort()).toEqual(["methods", "personalLoginAvailable", "providers", "step", "targetRegion"]);+ });+});diff --git a/packages/auth-client/src/emailLoginDiscovery.ts b/packages/auth-client/src/emailLoginDiscovery.tsnew file mode 100644index 0000000000..4147a4c394--- /dev/null+++ b/packages/auth-client/src/emailLoginDiscovery.ts@@ -0,0 +1,73 @@+import { AuthApiError } from "./client.js";+import { isValidEmail } from "./email.js";+import {+ ssoOrgDiscoveryToMethods,+ type AuthMembership,+ type AuthRegion,+ type LoginMethod,+ type SsoOrgDiscovery,+} from "./types.js";++/** Email login shares enterprise realm discovery; personal codes stay in the build region. */+export async function discoverEmailLogin(+ value: string,+ options: {+ buildRegion: AuthRegion;+ discoverOrganization: (domain: string) => Promise<SsoOrgDiscovery>;+ discoverPersonal: (email: string) => Promise<LoginMethod[]>;+ },+): Promise<{ email: string; region: AuthRegion; methods: LoginMethod[] }> {+ const email = value.trim().toLowerCase();+ if (email.length > 254 || !isValidEmail(email)) {+ throw new AuthApiError("INVALID_PARAMS", 400, "Invalid email address");+ }+ let organization: SsoOrgDiscovery | null = null;+ try {+ // Only send the domain to the peer region, never the full email address.+ organization = await options.discoverOrganization(+ email.slice(email.indexOf("@") + 1),+ );+ } catch (error) {+ // Ambiguous/unavailable regions must not be treated as a confirmed absence.+ if (!(error instanceof AuthApiError) || error.code !== "ORG_SSO_NOT_FOUND")+ throw error;+ }+ if (organization && organization.region !== options.buildRegion) {+ return {+ email,+ region: organization.region,+ methods: [+ ...ssoOrgDiscoveryToMethods(organization),+ { type: "email_code" },+ ],+ };+ }+ return {+ email,+ region: options.buildRegion,+ // Preserve the existing same-region login methods and SSO preference.+ methods: await options.discoverPersonal(email),+ };+}++/** A successful personal login may offer SSO; discovery failure cannot undo that login. */+export async function discoverPersonalLoginOrganization(+ membership: AuthMembership,+ options: {+ handledEmail: string | null;+ discoverOrganization: (domain: string) => Promise<SsoOrgDiscovery>;+ },+): Promise<SsoOrgDiscovery | null> {+ const email = membership.email?.trim().toLowerCase();+ if (+ membership.kind !== "personal" || !email || email.length > 254 ||+ !isValidEmail(email) || email === options.handledEmail+ ) return null;+ try {+ return await options.discoverOrganization(email.slice(email.indexOf("@") + 1));+ } catch {+ // A hint is optional. Never guess a region from a partial/ambiguous result,+ // and never discard tokens the original region has already issued.+ return null;+ }+}diff --git a/packages/auth-client/src/index.ts b/packages/auth-client/src/index.tsindex f1e8a81e2f..46e8c21da5 100644--- a/packages/auth-client/src/index.ts+++ b/packages/auth-client/src/index.ts@@ -7,6 +7,7 @@ export {storedAccountMetadataFromMembership,} from "./accountMetadata.js";export { discoverSsoOrgRealm } from "./orgRealmDiscovery.js";+export { discoverEmailLogin, discoverPersonalLoginOrganization } from "./emailLoginDiscovery.js";export {MAX_SSO_ORG_HISTORY_ENTRIES,MAX_SSO_ORG_IDENTIFIER_LENGTH,diff --git a/packages/auth-client/src/types.ts b/packages/auth-client/src/types.tsindex 37cd47ff7e..58a2f20150 100644--- a/packages/auth-client/src/types.ts+++ b/packages/auth-client/src/types.ts@@ -321,6 +321,10 @@ export type AuthFlowState =| {step: "realm-confirmation";targetRegion: AuthRegion;+ /** Present for email discovery; personal verification still uses the build region. */+ email?: string;+ /** Host retains the successful personal login; declining resumes it in its original region. */+ personalLoginAvailable?: boolean;providers: ProviderConfig;methods: LoginMethod[];}@@ -352,6 +356,8 @@ export type AuthFlowAction =| {type: "realm-switch-required";targetRegion: AuthRegion;+ email?: string;+ personalLoginAvailable?: boolean;providers: ProviderConfig;methods: LoginMethod[];}@@ -387,6 +393,8 @@ export function reduceAuthFlow(return {step: "realm-confirmation",targetRegion: action.targetRegion,+ ...(action.email !== undefined ? { email: action.email } : {}),+ ...(action.personalLoginAvailable ? { personalLoginAvailable: true } : {}),providers: action.providers,methods: action.methods,};