Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(auth): route organization sign-in by auth region (#748)

bobo12c216d42621
diff --git a/README.md b/README.md
index 95dec39a61..8d8884b433 100644
--- a/README.md
+++ b/README.md
@@ -130,6 +130,7 @@ servers.
- [`DESIGN.md`](DESIGN.md) — visual design system, color tokens, and UI conventions
- [`docs/README.md`](docs/README.md) — complete documentation and rules index
+- [`docs/auth-realm-routing.md`](docs/auth-realm-routing.md) — organization SSO region discovery and session endpoint routing
- [`CONTRIBUTING.en.md`](CONTRIBUTING.en.md) — contributor setup, validation, and submission workflow
- [`AGENTS.md`](AGENTS.md) — engineering rules, launch/runtime contracts, and module boundaries
- [`docs/dev-rules/`](docs/dev-rules/) — deep-dive architecture docs (e.g. Orca multi-agent orchestration)
diff --git a/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts b/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts
index 45613aa60f..cd760d8f44 100644
--- a/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts
@@ -14,23 +14,69 @@ describe('desktop auth account-deletion lifecycle', () => {
const end = source.indexOf('\n}\n\n/**\n * Confirm deletion', start);
const body = source.slice(start, end);
- expect(body).toContain('writeSafe(ACCOUNT_DELETION_RECEIPT_KEY, challenge.receiptToken)');
- expect(body.indexOf('writeSafe(')).toBeLessThan(body.indexOf('return {'));
+ expect(body).toContain('writePersistedAccountDeletionReceipt(');
+ expect(body.indexOf('writePersistedAccountDeletionReceipt(')).toBeLessThan(
+ body.indexOf('return {'),
+ );
expect(body).not.toContain('receiptToken: challenge.receiptToken');
});
- it('recovers an ambiguous confirm through receipt status before local logout', () => {
+ it('recovers an ambiguous confirm through the receipt realm before local logout', () => {
const start = source.indexOf('export async function confirmAccountDeletion(');
const end = source.indexOf('\n}\n\n/** Query the persisted receipt', start);
const body = source.slice(start, end);
expect(body).toContain("['NETWORK_ERROR', 'REQUEST_TIMEOUT', 'INVALID_RESPONSE']");
- expect(body).toContain('client.getAccountDeletionStatus(receiptToken)');
+ expect(body).toContain('const client = createAuthClient(receipt.realm);');
+ expect(body).toContain('.getAccountDeletionStatus(receipt.receiptToken)');
expect(body).toContain("recovered.status === 'cancelled'");
- expect(body).toContain('commitAccountDeletionConfirmation(expectedIdentity, status)');
+ expect(body).toContain(
+ 'commitAccountDeletionConfirmation(expectedIdentity, receipt.realm, status)',
+ );
expect(body).not.toContain("apiFetch('/api/auth/logout'");
});
+ it('binds confirmation to the credential identity and realm that requested the challenge', () => {
+ const helperStart = source.indexOf('function writePersistedAccountDeletionReceipt(');
+ const helperEnd = source.indexOf('\n}\n\n// ── PKCE', helperStart);
+ const helperBody = source.slice(helperStart, helperEnd);
+ expect(helperBody).toContain(
+ 'serializeAccountDeletionReceiptRecord(realm, receiptToken, authIdentity)',
+ );
+
+ const requestStart = source.indexOf('export async function requestAccountDeletionChallenge()');
+ const requestEnd = source.indexOf('\n}\n\n/**\n * Confirm deletion', requestStart);
+ const requestBody = source.slice(requestStart, requestEnd);
+ expect(requestBody).toContain('const expectedIdentity = currentAccountDeletionAuthIdentity();');
+ expect(requestBody).toContain('const expectedRealm = activeAuthRealm;');
+ expect(requestBody).toMatch(
+ /writePersistedAccountDeletionReceipt\(\s*challenge\.receiptToken,\s*expectedRealm,\s*expectedIdentity,?\s*\)/,
+ );
+
+ const confirmStart = source.indexOf('export async function confirmAccountDeletion(');
+ const confirmEnd = source.indexOf('\n}\n\n/** Query the persisted receipt', confirmStart);
+ const confirmBody = source.slice(confirmStart, confirmEnd);
+ expect(confirmBody).toContain('receipt.version !== 2');
+ expect(confirmBody).toContain('receipt.authIdentity !== expectedIdentity');
+ expect(confirmBody).toContain('receipt.realm !== activeAuthRealm');
+ expect(confirmBody.indexOf('receipt.authIdentity !== expectedIdentity')).toBeLessThan(
+ confirmBody.indexOf('client.confirmAccountDeletion(token'),
+ );
+ });
+
+ it('queries a persisted deletion receipt against its original realm after logout', () => {
+ const statusStart = source.indexOf('export async function getAccountDeletionStatus()');
+ const statusEnd = source.indexOf(
+ '\n}\n\nexport function clearAccountDeletionReceipt',
+ statusStart,
+ );
+ const statusBody = source.slice(statusStart, statusEnd);
+ expect(statusBody).toContain('await loadClientEndpointsForRealm(receipt.realm);');
+ expect(statusBody).toContain(
+ 'createAuthClient(receipt.realm).getAccountDeletionStatus(receipt.receiptToken)',
+ );
+ });
+
it('preserves a confirmed receipt on local clear but drops it on ordinary logout', () => {
const localClearStart = source.indexOf(
'export function clearLocalSessionAfterAccountDeletion(): boolean {',
@@ -103,8 +149,20 @@ describe('desktop auth account-deletion lifecycle', () => {
expect(helperBody).toContain("error.code === 'ACCOUNT_UNAVAILABLE'");
expect(helperBody).toContain("void invalidateSession('account-unavailable')");
- expect(source).toContain(
- 'return runProtectedAuthRequest(() =>\n createAuthClient().getAccountDeletionAvailability(token)',
+ const availabilityStart = source.indexOf(
+ 'export function getAccountDeletionAvailability()',
+ );
+ const availabilityEnd = source.indexOf(
+ '\n}\n\n/**\n * Request an OTP',
+ availabilityStart,
+ );
+ const availabilityBody = source.slice(
+ availabilityStart,
+ availabilityEnd,
+ );
+ expect(availabilityBody).toContain('return runProtectedAuthRequest(() =>');
+ expect(availabilityBody).toContain(
+ 'createAuthClient().getAccountDeletionAvailability(token)',
);
});
});
diff --git a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts b/apps/desktop/src/main/__tests__/authHostedCallback.test.ts
index 21a2dbcf64..d486dfb4ec 100644
--- a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts
+++ b/apps/desktop/src/main/__tests__/authHostedCallback.test.ts
@@ -262,12 +262,15 @@ describe('openSystemBrowserAuthorization 分流', () => {
'\n',
);
- it('按端点清单字段分流,空值回落 loopback(默认关闭)', () => {
+ it('按本次登录区域的端点清单分流,空值回落 loopback(默认关闭)', () => {
const start = source.indexOf('async function openSystemBrowserAuthorization(');
expect(start).toBeGreaterThan(-1);
const body = source.slice(start, source.indexOf('\n}', start));
- expect(body).toContain("getClientEndpoint('authDesktopCallbackUrl')");
+ expect(body).toContain('pendingAuthRealm ?? activeAuthRealm');
+ expect(body).toContain(
+ "getClientEndpointForRealm(loginRealm, 'authDesktopCallbackUrl')",
+ );
// 三元方向:非空 → hosted,空 → loopback。写反即所有存量用户登录中断。
expect(body).toContain('? openHostedBrowserAuthorization(');
expect(body).toContain(': openLoopbackBrowserAuthorization(');
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index ad18e6ad74..834964e7c4 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -8,6 +8,14 @@ describe('auth login-flow reset', () => {
/\r\n/g,
'\n',
);
+ const deviceLinkSource = readFileSync(
+ resolve(process.cwd(), 'src/main/device-link/index.ts'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
+ const hookControlSource = readFileSync(
+ resolve(process.cwd(), 'src/main/hook-control/ipc.ts'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
it('clears renderer state, provider cache, and private tickets whenever auth is cleared', () => {
const resetStart = source.indexOf('function resetLoginFlowState(): void {');
@@ -41,15 +49,56 @@ describe('auth login-flow reset', () => {
expect(source).not.toContain('setJwt(');
});
- it('registers enterprise-id SSO discovery into the start-browser connection whitelist', () => {
- // 企业 ID discovery 的连接必须写入 discoveredMethods:start-browser 的
- // connectionId 校验以它为白名单,漏写会让该入口发起的 SSO 全部 404。
+ it('requires confirmation only when enterprise discovery crosses the build region', () => {
const start = source.indexOf("if (action.type === 'discover-sso-org') {");
expect(start).toBeGreaterThan(-1);
- const body = source.slice(start, source.indexOf('\n }', start));
- expect(body).toContain('discoveredMethods = ssoOrgDiscoveryToMethods(discovery)');
+ const body = source.slice(
+ start,
+ source.indexOf("\n if (action.type === 'request-code')", start),
+ );
+ expect(body).toContain('const methods = ssoOrgDiscoveryToMethods(discovery)');
+ expect(body).toContain('if (discovery.region !== AUTH_REGION)');
+ expect(body).toContain("type: 'realm-switch-required'");
expect(body).toContain("type: 'discovery-loaded'");
expect(body).toContain("email: ''");
+
+ // 跨区连接只有 confirm action 才写入 start-browser 白名单;弹窗阶段不能
+ // 通过伪造 connectionId 直接跳过确认。
+ const confirmStart = source.indexOf("if (action.type === 'confirm-sso-realm') {");
+ const confirmBody = source.slice(
+ confirmStart,
+ source.indexOf("\n if (action.type === 'cancel-sso-realm')", confirmStart),
+ );
+ expect(confirmBody).toContain('discoveredMethods = confirmation.methods;');
+ expect(confirmBody).toContain("type: 'discovery-loaded'");
+ });
+
+ it('clears stale organization realm state before personal login and a new discovery', () => {
+ const discoveryStart = source.indexOf(
+ 'async function discoverOrganizationRealm(org: string)',
+ );
+ const discoveryBody = source.slice(
+ discoveryStart,
+ source.indexOf('\n}', discoveryStart),
+ );
+ expect(discoveryBody).toContain('pendingAuthRealm = null;');
+
+ const actionStart = source.indexOf(
+ 'async function runLoginAction(action: DesktopLoginAction)',
+ );
+ const actionPreamble = source.slice(
+ actionStart,
+ source.indexOf('const stateBeforeAction', actionStart),
+ );
+ expect(actionPreamble).toContain("action.type === 'discover'");
+ expect(actionPreamble).toContain("action.type === 'request-code'");
+ expect(actionPreamble).toContain("action.type === 'verify-code'");
+ expect(actionPreamble).toContain(
+ "action.type === 'start-browser' && action.kind === 'social'",
+ );
+ expect(actionPreamble).toContain(
+ 'if (startsBuildRealmFlow) pendingAuthRealm = null;',
+ );
});
it('does not leave expired private tickets on a screen that can only reuse them', () => {
@@ -104,7 +153,7 @@ describe('auth login-flow reset', () => {
const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);
const initializeBody = source.slice(initializeStart, initializeEnd);
const localGuard = initializeBody.indexOf("getActiveAppSession().mode === 'local'");
- const refreshTokenRead = initializeBody.indexOf('readSafe(REFRESH_TOKEN_KEY)');
+ const refreshTokenRead = initializeBody.indexOf('readPersistedAuthSession()');
expect(localGuard).toBeGreaterThan(-1);
expect(refreshTokenRead).toBeGreaterThan(localGuard);
@@ -125,6 +174,24 @@ describe('auth login-flow reset', () => {
expect(refreshBody).toContain("refreshWasSuperseded('catch')");
});
+ it('reconnects realm-bound main clients after a runtime realm change commits its new token', () => {
+ const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');
+ const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);
+ const refreshBody = source.slice(refreshStart, refreshEnd);
+
+ expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');
+ expect(refreshBody).toContain('writePersistedAuthSession(data.refreshToken, refreshRealm);');
+ expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');
+ expect(refreshBody).toContain('previousUserId !== currentUser.id || authRealmChanged');
+ expect(refreshBody).toContain('if (authRealmChanged) {\n notifyAuthListeners();');
+
+ expect(deviceLinkSource).toContain('restartDeviceLinkForAuthRealmChange();');
+ expect(deviceLinkSource).toContain('void stopArbitrationAndTeardown()');
+ expect(deviceLinkSource).toContain('authManager.getActiveAuthRealm() !== targetRealm');
+ expect(hookControlSource).toContain('} else if (realmChanged) {');
+ expect(hookControlSource).toContain('manager?.sync();');
+ });
+
it('tears down the owner boundary before notifying runtime auth expiry', () => {
const helperStart = source.indexOf('async function expireRuntimeAuth(');
const helperEnd = source.indexOf('\n}\n\n// ── Public API', helperStart);
diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
index f30513bc2e..c402b4fa42 100644
--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
@@ -51,10 +51,13 @@ describe('passive shared-userData instance auth isolation', () => {
const guardIdx = body.indexOf('if (!opts.preservePersistedRefreshToken) {');
const passiveIdx = body.indexOf('if (isPassiveSharedUserDataInstance()) {');
expect(guardIdx).toBeGreaterThan(-1);
- // passive 判定必须落在 opts 守卫之内、三个 removeSafe 之前——即显式 preserve 与
+ // passive 判定必须落在 opts 守卫之内、四个 removeSafe 之前——即显式 preserve 与
// passive 身份是两道独立的闸,任一命中都不得删盘。
expect(passiveIdx).toBeGreaterThan(guardIdx);
- expect(body.indexOf('removeSafe(REFRESH_TOKEN_KEY);')).toBeGreaterThan(passiveIdx);
+ expect(body.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(passiveIdx);
+ expect(body.indexOf('removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);')).toBeGreaterThan(
+ passiveIdx,
+ );
expect(body.indexOf('removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);')).toBeGreaterThan(passiveIdx);
expect(body.indexOf('removeSafe(LEGACY_REFRESH_TOKEN_KEY);')).toBeGreaterThan(passiveIdx);
});
@@ -137,21 +140,35 @@ describe('passive shared-userData instance auth isolation', () => {
// 非 passive 分支里。
const passiveIdx = body.indexOf('if (isPassiveSharedUserDataInstance()) {');
expect(passiveIdx).toBeGreaterThan(-1);
- expect(body.indexOf('removeSafe(REFRESH_TOKEN_KEY);')).toBeGreaterThan(passiveIdx);
+ expect(body.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(passiveIdx);
+ expect(body.indexOf('removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);')).toBeGreaterThan(
+ passiveIdx,
+ );
expect(body.indexOf('clearReloginFlag();')).toBeGreaterThan(passiveIdx);
});
it('legacy 凭证清理:passive 启动不得删掉老构建 primary 可能还在用的文件', () => {
const start = authSource.indexOf('// Old Feishu-auth refresh tokens');
- const end = authSource.indexOf('const storedToken = readSafe(REFRESH_TOKEN_KEY);', start);
+ const end = authSource.indexOf('const storedToken = persistedSession.refreshToken;', start);
const body = authSource.slice(start, end);
// dev + packaged 共库双开是受支持的场景(--preserve-running):老构建的 primary
- // 可能仍在消费这两个 legacy 文件,passive 只是启动一下就把它们删了。
+ // 可能仍在消费三个 legacy 文件,passive 只能写入新原子记录,不能删除旧文件。
expect(body).toContain('if (!isPassiveSharedUserDataInstance()) {');
const guardIdx = body.indexOf('if (!isPassiveSharedUserDataInstance()) {');
expect(body.indexOf('removeSafe(LEGACY_REFRESH_TOKEN_KEY);')).toBeGreaterThan(guardIdx);
expect(body.indexOf('removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);')).toBeGreaterThan(guardIdx);
+ const legacyTokenIdx = body.indexOf(
+ 'const legacyToken = readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);',
+ );
+ const migrationGuardIdx = body.indexOf(
+ 'if (!isPassiveSharedUserDataInstance()) {',
+ legacyTokenIdx,
+ );
+ expect(migrationGuardIdx).toBeGreaterThan(legacyTokenIdx);
+ expect(body.indexOf('removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);')).toBeGreaterThan(
+ migrationGuardIdx,
+ );
});
it('其余整机一份的账号派生状态:canary flag 与账号删除 receipt 都不被 passive 清掉', () => {
@@ -186,8 +203,11 @@ describe('passive shared-userData instance auth isolation', () => {
// passive 冷启动拿到 INVALID_REFRESH_TOKEN,最常见的原因就是 primary 刚轮换过它。
expect(body).toContain('if (isPassiveSharedUserDataInstance()) {');
// 非 passive 也不能无条件删:判定与删除之间另一个实例可能写入了替换凭证。
- expect(body).toContain('removeSafeIfUnchanged(REFRESH_TOKEN_KEY, storedToken)');
- expect(body).not.toContain('removeSafe(REFRESH_TOKEN_KEY);');
+ expect(body).toContain(
+ 'const expectedSession = serializeAuthSessionRecord(storedRealm, storedToken);',
+ );
+ expect(body).toContain('removeSafeIfUnchanged(AUTH_SESSION_KEY, expectedSession)');
+ expect(body).not.toContain('removeSafe(AUTH_SESSION_KEY);');
// 三种结果各自如实记日志,尤其 'failed' 不得报成已清理。
expect(body).toContain("case 'deleted':");
expect(body).toContain("case 'changed':");
diff --git a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts
index 48a26c1de3..95cd2640bc 100644
--- a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts
+++ b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts
@@ -36,12 +36,12 @@ describe('desktop auth session-expiry detection', () => {
expect(body).toContain("refreshWasSuperseded('missing-persisted-token')");
// 防误踢:文件还在但读/解密失败(或加密暂不可用)是瞬时故障,按 transient 处理,
// 不得 expireRuntimeAuth——否则密钥链一次抖动就会把有效用户强制登出。
- expect(body).toContain('isPersistedSecretAbsent(REFRESH_TOKEN_KEY)');
+ expect(body).toContain('isPersistedSecretAbsent(AUTH_SESSION_KEY)');
expect(body).toContain('treating as transient');
// 瞬时分支必须重排 refresh 重试:正常 timer 已触发过,不重排则密钥链/IO 抖动
// 后有效会话在 access token 到期前没有任何后续 refresh(半死)。
expect(body).toContain('scheduleRefreshRetryAfterTransientFailure();');
- expect(body.indexOf('isPersistedSecretAbsent(REFRESH_TOKEN_KEY)')).toBeLessThan(
+ expect(body.indexOf('isPersistedSecretAbsent(AUTH_SESSION_KEY)')).toBeLessThan(
body.indexOf("await expireRuntimeAuth(previousUserId, 'credential-lost', {"),
);
// 无活会话(冷启动 / 已登出)保持静默跳过。
@@ -60,7 +60,10 @@ describe('desktop auth session-expiry detection', () => {
// 三个 refresh token 相关文件的删除必须整体收在 preserve 守卫之内。
expect(body).toContain('if (!opts.preservePersistedRefreshToken) {');
const guardIdx = body.indexOf('if (!opts.preservePersistedRefreshToken) {');
- expect(body.indexOf('removeSafe(REFRESH_TOKEN_KEY);')).toBeGreaterThan(guardIdx);
+ expect(body.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(guardIdx);
+ expect(body.indexOf('removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);')).toBeGreaterThan(
+ guardIdx,
+ );
expect(body.indexOf('removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);')).toBeGreaterThan(guardIdx);
expect(body.indexOf('removeSafe(LEGACY_REFRESH_TOKEN_KEY);')).toBeGreaterThan(guardIdx);
diff --git a/apps/desktop/src/main/__tests__/authSessionHint.test.ts b/apps/desktop/src/main/__tests__/authSessionHint.test.ts
index 5cd05afde9..ce9893320c 100644
--- a/apps/desktop/src/main/__tests__/authSessionHint.test.ts
+++ b/apps/desktop/src/main/__tests__/authSessionHint.test.ts
@@ -24,15 +24,20 @@ describe('hasPersistedSessionHint', () => {
expect(hasPersistedSessionHint(makeDeps({}))).toBe(false);
});
- it('存在持久化 refresh token → true(cloud 会话冷启动可恢复,非首启)', () => {
+ it('存在原子 auth session → true(cloud 会话冷启动可恢复,非首启)', () => {
expect(
hasPersistedSessionHint(
- makeDeps({ 'safe-storage/cindy_auth_refresh_token.enc': true }),
+ makeDeps({ 'safe-storage/cindy_auth_session_v1.enc': true }),
),
).toBe(true);
});
it('legacy token 文件同样算存量会话', () => {
+ expect(
+ hasPersistedSessionHint(
+ makeDeps({ 'safe-storage/cindy_auth_refresh_token.enc': true }),
+ ),
+ ).toBe(true);
expect(
hasPersistedSessionHint(makeDeps({ 'safe-storage/refresh_token.enc': true })),
).toBe(true);
diff --git a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
index e9d675700f..62aaa8496b 100644
--- a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
+++ b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts
@@ -9,17 +9,24 @@
* file 模式的 allowHttp 放行、init 前 getter 抛错(启动时序守卫)、sendSync IPC 形状。
*/
import path from 'node:path';
+import { EventEmitter } from 'node:events';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { TEST_CLIENT_ENDPOINTS } from '../../test/vitest/clientEndpointsFixture';
const ipcOn = vi.hoisted(() => vi.fn());
+const netRequest = vi.hoisted(() => vi.fn());
vi.mock('electron', () => ({
- app: { getPath: vi.fn(), getAppPath: vi.fn(() => '/repo/apps/desktop'), isPackaged: false, exit: vi.fn() },
+ app: {
+ getPath: vi.fn(),
+ getAppPath: vi.fn(() => '/repo/apps/desktop'),
+ isPackaged: false,
+ exit: vi.fn(),
+ },
dialog: { showMessageBoxSync: vi.fn() },
ipcMain: { on: ipcOn },
- net: { request: vi.fn() },
+ net: { request: netRequest },
}));
vi.mock('../logger', () => ({
@@ -27,9 +34,13 @@ vi.mock('../logger', () => ({
}));
import {
+ activateClientEndpointRealm,
getClientEndpoint,
+ getClientEndpointForRealm,
getResolvedClientEndpoints,
+ loadClientEndpointsForRealm,
registerClientEndpointsIpc,
+ resetClientEndpointRealm,
resetClientEndpointsForTest,
resolveClientEndpointsBlocking,
resolveEndpointSource,
@@ -40,6 +51,7 @@ import {
afterEach(() => {
resetClientEndpointsForTest();
ipcOn.mockClear();
+ netRequest.mockReset();
});
const FULL_MANIFEST = JSON.stringify({
@@ -84,7 +96,11 @@ describe('resolveEndpointSource(清单来源三选一)', () => {
},
{ kind: 'cdn' },
],
- ['dev 默认读仓内 cn 正本', { isPackaged: false, env: {} }, { kind: 'file', filePath: DEFAULT_FILE }],
+ [
+ 'dev 默认读仓内 cn 正本',
+ { isPackaged: false, env: {} },
+ { kind: 'file', filePath: DEFAULT_FILE },
+ ],
[
'dev + XDT_ENDPOINTS_CDN=1 走 CDN',
{ isPackaged: false, env: { XDT_ENDPOINTS_CDN: '1' } },
@@ -125,6 +141,22 @@ const NO_AUTO_RETRY = { autoRetryDelaysMs: [] as readonly number[] };
const okFetch = (text: string) => async () => ({ ok: true as const, text });
const failFetch = (detail: string) => async () => ({ ok: false as const, detail });
+function mockNetManifest(text: string): void {
+ const request = new EventEmitter() as EventEmitter & {
+ abort: ReturnType<typeof vi.fn>;
+ end: ReturnType<typeof vi.fn>;
+ };
+ request.abort = vi.fn();
+ request.end = vi.fn(() => {
+ const response = new EventEmitter() as EventEmitter & { statusCode: number };
+ response.statusCode = 200;
+ request.emit('response', response);
+ response.emit('data', Buffer.from(text));
+ response.emit('end');
+ });
+ netRequest.mockReturnValueOnce(request);
+}
+
describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)', () => {
it('首次成功:不进 prompt,所有值来自清单', async () => {
const promptRetry = vi.fn();
@@ -138,6 +170,35 @@ describe('resolveClientEndpointsBlocking(阻断循环,清单即唯一事实源)'
expect(promptRetry).not.toHaveBeenCalled();
});
+ it('清单自报区域与构建区域不一致时阻断,老清单缺 region 仍兼容', async () => {
+ const promptRetry = vi.fn().mockReturnValue('exit');
+ const mismatch = await resolveClientEndpointsBlocking({
+ fetchManifest: okFetch(
+ JSON.stringify({
+ ...(JSON.parse(FULL_MANIFEST) as object),
+ region: 'global',
+ }),
+ ),
+ promptRetry,
+ exitApp: vi.fn(),
+ expectedRegionWhenPresent: 'cn',
+ ...NO_AUTO_RETRY,
+ });
+ expect(mismatch).toBeNull();
+ expect(promptRetry).toHaveBeenCalledWith('region-mismatch:cn:global');
+
+ await expect(
+ resolveClientEndpointsBlocking({
+ fetchManifest: okFetch(FULL_MANIFEST),
+ promptRetry: vi.fn(),
+ exitApp: vi.fn(),
+ expectedRegionWhenPresent: 'cn',
+ }),
+ ).resolves.toMatchObject({
+ authApiBaseUrl: 'https://auth.remote.example.com',
+ });
+ });
+
it('失败 → prompt 选重试 → 第二次成功(无静默降级)', async () => {
const fetchManifest = vi
.fn<BlockingResolveDeps['fetchManifest']>()
@@ -308,7 +369,13 @@ describe('弹框前的自动重试(mac 首装瞬时失败自愈)', () => {
it.each([
['JSON 非法', 'not json at all'],
['schema 版本非法', JSON.stringify({ schemaVersion: 0 })],
- ['非空值非法', JSON.stringify({ ...(JSON.parse(FULL_MANIFEST) as object), cdnBaseUrl: 'ftp://x.example.com' })],
+ [
+ '非空值非法',
+ JSON.stringify({
+ ...(JSON.parse(FULL_MANIFEST) as object),
+ cdnBaseUrl: 'ftp://x.example.com',
+ }),
+ ],
])('%s(配置事故)不消耗重试预算,立刻弹框', async (_label, text) => {
const fetchManifest = vi.fn<BlockingResolveDeps['fetchManifest']>().mockResolvedValue({
ok: true,
@@ -417,4 +484,98 @@ describe('getter / IPC', () => {
expect(getResolvedClientEndpoints().websiteUrl).toBe('https://site.example.com');
expect(getClientEndpoint('websiteUrl')).toBe('https://site.example.com');
});
+
+ it('组织会话切换所有 token 消费端点,但安装身份与更新链保持构建区域', () => {
+ const cn = {
+ ...TEST_CLIENT_ENDPOINTS,
+ authApiBaseUrl: 'https://auth.cn.example.com',
+ oauthBrokerApiBaseUrl: 'https://oauth.cn.example.com',
+ deviceLinkApiBaseUrl: 'https://device.cn.example.com',
+ modelAccessApiBaseUrl: 'https://model.cn.example.com',
+ voiceApiBaseUrl: 'https://voice.cn.example.com',
+ websiteUrl: 'https://www.cn.example.com',
+ cdnBaseUrl: 'https://cdn.cn.example.com/app',
+ mobileUpdateBaseUrl: 'https://update.cn.example.com',
+ };
+ const global = {
+ ...TEST_CLIENT_ENDPOINTS,
+ authApiBaseUrl: 'https://auth.global.example.com',
+ oauthBrokerApiBaseUrl: 'https://oauth.global.example.com',
+ deviceLinkApiBaseUrl: 'https://device.global.example.com',
+ modelAccessApiBaseUrl: 'https://model.global.example.com',
+ voiceApiBaseUrl: 'https://voice.global.example.com',
+ websiteUrl: 'https://www.global.example.com',
+ cdnBaseUrl: 'https://cdn.global.example.com/app',
+ mobileUpdateBaseUrl: 'https://update.global.example.com',
+ };
+ resetClientEndpointsForTest(cn, {
+ buildRegion: 'cn',
+ realmEndpoints: { global },
+ });
+
+ expect(getClientEndpoint('authApiBaseUrl')).toBe(cn.authApiBaseUrl);
+ activateClientEndpointRealm('global');
+ expect(getClientEndpoint('authApiBaseUrl')).toBe(global.authApiBaseUrl);
+ expect(getClientEndpoint('oauthBrokerApiBaseUrl')).toBe(global.oauthBrokerApiBaseUrl);
+ expect(getClientEndpoint('deviceLinkApiBaseUrl')).toBe(global.deviceLinkApiBaseUrl);
+ expect(getClientEndpoint('modelAccessApiBaseUrl')).toBe(global.modelAccessApiBaseUrl);
+ expect(getClientEndpoint('voiceApiBaseUrl')).toBe(global.voiceApiBaseUrl);
+
+ expect(getClientEndpoint('websiteUrl')).toBe(cn.websiteUrl);
+ expect(getClientEndpoint('cdnBaseUrl')).toBe(cn.cdnBaseUrl);
+ expect(getClientEndpoint('mobileUpdateBaseUrl')).toBe(cn.mobileUpdateBaseUrl);
+ expect(getClientEndpointForRealm('global', 'cdnBaseUrl')).toBe(cn.cdnBaseUrl);
+
+ resetClientEndpointRealm();
+ expect(getClientEndpoint('authApiBaseUrl')).toBe(cn.authApiBaseUrl);
+ });
+
+ it('不依赖远端跨区字段,按构建期可信地址加载旧格式对端清单', async () => {
+ resetClientEndpointsForTest(TEST_CLIENT_ENDPOINTS, {
+ buildRegion: 'cn',
+ realmManifestBaseUrls: {
+ cn: 'https://manifest.cn.example.com/app',
+ global: 'https://manifest.global.example.com/app',
+ },
+ });
+ const globalManifest = {
+ ...(JSON.parse(FULL_MANIFEST) as Record<string, unknown>),
+ authApiBaseUrl: 'https://auth.global.example.com',
+ };
+ mockNetManifest(JSON.stringify(globalManifest));
+
+ await expect(loadClientEndpointsForRealm('global')).resolves.toMatchObject({
+ authApiBaseUrl: 'https://auth.global.example.com',
+ });
+ expect(netRequest).toHaveBeenCalledTimes(1);
+ expect(netRequest).toHaveBeenCalledWith(
+ expect.stringMatching(
+ /^https:\/\/manifest\.global\.example\.com\/app\/endpoint\.json\?t=\d+$/,
+ ),
+ );
+ });
+
+ it('对端清单自报 region 时必须与目标区域一致,拒绝后不污染缓存', async () => {
+ resetClientEndpointsForTest(TEST_CLIENT_ENDPOINTS, {
+ buildRegion: 'cn',
+ realmManifestBaseUrls: {
+ cn: 'https://manifest.cn.example.com/app',
+ global: 'https://manifest.global.example.com/app',
+ },
+ });
+ const globalManifest = {
+ ...(JSON.parse(FULL_MANIFEST) as Record<string, unknown>),
+ authApiBaseUrl: 'https://auth.global.example.com',
+ };
+ mockNetManifest(JSON.stringify({ ...globalManifest, region: 'cn' }));
+ mockNetManifest(JSON.stringify(globalManifest));
+
+ await expect(loadClientEndpointsForRealm('global')).rejects.toThrow(
+ 'region-mismatch:global:cn',
+ );
+ await expect(loadClientEndpointsForRealm('global')).resolves.toMatchObject({
+ authApiBaseUrl: 'https://auth.global.example.com',
+ });
+ expect(netRequest).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/apps/desktop/src/main/__tests__/endpointEnvUsageGuard.test.ts b/apps/desktop/src/main/__tests__/endpointEnvUsageGuard.test.ts
index f8b96d8d0f..43d5ae03f4 100644
--- a/apps/desktop/src/main/__tests__/endpointEnvUsageGuard.test.ts
+++ b/apps/desktop/src/main/__tests__/endpointEnvUsageGuard.test.ts
@@ -21,8 +21,9 @@ import { describe, expect, it } from 'vitest';
const SRC_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
const ENDPOINT_ENV_KEYS = [
- // 现役:端点清单自举基址(唯一烘焙远程 URL)。
+ // 现役:本区与对端的两份端点清单自举基址。
'VITE_ENDPOINT_MANIFEST_BASE_URL',
+ 'VITE_ENDPOINT_MANIFEST_PEER_BASE_URL',
// 以下为已退役键(2026-07 端点清单重构后不再注入)——保留在名单里防复活:
// 谁重新读它们,拿到的永远是空串/漂移值。
'VITE_API_BASE_URL',
diff --git a/apps/desktop/src/main/__tests__/heartbeatService.test.ts b/apps/desktop/src/main/__tests__/heartbeatService.test.ts
index 6f1c441f94..24f1e3ea8f 100644
--- a/apps/desktop/src/main/__tests__/heartbeatService.test.ts
+++ b/apps/desktop/src/main/__tests__/heartbeatService.test.ts
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
user: null,
} as TestAuthState,
authListener: null as AuthListener | null,
+ authRealm: 'cn' as 'cn' | 'global',
createHeartbeatClient: vi.fn(),
heartbeatStop: vi.fn(),
unsubscribeAuth: vi.fn(),
@@ -40,6 +41,7 @@ vi.mock('@cindy/heartbeat-client', () => ({
vi.mock('../authManager', () => ({
getAuthState: () => mocks.authState,
+ getActiveAuthRealm: () => mocks.authRealm,
onAuthStateChange: (listener: AuthListener) => {
mocks.authListener = listener;
return mocks.unsubscribeAuth;
@@ -47,7 +49,7 @@ vi.mock('../authManager', () => ({
}));
vi.mock('../clientEndpointsService', () => ({
- getClientEndpoint: () => 'https://heartbeat.example.test',
+ getClientEndpoint: () => `https://heartbeat.${mocks.authRealm}.example.test`,
}));
vi.mock('../lifecycle', () => ({
@@ -87,6 +89,7 @@ describe('heartbeat service app-mode isolation', () => {
vi.setSystemTime(new Date(2026, 6, 22, 23, 59, 0));
vi.resetModules();
mocks.authState = authState('signed-out');
+ mocks.authRealm = 'cn';
mocks.authListener = null;
mocks.onQuitDisposer = null;
mocks.createHeartbeatClient.mockReset().mockReturnValue({
@@ -116,7 +119,7 @@ describe('heartbeat service app-mode isolation', () => {
expect(mocks.createHeartbeatClient).toHaveBeenCalledTimes(1);
const options = mocks.createHeartbeatClient.mock.calls[0][0];
- expect(options.endpoint).toBe('https://heartbeat.example.test');
+ expect(options.endpoint).toBe('https://heartbeat.cn.example.test');
expect(options.host.getUid()).toBe('cloud-user-1');
pushAuthState(authState('local'));
@@ -136,6 +139,21 @@ describe('heartbeat service app-mode isolation', () => {
expect(mocks.createHeartbeatClient.mock.calls[1][0].host.getUid()).toBe('cloud-user-2');
});
+ it('restarts Cindy heartbeat when the same authenticated owner moves to another realm', async () => {
+ mocks.authState = authState('cloud', 'cloud-user-1');
+ const { initHeartbeatService } = await loadService();
+ initHeartbeatService();
+
+ mocks.authRealm = 'global';
+ pushAuthState(authState('cloud', 'cloud-user-1'));
+
+ expect(mocks.heartbeatStop).toHaveBeenCalledTimes(1);
+ expect(mocks.createHeartbeatClient).toHaveBeenCalledTimes(2);
+ expect(mocks.createHeartbeatClient.mock.calls[1][0].endpoint).toBe(
+ 'https://heartbeat.global.example.test',
+ );
+ });
+
it('keeps the TapDB daily-active cadence across signed-out, local, and cloud modes', async () => {
const { initHeartbeatService } = await loadService();
initHeartbeatService();
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index bc3f682173..cd3f978378 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -89,6 +89,51 @@ describe('serverApiFetch', () => {
);
});
+ it('refresh 切换区域后重新解析业务端点,避免新 token 重试到旧区域', async () => {
+ let baseUrl = 'https://resource.cn.example.com';
+ mocks.getAccessToken.mockReturnValueOnce('token-cn').mockReturnValueOnce('token-global');
+ mocks.refresh.mockImplementation(async () => {
+ baseUrl = 'https://resource.global.example.com';
+ return true;
+ });
+ mocks.netFetch
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 401,
+ json: async () => ({ error: { code: 'TOKEN_EXPIRED' } }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: async () => ({ ok: true }),
+ });
+ const resolveBaseUrl = vi.fn(() => baseUrl);
+
+ await expect(
+ serverApiFetch('/api/resource', {
+ baseUrl: resolveBaseUrl,
+ }),
+ ).resolves.toEqual({ ok: true });
+
+ expect(resolveBaseUrl).toHaveBeenCalledTimes(2);
+ expect(mocks.netFetch).toHaveBeenNthCalledWith(
+ 1,
+ 'https://resource.cn.example.com/api/resource',
+ expect.objectContaining({
+ headers: expect.objectContaining({ Authorization: 'Bearer token-cn' }),
+ }),
+ );
+ expect(mocks.netFetch).toHaveBeenNthCalledWith(
+ 2,
+ 'https://resource.global.example.com/api/resource',
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ Authorization: 'Bearer token-global',
+ }),
+ }),
+ );
+ });
+
it('ACCOUNT_UNAVAILABLE 不 refresh,直接完整退登', async () => {
mocks.getAccessToken.mockReturnValue('token-a');
mocks.invalidateSession.mockResolvedValue(undefined);
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 803edc6bfd..f38cce4777 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -23,8 +23,13 @@ import { machineIdSync } from 'node-machine-id';
import {
AuthApiError,
CindyAuthClient,
+ discoverSsoOrgRealm,
+ parseAccountDeletionReceiptRecord,
+ parseAuthSessionRecord,
reduceAuthFlow,
+ serializeAccountDeletionReceiptRecord,
ssoOrgDiscoveryToMethods,
+ serializeAuthSessionRecord,
type AuthFlowState,
type AuthMembership,
type AuthRegion,
@@ -59,10 +64,7 @@ import {
renderAuthLoopbackPage,
type AuthLoopbackDevBridge,
} from './authLoopbackCallback';
-import {
- createDesktopPollCredentials,
- runHostedCallbackPolling,
-} from './authHostedCallback';
+import { createDesktopPollCredentials, runHostedCallbackPolling } from './authHostedCallback';
// dev-only 登录 scenario harness(implementation-plan Step 0 WHAT4):静态 import
// (main 禁运行时动态 import),生产构建由 vite alias 把整模块替换为空 stub
// (vite.main.config.ts),运行时另有 app.isPackaged guard 双保险。
@@ -71,7 +73,14 @@ import { resolveLoginScenarioFetch } from '@cindy/auth-client/fixtures';
import { createLogger } from './logger';
import { buildFocusDeepLink } from './deepLink';
import { getResolvedMainLocale, t } from './i18n';
-import { getClientEndpoint } from './clientEndpointsService.js';
+import {
+ activateClientEndpointRealm,
+ getClientEndpoint,
+ getClientEndpointForRealm,
+ getClientEndpointRealmConfig,
+ loadClientEndpointsForRealm,
+ resetClientEndpointRealm,
+} from './clientEndpointsService.js';
import {
parseDesktopLoginAction,
type DesktopAccountDeletionChallenge,
@@ -114,11 +123,12 @@ const AUTH_REGION: AuthRegion =
import.meta.env.VITE_CINDY_AUTH_REGION === 'global' ? 'global' : 'cn';
// 端点惰性读取(勿固化成模块级常量):远程清单在 app.ready 内解析,
// 顶层求值会把值钉死在烘焙值上。clientEndpointsService 的烘焙值已含 dev fallback。
-// auth 清单字段不分 region——国内/海外两条 CDN 各发各的清单,无脑取即可。
-function authServerUrl(): string {
- return getClientEndpoint('authApiBaseUrl');
+// 默认读取构建区域;组织 SSO 发现后按冻结的 session realm 读取对应清单。
+function authServerUrl(realm: AuthRegion = activeAuthRealm): string {
+ return getClientEndpointForRealm(realm, 'authApiBaseUrl');
}
-const REFRESH_TOKEN_KEY = 'cindy_auth_refresh_token';
+const AUTH_SESSION_KEY = 'cindy_auth_session_v1';
+const LEGACY_RESOURCE_REFRESH_TOKEN_KEY = 'cindy_auth_refresh_token';
const ACCOUNT_DELETION_RECEIPT_KEY = 'cindy_auth_account_deletion_receipt';
const LEGACY_ACCOUNT_REFRESH_TOKEN_KEY = 'cindy_auth_account_refresh_token';
const LEGACY_REFRESH_TOKEN_KEY = 'refresh_token';
@@ -218,6 +228,10 @@ let authSessionTeardown: AuthSessionTeardown | null = null;
let accessToken: string | null = null;
let currentUser: CurrentUser | null = null;
+/** 已登录会话区域;安装包区域 AUTH_REGION 始终不变。 */
+let activeAuthRealm: AuthRegion = AUTH_REGION;
+/** 企业发现成功后冻结到整次 SSO 流程,reset/cancel/失败回收时清除。 */
+let pendingAuthRealm: AuthRegion | null = null;
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
let refreshPromise: Promise<boolean> | null = null;
let sessionInvalidationPromise: Promise<void> | null = null;
@@ -244,11 +258,16 @@ let loginActionPromise: Promise<DesktopLoginActionResult> | null = null;
// main-only until the final resource-token login commits.
let pendingAccountDeletionRestored = false;
let accountDeletionRestoredNoticePending = false;
-// Set only after auth-server has accepted deletion. The identity guard keeps a
-// late confirmation from tearing down a different account selected meanwhile.
-let confirmedAccountDeletionAuthIdentity: string | null = null;
-
-function createAuthClient(): CindyAuthClient {
+// Set only after auth-server has accepted deletion. The credential guard keeps a
+// late confirmation from tearing down another account or realm selected meanwhile.
+let confirmedAccountDeletionCredential: {
+ identity: string;
+ realm: AuthRegion;
+} | null = null;
+
+function createAuthClient(
+ realm: AuthRegion = pendingAuthRealm ?? activeAuthRealm,
+): CindyAuthClient {
// 登录 scenario harness 注入点(仅 client 构造参数,不替换 client、不 fake 方法;
// zod schema/错误归一/REGION_MISMATCH 路径全真)。guard:!app.isPackaged +
// XDT_LOGIN_SCENARIO(值域见 implementation-plan 附录 A,经 restart 脚本
@@ -256,11 +275,11 @@ function createAuthClient(): CindyAuthClient {
const scenarioFetch = resolveLoginScenarioFetch({
devModeActive: !app.isPackaged,
scenario: process.env.XDT_LOGIN_SCENARIO,
- region: AUTH_REGION,
+ region: realm,
});
return new CindyAuthClient({
- baseUrl: authServerUrl(),
- region: AUTH_REGION,
+ baseUrl: authServerUrl(realm),
+ region: realm,
deviceId,
clientType: 'desktop',
locale: getResolvedMainLocale(),
@@ -349,7 +368,8 @@ function isPersistedSecretAbsent(key: string): boolean {
}
}
-function writeSafe(key: string, value: string): boolean { try {
+function writeSafe(key: string, value: string): boolean {
+ try {
if (!safeStorage.isEncryptionAvailable()) return false;
const dir = SAFE_STORAGE_DIR();
fs.mkdirSync(dir, { recursive: true });
@@ -372,6 +392,42 @@ function removeSafe(key: string): void {
}
}
+function readPersistedAuthSession() {
+ return parseAuthSessionRecord(readSafe(AUTH_SESSION_KEY));
+}
+
+function readPersistedRefreshToken(realm = activeAuthRealm): string | null {
+ const session = readPersistedAuthSession();
+ return session?.realm === realm ? session.refreshToken : null;
+}
+
+function writePersistedAuthSession(refreshToken: string, realm = activeAuthRealm): boolean {
+ return writeSafe(AUTH_SESSION_KEY, serializeAuthSessionRecord(realm, refreshToken));
+}
+
+function readPersistedAccountDeletionReceipt() {
+ const raw = readSafe(ACCOUNT_DELETION_RECEIPT_KEY);
+ const record = parseAccountDeletionReceiptRecord(raw);
+ if (record) return record;
+ // Older builds stored the opaque receipt directly. Those receipts could only
+ // have been issued by the build region, so preserve that deterministic
+ // migration rule without trying another region.
+ return raw && !raw.trimStart().startsWith('{')
+ ? { version: 1 as const, realm: AUTH_REGION, receiptToken: raw }
+ : null;
+}
+
+function writePersistedAccountDeletionReceipt(
+ receiptToken: string,
+ realm: AuthRegion,
+ authIdentity: string,
+): boolean {
+ return writeSafe(
+ ACCOUNT_DELETION_RECEIPT_KEY,
+ serializeAccountDeletionReceiptRecord(realm, receiptToken, authIdentity),
+ );
+}
+
/**
* 只在磁盘内容仍等于 `expected` 时删除(compare-and-delete)。
*
@@ -442,10 +498,7 @@ function removeSafeIfUnchanged(key: string, expected: string): RemoveIfUnchanged
function generatePKCE(): { codeVerifier: string; codeChallenge: string } {
const codeVerifier = crypto.randomBytes(32).toString('base64url');
- const codeChallenge = crypto
- .createHash('sha256')
- .update(codeVerifier)
- .digest('base64url');
+ const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
return { codeVerifier, codeChallenge };
}
@@ -477,9 +530,8 @@ async function apiFetch<T>(
}
const effectiveTimeout = options?.timeoutMs ?? API_FETCH_TIMEOUT_MS;
const controller = new AbortController();
- const timer = effectiveTimeout > 0
- ? setTimeout(() => controller.abort(), effectiveTimeout)
- : undefined;
+ const timer =
+ effectiveTimeout > 0 ? setTimeout(() => controller.abort(), effectiveTimeout) : undefined;
try {
const response = await net.fetch(url, {
method,
@@ -502,13 +554,17 @@ async function apiFetch<T>(
}
}
-function requestAuthRefresh(refreshToken: string): Promise<AuthRefreshResult> {
+function requestAuthRefresh(
+ refreshToken: string,
+ realm = activeAuthRealm,
+): Promise<AuthRefreshResult> {
// refresh 是 token-rotating 端点,禁用 abort timeout——若服务端已轮换但
// 客户端 abort,重试旧 token 会触发 INVALID_REFRESH_TOKEN。
return apiFetch<RefreshResponse | AuthErrorResponse>('/api/auth/refresh', {
method: 'POST',
body: { refreshToken, deviceId },
timeoutMs: 0,
+ baseUrl: authServerUrl(realm),
});
}
@@ -691,7 +747,8 @@ async function openSystemBrowserAuthorization(
input: BrowserAuthorizationInput,
signal: AbortSignal,
): Promise<{ code: string } | { error: string }> {
- const hostedCallbackUrl = getClientEndpoint('authDesktopCallbackUrl');
+ const loginRealm = pendingAuthRealm ?? activeAuthRealm;
+ const hostedCallbackUrl = getClientEndpointForRealm(loginRealm, 'authDesktopCallbackUrl');
return hostedCallbackUrl
? openHostedBrowserAuthorization(input, hostedCallbackUrl, signal)
: openLoopbackBrowserAuthorization(input, signal);
@@ -712,7 +769,9 @@ async function openLoopbackBrowserAuthorization(
return renderAuthLoopbackPage({
htmlLang: getResolvedMainLocale(),
variant: isError ? 'error' : 'success',
- title: t(isError ? 'login.browserCallback.errorTitle' : 'login.browserCallback.successTitle'),
+ title: t(
+ isError ? 'login.browserCallback.errorTitle' : 'login.browserCallback.successTitle',
+ ),
body: t(isError ? 'login.browserCallback.errorBody' : 'login.browserCallback.successBody'),
detail: isError ? result.error : undefined,
action: {
@@ -797,9 +856,7 @@ function scheduleRefresh(token: string): void {
// 轮换本身不会踢人:2026-07-27 两个实例每 55 分钟互刷一次,primary 每次都靠
// replacement-retry 恢复,一次没掉线;把 primary 踢下线的是删除凭证。
try {
- const payload = JSON.parse(
- Buffer.from(token.split('.')[1], 'base64').toString('utf-8'),
- );
+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString('utf-8'));
const delay = (payload.exp - 300) * 1000 - Date.now();
if (delay <= 0) {
refresh();
@@ -928,6 +985,7 @@ async function runAuthRefreshWithReplacementRetry(
initialRefreshToken: string,
opts: {
phase: 'cold-start' | 'runtime';
+ realm: AuthRegion;
withTransientRetry: boolean;
rateLimitDelayMs?: number;
onFailure?: (info: RefreshFailureInfo) => void;
@@ -941,8 +999,8 @@ async function runAuthRefreshWithReplacementRetry(
failureAction?: RefreshFailureAction;
}> {
const run = await runRefreshWithReplacementRetry(initialRefreshToken, {
- doRefresh: requestAuthRefresh,
- readLatestStoredToken: () => readSafe(REFRESH_TOKEN_KEY),
+ doRefresh: (refreshToken) => requestAuthRefresh(refreshToken, opts.realm),
+ readLatestStoredToken: () => readPersistedRefreshToken(opts.realm),
transientRetry: opts.withTransientRetry
? {
rateLimitDelayMs: opts.rateLimitDelayMs,
@@ -1040,7 +1098,7 @@ function snapshotAuthState(): AuthState {
isAuthenticated: isCloudAuthenticated,
isCanary: currentUser !== null && canaryFlagStore.read(),
deviceId,
- hasAccountDeletionReceipt: readSafe(ACCOUNT_DELETION_RECEIPT_KEY) !== null,
+ hasAccountDeletionReceipt: readPersistedAccountDeletionReceipt() !== null,
accountDeletionRestored: accountDeletionRestoredNoticePending,
};
}
@@ -1055,7 +1113,7 @@ function snapshotLoggedOutAuthState(): AuthState {
isAuthenticated: false,
isCanary: false,
deviceId,
- hasAccountDeletionReceipt: readSafe(ACCOUNT_DELETION_RECEIPT_KEY) !== null,
+ hasAccountDeletionReceipt: readPersistedAccountDeletionReceipt() !== null,
accountDeletionRestored: false,
};
}
@@ -1133,9 +1191,15 @@ function resetLoginFlowState(): void {
pendingLoginTicket = null;
pendingBindTicket = null;
pendingSsoVerificationTicket = null;
+ pendingAuthRealm = null;
pendingAccountDeletionRestored = false;
}
+function resetActiveAuthRealmToBuild(): void {
+ activeAuthRealm = AUTH_REGION;
+ resetClientEndpointRealm();
+}
+
async function reloadPerAccountIntegrationsFromDisk(_accessToken: string | null): Promise<void> {
void _accessToken;
// 登录账号级集成清单当前为空(见 clearPerAccountIntegrations 顶注)。
@@ -1192,7 +1256,7 @@ function clearAuth(
pendingAccountToken = null;
currentUser = null;
accountDeletionRestoredNoticePending = false;
- confirmedAccountDeletionAuthIdentity = null;
+ confirmedAccountDeletionCredential = null;
resetLoginFlowState();
persistedRefreshTokenNeedsIdentityCheck = false;
lastAcceptedRefreshToken = null;
@@ -1211,11 +1275,13 @@ function clearAuth(
'passive shared-userData instance keeps the persisted refresh token (local sign-out only)',
);
} else {
- removeSafe(REFRESH_TOKEN_KEY);
+ removeSafe(AUTH_SESSION_KEY);
+ removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);
removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);
removeSafe(LEGACY_REFRESH_TOKEN_KEY);
}
}
+ resetActiveAuthRealmToBuild();
// 未登录时固定使用 stable;同步中的旧请求会被 authStateEpoch 守卫丢弃。
// canary-flag.json 同样是整机一份的账号派生状态:passive 清掉它,packaged primary
// 下次更新轮询就会把自己当 stable 用户,拉到错误的 manifest(见 manifestService
@@ -1260,7 +1326,9 @@ async function expireRuntimeAuth(
if (accountSwitchTeardown) {
await accountSwitchTeardown({ previousUserId, nextUserId: 'signed-out' });
} else {
- log.warn('runtime auth expiry teardown hook is not registered; falling back to localDb close');
+ log.warn(
+ 'runtime auth expiry teardown hook is not registered; falling back to localDb close',
+ );
}
} catch (err) {
// A teardown failure must not restore an expired credential. Continue with
@@ -1344,6 +1412,11 @@ export function getAccessToken(): string | null {
return accessToken;
}
+/** 当前已认证会话的数据区域;主进程长连接据此识别同账号的跨区切换。 */
+export function getActiveAuthRealm(): AuthRegion {
+ return activeAuthRealm;
+}
+
/** SkillHub v0.2.1: 返回当前登录用户 id(cuid),未登录时返回 null */
export function getCurrentUserId(): string | null {
return currentUser?.id ?? null;
@@ -1411,16 +1484,23 @@ function currentAccountDeletionAuthIdentity(): string | null {
function commitAccountDeletionConfirmation(
expectedIdentity: string,
+ expectedRealm: AuthRegion,
status: AccountDeletionStatus,
): AccountDeletionStatus {
- if (currentAccountDeletionAuthIdentity() !== expectedIdentity) {
+ if (
+ currentAccountDeletionAuthIdentity() !== expectedIdentity ||
+ activeAuthRealm !== expectedRealm
+ ) {
throw new AuthApiError(
'AUTH_FLOW_SUPERSEDED',
409,
'Account deletion was superseded by a newer auth action',
);
}
- confirmedAccountDeletionAuthIdentity = expectedIdentity;
+ confirmedAccountDeletionCredential = {
+ identity: expectedIdentity,
+ realm: expectedRealm,
+ };
return status;
}
@@ -1443,9 +1523,7 @@ async function runProtectedAuthRequest<T>(request: () => Promise<T>): Promise<T>
/** Server-controlled visibility and verification channel for personal-account deletion. */
export function getAccountDeletionAvailability(): Promise<AccountDeletionAvailability> {
const token = requireAccountDeletionAccessToken();
- return runProtectedAuthRequest(() =>
- createAuthClient().getAccountDeletionAvailability(token),
- );
+ return runProtectedAuthRequest(() => createAuthClient().getAccountDeletionAvailability(token));
}
/**
@@ -1454,12 +1532,29 @@ export function getAccountDeletionAvailability(): Promise<AccountDeletionAvailab
* desktop's immediate local logout after confirmation.
*/
export async function requestAccountDeletionChallenge(): Promise<DesktopAccountDeletionChallenge> {
- confirmedAccountDeletionAuthIdentity = null;
+ confirmedAccountDeletionCredential = null;
const token = requireAccountDeletionAccessToken();
+ const expectedIdentity = currentAccountDeletionAuthIdentity();
+ const expectedRealm = activeAuthRealm;
+ if (!expectedIdentity) {
+ throw new AuthApiError('UNAUTHENTICATED', 401, 'Account deletion requires an active login');
+ }
const challenge = await runProtectedAuthRequest(() =>
- createAuthClient().requestAccountDeletionChallenge(token),
+ createAuthClient(expectedRealm).requestAccountDeletionChallenge(token),
);
- if (!writeSafe(ACCOUNT_DELETION_RECEIPT_KEY, challenge.receiptToken)) {
+ if (
+ currentAccountDeletionAuthIdentity() !== expectedIdentity ||
+ activeAuthRealm !== expectedRealm
+ ) {
+ throw new AuthApiError(
+ 'AUTH_FLOW_SUPERSEDED',
+ 409,
+ 'Account deletion was superseded by a newer auth action',
+ );
+ }
+ if (
+ !writePersistedAccountDeletionReceipt(challenge.receiptToken, expectedRealm, expectedIdentity)
+ ) {
throw new AuthApiError(
'ACCOUNT_DELETION_RECEIPT_STORE_FAILED',
0,
@@ -1487,22 +1582,34 @@ export async function confirmAccountDeletion(input: {
if (!expectedIdentity) {
throw new AuthApiError('UNAUTHENTICATED', 401, 'Account deletion requires an active login');
}
- confirmedAccountDeletionAuthIdentity = null;
- const receiptToken = readSafe(ACCOUNT_DELETION_RECEIPT_KEY);
- if (!receiptToken) {
+ confirmedAccountDeletionCredential = null;
+ const receipt = readPersistedAccountDeletionReceipt();
+ if (!receipt) {
throw new AuthApiError(
'ACCOUNT_DELETION_RECEIPT_MISSING',
400,
'Request a new account deletion challenge',
);
}
- const client = createAuthClient();
+ if (
+ receipt.version !== 2 ||
+ receipt.authIdentity !== expectedIdentity ||
+ receipt.realm !== activeAuthRealm
+ ) {
+ removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);
+ throw new AuthApiError(
+ 'ACCOUNT_DELETION_RECEIPT_MISSING',
+ 400,
+ 'Request a new account deletion challenge',
+ );
+ }
+ const client = createAuthClient(receipt.realm);
let status: AccountDeletionStatus;
try {
status = await runProtectedAuthRequest(() =>
client.confirmAccountDeletion(token, {
...input,
- receiptToken,
+ receiptToken: receipt.receiptToken,
acknowledged: true,
}),
);
@@ -1511,18 +1618,19 @@ export async function confirmAccountDeletion(input: {
error instanceof AuthApiError &&
['NETWORK_ERROR', 'REQUEST_TIMEOUT', 'INVALID_RESPONSE'].includes(error.code);
if (!ambiguous) throw error;
- const recovered = await client.getAccountDeletionStatus(receiptToken).catch(() => null);
+ const recovered = await client.getAccountDeletionStatus(receipt.receiptToken).catch(() => null);
if (!recovered || recovered.status === 'cancelled') throw error;
status = recovered;
}
- return commitAccountDeletionConfirmation(expectedIdentity, status);
+ return commitAccountDeletionConfirmation(expectedIdentity, receipt.realm, status);
}
/** Query the persisted receipt without requiring an authenticated session. */
export async function getAccountDeletionStatus(): Promise<AccountDeletionStatus | null> {
- const receiptToken = readSafe(ACCOUNT_DELETION_RECEIPT_KEY);
- if (!receiptToken) return null;
- return createAuthClient().getAccountDeletionStatus(receiptToken);
+ const receipt = readPersistedAccountDeletionReceipt();
+ if (!receipt) return null;
+ await loadClientEndpointsForRealm(receipt.realm);
+ return createAuthClient(receipt.realm).getAccountDeletionStatus(receipt.receiptToken);
}
/**
@@ -1555,8 +1663,9 @@ export function consumeAccountDeletionRestoredNotice(): boolean {
*/
export function isConfirmedAccountDeletionSessionCurrent(): boolean {
return (
- confirmedAccountDeletionAuthIdentity !== null &&
- currentAccountDeletionAuthIdentity() === confirmedAccountDeletionAuthIdentity
+ confirmedAccountDeletionCredential !== null &&
+ currentAccountDeletionAuthIdentity() === confirmedAccountDeletionCredential.identity &&
+ activeAuthRealm === confirmedAccountDeletionCredential.realm
);
}
@@ -1704,7 +1813,8 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
reloginFlag.version,
);
lastAcceptedRefreshToken = null;
- removeSafe(REFRESH_TOKEN_KEY);
+ removeSafe(AUTH_SESSION_KEY);
+ removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);
pendingAccountToken = null;
removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);
removeSafe(LEGACY_REFRESH_TOKEN_KEY);
@@ -1716,7 +1826,7 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
// Old Feishu-auth refresh tokens are intentionally not portable to auth-server.
// 早期测试版曾持久化 account refresh token;该会话现已收窄为登录期内存态。
//
- // 这两个 legacy 文件同样是整机一份,而 dev + packaged 共库双开是受支持的场景
+ // 三个 legacy 凭证文件同样是整机一份,而 dev + packaged 共库双开是受支持的场景
// (--preserve-running):老构建的 primary 可能还在消费它们,passive 只是启动一下
// 就把它们删掉,等于删了对方的活凭证。清理属于「搬家式迁移」,留给独占启动的
// 非 passive 实例做。
@@ -1724,18 +1834,44 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
removeSafe(LEGACY_REFRESH_TOKEN_KEY);
removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);
}
- const storedToken = readSafe(REFRESH_TOKEN_KEY);
- if (!storedToken) {
+ let persistedSession = readPersistedAuthSession();
+ if (!persistedSession) {
+ // 旧版只保存裸 refresh token;迁移时按安装包区域解释,并以单个加密 JSON
+ // 原子记录替代,确保 token 与 realm 永不分离。passive 可以写入有效的新记录,
+ // 但旧文件仍留给可能正在消费它的旧版 primary。
+ const legacyToken = readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);
+ if (legacyToken && writePersistedAuthSession(legacyToken, AUTH_REGION)) {
+ if (!isPassiveSharedUserDataInstance()) {
+ removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);
+ }
+ persistedSession = { version: 1, realm: AUTH_REGION, refreshToken: legacyToken };
+ }
+ }
+ if (!persistedSession) {
+ commitActiveAppSession('signed-out');
+ return snapshotLoggedOutAuthState();
+ }
+ try {
+ await loadClientEndpointsForRealm(persistedSession.realm);
+ activateClientEndpointRealm(persistedSession.realm);
+ activeAuthRealm = persistedSession.realm;
+ } catch (error) {
+ // 对端区域清单暂不可用时保留原子凭据;退回构建区 refresh 会把有效 token
+ // 当成非法凭据,因此本次仅以未登录放行 UI,下一次 initialize/重启可重试。
+ log.warn('persisted auth realm manifest unavailable; keeping session for retry', error);
commitActiveAppSession('signed-out');
return snapshotLoggedOutAuthState();
}
+ const storedToken = persistedSession.refreshToken;
// 进程内去重:主窗流程还挂着(黑洞网络)时,副窗 / 右侧栏窗口 mount 触发的
// initialize() 复用同一个 in-flight promise,避免并发轮换同一枚 refresh token。
if (coldStartAuthInFlight === null) {
- coldStartAuthInFlight = runColdStartRefreshFlow(storedToken).finally(() => {
- coldStartAuthInFlight = null;
- });
+ coldStartAuthInFlight = runColdStartRefreshFlow(storedToken, persistedSession.realm).finally(
+ () => {
+ coldStartAuthInFlight = null;
+ },
+ );
}
// 黑洞 / captive-portal 网络护栏:限时等待,超时先以未登录返回解锁 splash,
// 流程继续后台跑;迟到成功由流程内部广播登录态(renderer 自动跳回主界面)。
@@ -1753,8 +1889,7 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
log.info(
`cold-start auth settled after startup gate timeout — isAuthenticated=${state.isAuthenticated}`,
),
- onLateError: (err) =>
- log.error('cold-start auth flow threw after startup gate timeout', err),
+ onLateError: (err) => log.error('cold-start auth flow threw after startup gate timeout', err),
});
}
@@ -1764,7 +1899,10 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
* authStateEpoch:用户手动登录 / 登出过就整体丢弃迟到结果,绝不覆盖更新的登录态、
* 不删除新登录写入的 refresh token(见 authStateEpoch 常量注释)。
*/
-async function runColdStartRefreshFlow(storedToken: string): Promise<AuthState> {
+async function runColdStartRefreshFlow(
+ storedToken: string,
+ storedRealm: AuthRegion,
+): Promise<AuthState> {
const epochAtStart = authStateEpoch;
let releaseBoundary: (() => void) | null = null;
const epochChanged = (point: string): boolean => {
@@ -1790,6 +1928,7 @@ async function runColdStartRefreshFlow(storedToken: string): Promise<AuthState>
failureAction,
} = await runAuthRefreshWithReplacementRetry(storedToken, {
phase: 'cold-start',
+ realm: storedRealm,
withTransientRetry: true,
rateLimitDelayMs: 0,
onFailure: ({ attempt, status, code, definitive, willRetry }) =>
@@ -1802,6 +1941,14 @@ async function runColdStartRefreshFlow(storedToken: string): Promise<AuthState>
if (epochChanged('after-refresh')) {
return snapshotAuthState();
}
+ const latestSession = readPersistedAuthSession();
+ if (latestSession && latestSession.realm !== storedRealm) {
+ // 共享 userData 的另一个实例已切到其它区域。旧区域请求无论成功失败都不能
+ // 覆盖/删除新原子记录;本实例本次以未登录返回,后续 initialize 可加载新清单。
+ log.warn('cold-start auth realm changed on disk; discarding stale refresh result');
+ commitActiveAppSession('signed-out');
+ return snapshotLoggedOutAuthState();
+ }
if (!refreshResult.ok) {
// 只在「确定性凭据失效」时清除 token。429 限流 / 5xx / 断网等瞬时失败保留 token,
// 让下次启动(或后续 refresh)能恢复登录,避免冷启动撞限流 / 网络抖动即被永久登出。
@@ -1817,27 +1964,29 @@ async function runColdStartRefreshFlow(storedToken: string): Promise<AuthState>
'cold-start refresh: definitive credential failure — passive shared-userData instance starts logged out and keeps the persisted refresh token',
);
} else {
- switch (removeSafeIfUnchanged(REFRESH_TOKEN_KEY, storedToken)) {
+ const expectedSession = serializeAuthSessionRecord(storedRealm, storedToken);
+ switch (removeSafeIfUnchanged(AUTH_SESSION_KEY, expectedSession)) {
case 'deleted':
log.warn(
- 'cold-start refresh: definitive credential failure — cleared persisted refresh token',
+ 'cold-start refresh: definitive credential failure — cleared persisted auth session',
);
break;
case 'changed':
- // 判定失败后磁盘 token 已被换掉(另一个实例写入了替换凭证):那枚不在
- // 本次判定范围内,不能删。
+ // 判定失败后磁盘会话已被换掉(另一个实例写入了新 token 或 realm):
+ // 那枚不在本次判定范围内,不能删。
log.warn(
- 'cold-start refresh: definitive credential failure, but the persisted refresh token changed meanwhile — keeping the replacement',
+ 'cold-start refresh: definitive credential failure, but the persisted auth session changed meanwhile — keeping the replacement',
);
break;
case 'failed':
// 删除真的失败了:凭证仍在盘上,下次启动会再判一次。不能报成已清理。
log.error(
- 'cold-start refresh: definitive credential failure, but deleting the persisted refresh token failed — it is still on disk',
+ 'cold-start refresh: definitive credential failure, but deleting the persisted auth session failed — it is still on disk',
);
break;
}
}
+ resetActiveAuthRealmToBuild();
} else if (action.kind === 'replacement-retry') {
log.warn(
`cold-start refresh failed for a stale token after ${attempts} attempt(s) — keeping latest refresh token, starting logged out`,
@@ -1874,7 +2023,7 @@ async function runColdStartRefreshFlow(storedToken: string): Promise<AuthState>
releaseBoundary = null;
return snapshotAuthState();
}
- writeSafe(REFRESH_TOKEN_KEY, refreshData.refreshToken);
+ writePersistedAuthSession(refreshData.refreshToken);
lastAcceptedRefreshToken = refreshData.refreshToken;
accessToken = refreshData.accessToken;
@@ -1906,7 +2055,10 @@ async function runColdStartRefreshFlow(storedToken: string): Promise<AuthState>
// **之后**的本地状态同步代码(writeSafe / provider owner reconcile 等)抛异常——
// 此时新 refresh token 已轮换并落盘,删除它只会把有效凭据丢掉。保留 token、记录
// 错误,本次以未登录返回,留待下次启动自愈。
- log.error('cold-start auth initialize threw after refresh — keeping persisted refresh token', err);
+ log.error(
+ 'cold-start auth initialize threw after refresh — keeping persisted refresh token',
+ err,
+ );
// 迟到守卫③:异常清理同样不能覆盖用户手动登录后的状态。
if (!epochChanged('catch')) {
accessToken = null;
@@ -1919,9 +2071,7 @@ async function runColdStartRefreshFlow(storedToken: string): Promise<AuthState>
releaseBoundary?.();
releaseBoundary = null;
if (!epochChanged('catch-return')) commitActiveAppSession('signed-out');
- return epochChanged('catch-return-state')
- ? snapshotAuthState()
- : snapshotLoggedOutAuthState();
+ return epochChanged('catch-return-state') ? snapshotAuthState() : snapshotLoggedOutAuthState();
}
}
@@ -1932,7 +2082,8 @@ async function loadLoginProviders(): Promise<AuthFlowState> {
pendingBindTicket = null;
pendingSsoVerificationTicket = null;
pendingAccountDeletionRestored = false;
- providerConfig = await createAuthClient().getProviders();
+ pendingAuthRealm = null;
+ providerConfig = await createAuthClient(AUTH_REGION).getProviders();
loginFlowState = reduceAuthFlow(loginFlowState, {
type: 'providers-loaded',
providers: providerConfig,
@@ -1940,6 +2091,35 @@ async function loadLoginProviders(): Promise<AuthFlowState> {
return loginFlowState;
}
+async function discoverOrganizationRealm(org: string) {
+ // 新的一次组织发现不得复用上一轮成功结果;只有本轮双区判定成功后才重新冻结。
+ pendingAuthRealm = null;
+ const realmConfig = getClientEndpointRealmConfig();
+ if (!realmConfig.crossRealmOrgLoginEnabled || !realmConfig.realmManifestBaseUrls) {
+ pendingAuthRealm = AUTH_REGION;
+ return createAuthClient(AUTH_REGION).discoverSsoOrg(org);
+ }
+
+ // 先并行加载/校验两区清单,再并行做 home-realm discovery。任一清单或请求
+ // 不可用都 fail closed,不凭另一侧成功结果猜区域;只有发现结果跨出安装包
+ // 区域时,后续状态机才要求用户确认。
+ try {
+ await Promise.all([loadClientEndpointsForRealm('cn'), loadClientEndpointsForRealm('global')]);
+ } catch {
+ throw new AuthApiError(
+ 'ORG_REALM_UNAVAILABLE',
+ 503,
+ 'Unable to load both enterprise auth region manifests',
+ );
+ }
+ const selected = await discoverSsoOrgRealm(org, {
+ cn: createAuthClient('cn'),
+ global: createAuthClient('global'),
+ });
+ pendingAuthRealm = selected.region;
+ return selected.discovery;
+}
+
export async function getLoginState(): Promise<DesktopLoginActionResult> {
try {
if (loginFlowState) return { success: true, state: loginFlowState };
@@ -2012,7 +2192,10 @@ async function completeLogin(
accessToken = outcome.accessToken;
persistedRefreshTokenNeedsIdentityCheck = false;
clearReplacementIntegrationReloadTimers();
- writeSafe(REFRESH_TOKEN_KEY, outcome.refreshToken);
+ const committedRealm = pendingAuthRealm ?? AUTH_REGION;
+ activateClientEndpointRealm(committedRealm);
+ activeAuthRealm = committedRealm;
+ writePersistedAuthSession(outcome.refreshToken, committedRealm);
removeSafe(LEGACY_REFRESH_TOKEN_KEY);
lastAcceptedRefreshToken = outcome.refreshToken;
removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);
@@ -2022,6 +2205,7 @@ async function completeLogin(
passiveLocalSignOut = false;
currentUser = nextUser;
commitActiveAppSession('cloud', currentUser.id);
+ pendingAuthRealm = null;
} finally {
releaseBoundary?.();
}
@@ -2074,7 +2258,15 @@ async function acceptLoginOutcome(outcome: LoginOutcome): Promise<AuthFlowState>
}
async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginActionResult> {
- const client = createAuthClient();
+ const startsBuildRealmFlow =
+ action.type === 'discover' ||
+ action.type === 'request-code' ||
+ action.type === 'verify-code' ||
+ (action.type === 'start-browser' && action.kind === 'social');
+ if (startsBuildRealmFlow) pendingAuthRealm = null;
+ const client = createAuthClient(
+ startsBuildRealmFlow ? AUTH_REGION : pendingAuthRealm ?? activeAuthRealm,
+ );
const stateBeforeAction = loginFlowState?.step === 'error' ? null : loginFlowState;
try {
// Cancellation is intercepted by dispatchLoginAction so it can settle the
@@ -2085,6 +2277,43 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA
if (action.type === 'reset') {
return { success: true, state: await loadLoginProviders() };
}
+ if (action.type === 'confirm-sso-realm') {
+ const confirmation = loginFlowState;
+ if (
+ confirmation?.step !== 'realm-confirmation' ||
+ pendingAuthRealm !== confirmation.targetRegion
+ ) {
+ throw new AuthApiError(
+ 'INVALID_AUTH_ACTION',
+ 400,
+ 'No enterprise region switch is waiting for confirmation',
+ );
+ }
+ discoveredMethods = confirmation.methods;
+ loginFlowState = reduceAuthFlow(loginFlowState, {
+ type: 'discovery-loaded',
+ email: '',
+ methods: confirmation.methods,
+ });
+ return { success: true, state: loginFlowState };
+ }
+ if (action.type === 'cancel-sso-realm') {
+ const confirmation = loginFlowState;
+ if (confirmation?.step !== 'realm-confirmation') {
+ throw new AuthApiError(
+ 'INVALID_AUTH_ACTION',
+ 400,
+ 'No enterprise region switch is waiting for cancellation',
+ );
+ }
+ pendingAuthRealm = null;
+ discoveredMethods = [];
+ loginFlowState = reduceAuthFlow(loginFlowState, {
+ type: 'providers-loaded',
+ providers: confirmation.providers,
+ });
+ return { success: true, state: loginFlowState };
+ }
if (!providerConfig) await loadLoginProviders();
if (action.type === 'discover') {
@@ -2099,10 +2328,29 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA
}
// 企业 SSO 入口(按组织 ID/slug/已验证域名):结果映射进 method-choice,
- // 使 start-browser 的 connectionId 白名单校验与连接选择 UI 直接复用。
+ // 同区域直接进入连接选择;跨区域先进入确认状态,确认后才把连接写入
+ // start-browser 白名单并允许继续 SSO。
if (action.type === 'discover-sso-org') {
- const discovery = await client.discoverSsoOrg(action.org.trim().toLowerCase());
- discoveredMethods = ssoOrgDiscoveryToMethods(discovery);
+ const discovery = await discoverOrganizationRealm(action.org.trim().toLowerCase());
+ const methods = ssoOrgDiscoveryToMethods(discovery);
+ if (discovery.region !== AUTH_REGION) {
+ if (!providerConfig) {
+ throw new AuthApiError(
+ 'AUTH_SERVICE_UNAVAILABLE',
+ 503,
+ 'Login provider configuration is unavailable',
+ );
+ }
+ discoveredMethods = [];
+ loginFlowState = reduceAuthFlow(loginFlowState, {
+ type: 'realm-switch-required',
+ targetRegion: discovery.region,
+ providers: providerConfig,
+ methods,
+ });
+ return { success: true, state: loginFlowState };
+ }
+ discoveredMethods = methods;
loginFlowState = reduceAuthFlow(loginFlowState, {
type: 'discovery-loaded',
email: '',
@@ -2285,12 +2533,14 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA
'INVALID_AUTH_CODE',
'INVALID_TOKEN',
'TOKEN_EXPIRED',
+ 'USER_CANCELLED',
].includes(code);
if (flowCannotRetry) {
pendingAccountToken = null;
pendingLoginTicket = null;
pendingBindTicket = null;
pendingSsoVerificationTicket = null;
+ pendingAuthRealm = null;
}
// Keep the last usable screen so validation/network failures can be retried
// without discarding the entered identifier or requesting another code.
@@ -2348,7 +2598,19 @@ export async function refresh(): Promise<boolean> {
);
return true;
};
- const storedToken = readSafe(REFRESH_TOKEN_KEY);
+ const persistedSession = readPersistedAuthSession();
+ const refreshRealm = persistedSession?.realm ?? activeAuthRealm;
+ if (persistedSession && persistedSession.realm !== activeAuthRealm) {
+ try {
+ await loadClientEndpointsForRealm(persistedSession.realm);
+ } catch (error) {
+ log.warn('runtime auth realm manifest unavailable; retrying later', error);
+ scheduleRefreshRetryAfterTransientFailure();
+ return false;
+ }
+ }
+ const storedToken =
+ persistedSession?.realm === refreshRealm ? persistedSession.refreshToken : null;
if (!storedToken) {
// 磁盘 refresh token 消失但本进程仍持有活会话:本进程内 logout 会同步清内存态
// 并取消 refresh timer,冷启动 / 已登出时 currentUser 为 null —— 所以这个组合
@@ -2357,7 +2619,7 @@ export async function refresh(): Promise<boolean> {
// 「自以为登录、实际已死」的半死状态(模型源消失、device-link 无限 401)。
if (currentUser !== null) {
if (refreshWasSuperseded('missing-persisted-token')) return false;
- if (!isPersistedSecretAbsent(REFRESH_TOKEN_KEY)) {
+ if (!isPersistedSecretAbsent(AUTH_SESSION_KEY)) {
// 文件还在但读/解密失败(或加密暂不可用):瞬时故障,不能按凭证丢失
// 强踢用户;保留会话,等下个 refresh 周期或 device-link 自救重试。
log.warn(
@@ -2394,9 +2656,17 @@ export async function refresh(): Promise<boolean> {
const { result, failureAction, replacementRetries } =
await runAuthRefreshWithReplacementRetry(storedToken, {
phase: 'runtime',
+ realm: refreshRealm,
withTransientRetry: false,
});
if (refreshWasSuperseded('after-refresh')) return false;
+ const latestSession = readPersistedAuthSession();
+ if (latestSession && latestSession.realm !== refreshRealm) {
+ // 另一实例在请求期间完成了跨区域登录;旧区域结果不得覆盖或删除新记录。
+ log.warn('runtime auth realm changed on disk; discarding stale refresh result');
+ scheduleRefreshRetryAfterTransientFailure();
+ return false;
+ }
if (!result.ok) {
const action: RefreshFailureAction = failureAction ?? { kind: 'transient-failure' };
const code = getRefreshErrorCode(result);
@@ -2404,7 +2674,8 @@ export async function refresh(): Promise<boolean> {
log.warn(
`runtime refresh: definitive credential failure code=${code} — clearing auth, notifying session expired`,
);
- const previousUserId = currentUser?.id ?? getActiveAppSession().dataOwnerId ?? 'signed-out';
+ const previousUserId =
+ currentUser?.id ?? getActiveAppSession().dataOwnerId ?? 'signed-out';
await expireRuntimeAuth(previousUserId, resolveSessionExpiredReason(code));
} else if (action.kind === 'replacement-retry') {
log.warn(
@@ -2420,6 +2691,7 @@ export async function refresh(): Promise<boolean> {
return false;
}
+ const authRealmChanged = refreshRealm !== activeAuthRealm;
const data = result.data as RefreshResponse;
const needsIdentityCheck =
replacementRetries > 0 ||
@@ -2430,7 +2702,7 @@ export async function refresh(): Promise<boolean> {
// instance. Verify / reconcile the account before accepting its access token,
// otherwise renderer state could still show account A while API calls use B.
persistedRefreshTokenNeedsIdentityCheck = true;
- writeSafe(REFRESH_TOKEN_KEY, data.refreshToken);
+ writePersistedAuthSession(data.refreshToken, refreshRealm);
lastAcceptedRefreshToken = data.refreshToken;
const previousUserId = currentUser?.id ?? null;
@@ -2484,6 +2756,10 @@ export async function refresh(): Promise<boolean> {
}
}
+ if (authRealmChanged) {
+ activateClientEndpointRealm(refreshRealm);
+ activeAuthRealm = refreshRealm;
+ }
accessToken = data.accessToken;
currentUser = nextUser;
try {
@@ -2498,7 +2774,10 @@ export async function refresh(): Promise<boolean> {
await clearPerAccountIntegrations();
await reloadPerAccountIntegrationsFromDisk(accessToken);
} catch (err) {
- log.error('reload per-account integrations after replacement account switch failed', err);
+ log.error(
+ 'reload per-account integrations after replacement account switch failed',
+ err,
+ );
}
if (refreshWasSuperseded('after-integration-reload')) return false;
scheduleReplacementIntegrationReloadRetries(currentUser.id);
@@ -2510,20 +2789,27 @@ export async function refresh(): Promise<boolean> {
});
scheduleRefresh(data.accessToken);
notifyRenderer();
- if (previousUserId !== currentUser.id) {
+ if (previousUserId !== currentUser.id || authRealmChanged) {
notifyAuthListeners();
}
return true;
}
+ if (authRealmChanged) {
+ activateClientEndpointRealm(refreshRealm);
+ activeAuthRealm = refreshRealm;
+ }
accessToken = data.accessToken;
currentUser = mergeMembershipWithExisting(data.membership, currentUser);
commitActiveAppSession('cloud', currentUser.id);
persistedRefreshTokenNeedsIdentityCheck = false;
- writeSafe(REFRESH_TOKEN_KEY, data.refreshToken);
+ writePersistedAuthSession(data.refreshToken);
lastAcceptedRefreshToken = data.refreshToken;
scheduleRefresh(data.accessToken);
notifyRenderer();
+ if (authRealmChanged) {
+ notifyAuthListeners();
+ }
return true;
} catch (err) {
if (refreshWasSuperseded('catch')) return false;
@@ -2544,6 +2830,7 @@ export async function refresh(): Promise<boolean> {
export async function logout(): Promise<void> {
const currentAccessToken = accessToken;
+ const currentAuthBaseUrl = authServerUrl(activeAuthRealm);
// 注意:真实登出入口(bootstrap auth:logout handler)在调用本函数**之前**已
// dispose DbClient 并释放 device-link 持有权(releaseDeviceLinkOwnershipBeforeLogout);
// 需要在 DB 关闭前收尾写入的逻辑应挂在那条链路上,而不是本函数内(此时已太晚)。
@@ -2576,6 +2863,7 @@ export async function logout(): Promise<void> {
method: 'POST',
body: { deviceId },
token: currentAccessToken,
+ baseUrl: currentAuthBaseUrl,
}).catch(() => {});
}
}
@@ -2587,9 +2875,7 @@ export async function logout(): Promise<void> {
export function handleResume(): void {
if (accessToken === null) return;
try {
- const payload = JSON.parse(
- Buffer.from(accessToken.split('.')[1], 'base64').toString('utf-8'),
- );
+ const payload = JSON.parse(Buffer.from(accessToken.split('.')[1], 'base64').toString('utf-8'));
if (payload.exp * 1000 - Date.now() <= 5 * 60 * 1000) {
refresh();
}
diff --git a/apps/desktop/src/main/authSessionHint.ts b/apps/desktop/src/main/authSessionHint.ts
index 2535679022..d5bdd83b1d 100644
--- a/apps/desktop/src/main/authSessionHint.ts
+++ b/apps/desktop/src/main/authSessionHint.ts
@@ -13,9 +13,10 @@
import path from 'node:path';
import fs from 'node:fs';
-/** 与 authManager.ts 的 REFRESH_TOKEN_KEY / LEGACY_*_KEY 对应(那边是
+/** 与 authManager.ts 的 AUTH_SESSION_KEY / LEGACY_*_KEY 对应(那边是
* module-private 常量;此处只按 safe-storage 落盘文件名做存在性检查)。 */
const PERSISTED_TOKEN_FILES = [
+ 'cindy_auth_session_v1.enc',
'cindy_auth_refresh_token.enc',
'cindy_auth_account_refresh_token.enc',
'refresh_token.enc',
diff --git a/apps/desktop/src/main/billing/__tests__/index.test.ts b/apps/desktop/src/main/billing/__tests__/index.test.ts
index 0b6cde0f8c..576759a42b 100644
--- a/apps/desktop/src/main/billing/__tests__/index.test.ts
+++ b/apps/desktop/src/main/billing/__tests__/index.test.ts
@@ -119,10 +119,14 @@ describe('billing IPC', () => {
observedAt: '2026-07-23T12:00:00.000Z',
});
expect(fetch).toHaveBeenCalledWith('/api/model-access/balance', {
- baseUrl: 'https://model-access.example',
+ baseUrl: expect.any(Function),
timeoutMs: 20_000,
redactErrorDetails: true,
});
+ const baseUrl = fetch.mock.calls[0]?.[1]?.baseUrl;
+ expect(typeof baseUrl === 'function' ? baseUrl() : baseUrl).toBe(
+ 'https://model-access.example',
+ );
});
it('rejects any balance payload before network access', async () => {
@@ -151,7 +155,7 @@ describe('billing IPC', () => {
promotionalGrantConsistency: 'OBSERVED',
});
expect(fetch).toHaveBeenCalledWith('/api/model-access/credit-usage', {
- baseUrl: 'https://model-access.example',
+ baseUrl: expect.any(Function),
timeoutMs: 20_000,
redactErrorDetails: true,
});
@@ -211,7 +215,7 @@ describe('billing IPC', () => {
});
expect(fetch).toHaveBeenCalledWith('/api/billing/credit-topup/orders', {
- baseUrl: 'https://model-access.example',
+ baseUrl: expect.any(Function),
timeoutMs: 20_000,
redactErrorDetails: true,
method: 'POST',
@@ -230,7 +234,7 @@ describe('billing IPC', () => {
purchaseAttemptId: 'attempt/1',
});
expect(fetch).toHaveBeenCalledWith('/api/billing/subscriptions/purchases/attempt%2F1/refresh', {
- baseUrl: 'https://model-access.example',
+ baseUrl: expect.any(Function),
timeoutMs: 20_000,
redactErrorDetails: true,
method: 'POST',
@@ -254,7 +258,7 @@ describe('billing IPC', () => {
await expect(call(BILLING_INVOKE.CANCEL_CURRENT_SUBSCRIPTION)).resolves.toEqual(canceled);
expect(fetch).toHaveBeenCalledWith('/api/billing/subscription', {
- baseUrl: 'https://model-access.example',
+ baseUrl: expect.any(Function),
timeoutMs: 20_000,
redactErrorDetails: true,
method: 'DELETE',
@@ -389,7 +393,7 @@ describe('billing IPC', () => {
}),
).resolves.toEqual(change);
expect(fetch).toHaveBeenCalledWith('/api/billing/subscription/plan-change-quotes', {
- baseUrl: 'https://model-access.example',
+ baseUrl: expect.any(Function),
timeoutMs: 20_000,
redactErrorDetails: true,
method: 'POST',
@@ -443,7 +447,7 @@ describe('billing IPC', () => {
await call(BILLING_INVOKE.CANCEL_PLAN_CHANGE, { planChangeId: 'plan/1' });
expect(fetch).toHaveBeenCalledWith('/api/billing/subscription/plan-changes/plan%2F1', {
- baseUrl: 'https://model-access.example',
+ baseUrl: expect.any(Function),
timeoutMs: 20_000,
redactErrorDetails: true,
method: 'DELETE',
diff --git a/apps/desktop/src/main/billing/index.ts b/apps/desktop/src/main/billing/index.ts
index 4eabb1d170..96f4624326 100644
--- a/apps/desktop/src/main/billing/index.ts
+++ b/apps/desktop/src/main/billing/index.ts
@@ -187,7 +187,7 @@ export function createBillingHandlers(
timeoutMs: BILLING_REQUEST_TIMEOUT_MS,
...options,
redactErrorDetails: true,
- baseUrl: getBaseUrl(),
+ baseUrl: getBaseUrl,
});
} catch (error) {
throwBillingFetchError(error);
@@ -211,7 +211,7 @@ export function createBillingHandlers(
response = await fetch<unknown>('/api/model-access/balance', {
timeoutMs: BILLING_REQUEST_TIMEOUT_MS,
redactErrorDetails: true,
- baseUrl: getBaseUrl(),
+ baseUrl: getBaseUrl,
});
} catch (error) {
throwBalanceFetchError(error);
@@ -227,7 +227,7 @@ export function createBillingHandlers(
response = await fetch<unknown>('/api/model-access/credit-usage', {
timeoutMs: BILLING_REQUEST_TIMEOUT_MS,
redactErrorDetails: true,
- baseUrl: getBaseUrl(),
+ baseUrl: getBaseUrl,
});
} catch (error) {
throwBalanceFetchError(error);
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 9fad8c81be..b1472ab7b9 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1902,7 +1902,7 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
return serverApiFetch(path, {
method: 'POST',
body,
- baseUrl: getClientEndpoint('oauthBrokerApiBaseUrl'),
+ baseUrl: () => getClientEndpoint('oauthBrokerApiBaseUrl'),
});
},
hasLoginToken: () => getAccessToken() !== null,
diff --git a/apps/desktop/src/main/clientEndpointsService.ts b/apps/desktop/src/main/clientEndpointsService.ts
index 985a6294b1..bdffbc5bba 100644
--- a/apps/desktop/src/main/clientEndpointsService.ts
+++ b/apps/desktop/src/main/clientEndpointsService.ts
@@ -14,8 +14,9 @@
* 仍失败照样阻断,所以严格语义不变。
*
* 清单来源按运行形态三选一(resolveEndpointSource,纯函数可单测):
- * - packaged / dev + --endpoints-cdn:从烘焙自举基址 ENDPOINT_MANIFEST_BASE_URL
- * (region 化 hotfix 域名,客户端唯一"有感"的烘焙远程 URL)直连拉取;
+ * - packaged / dev + --endpoints-cdn:从当前构建区域的烘焙自举基址
+ * ENDPOINT_MANIFEST_BASE_URL 直连拉取;另一物理区域的基址也在构建期注入,
+ * 只用于组织区域发现和已绑定会话恢复;
* - dev 默认:读仓内 `config/endpoint.json`(XDT_ENDPOINT_MANIFEST_FILE 可
* 指定其它文件,restart:desktop:local 用它指到 config/endpoint.local.json),
* 同一条阻断循环,文件缺失 / 非法同样弹框——配置错要炸出来,不静默猜测;
@@ -38,14 +39,34 @@ import {
resolveClientEndpointsStrict,
type ClientEndpointKey,
type ClientEndpointMap,
+ type ClientEndpointRegion,
+ type ParseClientEndpointManifestResult,
+ type RealmManifestBaseUrls,
} from '@cindy/maker-shared/client-endpoints';
import { createLogger } from './logger';
-import { ENDPOINT_MANIFEST_BASE_URL } from '../shared/endpoints';
+import {
+ ENDPOINT_MANIFEST_BASE_URL,
+ ENDPOINT_MANIFEST_PEER_BASE_URL,
+} from '../shared/endpoints';
const log = createLogger('clientEndpoints');
const MANIFEST_FILE_NAME = 'endpoint.json';
+const BUILD_VARIANT = import.meta.env.VITE_CINDY_AUTH_REGION;
+/** 与 authManager 的构建区域判定保持一致;dev 使用 CN auth 身份。 */
+const BUILD_AUTH_REGION: ClientEndpointRegion =
+ BUILD_VARIANT === 'global' ? 'global' : 'cn';
+const DEFAULT_REALM_MANIFEST_BASE_URLS: RealmManifestBaseUrls =
+ BUILD_AUTH_REGION === 'global'
+ ? {
+ cn: ENDPOINT_MANIFEST_PEER_BASE_URL,
+ global: ENDPOINT_MANIFEST_BASE_URL,
+ }
+ : {
+ cn: ENDPOINT_MANIFEST_BASE_URL,
+ global: ENDPOINT_MANIFEST_PEER_BASE_URL,
+ };
/** 单次请求的网络超时——只用于触发错误框,不是静默降级。 */
const ATTEMPT_TIMEOUT_MS = 15_000;
@@ -72,9 +93,7 @@ export const CLIENT_ENDPOINTS_SYNC_CHANNEL = 'client-endpoints:get-sync';
// ── 清单来源解析(纯函数,规则 14:内存 harness 可测) ─────────────────────
-export type EndpointSource =
- | { kind: 'cdn' }
- | { kind: 'file'; filePath: string };
+export type EndpointSource = { kind: 'cdn' } | { kind: 'file'; filePath: string };
export interface ResolveEndpointSourceInput {
isPackaged: boolean;
@@ -110,9 +129,7 @@ export function resolveEndpointSource(input: ResolveEndpointSourceInput): Endpoi
* error 对象整个丢掉、统一折叠成 `fetch-failed`,现场只能看到一句
* "fetch-failed",日志里也无从区分 DNS / 代理 / TLS / 超时,排查全靠猜。
*/
-export type ManifestFetchResult =
- | { ok: true; text: string }
- | { ok: false; detail: string };
+export type ManifestFetchResult = { ok: true; text: string } | { ok: false; detail: string };
/** 归一为单行并截断:避免多行栈把弹框 detail 与日志行撑爆。 */
function normalizeDetail(detail: string): string {
@@ -142,15 +159,17 @@ function fetchTextViaNet(url: string, timeoutMs: number): Promise<ManifestFetchR
const request = net.request(url);
let body = '';
let settled = false;
- let timeout: ReturnType<typeof setTimeout> | undefined;
- const finish = (value: ManifestFetchResult) => {
+ const finish = (
+ value: ManifestFetchResult,
+ timeoutToClear?: ReturnType<typeof setTimeout>,
+ ) => {
if (settled) return;
settled = true;
- clearTimeout(timeout);
+ if (timeoutToClear !== undefined) clearTimeout(timeoutToClear);
if (!value.ok) log.debug('fetch failed (%s) for %s', value.detail, url);
resolve(value);
};
- timeout = setTimeout(() => {
+ const timeout = setTimeout(() => {
request.abort();
finish({ ok: false, detail: `timeout-${timeoutMs}ms` });
}, timeoutMs);
@@ -158,16 +177,20 @@ function fetchTextViaNet(url: string, timeoutMs: number): Promise<ManifestFetchR
request.on('response', (response) => {
if (response.statusCode !== 200) {
response.on('data', () => {});
- finish({ ok: false, detail: `http-${response.statusCode}` });
+ finish({ ok: false, detail: `http-${response.statusCode}` }, timeout);
return;
}
response.on('data', (chunk) => {
body += chunk.toString();
});
- response.on('end', () => finish({ ok: true, text: body }));
- response.on('error', (err) => finish({ ok: false, detail: describeFetchError(err) }));
+ response.on('end', () => finish({ ok: true, text: body }, timeout));
+ response.on('error', (err) =>
+ finish({ ok: false, detail: describeFetchError(err) }, timeout),
+ );
});
- request.on('error', (err) => finish({ ok: false, detail: describeFetchError(err) }));
+ request.on('error', (err) =>
+ finish({ ok: false, detail: describeFetchError(err) }, timeout),
+ );
request.end();
} catch (err) {
resolve({ ok: false, detail: describeFetchError(err) });
@@ -214,6 +237,10 @@ export interface BlockingResolveDeps {
timeoutMs?: number;
/** 仅 dev 本地文件路径为 true(localhost http);CDN 路径一律不传。 */
allowHttp?: boolean;
+ /**
+ * 清单带 region 元数据时必须与构建区域一致;缺少元数据的旧清单仍保持兼容。
+ */
+ expectedRegionWhenPresent?: ClientEndpointRegion;
/**
* 弹框前的自动重试节奏,默认 AUTO_RETRY_DELAYS_MS。file 模式传 `[]` 关闭:
* 本地文件读不到 / 内容非法都是配置事故,重读同一路径没有意义,只会白等。
@@ -221,6 +248,8 @@ export interface BlockingResolveDeps {
autoRetryDelaysMs?: readonly number[];
/** 仅测试注入(默认 setTimeout);让重试节奏在内存 harness 里零等待可测。 */
sleep?(ms: number): Promise<void>;
+ /** 启动宿主保存清单元数据;纯端点调用方无需提供。 */
+ onResolved?(manifest: Extract<ParseClientEndpointManifestResult, { ok: true }>): void;
}
/**
@@ -250,7 +279,18 @@ export async function resolveClientEndpointsBlocking(
if (fetched.ok) {
const parsed = resolveClientEndpointsStrict(fetched.text, options);
- if (parsed.ok) return parsed.endpoints;
+ if (parsed.ok) {
+ if (
+ deps.expectedRegionWhenPresent &&
+ parsed.region !== null &&
+ parsed.region !== deps.expectedRegionWhenPresent
+ ) {
+ reason = `region-mismatch:${deps.expectedRegionWhenPresent}:${parsed.region}`;
+ break;
+ }
+ deps.onResolved?.(parsed);
+ return parsed.endpoints;
+ }
// 拿到了正文但解析/校验不过 = 配置事故:重试同一份内容没有意义,直接弹框。
reason = parsed.reason;
break;
@@ -305,6 +345,17 @@ function promptRetryDialog(reason: string, sourceLabel: string): 'retry' | 'exit
// ── 模块状态与启动入口 ──────────────────────────────────────────────────────
let resolvedEndpoints: ClientEndpointMap | null = null;
+let resolvedRegion: ClientEndpointRegion | null = null;
+let crossRealmOrgLoginEnabled = BUILD_VARIANT !== 'dev';
+let realmManifestBaseUrls: RealmManifestBaseUrls = DEFAULT_REALM_MANIFEST_BASE_URLS;
+let activeSessionRealm: ClientEndpointRegion | null = null;
+const realmEndpointCache = new Map<ClientEndpointRegion, ClientEndpointMap>();
+
+const BUILD_SCOPED_ENDPOINT_KEYS = new Set<ClientEndpointKey>([
+ 'websiteUrl',
+ 'cdnBaseUrl',
+ 'mobileUpdateBaseUrl',
+]);
/**
* 启动第一步(先于一切更新检查):阻断式解析清单(packaged=CDN;dev=本地文件,
@@ -322,9 +373,13 @@ export async function initClientEndpoints(): Promise<boolean> {
repoRoot: path.resolve(app.getAppPath(), '..', '..'),
});
const sourceLabel =
- source.kind === 'cdn'
- ? `${ENDPOINT_MANIFEST_BASE_URL}/${MANIFEST_FILE_NAME}`
- : source.filePath;
+ source.kind === 'cdn' ? `${ENDPOINT_MANIFEST_BASE_URL}/${MANIFEST_FILE_NAME}` : source.filePath;
+ // The resolver reports the parsed manifest through a callback. Keep it in a
+ // box so TypeScript does not incorrectly conclude that the callback-owned
+ // assignment is unreachable at the reads below.
+ const resolvedManifestBox: {
+ value: Extract<ParseClientEndpointManifestResult, { ok: true }> | null;
+ } = { value: null };
const endpoints = await resolveClientEndpointsBlocking({
fetchManifest:
source.kind === 'cdn'
@@ -333,11 +388,22 @@ export async function initClientEndpoints(): Promise<boolean> {
promptRetry: (reason) => promptRetryDialog(reason, sourceLabel),
exitApp: () => app.exit(1),
allowHttp: source.kind === 'file',
+ expectedRegionWhenPresent: BUILD_AUTH_REGION,
// dev 本地文件:读不到就是路径/内容配置错,不自动重试(见 BlockingResolveDeps)。
autoRetryDelaysMs: source.kind === 'cdn' ? undefined : [],
+ onResolved: (manifest) => {
+ resolvedManifestBox.value = manifest;
+ },
});
if (endpoints === null) return false; // 用户选择退出,app.exit 已调用
+ const resolvedManifest = resolvedManifestBox.value;
resolvedEndpoints = endpoints;
+ resolvedRegion = resolvedManifest?.region ?? null;
+ // 老清单没有 region 元数据,但它一定来自构建区域的自举地址。只把这份端点
+ // 缓存在构建区域,不能同时塞进两区,否则升级后留下的跨区 token 会被误发。
+ activeSessionRealm = resolvedRegion ?? BUILD_AUTH_REGION;
+ realmEndpointCache.clear();
+ realmEndpointCache.set(activeSessionRealm, endpoints);
log.info(
'resolved from %s (%s): auth=%s cdn=%s',
source.kind === 'cdn' ? 'remote manifest' : 'local manifest file',
@@ -358,9 +424,94 @@ export function getClientEndpoint(key: ClientEndpointKey): string {
`client endpoints not initialized (getClientEndpoint('${key}') called before initClientEndpoints)`,
);
}
+ if (BUILD_SCOPED_ENDPOINT_KEYS.has(key) || activeSessionRealm === null) {
+ return resolvedEndpoints[key];
+ }
+ const sessionEndpoints = realmEndpointCache.get(activeSessionRealm);
+ if (!sessionEndpoints) {
+ throw new Error(`client endpoints for active realm '${activeSessionRealm}' not loaded`);
+ }
+ return sessionEndpoints[key];
+}
+
+/** 安装包身份/更新链始终读取启动时清单,不随组织会话区域切换。 */
+export function getBuildClientEndpoint(key: ClientEndpointKey): string {
+ if (resolvedEndpoints === null) {
+ throw new Error('client endpoints not initialized');
+ }
return resolvedEndpoints[key];
}
+export function getClientEndpointRealmConfig(): {
+ buildRegion: ClientEndpointRegion;
+ crossRealmOrgLoginEnabled: boolean;
+ realmManifestBaseUrls: RealmManifestBaseUrls;
+} {
+ if (resolvedEndpoints === null) {
+ throw new Error('client endpoints not initialized');
+ }
+ return {
+ buildRegion: BUILD_AUTH_REGION,
+ crossRealmOrgLoginEnabled,
+ realmManifestBaseUrls,
+ };
+}
+
+/**
+ * 从构建期受信任地址加载指定区域清单。区域身份由地址表的 key 决定;清单不必
+ * 重复自报 region,但一旦携带就必须与目标区域一致。失败不会修改当前会话端点,
+ * 也不会退回构建区域发送跨区 token。
+ */
+export async function loadClientEndpointsForRealm(
+ region: ClientEndpointRegion,
+): Promise<ClientEndpointMap> {
+ const cached = realmEndpointCache.get(region);
+ if (cached) return cached;
+ const baseUrl = realmManifestBaseUrls[region];
+ if (!baseUrl) {
+ throw new Error('realm-manifest-url-unavailable');
+ }
+ const fetched = await fetchTextViaNet(
+ `${baseUrl}/${MANIFEST_FILE_NAME}?t=${Date.now()}`,
+ ATTEMPT_TIMEOUT_MS,
+ );
+ if (!fetched.ok) {
+ throw new Error(fetchFailedReason(fetched.detail));
+ }
+ const parsed = resolveClientEndpointsStrict(fetched.text);
+ if (!parsed.ok) {
+ throw new Error(parsed.reason);
+ }
+ if (parsed.region !== null && parsed.region !== region) {
+ throw new Error(`region-mismatch:${region}:${parsed.region}`);
+ }
+ realmEndpointCache.set(region, parsed.endpoints);
+ return parsed.endpoints;
+}
+
+export function getClientEndpointForRealm(
+ region: ClientEndpointRegion,
+ key: ClientEndpointKey,
+): string {
+ if (BUILD_SCOPED_ENDPOINT_KEYS.has(key)) return getBuildClientEndpoint(key);
+ const endpoints = realmEndpointCache.get(region);
+ if (!endpoints) {
+ throw new Error(`client endpoints for realm '${region}' not loaded`);
+ }
+ return endpoints[key];
+}
+
+export function activateClientEndpointRealm(region: ClientEndpointRegion): void {
+ if (!realmEndpointCache.has(region)) {
+ throw new Error(`client endpoints for realm '${region}' not loaded`);
+ }
+ activeSessionRealm = region;
+}
+
+export function resetClientEndpointRealm(): void {
+ activeSessionRealm = resolvedRegion ?? BUILD_AUTH_REGION;
+}
+
export function getResolvedClientEndpoints(): ClientEndpointMap {
if (resolvedEndpoints === null) {
throw new Error('client endpoints not initialized');
@@ -375,7 +526,39 @@ export function registerClientEndpointsIpc(): void {
});
}
+export interface ResetClientEndpointsForTestOptions {
+ /** 指定后模拟一份真实带 region 元数据的构建清单。 */
+ buildRegion?: ClientEndpointRegion;
+ /** 注入其它区域清单,供运行期 realm 切换测试使用。 */
+ realmEndpoints?: Partial<Record<ClientEndpointRegion, ClientEndpointMap>>;
+ crossRealmOrgLoginEnabled?: boolean;
+ realmManifestBaseUrls?: RealmManifestBaseUrls | null;
+}
+
/** 仅测试:重置/注入模块状态。 */
-export function resetClientEndpointsForTest(resolved?: ClientEndpointMap): void {
+export function resetClientEndpointsForTest(
+ resolved?: ClientEndpointMap,
+ options?: ResetClientEndpointsForTestOptions,
+): void {
resolvedEndpoints = resolved ?? null;
+ resolvedRegion = resolved ? (options?.buildRegion ?? null) : null;
+ crossRealmOrgLoginEnabled = options?.crossRealmOrgLoginEnabled ?? BUILD_VARIANT !== 'dev';
+ realmManifestBaseUrls =
+ options?.realmManifestBaseUrls ?? DEFAULT_REALM_MANIFEST_BASE_URLS;
+ activeSessionRealm = resolvedRegion;
+ realmEndpointCache.clear();
+ // 既有 desktop 单测只注入一份逻辑端点,不关心物理区域;让两种构建区域都能
+ // 使用同一 fixture,避免测试辅助接口被生产清单元数据耦合。
+ if (resolved) {
+ if (resolvedRegion) {
+ realmEndpointCache.set(resolvedRegion, resolved);
+ } else {
+ realmEndpointCache.set('cn', resolved);
+ realmEndpointCache.set('global', resolved);
+ }
+ }
+ for (const region of ['cn', 'global'] as const) {
+ const endpoints = options?.realmEndpoints?.[region];
+ if (endpoints) realmEndpointCache.set(region, endpoints);
+ }
}
diff --git a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
index 77a33c16cf..4f98642642 100644
--- a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
@@ -112,9 +112,13 @@ describe('uploadLocalFile — 小文件整体 PUT', () => {
expect.objectContaining({
method: 'POST',
body: { size: 100, ext: 'png', contentType: 'image/png' },
- baseUrl: 'http://relay.test:3335',
+ baseUrl: expect.any(Function),
}),
);
+ const relayBaseUrl = apiFetch.mock.calls[0]?.[1]?.baseUrl;
+ expect(
+ typeof relayBaseUrl === 'function' ? relayBaseUrl() : relayBaseUrl,
+ ).toBe('http://relay.test:3335');
const [url, init] = undiciFetchMock.mock.calls[0];
expect(url).toBe('https://oss.example/put');
expect(init.method).toBe('PUT');
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index a724c50bcd..847571e6dd 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -92,6 +92,9 @@ export function deviceLinkApiBase(): string {
let client: DeviceLinkClient | null = null;
let arbiter: DeviceLinkOwnershipArbiter | null = null;
+let observedAuthRealm: ReturnType<typeof authManager.getActiveAuthRealm> | null = null;
+let authRealmReconnectGeneration = 0;
+let unsubscribeAuthState: (() => void) | null = null;
/** ownership store 按 DbClient 实例缓存(避免每 tick 建对象);换库(换账号)自动重建 */
let ownershipStoreCache: { db: unknown; store: OwnershipStore } | null = null;
/**
@@ -428,11 +431,19 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
});
// 登录态驱动仲裁:已登录即参与认领(控制端列表/被控端可达都依赖这条 WS)
+ observedAuthRealm = authManager.getActiveAuthRealm();
syncWithAuthState(authManager.getAuthState().isAuthenticated);
- authManager.onAuthStateChange((state) => {
- syncWithAuthState(state.isAuthenticated);
+ unsubscribeAuthState = authManager.onAuthStateChange((state) => {
+ const nextRealm = authManager.getActiveAuthRealm();
+ const realmChanged = observedAuthRealm !== null && observedAuthRealm !== nextRealm;
+ observedAuthRealm = nextRealm;
+ syncWithAuthState(state.isAuthenticated, realmChanged);
});
onQuit('device-link', () => {
+ authRealmReconnectGeneration += 1;
+ unsubscribeAuthState?.();
+ unsubscribeAuthState = null;
+ observedAuthRealm = null;
if (busyTimer) {
clearInterval(busyTimer);
busyTimer = null;
@@ -463,16 +474,46 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
log.info(`device-link service initialized → ${wsUrl()}`);
}
-function syncWithAuthState(isAuthenticated: boolean): void {
+function syncWithAuthState(isAuthenticated: boolean, realmChanged = false): void {
if (!client || !arbiter) return;
if (isAuthenticated) {
+ if (realmChanged) {
+ restartDeviceLinkForAuthRealmChange();
+ return;
+ }
// 不直接 client.start():先参与仲裁,认领成功由 onAcquire 启动连接
arbiter.start();
} else {
+ authRealmReconnectGeneration += 1;
stopArbitrationAndTeardown();
}
}
+/**
+ * 同账号被另一 shared-userData 实例切到其它区域时,登录态仍是 authenticated,
+ * 普通 arbiter.start() 会幂等早退,旧 WS 因而不会换区。先完整释放持有权并拆掉
+ * 旧 client,再以最新 realm/token 重新参与仲裁;generation 防止等待释放期间登出
+ * 或再次切区后把过期连接复活。
+ */
+function restartDeviceLinkForAuthRealmChange(): void {
+ const generation = ++authRealmReconnectGeneration;
+ const targetRealm = authManager.getActiveAuthRealm();
+ void stopArbitrationAndTeardown()
+ .catch((error) => {
+ log.warn('device-link ownership release during auth realm switch failed', error);
+ })
+ .then(() => {
+ if (
+ generation !== authRealmReconnectGeneration ||
+ !authManager.getAuthState().isAuthenticated ||
+ authManager.getActiveAuthRealm() !== targetRealm
+ ) {
+ return;
+ }
+ arbiter?.start();
+ });
+}
+
/**
* 登出 / 掉登录态的统一收口:先停仲裁(若持有 → 释放行 + onDemote → teardown),
* 非持有者再补一次 teardown 保证被控状态彻底清空。可能被连续触发(显式登出释放
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index eb477c880a..50530c126f 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -115,7 +115,8 @@ export function defaultDeps(): DeviceLinkIpcDeps {
},
setEnabled: setRemoteControlEnabled,
setKeepAwake: setKeepAwakeEnabled,
- apiFetch: (path, opts) => serverApiFetch(path, { ...opts, baseUrl: deviceLinkApiBase() }),
+ apiFetch: (path, opts) =>
+ serverApiFetch(path, { ...opts, baseUrl: deviceLinkApiBase }),
openLink: openRemoteLink,
closeLink: closeRemoteLink,
invoke: (...args) => {
diff --git a/apps/desktop/src/main/device-link/mediaTransfer.ts b/apps/desktop/src/main/device-link/mediaTransfer.ts
index 0b38de7d6d..1935e33a2d 100644
--- a/apps/desktop/src/main/device-link/mediaTransfer.ts
+++ b/apps/desktop/src/main/device-link/mediaTransfer.ts
@@ -120,7 +120,7 @@ async function presignPut(
return serverApiFetch<PresignPutResponse>(PRESIGN_PUT_PATH, {
method: 'POST',
body: { size, ext, contentType },
- baseUrl: deviceLinkApiBase(),
+ baseUrl: deviceLinkApiBase,
});
}
@@ -130,7 +130,7 @@ async function presignGet(key: string): Promise<PresignGetResponse> {
return serverApiFetch<PresignGetResponse>(PRESIGN_GET_PATH, {
method: 'POST',
body: { key },
- baseUrl: deviceLinkApiBase(),
+ baseUrl: deviceLinkApiBase,
});
}
@@ -626,7 +626,7 @@ export async function removeRemote(key: string): Promise<void> {
await serverApiFetch<{ deleted: boolean }>(DELETE_PATH, {
method: 'DELETE',
body: { key },
- baseUrl: deviceLinkApiBase(),
+ baseUrl: deviceLinkApiBase,
});
log.debug(`removed key=${key}`);
} catch (err) {
diff --git a/apps/desktop/src/main/github-issue/index.ts b/apps/desktop/src/main/github-issue/index.ts
index 78cc7fb4d2..77fb588ccb 100644
--- a/apps/desktop/src/main/github-issue/index.ts
+++ b/apps/desktop/src/main/github-issue/index.ts
@@ -86,8 +86,8 @@ export async function submitGithubIssueForSession(
bodyFactory,
// 独立部署的 github-server(服务端仓);登录 JWT 验签与
// auth-server 同侧。bodyFactory 随 401 refresh 重建,确保账号切换后
- // userName 与最终 Bearer membership 一致。
- baseUrl: getClientEndpoint('githubApiBaseUrl'),
+ // userName、区域端点与最终 Bearer membership 一致。
+ baseUrl: () => getClientEndpoint('githubApiBaseUrl'),
},
);
},
diff --git a/apps/desktop/src/main/heartbeatService.ts b/apps/desktop/src/main/heartbeatService.ts
index abd503020f..9cfc305d41 100644
--- a/apps/desktop/src/main/heartbeatService.ts
+++ b/apps/desktop/src/main/heartbeatService.ts
@@ -35,6 +35,7 @@ type AuthStateSnapshot = ReturnType<typeof authManager.getAuthState>;
let handle: HeartbeatHandle | null = null;
let handleUid: string | null = null;
+let handleRealm: ReturnType<typeof authManager.getActiveAuthRealm> | null = null;
let tapdbTimer: NodeJS.Timeout | null = null;
let unsubscribeAuth: (() => void) | null = null;
let lastTapdbActiveDate = getLocalDateKey();
@@ -48,6 +49,7 @@ function startCloudHeartbeat(uid: string): void {
// 运行期端点清单(initClientEndpoints 在 app.ready 内早于本服务,清单全权无兜底)
const endpoint = getClientEndpoint('heartbeatUrl');
handleUid = uid;
+ handleRealm = authManager.getActiveAuthRealm();
handle = createHeartbeatClient({
endpoint,
intervalMs: DEFAULT_INTERVAL_MS,
@@ -66,13 +68,16 @@ function startCloudHeartbeat(uid: string): void {
},
},
});
- log.info(`heartbeat client started → ${endpoint} (interval=${DEFAULT_INTERVAL_MS}ms, uid=${uid})`);
+ log.info(
+ `heartbeat client started → ${endpoint} (interval=${DEFAULT_INTERVAL_MS}ms, uid=${uid})`,
+ );
}
function stopCloudHeartbeat(): void {
handle?.stop();
handle = null;
handleUid = null;
+ handleRealm = null;
}
function applyAuthState(state: AuthStateSnapshot): void {
@@ -84,7 +89,8 @@ function applyAuthState(state: AuthStateSnapshot): void {
}
return;
}
- if (handle && handleUid === uid) return;
+ const realm = authManager.getActiveAuthRealm();
+ if (handle && handleUid === uid && handleRealm === realm) return;
if (handle) stopCloudHeartbeat();
startCloudHeartbeat(uid);
}
diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.ts
index ad11cea1c7..a192930f8d 100644
--- a/apps/desktop/src/main/hook-control/ipc.ts
+++ b/apps/desktop/src/main/hook-control/ipc.ts
@@ -81,6 +81,7 @@ const log = createLogger('hook-control');
let store: SlackHookStore | null = null;
let manager: HookControlManager | null = null;
let disposeAuthListener: (() => void) | null = null;
+let observedAuthRealm: ReturnType<typeof authManager.getActiveAuthRealm> | null = null;
let codexMcpRefreshPending = false;
let codexMcpRefreshRunning = false;
let codexMcpRefreshRetryTimer: NodeJS.Timeout | null = null;
@@ -772,13 +773,21 @@ export function registerHookControlIpc(): void {
// fail-closed backstop for signed-out/local sessions; activation waits for
// the next owner DB readiness callback (with app:ready-for-bot as a
// compatibility retry).
+ observedAuthRealm = authManager.getActiveAuthRealm();
disposeAuthListener = authManager.onAuthStateChange(() => {
+ const nextRealm = authManager.getActiveAuthRealm();
+ const realmChanged = observedAuthRealm !== null && observedAuthRealm !== nextRealm;
+ observedAuthRealm = nextRealm;
if (!hookControlAvailable()) {
void stopHookControlAccount().catch((err: unknown) => {
log.warn(
`hook-control account deactivation failed (${err instanceof Error ? err.name : 'unknown'})`,
);
});
+ } else if (realmChanged) {
+ // manager.sync() 同时 dispose 两条旧 transport,并用当前清单重读
+ // Slack / Telegram URL;authManager 已在发通知前提交新 token。
+ manager?.sync();
}
});
@@ -811,5 +820,6 @@ export function disposeHookControl(): void {
}
disposeAuthListener?.();
disposeAuthListener = null;
+ observedAuthRealm = null;
resetHookControlOwnerBoundary();
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
index 41786e2542..3bd8e6803e 100644
--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderConnectionClaim.test.ts
@@ -77,7 +77,7 @@ vi.mock('../../authManager.js', () => ({ getAuthState: () => ({ mode: 'local' as
vi.mock('../../appCapabilities.js', () => ({ getAppCapabilities: () => ({ canUseCindyGateway: false }) }));
vi.mock('../../ownerNamespaceMigration.js', () => ({ hasLegacyOwnerNamespaceClaim: () => false }));
vi.mock('../../manifestService.js', () => ({ isDev: () => true, getBaseUrl: () => 'https://example.invalid' }));
-vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://example.invalid' }));
+vi.mock('../../clientEndpointsService.js', () => ({ getBuildClientEndpoint: () => 'https://example.invalid', getClientEndpoint: () => 'https://example.invalid' }));
vi.mock('../../secrets/providerSecretStore.js', () => ({
genericOAuthSecretIo: {},
setProviderSecretsClearedListener: () => {},
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
new file mode 100644
index 0000000000..afdf344da4
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts
@@ -0,0 +1,151 @@
+import os from 'node:os';
+
+import { describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ endpoint: 'https://model.cn.example',
+ buildEndpoint: 'https://model.cn.example',
+ loads: [] as Array<{
+ source: Record<string, unknown>;
+ resolve: (catalog: unknown) => void;
+ }>,
+}));
+
+vi.mock('electron', () => ({
+ app: { getPath: () => os.tmpdir() },
+ net: { request: vi.fn() },
+}));
+
+vi.mock('@cindy/model-providers', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@cindy/model-providers')>();
+ return {
+ ...actual,
+ loadCatalog: vi.fn(
+ (source: Record<string, unknown>) =>
+ new Promise((resolve) => {
+ h.loads.push({ source, resolve });
+ }),
+ ),
+ };
+});
+
+vi.mock('../../manifestService.js', () => ({
+ getBaseUrl: () => 'https://legacy-build-cdn.example',
+ isDev: () => false,
+}));
+vi.mock('../../clientEndpointsService.js', () => ({
+ getBuildClientEndpoint: () => h.buildEndpoint,
+ getClientEndpoint: () => h.endpoint,
+}));
+vi.mock('../../authManager.js', () => ({
+ getAuthState: () => ({ mode: 'signed-out', user: null }),
+}));
+vi.mock('../../appSessionState.js', () => ({
+ getActiveAppSession: () => ({ mode: 'signed-out', dataOwnerId: null }),
+}));
+vi.mock('../../appCapabilities.js', () => ({
+ getAppCapabilities: () => ({ canUseCindyGateway: false }),
+}));
+vi.mock('../../ownerNamespaceMigration.js', () => ({
+ hasLegacyOwnerNamespaceClaim: () => false,
+}));
+vi.mock('../auth-adapters.js', () => ({
+ readClaudeApiKey: () => null,
+ desktopCodexAuthAdapter: {
+ hasCodexOAuthLogin: () => false,
+ hasCodexOAuthLoginReadOnly: () => false,
+ hasCodexOAuthLoginUnbound: () => false,
+ },
+}));
+vi.mock('../claude-credentials-store.js', () => ({
+ hasClaudeAiOAuth: () => false,
+ hasClaudeAiOAuthUnbound: () => false,
+}));
+vi.mock('../grok-oauth-login.js', () => ({
+ getGrokAccessToken: () => null,
+ hasGrokOAuthLogin: () => false,
+ hasGrokOAuthLoginUnbound: () => false,
+ resetGrokOAuthMemoryCache: () => undefined,
+}));
+vi.mock('../generic-oauth.js', () => ({
+ configureGenericOAuth: () => undefined,
+ hasGenericOAuthLogin: () => false,
+ readCachedGenericOAuthAccessToken: () => null,
+ resetGenericOAuthMemoryCache: () => undefined,
+}));
+vi.mock('../../secrets/providerSecretStore.js', () => ({
+ genericOAuthSecretIo: {},
+ readCustomProviderKey: () => null,
+ setProviderSecretsClearedListener: () => undefined,
+}));
+vi.mock('../provider-route.js', () => ({
+ setCustomProviderKeyReader: () => undefined,
+ setOAuthTokenReader: () => undefined,
+ setProviderOAuthTokenReader: () => undefined,
+}));
+vi.mock('../provider-diagnostics.js', () => ({
+ setDiagnosticsKeyReader: () => undefined,
+ setDiagnosticsOAuthTokenReader: () => undefined,
+}));
+vi.mock('../codex-model-discovery.js', () => ({
+ readCodexDiscoveredModels: async () => null,
+ readCodexDiscoveredModelsForAuthRefresh: async () => [],
+}));
+vi.mock('../model-discovery/anthropic.js', () => ({
+ getAnthropicModelDiscoveryFailure: () => null,
+ loadAnthropicModelsFromDiskCache: async () => undefined,
+ refreshAnthropicModelsFromHttp: async () => undefined,
+}));
+
+import { BUNDLED_CATALOG, type Catalog } from '@cindy/model-providers';
+import { getActiveCatalog } from '../active-catalog.js';
+import {
+ ensureActiveCatalogLoaded,
+ reloadActiveCatalogForEndpointChange,
+} from '../createDesktopProviderService.js';
+
+function catalogNamed(name: string): Catalog {
+ return {
+ ...BUNDLED_CATALOG,
+ providers: BUNDLED_CATALOG.providers.map((provider, index) =>
+ index === 0 ? { ...provider, name } : provider,
+ ),
+ };
+}
+
+function activeMarker(): string | undefined {
+ return getActiveCatalog().providers[0]?.name;
+}
+
+describe('provider catalog realm reload', () => {
+ it('invalidates the old realm immediately and ignores a stale cross-realm response', async () => {
+ const initial = ensureActiveCatalogLoaded();
+ expect(h.loads[0]?.source).toMatchObject({
+ baseUrl: 'https://model.cn.example',
+ fallbackBaseUrl: 'https://legacy-build-cdn.example',
+ });
+ h.loads[0]!.resolve(catalogNamed('catalog-cn-initial'));
+ await initial;
+ expect(activeMarker()).toBe('catalog-cn-initial');
+
+ h.endpoint = 'https://model.global.example';
+ const globalReload = reloadActiveCatalogForEndpointChange();
+ // Endpoint activation must synchronously remove the CN catalog before any await.
+ expect(activeMarker()).not.toBe('catalog-cn-initial');
+ expect(h.loads[1]?.source).toMatchObject({
+ baseUrl: 'https://model.global.example',
+ });
+ expect(h.loads[1]?.source.fallbackBaseUrl).toBeUndefined();
+
+ // A quick switch back to CN supersedes the still-pending Global request.
+ h.endpoint = 'https://model.cn.example';
+ const cnReload = reloadActiveCatalogForEndpointChange();
+ h.loads[1]!.resolve(catalogNamed('catalog-global-stale'));
+ await globalReload;
+ expect(activeMarker()).not.toBe('catalog-global-stale');
+
+ h.loads[2]!.resolve(catalogNamed('catalog-cn-latest'));
+ await cnReload;
+ expect(activeMarker()).toBe('catalog-cn-latest');
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index 5cc837f1f0..3d020df36e 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -20,6 +20,7 @@ import { promises as fsp } from 'node:fs';
import path from 'node:path';
import {
+ BUNDLED_CATALOG,
buildUserProvider,
DEFAULT_REMOTE_CATALOG_BUDGET_MS,
loadCatalog,
@@ -31,7 +32,7 @@ import {
import { createLogger } from '../logger.js';
import { getBaseUrl, isDev } from '../manifestService.js';
-import { getClientEndpoint } from '../clientEndpointsService.js';
+import { getBuildClientEndpoint, getClientEndpoint } from '../clientEndpointsService.js';
import {
getActiveCatalog,
setActiveCatalog,
@@ -148,21 +149,34 @@ const io: CatalogIO = {
/**
* 构建目录源配置。release 使用区域化 Model Access 公共接口,旧 OSS 保留为迁移期回退;dev 不联网。
*
- * 注:区域 endpoint 或 OSS base 在会话中途切换(办公室↔家)只影响下次进程加载;本进程仍持有
- * 已校验目录。远端不可用时依次退化到旧 OSS 与 bundled,不影响基础 Provider 可用性。
+ * 会话切到另一 auth realm 时,Model Access 公共接口随 active endpoint 改变并触发整份目录
+ * 重载。旧 OSS 只属于安装包区域,因此仅同区加载允许使用;跨区主源失败时直接退化 bundled,
+ * 绝不把安装区域的 provider/routing 目录冒充成组织区域目录。
*/
function buildSource(): CatalogSourceConfig {
const dev = isDev();
+ const baseUrl = dev ? undefined : getClientEndpoint('modelAccessApiBaseUrl');
+ const usesBuildRealm = !dev && baseUrl === getBuildClientEndpoint('modelAccessApiBaseUrl');
return {
url: process.env.XDT_MODELS_URL,
localPath: process.env.XDT_MODELS_PATH,
- baseUrl: dev ? undefined : getClientEndpoint('modelAccessApiBaseUrl'),
- fallbackBaseUrl: dev ? undefined : getBaseUrl(),
+ baseUrl,
+ fallbackBaseUrl: dev || !usesBuildRealm ? undefined : getBaseUrl(),
remoteBudgetMs: DEFAULT_REMOTE_CATALOG_BUDGET_MS,
disableFetch: dev || process.env.XDT_DISABLE_MODELS_FETCH === '1',
};
}
+function catalogSourceKey(source: CatalogSourceConfig): string {
+ return JSON.stringify({
+ url: source.url ?? null,
+ localPath: source.localPath ?? null,
+ baseUrl: source.baseUrl ?? null,
+ fallbackBaseUrl: source.fallbackBaseUrl ?? null,
+ disableFetch: source.disableFetch ?? false,
+ });
+}
+
/**
* 一次性清理旧版本遗留的目录磁盘缓存(provider-catalog-cache.json + .tmp)。
* 现版本目录每进程拉一次存内存、不落盘,这两个文件不再被读写,纯属历史孤儿。
@@ -182,6 +196,12 @@ async function cleanupLegacyCatalogCache(): Promise<void> {
let activeLoaded = false;
let activeInflight: Promise<Catalog> | null = null;
let catalogRefreshInflight: Promise<Catalog> | null = null;
+let activeCatalogSourceKey: string | null = null;
+let endpointReloadGeneration = 0;
+let endpointReloadInflight: {
+ sourceKey: string;
+ promise: Promise<Catalog>;
+} | null = null;
/**
* 启动期(splash)await 一次:加载远端目录写入 active-catalog。幂等 + 并发去重。
@@ -218,10 +238,13 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {
setDiagnosticsOAuthTokenReader(readOAuthToken);
if (activeLoaded) return Promise.resolve(getActiveCatalog());
if (!activeInflight) {
+ const source = buildSource();
+ const sourceKey = catalogSourceKey(source);
// 首次加载时顺手清掉旧版磁盘缓存孤儿(fire-and-forget,每进程一次)。
void cleanupLegacyCatalogCache();
- activeInflight = loadCatalog(buildSource(), io)
+ activeInflight = loadCatalog(source, io)
.then(async (catalog) => {
+ activeCatalogSourceKey = sourceKey;
setActiveCatalog(catalog);
// 读 codex models_cache.json 得到规范化快照,由 active-catalog 同时投影到 Codex 与
// Claude bridge。null 表示没读到有效 cache,保留现值 / 静态兜底;[] 表示合法空快照。
@@ -246,6 +269,51 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {
return activeInflight;
}
+/**
+ * Auth realm 激活后的整目录重载。若目标端点变化,先同步失效旧区域目录并回到
+ * bundled,再异步加载目标区域;generation 保证快速 CN↔Global 切换时迟到响应
+ * 不能覆盖最新区域。
+ */
+export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
+ if (!activeLoaded) {
+ return ensureActiveCatalogLoaded().then(() => reloadActiveCatalogForEndpointChange());
+ }
+
+ const source = buildSource();
+ const sourceKey = catalogSourceKey(source);
+ if (endpointReloadInflight?.sourceKey === sourceKey) {
+ return endpointReloadInflight.promise;
+ }
+ if (activeCatalogSourceKey === sourceKey && endpointReloadInflight === null) {
+ return Promise.resolve(getActiveCatalog());
+ }
+
+ const generation = ++endpointReloadGeneration;
+ activeCatalogSourceKey = null;
+ // 必须在网络 await 前失效:登录提交后 renderer/agent 可能立即读取目录。
+ setActiveCatalog(BUNDLED_CATALOG);
+
+ const flight = loadCatalog(source, io)
+ .then((catalog) => {
+ if (
+ endpointReloadGeneration !== generation ||
+ catalogSourceKey(buildSource()) !== sourceKey
+ ) {
+ return getActiveCatalog();
+ }
+ activeCatalogSourceKey = sourceKey;
+ setActiveCatalog(catalog);
+ return getActiveCatalog();
+ })
+ .finally(() => {
+ if (endpointReloadInflight?.promise === flight) {
+ endpointReloadInflight = null;
+ }
+ });
+ endpointReloadInflight = { sourceKey, promise: flight };
+ return flight;
+}
+
/**
* 手动重载 xAI 模型目录。先确保启动期动态发现已完成,再复用同一 `loadCatalog`
* 源选择与 bundled fallback;只投影 xAI 的静态模型列表,当前 routing/auth 以及其它
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index a9606e138a..521aaa8915 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -68,6 +68,7 @@ import { deriveAvailableModels, refreshCatalogDerivedModels } from './catalog-to
import { clearChatgptBridgeCredentialCache } from './anthropic-responses-bridge-host.js';
import {
getDesktopSelectableCatalog,
+ reloadActiveCatalogForEndpointChange,
refreshDiscoveredCodexModels,
setNativeProviderClaimListener,
} from './createDesktopProviderService.js';
@@ -205,6 +206,16 @@ setNativeProviderClaimListener(() => {
/** Re-project provider/model availability after the Cindy auth session changes. */
export function refreshProviderAccessAfterAuthChange(): void {
+ resetProviderModelAutoRefreshCooldowns();
+ void reloadActiveCatalogForEndpointChange()
+ .then(() => {
+ refreshSelectableModelsAndBroadcast({});
+ })
+ .catch((error) => {
+ desktopMakerLogger.warn('provider catalog reload after auth realm change failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
try {
refreshSelectableModelsAndBroadcast({});
} catch (error) {
diff --git a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
index 998eb7ab79..d2340d994d 100644
--- a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
@@ -22,6 +22,19 @@ describe('waitForModelsSyncRefresh', () => {
expect(XD_MODELS_SYNC_TIMEOUT_MS).toBeGreaterThan(0);
});
+ it('preserves a live endpoint resolver for post-refresh realm changes', () => {
+ const resolveBaseUrl = vi.fn(() => 'https://model-access.global.example.com');
+ const request = buildModelsSyncRequest(resolveBaseUrl);
+
+ expect(request.options.baseUrl).toBe(resolveBaseUrl);
+ if (typeof request.options.baseUrl !== 'function') {
+ throw new Error('expected a live endpoint resolver');
+ }
+ expect(request.options.baseUrl()).toBe(
+ 'https://model-access.global.example.com',
+ );
+ });
+
it('bounds the complete fetch lifecycle without cancelling the underlying auth refresh', async () => {
vi.useFakeTimers();
try {
diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.ts
index eb15faac96..bbbdccdf2e 100644
--- a/apps/desktop/src/main/model-access/index.ts
+++ b/apps/desktop/src/main/model-access/index.ts
@@ -70,14 +70,14 @@ function notifyXdProviderKeyChanged(): void {
function fetchCredentials(): Promise<CredentialsPayload> {
return serverApiFetch<CredentialsPayload>(CREDENTIALS_PATH, {
- baseUrl: getClientEndpoint('modelAccessApiBaseUrl'),
+ baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),
});
}
function rotateCredentials(): Promise<CredentialsPayload> {
return serverApiFetch<CredentialsPayload>(`${CREDENTIALS_PATH}/rotate`, {
method: 'POST',
- baseUrl: getClientEndpoint('modelAccessApiBaseUrl'),
+ baseUrl: () => getClientEndpoint('modelAccessApiBaseUrl'),
});
}
@@ -184,7 +184,9 @@ async function runModelsSync(
): Promise<void> {
let payload: { models: ModelAccessGatewayModel[] };
try {
- const request = buildModelsSyncRequest(getClientEndpoint('modelAccessApiBaseUrl'));
+ const request = buildModelsSyncRequest(() =>
+ getClientEndpoint('modelAccessApiBaseUrl'),
+ );
payload = await withModelsSyncOverallDeadline(
serverApiFetch<{ models: ModelAccessGatewayModel[] }>(
request.path,
diff --git a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
index f55700376f..3ecd4500c8 100644
--- a/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
+++ b/apps/desktop/src/main/model-access/modelsSyncRefresh.ts
@@ -27,9 +27,9 @@ export function withModelsSyncOverallDeadline<T>(
});
}
-export function buildModelsSyncRequest(baseUrl: string): {
+export function buildModelsSyncRequest(baseUrl: string | (() => string)): {
path: '/api/model-access/models';
- options: { baseUrl: string; timeoutMs: number };
+ options: { baseUrl: string | (() => string); timeoutMs: number };
} {
return {
path: '/api/model-access/models',
diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.ts
index 10b9d3ab77..2db87eee4b 100644
--- a/apps/desktop/src/main/plugin-market/api.ts
+++ b/apps/desktop/src/main/plugin-market/api.ts
@@ -18,7 +18,7 @@ type Fetcher = <T>(
const defaultFetcher: Fetcher = (apiPath, options) =>
serverApiFetch(apiPath, {
...options,
- baseUrl: getClientEndpoint('pluginApiBaseUrl'),
+ baseUrl: () => getClientEndpoint('pluginApiBaseUrl'),
});
/** plugin-server 普通客户端 API;每个响应都经过共享 v2 parser fail-closed。 */
diff --git a/apps/desktop/src/main/serverApiClient.ts b/apps/desktop/src/main/serverApiClient.ts
index 19424ee785..850b158ea4 100644
--- a/apps/desktop/src/main/serverApiClient.ts
+++ b/apps/desktop/src/main/serverApiClient.ts
@@ -45,8 +45,12 @@ export interface ApiFetchOptions {
token?: string | null;
/** 跳过 401 自动 refresh(避免无限循环;refresh 自身调用时禁用)。 */
skipAutoRefresh?: boolean;
- /** 目标服务 base URL(必传;来自 clientEndpoints 的对应字段或注入方)。 */
- baseUrl: string;
+ /**
+ * 目标服务 base URL(必传;来自 clientEndpoints 的对应字段或注入方)。
+ * 区域相关服务必须传 resolver:401 refresh 可能切换登录区域,重试前要重新
+ * 读取端点,不能把新区域 token 发到首次请求的旧区域。
+ */
+ baseUrl: string | (() => string);
/** Abort the request after this many milliseconds; 0 disables the deadline. */
timeoutMs?: number;
/** Keep upstream response/network details out of local logs for sensitive flows. */
@@ -66,7 +70,8 @@ interface RawResponse<T> {
}
async function rawFetch<T>(apiPath: string, opts: ApiFetchOptions): Promise<RawResponse<T>> {
- const url = opts.baseUrl + apiPath;
+ const baseUrl = typeof opts.baseUrl === 'function' ? opts.baseUrl() : opts.baseUrl;
+ const url = baseUrl + apiPath;
const method = opts.method ?? 'GET';
const headers: Record<string, string> = {
'Content-Type': 'application/json',
diff --git a/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts b/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts
index a76884acbe..bd5bae6e50 100644
--- a/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/publishService.test.ts
@@ -249,8 +249,15 @@ describe('SkillPublishService', () => {
expect(serverApiFetch).toHaveBeenCalledWith('/api/skills-hub/skills/publish/init', {
method: 'POST',
body: { slug: 'lark-task', version: '1.1.0' },
- baseUrl: 'https://skillhub.test.invalid',
+ baseUrl: expect.any(Function),
});
+ const initCall = vi.mocked(serverApiFetch).mock.calls.find(
+ ([path]) => path === '/api/skills-hub/skills/publish/init',
+ );
+ const initBaseUrl = initCall?.[1]?.baseUrl;
+ expect(
+ typeof initBaseUrl === 'function' ? initBaseUrl() : initBaseUrl,
+ ).toBe('https://skillhub.test.invalid');
});
it('sends the hand-filled 280-char text to Hub commit as summary', async () => {
@@ -314,7 +321,7 @@ describe('SkillPublishService', () => {
expect(result.success).toBe(true);
expect(serverApiFetch).toHaveBeenCalledWith('/api/skills-hub/skills/publish/commit', {
method: 'POST',
- baseUrl: 'https://skillhub.test.invalid',
+ baseUrl: expect.any(Function),
body: expect.objectContaining({
displayName: 'Lark Task',
summary: 'Publish summary',
@@ -387,7 +394,7 @@ describe('SkillPublishService', () => {
expect(result.success).toBe(true);
expect(serverApiFetch).toHaveBeenCalledWith('/api/skills-hub/skills/publish/commit', {
method: 'POST',
- baseUrl: 'https://skillhub.test.invalid',
+ baseUrl: expect.any(Function),
body: expect.objectContaining({
categoryMode: 'auto',
categories: [],
@@ -457,7 +464,7 @@ describe('SkillPublishService', () => {
expect(result.success).toBe(true);
expect(serverApiFetch).toHaveBeenCalledWith('/api/skills-hub/skills/publish/commit', {
method: 'POST',
- baseUrl: 'https://skillhub.test.invalid',
+ baseUrl: expect.any(Function),
body: expect.objectContaining({
visibility: 'public',
visibleSlugs: [],
diff --git a/apps/desktop/src/main/skillhub/hubApi.ts b/apps/desktop/src/main/skillhub/hubApi.ts
index 1dc6ea23d8..164cf7076f 100644
--- a/apps/desktop/src/main/skillhub/hubApi.ts
+++ b/apps/desktop/src/main/skillhub/hubApi.ts
@@ -17,6 +17,6 @@ export function skillhubApiFetch<T>(
requireAppCapability('canUseSkillHubCloud', 'SkillHub cloud requires a Cindy account.');
return serverApiFetch<T>(apiPath, {
...opts,
- baseUrl: getClientEndpoint('skillhubApiBaseUrl'),
+ baseUrl: () => getClientEndpoint('skillhubApiBaseUrl'),
});
}
diff --git a/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts b/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts
index 2758aabe7d..acbb83357e 100644
--- a/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts
+++ b/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts
@@ -176,10 +176,11 @@ async function createCindyVoiceSession(input: {
sourceLanguage?: string;
}): Promise<CindyVoiceAsrSession> {
requireAppCapability('canUseCindyAccountServices', 'Cindy voice requires a Cindy account.');
- const baseUrl = getClientEndpoint('voiceApiBaseUrl');
- if (!baseUrl) throw new Error('Cindy voice service is unavailable in this region.');
+ if (!getClientEndpoint('voiceApiBaseUrl')) {
+ throw new Error('Cindy voice service is unavailable in this region.');
+ }
const request = {
- baseUrl,
+ baseUrl: () => getClientEndpoint('voiceApiBaseUrl'),
method: 'POST',
body: {
mode: 'dictation',
diff --git a/apps/desktop/src/renderer/components/login/LoginControls.tsx b/apps/desktop/src/renderer/components/login/LoginControls.tsx
index bcda83a74e..63efb6422e 100644
--- a/apps/desktop/src/renderer/components/login/LoginControls.tsx
+++ b/apps/desktop/src/renderer/components/login/LoginControls.tsx
@@ -892,7 +892,7 @@ export function LoginConsentDialog({
</div>
<div
id="login-consent-dialog-body"
- className="absolute text-center"
+ className="absolute whitespace-pre-line text-center"
style={{
left: CONSENT_DIALOG.body.x,
top: CONSENT_DIALOG.body.y,
diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsx
index 5ac3463422..b757a1456e 100644
--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx
+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx
@@ -134,6 +134,7 @@ export function LoginPage() {
// 企业 SSO 入口子视图:在 identifier 步骤内输入组织标识(本地展示态,不进 main)。
// 需先于 bottomReserve 计算声明——协议行只在 identifier 主视图渲染,sso-org 子视图隐藏。
const [ssoOrgMode, setSsoOrgMode] = useState(false);
+ const realmConfirmation = loginState?.step === 'realm-confirmation' ? loginState : null;
/* ── 协议同意链路(consent PR):radio 状态 + 未勾选拦截弹窗 + 同意后续接。
过门点(产品拍板 2026-07-24 二次):手机号提交、邮箱提交(discover 前)、
@@ -384,6 +385,8 @@ export function LoginPage() {
event.preventDefault();
const value = ssoOrg.trim();
if (!value) return;
+ // 组织区域先静默发现;仅当结果与安装包区域不一致时,main 状态机进入
+ // realm-confirmation,由下方弹窗在继续 SSO 前向用户确认。
void dispatch({ type: 'discover-sso-org', org: value });
};
@@ -1042,6 +1045,22 @@ export function LoginPage() {
onOpenPrivacy={() => openLegalLink('privacy')}
/>
)}
+ {realmConfirmation && (
+ <LoginConsentDialog
+ title={t('login.realmConsent.title')}
+ body={t(
+ realmConfirmation.targetRegion === 'cn'
+ ? 'login.realmConsent.bodyCn'
+ : 'login.realmConsent.bodyGlobal',
+ )}
+ agreeLabel={t('login.realmConsent.agree')}
+ disagreeLabel={t('login.realmConsent.disagree')}
+ onAgree={() => void dispatch({ type: 'confirm-sso-realm' })}
+ onDisagree={() => void dispatch({ type: 'cancel-sso-realm' })}
+ onOpenTerms={() => undefined}
+ onOpenPrivacy={() => undefined}
+ />
+ )}
</div>
);
}
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.tsx
index ba50af2e86..e28471b5ed 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
@@ -77,6 +77,19 @@ async function ssoOrgListState(org = 'example-corp') {
});
}
+async function realmConfirmationState(targetRegion: 'cn' | 'global') {
+ const identifier = await identifierState('providers:both');
+ if (identifier.step !== 'identifier') throw new Error('expected identifier');
+ const client = scenarioClient('sso:single', targetRegion);
+ const discovery = await client.discoverSsoOrg('example-corp');
+ return reduceAuthFlow(identifier, {
+ type: 'realm-switch-required',
+ targetRegion,
+ providers: identifier.providers,
+ methods: ssoOrgDiscoveryToMethods(discovery),
+ });
+}
+
function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.value>) {
loginHook.value = {
isLoading: false,
@@ -261,7 +274,7 @@ describe('ssoOrgMode 子视图', () => {
expect(screen.getByText('login.ssoOrgHint')).toBeTruthy();
});
- it('sso-org 填写态:输入企业 ID 后继续可用,提交派发 discover-sso-org', async () => {
+ it('sso-org 填写态:直接派发 discover-sso-org,不在查询前弹确认', async () => {
mount(await identifierState('providers:both'));
fireEvent.click(screen.getByTestId('login-social-sso'));
const input = screen.getByTestId('login-sso-org-input') as HTMLInputElement;
@@ -273,6 +286,29 @@ describe('ssoOrgMode 子视图', () => {
type: 'discover-sso-org',
org: 'example-corp',
});
+ expect(screen.queryByText('login.realmConsent.title')).toBeNull();
+ });
+
+ it('组织区域与安装区域不一致时才显示确认,确认或取消走独立 action', async () => {
+ mount(await realmConfirmationState('global'));
+ expect(screen.getByText('login.realmConsent.title')).toBeTruthy();
+ const bodyText = screen.getByText('login.realmConsent.bodyGlobal');
+ const body = bodyText.closest('#login-consent-dialog-body') as HTMLElement;
+ expect(body).toBeTruthy();
+ expect(body.style.fontSize).toBe('26px');
+ expect(body.style.lineHeight).toBe('40px');
+ expect(body.style.color).toBe('var(--login-secondary-text)');
+ expect(body.className).toContain('whitespace-pre-line');
+
+ fireEvent.click(screen.getByText('login.realmConsent.agree'));
+ expect(loginHook.value.dispatch).toHaveBeenCalledWith({
+ type: 'confirm-sso-realm',
+ });
+
+ fireEvent.click(screen.getByText('login.realmConsent.disagree'));
+ expect(loginHook.value.dispatch).toHaveBeenCalledWith({
+ type: 'cancel-sso-realm',
+ });
});
it('sso-org 连接列表态:单 connection 方式行 @148 + ssoOrgDetected 副标题', async () => {
diff --git a/apps/desktop/src/renderer/components/login/__tests__/legalSegments.catalog.test.ts b/apps/desktop/src/renderer/components/login/__tests__/legalSegments.catalog.test.ts
index 94ca9e0127..0ad314fb77 100644
--- a/apps/desktop/src/renderer/components/login/__tests__/legalSegments.catalog.test.ts
+++ b/apps/desktop/src/renderer/components/login/__tests__/legalSegments.catalog.test.ts
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { parseLegalSegments } from '../LoginControls';
+import { CONSENT_DIALOG } from '../loginDesignTokens';
/**
* 协议文案 catalog 严校验(codex 审查 P2):parseLegalSegments 对坏标记 fail-open
@@ -51,3 +52,32 @@ describe('consent 文案 catalog 严校验(4 语 × statement/body)', () => {
]);
});
});
+
+describe('区域确认文案排版预算(标准 26/40,最多 3 行)', () => {
+ const maxEstimatedUnits =
+ (CONSENT_DIALOG.body.width * 0.95 * 3) /
+ CONSENT_DIALOG.body.fontSize;
+ const estimatedUnits = (value: string) =>
+ [...value].reduce(
+ (sum, character) =>
+ sum + ((character.codePointAt(0) ?? 0) <= 0xff ? 0.5 : 1),
+ 0,
+ );
+
+ it.each(LOCALES)('%s:CN / Global 正文固定两行且每行无需二次折行', (locale) => {
+ const realmConsent = loadLogin(locale).realmConsent as {
+ bodyCn: string;
+ bodyGlobal: string;
+ };
+ for (const body of [realmConsent.bodyCn, realmConsent.bodyGlobal]) {
+ const lines = body.split('\n');
+ expect(lines, `${locale}: ${body}`).toHaveLength(2);
+ for (const line of lines) {
+ expect(
+ estimatedUnits(line),
+ `${locale}: ${line}`,
+ ).toBeLessThanOrEqual(maxEstimatedUnits / 3);
+ }
+ }
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index d3e346c603..6322f3faba 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3029,6 +3029,13 @@
"ssoOrgPlaceholder": "Company ID, slug, or domain",
"ssoOrgHint": "Don't know your enterprise sign-in identifier? Ask your admin",
"ssoOrgDetected": "Choose a single sign-on connection for \"{{org}}\"",
+ "realmConsent": {
+ "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.",
+ "agree": "Continue sign-in",
+ "disagree": "Cancel"
+ },
"ssoVerificationTitle": "Verify Your Work Identity",
"ssoVerificationSubtitle": "First-time sign-in requires verification of the contact returned by your identity provider: {{target}}",
"enterCode": "Enter verification code",
@@ -3077,6 +3084,8 @@
"RATE_LIMITED": "Too many attempts. Please wait and try again.",
"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.",
+ "ORG_REALM_UNAVAILABLE": "Cindy cannot verify the enterprise region right now. Check your connection and retry.",
"SSO_EMAIL_REQUIRED": "Your work identity did not provide a valid email. Ask your admin to check the IdP configuration.",
"INVALID_SSO_VERIFICATION_TICKET": "Work identity verification expired. Start SSO sign-in again.",
"SOCIAL_TOKEN_INVALID": "The provider authorization expired. Please try again.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e07e49c67d..bce137d1e4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3028,6 +3028,13 @@
"ssoOrgPlaceholder": "企業 ID、slug、またはドメイン",
"ssoOrgHint": "企業のログイン識別子が不明な場合は、管理者にお問い合わせください",
"ssoOrgDetected": "「{{org}}」のシングルサインオン方法を選択してください",
+ "realmConsent": {
+ "title": "企業のリージョンに接続",
+ "bodyCn": "この企業は中国本土リージョンにあります。\n続行すると Cindy はこの地域に接続します。",
+ "bodyGlobal": "この企業はグローバルリージョンにあります。\n続行すると Cindy はこの地域に接続します。",
+ "agree": "ログインを続ける",
+ "disagree": "キャンセル"
+ },
"ssoVerificationTitle": "企業 ID を確認",
"ssoVerificationSubtitle": "初回ログインでは ID プロバイダーから返された連絡先 {{target}} の確認が必要です",
"enterCode": "認証コードを入力",
@@ -3076,6 +3083,8 @@
"RATE_LIMITED": "試行が多すぎます。少し待ってから再試行してください。",
"SSO_LOGIN_REQUIRED": "この組織は SSO ログインが必要です。",
"ORG_SSO_NOT_FOUND": "該当する企業が見つからないか、SSO サインインが有効になっていません",
+ "ORG_REALM_AMBIGUOUS": "この企業識別子は両方の地域に存在します。管理者にお問い合わせください。",
+ "ORG_REALM_UNAVAILABLE": "企業の地域を現在確認できません。ネットワークを確認して再試行してください。",
"SSO_EMAIL_REQUIRED": "企業 ID から有効なメールアドレスを取得できません。IdP の設定を管理者に確認してください。",
"INVALID_SSO_VERIFICATION_TICKET": "企業 ID の確認期限が切れました。SSO サインインをやり直してください。",
"SOCIAL_TOKEN_INVALID": "プロバイダー認証の期限が切れました。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index c784d712fa..6ffcccbff3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3028,6 +3028,13 @@
"ssoOrgPlaceholder": "회사 ID, slug 또는 도메인",
"ssoOrgHint": "기업 로그인 식별자를 모르시나요? 관리자에게 문의하세요",
"ssoOrgDetected": "\"{{org}}\"의 통합 로그인 방식을 선택하세요",
+ "realmConsent": {
+ "title": "기업 지역에 연결",
+ "bodyCn": "이 기업은 중국 본토 지역에 있습니다.\n계속하면 Cindy가 해당 지역에 연결됩니다.",
+ "bodyGlobal": "이 기업은 글로벌 지역에 있습니다.\n계속하면 Cindy가 해당 지역에 연결됩니다.",
+ "agree": "로그인 계속",
+ "disagree": "취소"
+ },
"ssoVerificationTitle": "기업 신원 확인",
"ssoVerificationSubtitle": "최초 로그인 시 ID 공급자가 반환한 연락처 {{target}} 확인이 필요합니다",
"enterCode": "인증 코드 입력",
@@ -3076,6 +3083,8 @@
"RATE_LIMITED": "시도가 너무 많습니다. 잠시 후 다시 시도하세요.",
"SSO_LOGIN_REQUIRED": "이 조직은 SSO 로그인이 필요합니다.",
"ORG_SSO_NOT_FOUND": "해당 기업을 찾을 수 없거나 SSO 로그인이 활성화되어 있지 않습니다",
+ "ORG_REALM_AMBIGUOUS": "이 기업 식별자가 두 지역에 모두 존재합니다. 관리자에게 문의하세요.",
+ "ORG_REALM_UNAVAILABLE": "현재 기업 지역을 확인할 수 없습니다. 네트워크를 확인한 후 다시 시도하세요.",
"SSO_EMAIL_REQUIRED": "기업 신원에서 유효한 이메일을 받지 못했습니다. 관리자에게 IdP 설정을 확인해 달라고 요청하세요.",
"INVALID_SSO_VERIFICATION_TICKET": "기업 신원 확인이 만료되었습니다. SSO 로그인을 다시 시작하세요.",
"SOCIAL_TOKEN_INVALID": "제공자 인증이 만료되었습니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b26428c4ec..4ef42b4daa 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3028,6 +3028,13 @@
"ssoOrgPlaceholder": "请输入企业 ID、slug 或域名",
"ssoOrgHint": "不知道企业登录标识?请联系企业管理员",
"ssoOrgDetected": "选择企业「{{org}}」的单点登录方式",
+ "realmConsent": {
+ "title": "连接企业所在区域",
+ "bodyCn": "你的企业位于中国大陆区。\n继续后,Cindy 会连接该区域。",
+ "bodyGlobal": "你的企业位于国际区。\n继续后,Cindy 会连接该区域。",
+ "agree": "继续登录",
+ "disagree": "取消"
+ },
"ssoVerificationTitle": "验证企业联系方式",
"ssoVerificationSubtitle": "首次登录需要验证身份提供方返回的联系方式 {{target}}",
"enterCode": "输入验证码",
@@ -3076,6 +3083,8 @@
"RATE_LIMITED": "操作过于频繁,请稍后再试",
"SSO_LOGIN_REQUIRED": "该邮箱所属企业要求通过 SSO 登录",
"ORG_SSO_NOT_FOUND": "未找到该企业,或该企业未启用 SSO 登录",
+ "ORG_REALM_AMBIGUOUS": "该企业标识同时存在于两个区域,请联系企业管理员处理",
+ "ORG_REALM_UNAVAILABLE": "暂时无法确认企业所在区域,请检查网络后重试",
"SSO_EMAIL_REQUIRED": "该企业身份未提供有效邮箱,请联系企业管理员检查 IdP 配置",
"INVALID_SSO_VERIFICATION_TICKET": "企业身份验证已过期,请重新发起 SSO 登录",
"SOCIAL_TOKEN_INVALID": "第三方授权已失效,请重试",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 99686b4987..97dcd5b72d 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2,8 +2,10 @@
interface ImportMetaEnv {
readonly VITE_CINDY_AUTH_REGION: 'cn' | 'global' | 'dev';
- /** 端点清单自举基址(唯一烘焙远程 URL);业务端点走 electronAPI.clientEndpoints。 */
+ /** 当前构建区域的端点清单自举基址;业务端点走 electronAPI.clientEndpoints。 */
readonly VITE_ENDPOINT_MANIFEST_BASE_URL: string;
+ /** 另一物理区域的受信任端点清单自举基址。 */
+ readonly VITE_ENDPOINT_MANIFEST_PEER_BASE_URL: string;
}
interface ImportMeta {
diff --git a/apps/desktop/src/shared/__tests__/authIpc.test.ts b/apps/desktop/src/shared/__tests__/authIpc.test.ts
index 77d59ad0d4..78b732ea03 100644
--- a/apps/desktop/src/shared/__tests__/authIpc.test.ts
+++ b/apps/desktop/src/shared/__tests__/authIpc.test.ts
@@ -51,7 +51,20 @@ describe('desktop auth IPC validation', () => {
org: `${'a'.repeat(64)}.example.com`,
extra: 'x',
}),
- ).toEqual({ type: 'discover-sso-org', org: `${'a'.repeat(64)}.example.com` });
+ ).toEqual({
+ type: 'discover-sso-org',
+ org: `${'a'.repeat(64)}.example.com`,
+ });
+ expect(parseDesktopLoginAction({ type: 'discover-sso-org', org: 'corp' })).toEqual({
+ type: 'discover-sso-org',
+ org: 'corp',
+ });
+ expect(parseDesktopLoginAction({ type: 'confirm-sso-realm' })).toEqual({
+ type: 'confirm-sso-realm',
+ });
+ expect(parseDesktopLoginAction({ type: 'cancel-sso-realm' })).toEqual({
+ type: 'cancel-sso-realm',
+ });
expect(
parseDesktopLoginAction({
type: 'request-code',
diff --git a/apps/desktop/src/shared/authIpc.ts b/apps/desktop/src/shared/authIpc.ts
index 4a4342f8a3..7c775c9162 100644
--- a/apps/desktop/src/shared/authIpc.ts
+++ b/apps/desktop/src/shared/authIpc.ts
@@ -11,6 +11,8 @@ export type DesktopLoginAction =
| { type: 'cancel-browser' }
| { type: 'discover'; email: string }
| { type: 'discover-sso-org'; org: string }
+ | { type: 'confirm-sso-realm' }
+ | { type: 'cancel-sso-realm' }
| { type: 'request-code'; kind: VerificationKind; identifier: string }
| { type: 'verify-code'; kind: VerificationKind; identifier: string; code: string }
| {
@@ -93,6 +95,10 @@ export function parseDesktopLoginAction(value: unknown): DesktopLoginAction | nu
return isBoundedString(value.org, MAX_ORG_IDENTIFIER_LENGTH)
? { type: 'discover-sso-org', org: value.org }
: null;
+ case 'confirm-sso-realm':
+ return { 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)
diff --git a/apps/desktop/src/shared/endpoints.ts b/apps/desktop/src/shared/endpoints.ts
index df755c7706..a9a84ac4cd 100644
--- a/apps/desktop/src/shared/endpoints.ts
+++ b/apps/desktop/src/shared/endpoints.ts
@@ -6,10 +6,9 @@
* 解析的端点清单(main 走 getClientEndpoint(),renderer 走
* electronAPI.clientEndpoints)——本文件不再提供任何业务端点烘焙常量。
*
- * 仅存的烘焙注入是清单自举基址(构建脚本读 region 对应的 config/endpoint*.json
- * 的 cdnBaseUrl 注入 VITE_ENDPOINT_MANIFEST_BASE_URL);本文件只提供类型化出口,
- * 不保存任何生产地址。空值表示当前构建未配置,消费方(clientEndpointsService)
- * 会在启动时阻断暴露。
+ * 仅存的烘焙注入是本区与对端的两份清单自举基址(构建脚本分别读取
+ * config/endpoint*.json 的 cdnBaseUrl);本文件只提供类型化出口,不保存任何
+ * 生产地址。空值表示当前构建未配置,消费方(clientEndpointsService)会阻断暴露。
*/
function injectedEndpoint(value: string | undefined): string {
@@ -17,14 +16,17 @@ function injectedEndpoint(value: string | undefined): string {
}
/**
- * 端点清单(endpoint.json)的自举拉取基址,按 region(cn/global)构建期二选一
- * 烘焙。这是客户端唯一"有感"的烘焙远程 URL:完整拉取地址 = `${base}/endpoint.json`,
- * 其余业务端点(含更新链 CDN base)全部来自清单解析结果(getClientEndpoint)。
+ * 当前构建区域端点清单(endpoint.json)的自举拉取基址。另一物理区域使用下方
+ * PEER 基址;其余业务端点(含更新链 CDN base)全部来自清单解析结果。
*/
export const ENDPOINT_MANIFEST_BASE_URL = injectedEndpoint(
import.meta.env.VITE_ENDPOINT_MANIFEST_BASE_URL,
);
+/** 另一物理区域的端点清单基址;与本区基址共同构成受信任的双区地址表。 */
+export const ENDPOINT_MANIFEST_PEER_BASE_URL = injectedEndpoint(
+ import.meta.env.VITE_ENDPOINT_MANIFEST_PEER_BASE_URL,
+);
+
/** TapDB 埋点上报端点;第三方固定协议地址不属于生产端点私有配置。 */
export const TAPDB_EVENT_URL = 'https://e.tapdb.com/event';
-
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
index 3b626ae6f7..befd198ca4 100644
--- a/apps/desktop/vite.main.config.ts
+++ b/apps/desktop/vite.main.config.ts
@@ -36,12 +36,15 @@ export default defineConfig(({ mode }) => {
'import.meta.env.VITE_CINDY_AUTH_REGION': JSON.stringify(
readViteEnv('VITE_CINDY_AUTH_REGION'),
),
- // 端点清单自举基址(唯一烘焙远程 URL;业务端点已全部改走运行期清单,
+ // 本区与对端的两份端点清单自举基址(业务端点已全部改走运行期清单,
// 旧的 VITE_API_BASE_URL 等端点 define 随之退役)。dev 构建也注入 cn 值,
// `--endpoints-cdn` 才能零配置直连线上清单。
'import.meta.env.VITE_ENDPOINT_MANIFEST_BASE_URL': JSON.stringify(
readViteEnv('VITE_ENDPOINT_MANIFEST_BASE_URL'),
),
+ 'import.meta.env.VITE_ENDPOINT_MANIFEST_PEER_BASE_URL': JSON.stringify(
+ readViteEnv('VITE_ENDPOINT_MANIFEST_PEER_BASE_URL'),
+ ),
// Triage bot token (dev only — production 留空,BotTokenStore 走 safeStorage)
'process.env.TRIAGE_BOT_TOKEN': JSON.stringify(readMainEnv('TRIAGE_BOT_TOKEN')),
// Filo Google OAuth desktop client(main-only,仓库不保存实际值)。
diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.ts
index 855e1164da..3b3aaee116 100644
--- a/apps/desktop/vitest.config.ts
+++ b/apps/desktop/vitest.config.ts
@@ -11,6 +11,9 @@ export default defineConfig({
'import.meta.env.VITE_ENDPOINT_MANIFEST_BASE_URL': JSON.stringify(
clientBuildEnv.VITE_ENDPOINT_MANIFEST_BASE_URL,
),
+ 'import.meta.env.VITE_ENDPOINT_MANIFEST_PEER_BASE_URL': JSON.stringify(
+ clientBuildEnv.VITE_ENDPOINT_MANIFEST_PEER_BASE_URL,
+ ),
},
plugins: [
{
diff --git a/apps/mobile/.env.example b/apps/mobile/.env.example
index 74be1fada2..c58d794077 100644
--- a/apps/mobile/.env.example
+++ b/apps/mobile/.env.example
@@ -6,6 +6,7 @@
# 清单自举基址由 ensure-mobile-env 从对应 region 的 config/endpoint*.json.cdnBaseUrl 补写。
EXPO_PUBLIC_CINDY_AUTH_REGION=global
EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=
+EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=
EXPO_PUBLIC_CINDY_AUTH_BASE_URL=
EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL=
# Global Google 原生登录(部署时由 EAS environment 注入;仓库不存 provider 凭证)
diff --git a/apps/mobile/README.md b/apps/mobile/README.md
index a660d608d0..18d24bd740 100644
--- a/apps/mobile/README.md
+++ b/apps/mobile/README.md
@@ -21,7 +21,7 @@ Expo Go or an installed distribution build as proof that local source changes ar
Required Expo public env:
-- `EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL`: endpoint manifest bootstrap base (per-region hotfix CDN). Runtime business endpoints (auth / device-link / gateway) are resolved from `<base>/endpoint.json` at startup; in dev they default to the repo's `config/endpoint.global.json` and can still be overridden with explicit `EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL` / `EXPO_PUBLIC_CINDY_AUTH_BASE_URL`. Set `EXPO_PUBLIC_ENDPOINTS_CDN=1` to make dev fetch the online manifest used by packaged clients.
+- `EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL` / `EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL`: the current and peer region endpoint-manifest bootstrap bases. Runtime business endpoints are resolved from each trusted `<base>/endpoint.json`; organization discovery uses both manifests' `authApiBaseUrl` values. In dev, endpoint defaults still come from the repo region config. Set `EXPO_PUBLIC_ENDPOINTS_CDN=1` to make dev fetch the online manifest used by packaged clients.
The mobile redirect URI is region-specific: `cindycn://auth` for CN and
`cindy://auth` for Global. Cindy Auth and native social login callbacks must
diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.js
index 3866c5b8c9..856efb56dc 100644
--- a/apps/mobile/app.config.js
+++ b/apps/mobile/app.config.js
@@ -113,6 +113,22 @@ function resolveMobileBuildEnv() {
return loadMobileClientBuildEnv();
}
+function resolvePeerManifestBaseUrl(region) {
+ const previousRegion = process.env.EXPO_PUBLIC_CINDY_AUTH_REGION;
+ try {
+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION =
+ region === 'global' ? 'cn' : 'global';
+ const peerBuildEnv = loadMobileClientBuildEnv();
+ return peerBuildEnv.EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL;
+ } finally {
+ if (previousRegion === undefined) {
+ delete process.env.EXPO_PUBLIC_CINDY_AUTH_REGION;
+ } else {
+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = previousRegion;
+ }
+ }
+}
+
const REGION_CONFIG = {
cn: {
scheme: 'cindycn',
@@ -186,9 +202,17 @@ module.exports = (context = {}) => {
const baseConfig = context.config ?? appJson.expo;
const region = resolveRegion();
const mobileBuildEnv = resolveMobileBuildEnv();
- for (const [key, value] of Object.entries(mobileBuildEnv)) {
+ const mobileBundleEnv = {
+ ...mobileBuildEnv,
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL:
+ resolvePeerManifestBaseUrl(region),
+ };
+ for (const [key, value] of Object.entries(mobileBundleEnv)) {
if (!process.env[key]?.trim()) process.env[key] = value;
}
+ // xdtProductionEnv 是既有 Expo config / runtime fingerprint 的一部分。对端清单
+ // 基址只需通过上面的 EXPO_PUBLIC_* 环境变量进入 Metro bundle;不要把它追加到
+ // extra,否则本次纯 JS 登录路由会无意要求一次冷构建,并切断旧 runtime 的 OTA 链。
const selfHosted = process.env.EXPO_PUBLIC_XDT_OTA_SELFHOST === '1';
const usesLocalRegionConfig =
process.env.CINDY_USE_LOCAL_REGION_CONFIG === '1';
diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx
index b040f9e597..321d7835fd 100644
--- a/apps/mobile/app/(auth)/login.tsx
+++ b/apps/mobile/app/(auth)/login.tsx
@@ -116,6 +116,10 @@ export default function LoginScreen() {
// 企业 SSO 入口子视图:在 identifier 步骤内输入组织标识(本地展示态)
const [ssoOrgMode, setSsoOrgMode] = useState(false);
const [ssoOrg, setSsoOrg] = useState('');
+ const realmConfirmation =
+ auth.loginState?.step === 'realm-confirmation'
+ ? auth.loginState
+ : null;
/* ── 协议同意链路(consent PR,与桌面 LoginPage 同源语义):radio 状态 +
未勾选拦截弹窗 + 同意后续接。过门点(产品拍板 2026-07-24 二次):手机号提交、
邮箱提交(discover 前)、method-choice 个人行发码、社交圆钮(Apple/Google/
@@ -356,7 +360,12 @@ export default function LoginScreen() {
const submitSsoOrg = () => {
const value = ssoOrg.trim();
if (!value) return;
- void auth.dispatchLoginAction({ type: 'discover-sso-org', org: value });
+ // 先静默发现组织区域;只有跨出安装包区域时 AuthContext 才进入
+ // realm-confirmation,并由页面底部弹窗在继续 SSO 前确认。
+ void auth.dispatchLoginAction({
+ type: 'discover-sso-org',
+ org: value,
+ });
};
return (
<LoginPanel testID="login.panel.ssoOrg">
@@ -1145,7 +1154,9 @@ export default function LoginScreen() {
// 穿透读到文案、completed 态还能激活「我知道了」);② 入场未完成(opacity/pointerEvents
// 只管渲染与命中,读屏仍会念出不可见的注销状态)。iOS 走 accessibilityElementsHidden、
// Android 走 importantForAccessibility,两端都要给(PR #464 codex)。
- const deletionBubbleA11yHidden = consentDialogOpen || handoffPhase !== 'done';
+ const realmConsentOpen = realmConfirmation !== null;
+ const deletionBubbleA11yHidden =
+ consentDialogOpen || realmConsentOpen || handoffPhase !== 'done';
return (
<MobileLoginHandoffStage
@@ -1157,7 +1168,9 @@ export default function LoginScreen() {
collapsable={false}
// Android 读屏:弹窗打开时隐藏背景登录组(accessibilityViewIsModal 仅 iOS
// 生效;codex 审查 P2)。iOS 忽略此属性,无副作用。
- importantForAccessibility={consentDialogOpen ? 'no-hide-descendants' : 'auto'}
+ importantForAccessibility={
+ consentDialogOpen || realmConsentOpen ? 'no-hide-descendants' : 'auto'
+ }
onLayout={measureBaseline}
ref={outerGroupRef}
style={{
@@ -1240,6 +1253,27 @@ export default function LoginScreen() {
onOpenPrivacy={() => openLegalLink('privacy')}
/>
) : null}
+ {realmConfirmation ? (
+ <LoginConsentDialog
+ scale={groupScale}
+ title={loginText('realmConsentTitle')}
+ body={loginText(
+ realmConfirmation.targetRegion === 'cn'
+ ? 'realmConsentBodyCn'
+ : 'realmConsentBodyGlobal',
+ )}
+ agreeLabel={loginText('realmConsentAgree')}
+ disagreeLabel={loginText('realmConsentDisagree')}
+ onAgree={() =>
+ void auth.dispatchLoginAction({ type: 'confirm-sso-realm' })
+ }
+ onDisagree={() =>
+ void auth.dispatchLoginAction({ type: 'cancel-sso-realm' })
+ }
+ onOpenTerms={() => undefined}
+ onOpenPrivacy={() => undefined}
+ />
+ ) : null}
</MobileLoginHandoffStage>
);
}
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index 6bbd9a5421..b962283533 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -59,7 +59,6 @@ import {
} from '@/settings/mobileSettings';
import {
isPushSupported,
- markPendingUnregister,
readPushEnabled,
syncPushRegistration,
writePushEnabled,
@@ -528,7 +527,6 @@ export default function SettingsScreen() {
try {
await syncPushRegistration({ enabled: false, apiFetch: auth.apiFetch });
} catch {
- await markPendingUnregister().catch(() => undefined);
setPushMessage(t('settings.notifications.unregisterQueued'));
}
return;
diff --git a/apps/mobile/scripts/build-android.mjs b/apps/mobile/scripts/build-android.mjs
index 8fe09cad13..66d11c886a 100644
--- a/apps/mobile/scripts/build-android.mjs
+++ b/apps/mobile/scripts/build-android.mjs
@@ -67,7 +67,7 @@ import {
import { resolveJavaRuntimeEnv } from './java-runtime-env.mjs';
import { clearBundlerCache } from './lib/bundler-cache.mjs';
import { readEmbeddedRuntimeVersionFromApk } from './lib/embedded-runtime.mjs';
-import { loadEndpointManifestBaseUrl, mobileClientBuildEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
import { SELF_HOST_REGIONS, loadSelfHostRegions, missingSelfHostBakeFields, stripSelfHostRegionEnv } from './lib/self-host-region.mjs';
const MOBILE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -79,7 +79,7 @@ function log(msg) { console.error(msg); }
function selfhostEnv(region, versionCode, desktopVersion) {
const env = {
...process.env,
- ...mobileClientBuildEnv({ authRegion: region.authRegion }),
+ ...mobileClientBundleEnv({ authRegion: region.authRegion }),
EXPO_PUBLIC_XDT_OTA_SELFHOST: '1',
XDT_ANDROID_VERSION_CODE: String(versionCode),
};
@@ -95,8 +95,7 @@ function selfhostEnv(region, versionCode, desktopVersion) {
// 口令等机密)引入日志(与 selfhostEnv 注入的同名值一致)。
function bakedDisplayEnv(region, versionCode, desktopVersion) {
return {
- EXPO_PUBLIC_CINDY_AUTH_REGION: region.authRegion,
- EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: loadEndpointManifestBaseUrl({ authRegion: region.authRegion }),
+ ...mobileClientBundleEnv({ authRegion: region.authRegion }),
EXPO_PUBLIC_XDT_OTA_SELFHOST: '1',
...(desktopVersion ? { EXPO_PUBLIC_DESKTOP_VERSION: desktopVersion } : {}),
XDT_ANDROID_VERSION_CODE: String(versionCode),
diff --git a/apps/mobile/scripts/build-ios.mjs b/apps/mobile/scripts/build-ios.mjs
index ccc9057c28..9e6cc2db06 100644
--- a/apps/mobile/scripts/build-ios.mjs
+++ b/apps/mobile/scripts/build-ios.mjs
@@ -62,7 +62,7 @@ import {
import { buildExportOptionsPlist, resolveIosSigningEnv } from './lib/ios-local.mjs';
import { clearBundlerCache } from './lib/bundler-cache.mjs';
import { readEmbeddedRuntimeVersionFromIpa } from './lib/embedded-runtime.mjs';
-import { loadEndpointManifestBaseUrl, mobileClientBuildEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
import { SELF_HOST_REGIONS, loadSelfHostRegions, missingSelfHostBakeFields, stripSelfHostRegionEnv } from './lib/self-host-region.mjs';
const MOBILE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -74,7 +74,7 @@ function log(msg) { console.error(msg); }
function selfhostEnv(region, desktopVersion) {
const env = {
...process.env,
- ...mobileClientBuildEnv({ authRegion: region.authRegion }),
+ ...mobileClientBundleEnv({ authRegion: region.authRegion }),
EXPO_PUBLIC_XDT_OTA_SELFHOST: '1',
};
// 防止本机 shell / 旧 .env 残留变量混入构建;真实地址只认 config/endpoint*.json。
@@ -89,8 +89,7 @@ function selfhostEnv(region, desktopVersion) {
// 口令等机密)引入日志(与 selfhostEnv 注入的同名值一致)。
function bakedDisplayEnv(region, desktopVersion) {
return {
- EXPO_PUBLIC_CINDY_AUTH_REGION: region.authRegion,
- EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: loadEndpointManifestBaseUrl({ authRegion: region.authRegion }),
+ ...mobileClientBundleEnv({ authRegion: region.authRegion }),
EXPO_PUBLIC_XDT_OTA_SELFHOST: '1',
...(desktopVersion ? { EXPO_PUBLIC_DESKTOP_VERSION: desktopVersion } : {}),
};
diff --git a/apps/mobile/scripts/ensure-mobile-env.mjs b/apps/mobile/scripts/ensure-mobile-env.mjs
index 331667fcf5..6199df7d8f 100644
--- a/apps/mobile/scripts/ensure-mobile-env.mjs
+++ b/apps/mobile/scripts/ensure-mobile-env.mjs
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { mobileClientBuildEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
export const MOBILE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
// 2026-07 端点清单重构后收缩:dev 业务端点初值来自仓内 config/endpoint.json
@@ -10,6 +10,7 @@ export const MOBILE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..')
export const REQUIRED_MOBILE_ENV_KEYS = [
'EXPO_PUBLIC_CINDY_AUTH_REGION',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',
];
/**
@@ -45,7 +46,7 @@ export function ensureMobileEnv({
...easDefaults,
...(endpointEnv ??
(authRegion || needsClientBuildDefaults
- ? mobileClientBuildEnv({
+ ? mobileClientBundleEnv({
authRegion:
authRegion || existingRegion || easDefaults.EXPO_PUBLIC_CINDY_AUTH_REGION,
})
diff --git a/apps/mobile/scripts/lib/sim-whoami.mjs b/apps/mobile/scripts/lib/sim-whoami.mjs
index 24d10c32a1..a71c13dda2 100644
--- a/apps/mobile/scripts/lib/sim-whoami.mjs
+++ b/apps/mobile/scripts/lib/sim-whoami.mjs
@@ -1,7 +1,7 @@
import { execFileSync } from 'node:child_process';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { mobileClientBuildEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';
import { withLocalMobileRegionConfig } from './mobile-dev-region.mjs';
const mobileDir = resolve(dirname(fileURLToPath(import.meta.url)), '../..');
@@ -43,7 +43,7 @@ export function extractSimMetroPortArgs(args, defaultPort = 8081) {
export function resolveMobileSimulatorBundleId(region, options = {}) {
const run = options.execFile ?? execFileSync;
const buildEnv = withLocalMobileRegionConfig(
- mobileClientBuildEnv({ authRegion: region }),
+ mobileClientBundleEnv({ authRegion: region }),
);
let raw;
try {
diff --git a/apps/mobile/scripts/mobile-endpoints.mjs b/apps/mobile/scripts/mobile-endpoints.mjs
index 8f8c0f735c..66b608bf2a 100644
--- a/apps/mobile/scripts/mobile-endpoints.mjs
+++ b/apps/mobile/scripts/mobile-endpoints.mjs
@@ -11,7 +11,7 @@ import {
import { randomUUID } from 'node:crypto';
import { resolve } from 'node:path';
-import { mobileClientBuildEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
/**
* 临时向所有 EAS build profile 注入 region + 清单自举基址,并返回幂等恢复函数。
@@ -34,9 +34,9 @@ export function injectMobileEndpointsIntoEasFile(
options.endpointEnv
? null
: {
- cn: mobileClientBuildEnv({ authRegion: 'cn' }),
- global: mobileClientBuildEnv({ authRegion: 'global' }),
- dev: mobileClientBuildEnv({ authRegion: 'dev' }),
+ cn: mobileClientBundleEnv({ authRegion: 'cn' }),
+ global: mobileClientBundleEnv({ authRegion: 'global' }),
+ dev: mobileClientBundleEnv({ authRegion: 'dev' }),
}
);
const fallbackEndpointEnv = options.endpointEnv ?? endpointEnvByRegion?.cn;
diff --git a/apps/mobile/scripts/open-ios-xcode.mjs b/apps/mobile/scripts/open-ios-xcode.mjs
index b66a407ecd..81e7e2e1ba 100644
--- a/apps/mobile/scripts/open-ios-xcode.mjs
+++ b/apps/mobile/scripts/open-ios-xcode.mjs
@@ -7,7 +7,7 @@ import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { mobileClientBuildEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
import { podInstallBounded } from './sim-pod-install.mjs';
import { cwdOfPid, isInside, listenerPid, portInUse } from './sim-metro.mjs';
import { withLocalMobileRegionConfig } from './lib/mobile-dev-region.mjs';
@@ -45,7 +45,7 @@ async function main() {
}
const buildEnv = withLocalMobileRegionConfig(
- mobileClientBuildEnv({ authRegion: args.region }),
+ mobileClientBundleEnv({ authRegion: args.region }),
);
const env = { ...process.env, ...buildEnv };
const previousEnv = existsSync(envPath) ? readFileSync(envPath, 'utf8') : '';
diff --git a/apps/mobile/scripts/release-lib.mjs b/apps/mobile/scripts/release-lib.mjs
index 691a96c122..793fa6400c 100644
--- a/apps/mobile/scripts/release-lib.mjs
+++ b/apps/mobile/scripts/release-lib.mjs
@@ -86,12 +86,14 @@ export function assertProductionGitGate({ cwd = process.cwd(), git = runGit } =
}
/**
- * 自建纯构建必须齐全的公开构建变量:region 身份、端点清单自举基址、自建门控标志。
+ * 自建纯构建必须齐全的公开构建变量:region 身份、本区/对端清单自举基址、
+ * 自建门控标志。
* 值全部来自仓内 config/endpoint*.json 与脚本字面量(见 build 脚本的 selfhostEnv)。
*/
export const SELF_HOST_PUBLIC_ENV_KEYS = Object.freeze([
'EXPO_PUBLIC_CINDY_AUTH_REGION',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',
'EXPO_PUBLIC_XDT_OTA_SELFHOST',
]);
diff --git a/apps/mobile/scripts/sim-rebuild.mjs b/apps/mobile/scripts/sim-rebuild.mjs
index ceb76d6953..21591ab757 100644
--- a/apps/mobile/scripts/sim-rebuild.mjs
+++ b/apps/mobile/scripts/sim-rebuild.mjs
@@ -51,7 +51,7 @@ import {
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { mobileClientBuildEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
import { ensureMobileEnv, formatMobileEnvStatus } from './ensure-mobile-env.mjs';
import { computeFingerprintReport, parseFingerprintCliOutput } from './ci-fingerprint.mjs';
import {
@@ -83,7 +83,7 @@ const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });
const localConfigStatus = formatMobileLocalConfigStatus(localConfigResult, worktreeRoot);
if (localConfigStatus) console.log(localConfigStatus);
const buildEnv = withLocalMobileRegionConfig(
- mobileClientBuildEnv({ authRegion: region }),
+ mobileClientBundleEnv({ authRegion: region }),
);
const devProcessEnv = { ...process.env, ...buildEnv };
diff --git a/apps/mobile/scripts/sim-start.mjs b/apps/mobile/scripts/sim-start.mjs
index a3ae62325f..fc104d259a 100644
--- a/apps/mobile/scripts/sim-start.mjs
+++ b/apps/mobile/scripts/sim-start.mjs
@@ -22,7 +22,7 @@
import { execFileSync, spawn } from 'node:child_process';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { mobileClientBuildEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../scripts/shared/client-endpoint-build-env.mjs';
import { ensureMobileEnv, formatMobileEnvStatus } from './ensure-mobile-env.mjs';
import {
extractMobileDevRegionArgs,
@@ -51,7 +51,7 @@ const localConfigResult = ensureMobileLocalRegionConfig({ mobileDir });
const localConfigStatus = formatMobileLocalConfigStatus(localConfigResult, worktreeRoot);
if (localConfigStatus) console.log(localConfigStatus);
const buildEnv = withLocalMobileRegionConfig(
- mobileClientBuildEnv({ authRegion: region }),
+ mobileClientBundleEnv({ authRegion: region }),
);
const envResult = ensureMobileEnv({ mobileDir, authRegion: region, endpointEnv: buildEnv });
diff --git a/apps/mobile/src/__tests__/accountDeletion.test.ts b/apps/mobile/src/__tests__/accountDeletion.test.ts
index 00b31e2ee1..54d25bfca5 100644
--- a/apps/mobile/src/__tests__/accountDeletion.test.ts
+++ b/apps/mobile/src/__tests__/accountDeletion.test.ts
@@ -3,7 +3,10 @@ import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
function source(path: string): string {
- return readFileSync(resolve(process.cwd(), path), 'utf8').replace(/\r\n/g, '\n');
+ return readFileSync(resolve(process.cwd(), path), 'utf8').replace(
+ /\r\n/g,
+ '\n',
+ );
}
describe('mobile account deletion', () => {
@@ -17,7 +20,9 @@ describe('mobile account deletion', () => {
expect(settings).toContain('testID="settings.deleteAccountButton"');
expect(settings).toContain('{accountDeletionAvailable ? (');
expect(settings).toContain('style={styles.accountDeletionLinkText}');
- expect(settings).not.toContain("testID: 'settings.deleteAccountButton',\n tone: 'danger'");
+ expect(settings).not.toContain(
+ "testID: 'settings.deleteAccountButton',\n tone: 'danger'",
+ );
expect(visibilityBlock).toContain('availability.available');
expect(visibilityBlock).not.toContain('membershipKind');
});
@@ -41,9 +46,7 @@ describe('mobile account deletion', () => {
context.indexOf('const dispatchLoginAction', acceptStart),
);
- expect(context).toContain(
- "'cindy.mobile.auth.accountDeletionReceipt'",
- );
+ expect(context).toContain("'cindy.mobile.auth.accountDeletionReceipt'");
expect(acceptBody).toContain(
"if (outcome.status === 'ok' || outcome.status === 'select_account')",
);
@@ -54,7 +57,7 @@ describe('mobile account deletion', () => {
);
expect(acceptBody).toContain('pendingAccountDeletionRestoredRef.current =');
expect(acceptBody).toContain(
- "outcome.accountDeletionRestored === true ||\n pendingAccountDeletionRestoredRef.current",
+ 'outcome.accountDeletionRestored === true ||\n pendingAccountDeletionRestoredRef.current',
);
expect(acceptBody.indexOf('setToken(outcome.accessToken)')).toBeLessThan(
acceptBody.indexOf('setAccountDeletionRestored(deletionWasRestored)'),
@@ -62,6 +65,10 @@ describe('mobile account deletion', () => {
expect(requestBody.indexOf('persistAccountDeletionReceipt')).toBeLessThan(
requestBody.indexOf('return challenge'),
);
+ expect(context).toContain(
+ 'serializeAccountDeletionReceiptRecord(realm, receiptToken)',
+ );
+ expect(requestBody).toContain('activeAuthRealmRef.current,\n );');
expect(confirmBody).toContain('await clearLocalSession();');
expect(confirmBody).not.toContain(
'persistAccountDeletionReceipt(input.receiptToken)',
@@ -77,8 +84,21 @@ describe('mobile account deletion', () => {
logoutStart,
context.indexOf('const getAccessToken', logoutStart),
);
- expect(logoutBody.indexOf('persistAccountDeletionReceipt(null)')).toBeLessThan(
- logoutBody.indexOf('clearLocalSession()'),
+ expect(
+ logoutBody.indexOf('persistAccountDeletionReceipt(null)'),
+ ).toBeLessThan(logoutBody.indexOf('clearLocalSession()'));
+
+ const statusStart = context.indexOf('const getAccountDeletionStatus');
+ const statusBody = context.slice(
+ statusStart,
+ context.indexOf('const clearAccountDeletionReceipt', statusStart),
+ );
+ expect(statusBody).toContain(
+ 'const realm = accountDeletionReceiptRealmRef.current;',
+ );
+ expect(statusBody).toContain('await loadMobileEndpointsForRealm(realm);');
+ expect(statusBody).toContain(
+ 'authClientFor(did, realm).getAccountDeletionStatus(receiptToken)',
);
});
@@ -153,12 +173,10 @@ describe('mobile account deletion', () => {
expect(loginMessages).toContain('现在重新登录即可取消注销');
expect(loginMessages).toContain('Sign in now to cancel deletion.');
expect(login).toContain("cause.code === 'INVALID_RESPONSE'");
- expect(login).toContain('if (status.status === \'completed\') stopPolling()');
+ expect(login).toContain("if (status.status === 'completed') stopPolling()");
expect(nativeSocial).toContain('if (!credential.identityToken)');
expect(nativeSocial).not.toContain('!credential.authorizationCode');
- expect(nativeSocial).toContain(
- '...(credential.authorizationCode',
- );
+ expect(nativeSocial).toContain('...(credential.authorizationCode');
});
it('renders the deletion status as an opaque overlay bubble with a completed-only underline link (figma 678:1075)', () => {
@@ -177,7 +195,9 @@ describe('mobile account deletion', () => {
expect(panel).toContain('width: frame.width');
expect(panel).toContain('styles.deletionBubble');
// 内部几何按 frame.scale 折算(设计单位 → 物理 pt),不再写死物理值
- expect(panel).toContain('const scaled = (designUnits: number) => designUnits * frame.scale');
+ expect(panel).toContain(
+ 'const scaled = (designUnits: number) => designUnits * frame.scale',
+ );
expect(panel).toContain('borderRadius: scaled(B.radius)');
expect(panel).toContain('padding: scaled(B.padding)');
expect(panel).toContain('fontSize: scaled(B.font)');
@@ -202,16 +222,16 @@ describe('mobile account deletion', () => {
// 三状态:pending/processing 无按钮(调用点 onDismiss 仅 completed 才给),
// completed 渲染「我知道了」下划线文字链,保留原 onPress/testID/accessibilityRole。
- expect(login).toContain(
- "accountDeletionStatus.status === 'completed'",
- );
+ expect(login).toContain("accountDeletionStatus.status === 'completed'");
expect(login).toContain('() => void auth.clearAccountDeletionReceipt()');
expect(panel).toContain('{onDismiss ? (');
expect(panel).toContain('<Pressable');
expect(panel).toContain('accessibilityRole="button"');
expect(panel).toContain('onPress={onDismiss}');
expect(panel).toContain('testID="login.accountDeletionDismissButton"');
- expect(panel).toContain('hitSlop={resolveDeletionBubbleLinkHitSlop(frame.scale)}');
+ expect(panel).toContain(
+ 'hitSlop={resolveDeletionBubbleLinkHitSlop(frame.scale)}',
+ );
expect(panel).toContain('styles.deletionBubbleLinkText');
expect(login).toContain("textDecorationLine: 'underline'");
@@ -298,15 +318,20 @@ describe('mobile account deletion', () => {
// 仅 iOS 生效);② 入场未完成(opacity/pointerEvents 只管渲染与命中,读屏照念)。
// iOS 与 Android 属性都要给,条件收敛到一个常量避免两处漂移。
expect(login).toContain(
- "const deletionBubbleA11yHidden = consentDialogOpen || handoffPhase !== 'done';",
+ 'const realmConsentOpen = realmConfirmation !== null;',
+ );
+ expect(login).toContain(
+ "const deletionBubbleA11yHidden =\n consentDialogOpen || realmConsentOpen || handoffPhase !== 'done';",
+ );
+ expect(gate).toContain(
+ 'accessibilityElementsHidden={deletionBubbleA11yHidden}',
);
- expect(gate).toContain('accessibilityElementsHidden={deletionBubbleA11yHidden}');
expect(gate).toContain(
"deletionBubbleA11yHidden ? 'no-hide-descendants' : 'auto'",
);
// 登录组那层仍按弹窗条件隐藏(它本身在入场动画容器内,不需要入场条件)。
expect(login).toContain(
- "importantForAccessibility={consentDialogOpen ? 'no-hide-descendants' : 'auto'}",
+ "consentDialogOpen || realmConsentOpen ? 'no-hide-descendants' : 'auto'",
);
});
});
diff --git a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
index a8ba47d9b9..a2d54c8bbb 100644
--- a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
+++ b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
@@ -9,13 +9,35 @@ import { describe, expect, it } from 'vitest';
* 弱网冷启动直接把持有效 refresh token 的用户踢回登录页。
*/
describe('auth weak-network bootstrap', () => {
- const authSource = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'), 'utf8');
+ const authSource = readFileSync(
+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),
+ 'utf8',
+ );
- it('bootstrap 先用本地会话痕迹(refresh token + 用户快照)恢复登录视图', () => {
+ it('bootstrap 只在会话 realm 端点激活后用本地痕迹恢复登录视图', () => {
// 快照恢复必须双条件:refresh token 还在 + 有缓存资料;二者缺一不得凭空造登录态。
- expect(authSource).toContain('if (storedRefreshToken && cachedUser) {');
+ expect(authSource).toContain('if (storedSession && cachedUser) {');
expect(authSource).toContain('userRef.current = cachedUser;');
expect(authSource).toContain('setUser(cachedUser);');
+ const restoreStart = authSource.indexOf(
+ 'if (storedSession && cachedUser) {',
+ );
+ const restoreEnd = authSource.indexOf(
+ '\n if (!storedSession)',
+ restoreStart,
+ );
+ const restoreBody = authSource.slice(restoreStart, restoreEnd);
+ const loadRealmAt = restoreBody.indexOf(
+ 'await loadMobileEndpointsForRealm(storedSession.realm);',
+ );
+ const activateRealmAt = restoreBody.indexOf(
+ 'activateMobileSessionRealm(storedSession.realm);',
+ );
+ const publishUserAt = restoreBody.indexOf('setUser(cachedUser);');
+ expect(loadRealmAt).toBeGreaterThanOrEqual(0);
+ expect(activateRealmAt).toBeGreaterThan(loadRealmAt);
+ expect(publishUserAt).toBeGreaterThan(activateRealmAt);
+ expect(restoreBody).toContain('setDeferredSessionRecovery(true);');
// bootstrap 里的 refresh 失败必须是"保留降级会话",不许再出现坍缩式 .catch(() => null)。
expect(authSource).not.toContain('await refresh(did).catch(() => null)');
expect(authSource).toMatch(
@@ -28,12 +50,102 @@ describe('auth weak-network bootstrap', () => {
it('isAuthenticated 以 user 为准,token 未刷到时不闪回登录页', () => {
expect(authSource).toContain('isAuthenticated: user !== null');
- expect(authSource).not.toContain('isAuthenticated: accessToken !== null && user !== null');
+ expect(authSource).not.toContain(
+ 'isAuthenticated: accessToken !== null && user !== null',
+ );
+ });
+
+ it('已发布或因 realm 清单失败而延迟的降级会话都会自愈', () => {
+ expect(authSource).toMatch(
+ /const hasRecoverableSession\s*=\s*user !== null \|\| deferredSessionRecovery;/,
+ );
+ expect(authSource).toMatch(
+ /if \(\s*!initialized \|\|\s*accessToken \|\|\s*!hasRecoverableSession \|\|\s*sessionRecoverySuspendedRef\.current\s*\)\s*return;/,
+ );
+ expect(authSource).toContain(
+ 'const delay = Math.min(5_000 * 2 ** attempt, 60_000);',
+ );
+ });
+
+ it('用户开始新登录后立即停止旧会话自愈,迟到 refresh 也不能抢回界面', () => {
+ expect(authSource).toContain(
+ 'const sessionRecoverySuspendedRef = useRef(false);',
+ );
+ expect(authSource).toContain('authGenerationRef.current += 1;');
+ const dispatchStart = authSource.indexOf(
+ 'const dispatchLoginAction = useCallback',
+ );
+ const dispatchBody = authSource.slice(
+ dispatchStart,
+ authSource.indexOf(
+ 'const clearLocalSession = useCallback',
+ dispatchStart,
+ ),
+ );
+ expect(dispatchBody).toMatch(
+ /action: MobileLoginAction[\s\S]*suspendSessionRecoveryForLogin\(\);[\s\S]*loginActionInFlightRef/,
+ );
+ const healStart = authSource.indexOf('// 降级会话自愈');
+ const healBody = authSource.slice(
+ healStart,
+ authSource.indexOf('// 存量同意迁移', healStart),
+ );
+ expect(healBody).toContain('sessionRecoverySuspendedRef.current');
+ expect(healBody).toContain(
+ 'if (cancelled || sessionRecoverySuspendedRef.current) return;',
+ );
+ });
+
+ it('旧 refresh 的 realm 清单迟到时,必须先检查 generation 再激活区域', () => {
+ const refreshStart = authSource.indexOf('const refresh = useCallback');
+ const refreshBody = authSource.slice(
+ refreshStart,
+ authSource.indexOf('\n useEffect(() => {', refreshStart),
+ );
+ const readSessionAt = refreshBody.indexOf(
+ 'const session = await serializeRefreshTokenMutation(',
+ );
+ const emptySessionAt = refreshBody.indexOf('if (!session) {');
+ const loadRealmAt = refreshBody.indexOf(
+ 'await loadMobileEndpointsForRealm(session.realm);',
+ );
+ const activateRealmAt = refreshBody.indexOf(
+ 'activateMobileSessionRealm(session.realm);',
+ );
+ const guards = [
+ ...refreshBody.matchAll(
+ /if \(authGenerationRef\.current !== generation\) return null;/g,
+ ),
+ ].map((match) => match.index);
+
+ expect(readSessionAt).toBeGreaterThanOrEqual(0);
+ expect(
+ guards.some((index) => index > readSessionAt && index < emptySessionAt),
+ ).toBe(true);
+ expect(loadRealmAt).toBeGreaterThan(emptySessionAt);
+ expect(
+ guards.some((index) => index > loadRealmAt && index < activateRealmAt),
+ ).toBe(true);
});
- it('降级会话存在自愈路径:退避重试 + 回前台重试', () => {
- expect(authSource).toContain('if (!initialized || !user || accessToken) return;');
- expect(authSource).toContain('const delay = Math.min(5_000 * 2 ** attempt, 60_000);');
+ it('换账号或区域时先用旧会话撤销旧区域推送,再激活新区域', () => {
+ const acceptStart = authSource.indexOf('const acceptOutcome = useCallback');
+ const acceptBody = authSource.slice(
+ acceptStart,
+ authSource.indexOf('const refresh = useCallback', acceptStart),
+ );
+ const revokeAt = acceptBody.indexOf('await unregisterPushTokenBestEffort(');
+ const activateAt = acceptBody.indexOf(
+ 'activateMobileSessionRealm(committedRealm);',
+ );
+ expect(acceptBody).toContain(
+ 'const previousRealm = activeAuthRealmRef.current;',
+ );
+ expect(acceptBody).toMatch(
+ /unregisterPushTokenBestEffort\(\s*previousAccessToken,\s*previousRealm,?\s*\)/,
+ );
+ expect(revokeAt).toBeGreaterThanOrEqual(0);
+ expect(activateAt).toBeGreaterThan(revokeAt);
});
it('自愈路径处理 refresh 无异常返回 null:凭证确不在才登出,读取异常只退避(不静默卡死、不误登出)', () => {
@@ -41,16 +153,26 @@ describe('auth weak-network bootstrap', () => {
// 而二次读取 getSecureItem 的**异常**不能与「读到空值」折叠——异常时无从
// 判定凭证是否存在,只能继续退避,绝不能据此 applyUser(null) 误登出。
const healStart = authSource.indexOf('// 降级会话自愈');
- const healBody = authSource.slice(healStart, authSource.indexOf('}, [accessToken, applyUser', healStart));
- expect(healBody).toContain('storedRefreshToken = await getSecureItem(REFRESH_TOKEN_KEY);');
- expect(healBody).not.toContain('getSecureItem(REFRESH_TOKEN_KEY).catch(() => null)');
+ const healBody = authSource.slice(
+ healStart,
+ authSource.indexOf('}, [accessToken, applyUser', healStart),
+ );
+ expect(healBody).toContain(
+ 'storedSession = await readPersistedAuthSession();',
+ );
// 读取异常分支:只 scheduleNext,不 applyUser(null)
- const catchStart = healBody.indexOf('} catch {', healBody.indexOf('storedRefreshToken = await getSecureItem'));
- const catchBody = healBody.slice(catchStart, healBody.indexOf('}', catchStart + 10) + 1);
+ const catchStart = healBody.indexOf(
+ '} catch {',
+ healBody.indexOf('storedSession = await'),
+ );
+ const catchBody = healBody.slice(
+ catchStart,
+ healBody.indexOf('}', catchStart + 10) + 1,
+ );
expect(catchBody).toContain('scheduleNext();');
expect(catchBody).not.toContain('applyUser(null)');
// 成功读到空值才登出收敛
- expect(healBody).toContain('if (!storedRefreshToken) {');
+ expect(healBody).toContain('if (!storedSession) {');
expect(healBody).toContain('applyUser(null);');
});
@@ -59,10 +181,10 @@ describe('auth weak-network bootstrap', () => {
// 否则下次冷启动会用快照复活已失效的会话。
const occurrences = authSource.split('applyUser(null)').length - 1;
expect(occurrences).toBeGreaterThanOrEqual(2);
- expect(authSource).toContain(
- "const USER_PROFILE_KEY = 'cindy.mobile.auth.userProfile';",
+ expect(authSource).toMatch(
+ /const USER_PROFILE_KEY = ["']cindy\.mobile\.auth\.userProfile["'];/,
);
- expect(authSource).toContain("error.code === 'MEMBERSHIP_DISABLED'");
+ expect(authSource).toMatch(/error\.code === ["']MEMBERSHIP_DISABLED["']/);
expect(authSource).toContain('updateLoginState(null);');
});
diff --git a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts b/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
index 4bc2f371e6..20022d8e60 100644
--- a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
+++ b/apps/mobile/src/__tests__/clientEndpointStartup.test.ts
@@ -41,7 +41,10 @@ const FULL_MANIFEST_OBJECT = {
const FULL_MANIFEST = JSON.stringify(FULL_MANIFEST_OBJECT);
const okFetch = (text: string) => async () => ({ ok: true as const, text });
-const failFetch = (detail: string) => async () => ({ ok: false as const, detail });
+const failFetch = (detail: string) => async () => ({
+ ok: false as const,
+ detail,
+});
/** 关掉自动重试预算,测"单次尝试"原语义(不然失败路径会白等真实 backoff)。 */
const NO_AUTO_RETRY = { autoRetryDelaysMs: [] as readonly number[] };
@@ -56,7 +59,9 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
expect(outcome).toEqual({ ok: true, source: 'cdn' });
expect(env.AUTH_API_BASE_URL).toBe('https://auth-next.example.com');
- expect(env.OAUTH_BROKER_API_BASE_URL).toBe('https://oauth-next.example.com');
+ expect(env.OAUTH_BROKER_API_BASE_URL).toBe(
+ 'https://oauth-next.example.com',
+ );
expect(env.DEVICE_LINK_API_BASE_URL).toBe('https://relay-next.example.com');
// 语音网关地址与清单解耦(xdGatewayBaseUrl 已退役):保持构建期 env 值不动。
expect(env.MOBILE_VOICE_LITELLM_BASE_URL).toBe(
@@ -67,6 +72,31 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
expect(env.REVIEW_MODE).toBe(false);
});
+ it('清单自报区域与构建区域不一致时阻断,缺少 region 的老清单仍兼容', async () => {
+ const { env, startup } = await freshModules();
+ const mismatchedRegion =
+ env.BUILD_AUTH_REGION === 'cn' ? 'global' : 'cn';
+ await expect(
+ startup.runStartupEndpointResolve({
+ fetchManifest: okFetch(
+ JSON.stringify({
+ ...FULL_MANIFEST_OBJECT,
+ region: mismatchedRegion,
+ }),
+ ),
+ }),
+ ).resolves.toEqual({
+ ok: false,
+ reason: `region-mismatch:${env.BUILD_AUTH_REGION}:${mismatchedRegion}`,
+ });
+
+ await expect(
+ startup.runStartupEndpointResolve({
+ fetchManifest: okFetch(FULL_MANIFEST),
+ }),
+ ).resolves.toEqual({ ok: true, source: 'cdn' });
+ });
+
it('清单 review 命中二进制版本号且非 TestFlight → REVIEW_MODE=true', async () => {
vi.resetModules();
vi.doMock('expo-constants', () => ({
@@ -128,10 +158,7 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
return JSON.stringify(manifest);
})(),
],
- [
- '字段空串',
- JSON.stringify({ ...FULL_MANIFEST_OBJECT, heartbeatUrl: '' }),
- ],
+ ['字段空串', JSON.stringify({ ...FULL_MANIFEST_OBJECT, heartbeatUrl: '' })],
] as const)('%s → 放行并按空串回写', async (_label, text) => {
const { startup } = await freshModules();
const apply = vi.fn();
@@ -206,7 +233,10 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
...NO_AUTO_RETRY,
});
- expect(outcome).toEqual({ ok: false, reason: 'fetch-failed:timeout-10000ms' });
+ expect(outcome).toEqual({
+ ok: false,
+ reason: 'fetch-failed:timeout-10000ms',
+ });
expect(apply).not.toHaveBeenCalled();
expect(env.DEVICE_LINK_API_BASE_URL).toBe('https://relay.example.invalid');
});
@@ -214,7 +244,8 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
it('fetch 抛错视同拉取失败并阻断(reason 带 name);下一次重试成功后才回写', async () => {
const { env, startup } = await freshModules();
const initialAuthApiBaseUrl = env.AUTH_API_BASE_URL;
- const fetchManifest = vi.fn<FetchManifest>()
+ const fetchManifest = vi
+ .fn<FetchManifest>()
.mockRejectedValueOnce(new TypeError('Network request failed'))
.mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST });
@@ -238,11 +269,17 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
describe('返回失败前的自动重试(首装瞬时失败自愈)', () => {
it('拉取失败后自动重试成功:闸门不进错误屏', async () => {
const { env, startup } = await freshModules();
- const fetchManifest = vi.fn<FetchManifest>()
+ const fetchManifest = vi
+ .fn<FetchManifest>()
.mockResolvedValueOnce({ ok: false, detail: 'timeout-10000ms' })
- .mockResolvedValueOnce({ ok: false, detail: 'TypeError:Network request failed' })
+ .mockResolvedValueOnce({
+ ok: false,
+ detail: 'TypeError:Network request failed',
+ })
.mockResolvedValueOnce({ ok: true, text: FULL_MANIFEST });
- const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+ const sleep = vi
+ .fn<(ms: number) => Promise<void>>()
+ .mockResolvedValue(undefined);
const outcome = await startup.runStartupEndpointResolve({
fetchManifest,
@@ -258,7 +295,8 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
it('预算用尽才阻断,reason 是最后一次的错误码', async () => {
const { startup } = await freshModules();
- const fetchManifest = vi.fn<FetchManifest>()
+ const fetchManifest = vi
+ .fn<FetchManifest>()
.mockResolvedValueOnce({ ok: false, detail: 'AbortError:Aborted' })
.mockResolvedValue({ ok: false, detail: 'timeout-10000ms' });
@@ -269,14 +307,20 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
});
expect(fetchManifest).toHaveBeenCalledTimes(3); // 首发 + 2 次自动重试
- expect(outcome).toEqual({ ok: false, reason: 'fetch-failed:timeout-10000ms' });
+ expect(outcome).toEqual({
+ ok: false,
+ reason: 'fetch-failed:timeout-10000ms',
+ });
});
it('清单非法(配置事故)不消耗重试预算', async () => {
const { startup } = await freshModules();
- const fetchManifest = vi.fn<FetchManifest>()
+ const fetchManifest = vi
+ .fn<FetchManifest>()
.mockResolvedValue({ ok: true, text: 'not-json{' });
- const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+ const sleep = vi
+ .fn<(ms: number) => Promise<void>>()
+ .mockResolvedValue(undefined);
const outcome = await startup.runStartupEndpointResolve({
fetchManifest,
@@ -291,9 +335,12 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
it('missing-manifest-base-url(打包配置事故)不消耗重试预算', async () => {
const { startup } = await freshModules();
- const fetchManifest = vi.fn<FetchManifest>()
+ const fetchManifest = vi
+ .fn<FetchManifest>()
.mockResolvedValue({ ok: false, detail: 'missing-manifest-base-url' });
- const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+ const sleep = vi
+ .fn<(ms: number) => Promise<void>>()
+ .mockResolvedValue(undefined);
const outcome = await startup.runStartupEndpointResolve({
fetchManifest,
@@ -301,33 +348,48 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {
sleep,
});
- expect(outcome).toEqual({ ok: false, reason: 'fetch-failed:missing-manifest-base-url' });
- expect(fetchManifest).toHaveBeenCalledTimes(1);
- expect(sleep).not.toHaveBeenCalled();
- });
-
- it.each([403, 404, 301])('HTTP %d(永久性错误)不消耗重试预算', async (status) => {
- const { startup } = await freshModules();
- const fetchManifest = vi.fn<FetchManifest>()
- .mockResolvedValue({ ok: false, detail: `http-${status}` });
- const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
-
- const outcome = await startup.runStartupEndpointResolve({
- fetchManifest,
- autoRetryDelaysMs: [10, 20],
- sleep,
+ expect(outcome).toEqual({
+ ok: false,
+ reason: 'fetch-failed:missing-manifest-base-url',
});
-
- expect(outcome).toEqual({ ok: false, reason: `fetch-failed:http-${status}` });
expect(fetchManifest).toHaveBeenCalledTimes(1);
expect(sleep).not.toHaveBeenCalled();
});
+ it.each([403, 404, 301])(
+ 'HTTP %d(永久性错误)不消耗重试预算',
+ async (status) => {
+ const { startup } = await freshModules();
+ const fetchManifest = vi
+ .fn<FetchManifest>()
+ .mockResolvedValue({ ok: false, detail: `http-${status}` });
+ const sleep = vi
+ .fn<(ms: number) => Promise<void>>()
+ .mockResolvedValue(undefined);
+
+ const outcome = await startup.runStartupEndpointResolve({
+ fetchManifest,
+ autoRetryDelaysMs: [10, 20],
+ sleep,
+ });
+
+ expect(outcome).toEqual({
+ ok: false,
+ reason: `fetch-failed:http-${status}`,
+ });
+ expect(fetchManifest).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ },
+ );
+
it('HTTP 502(瞬时服务端错误)仍消耗重试预算', async () => {
const { startup } = await freshModules();
- const fetchManifest = vi.fn<FetchManifest>()
+ const fetchManifest = vi
+ .fn<FetchManifest>()
.mockResolvedValue({ ok: false, detail: 'http-502' });
- const sleep = vi.fn<(ms: number) => Promise<void>>().mockResolvedValue(undefined);
+ const sleep = vi
+ .fn<(ms: number) => Promise<void>>()
+ .mockResolvedValue(undefined);
const outcome = await startup.runStartupEndpointResolve({
fetchManifest,
@@ -454,7 +516,48 @@ describe('isReviewModeActive(送审版本号匹配纯函数)', () => {
});
describe('applyResolvedClientEndpoints', () => {
- it('auth 单一字段无脑取:undefined 不修改,空串明确清空', async () => {
+ it('构建区域缓存跟随 token 端点局部覆写,realm reset 不退回旧清单', async () => {
+ const { env, startup } = await freshModules();
+ await expect(
+ startup.runStartupEndpointResolve({
+ fetchManifest: okFetch(
+ JSON.stringify({ ...FULL_MANIFEST_OBJECT, region: 'cn' }),
+ ),
+ }),
+ ).resolves.toEqual({ ok: true, source: 'cdn' });
+ env.applyResolvedClientEndpoints({
+ authApiBaseUrl: 'https://auth.override.example.com',
+ deviceLinkApiBaseUrl: 'https://device.override.example.com',
+ voiceApiBaseUrl: 'https://voice.override.example.com',
+ });
+ expect(
+ env.getMobileEndpointForRealm(
+ env.BUILD_AUTH_REGION,
+ 'authApiBaseUrl',
+ ),
+ ).toBe(env.AUTH_API_BASE_URL);
+ expect(
+ env.getMobileEndpointForRealm(
+ env.BUILD_AUTH_REGION,
+ 'deviceLinkApiBaseUrl',
+ ),
+ ).toBe(env.DEVICE_LINK_API_BASE_URL);
+ expect(
+ env.getMobileEndpointForRealm(
+ env.BUILD_AUTH_REGION,
+ 'voiceApiBaseUrl',
+ ),
+ ).toBe(env.VOICE_API_BASE_URL);
+ env.activateMobileSessionRealm(env.BUILD_AUTH_REGION);
+ env.resetMobileSessionRealm();
+ expect(env.AUTH_API_BASE_URL).toBe('https://auth.override.example.com');
+ expect(env.DEVICE_LINK_API_BASE_URL).toBe(
+ 'https://device.override.example.com',
+ );
+ expect(env.VOICE_API_BASE_URL).toBe('https://voice.override.example.com');
+ });
+
+ it('构建区域 auth 字段:undefined 不修改,空串明确清空', async () => {
const { env } = await freshModules();
env.applyResolvedClientEndpoints({
authApiBaseUrl: 'https://auth-new.example.com',
@@ -465,4 +568,147 @@ describe('applyResolvedClientEndpoints', () => {
env.applyResolvedClientEndpoints({ authApiBaseUrl: '' });
expect(env.AUTH_API_BASE_URL).toBe('');
});
+
+ it('组织会话切换 token 消费端点,退出后恢复构建区域且不改变更新端点', async () => {
+ const { env, startup } = await freshModules();
+ await expect(
+ startup.runStartupEndpointResolve({
+ fetchManifest: okFetch(FULL_MANIFEST),
+ }),
+ ).resolves.toEqual({ ok: true, source: 'cdn' });
+
+ const buildUpdateBaseUrl = env.OTA_SERVER_BASE_URL;
+ const peerRegion = env.BUILD_AUTH_REGION === 'cn' ? 'global' : 'cn';
+ const peerManifest = {
+ ...FULL_MANIFEST_OBJECT,
+ authApiBaseUrl: `https://auth.${peerRegion}.example.com`,
+ oauthBrokerApiBaseUrl: `https://oauth.${peerRegion}.example.com`,
+ deviceLinkApiBaseUrl: `https://device.${peerRegion}.example.com`,
+ voiceApiBaseUrl: `https://voice.${peerRegion}.example.com`,
+ mobileUpdateBaseUrl: `https://update.${peerRegion}.example.com`,
+ };
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ text: async () => JSON.stringify(peerManifest),
+ } as Response);
+ try {
+ await env.loadMobileEndpointsForRealm(peerRegion);
+ env.activateMobileSessionRealm(peerRegion);
+
+ expect(env.AUTH_API_BASE_URL).toBe(peerManifest.authApiBaseUrl);
+ expect(env.OAUTH_BROKER_API_BASE_URL).toBe(
+ peerManifest.oauthBrokerApiBaseUrl,
+ );
+ expect(env.DEVICE_LINK_API_BASE_URL).toBe(
+ peerManifest.deviceLinkApiBaseUrl,
+ );
+ expect(env.VOICE_API_BASE_URL).toBe(peerManifest.voiceApiBaseUrl);
+ expect(env.OTA_SERVER_BASE_URL).toBe(buildUpdateBaseUrl);
+ expect(fetchSpy).toHaveBeenCalledWith(
+ expect.stringContaining(
+ `${env.ENDPOINT_MANIFEST_PEER_BASE_URL}/endpoint.json?t=`,
+ ),
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+
+ env.resetMobileSessionRealm();
+ expect(env.AUTH_API_BASE_URL).toBe(FULL_MANIFEST_OBJECT.authApiBaseUrl);
+ expect(env.OAUTH_BROKER_API_BASE_URL).toBe(
+ FULL_MANIFEST_OBJECT.oauthBrokerApiBaseUrl,
+ );
+ expect(env.DEVICE_LINK_API_BASE_URL).toBe(
+ FULL_MANIFEST_OBJECT.deviceLinkApiBaseUrl,
+ );
+ expect(env.VOICE_API_BASE_URL).toBe(FULL_MANIFEST_OBJECT.voiceApiBaseUrl);
+ } finally {
+ fetchSpy.mockRestore();
+ }
+ });
+
+ it('不依赖远端跨区字段,按构建期可信地址加载旧格式对端清单', async () => {
+ const { env, startup } = await freshModules();
+ const buildRegion = env.BUILD_AUTH_REGION;
+ const peerRegion = buildRegion === 'cn' ? 'global' : 'cn';
+ await expect(
+ startup.runStartupEndpointResolve({
+ fetchManifest: okFetch(FULL_MANIFEST),
+ }),
+ ).resolves.toEqual({ ok: true, source: 'cdn' });
+
+ const realmConfig = env.getMobileEndpointRealmConfig();
+ expect(realmConfig.crossRealmOrgLoginEnabled).toBe(true);
+ expect(realmConfig.realmManifestBaseUrls[buildRegion]).toBe(
+ env.ENDPOINT_MANIFEST_BASE_URL,
+ );
+ expect(realmConfig.realmManifestBaseUrls[peerRegion]).toBe(
+ env.ENDPOINT_MANIFEST_PEER_BASE_URL,
+ );
+
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ text: async () =>
+ JSON.stringify({
+ ...FULL_MANIFEST_OBJECT,
+ authApiBaseUrl: `https://auth.${peerRegion}.example.com`,
+ }),
+ } as Response);
+ try {
+ await expect(
+ env.loadMobileEndpointsForRealm(peerRegion),
+ ).resolves.toMatchObject({
+ authApiBaseUrl: `https://auth.${peerRegion}.example.com`,
+ });
+ expect(fetchSpy).toHaveBeenCalledWith(
+ expect.stringContaining(
+ `${env.ENDPOINT_MANIFEST_PEER_BASE_URL}/endpoint.json?t=`,
+ ),
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ } finally {
+ fetchSpy.mockRestore();
+ }
+ });
+
+ it('对端清单自报 region 时必须与目标区域一致,拒绝后不污染缓存', async () => {
+ const { env, startup } = await freshModules();
+ const buildRegion = env.BUILD_AUTH_REGION;
+ const peerRegion = buildRegion === 'cn' ? 'global' : 'cn';
+ await expect(
+ startup.runStartupEndpointResolve({
+ fetchManifest: okFetch(FULL_MANIFEST),
+ }),
+ ).resolves.toEqual({ ok: true, source: 'cdn' });
+
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValueOnce({
+ ok: true,
+ text: async () =>
+ JSON.stringify({
+ ...FULL_MANIFEST_OBJECT,
+ region: buildRegion,
+ }),
+ } as Response)
+ .mockResolvedValueOnce({
+ ok: true,
+ text: async () =>
+ JSON.stringify({
+ ...FULL_MANIFEST_OBJECT,
+ authApiBaseUrl: `https://auth.${peerRegion}.example.com`,
+ }),
+ } as Response);
+ try {
+ await expect(
+ env.loadMobileEndpointsForRealm(peerRegion),
+ ).rejects.toThrow(`region-mismatch:${peerRegion}:${buildRegion}`);
+ await expect(
+ env.loadMobileEndpointsForRealm(peerRegion),
+ ).resolves.toMatchObject({
+ authApiBaseUrl: `https://auth.${peerRegion}.example.com`,
+ });
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+ } finally {
+ fetchSpy.mockRestore();
+ }
+ });
});
diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
index b42b335398..98264e6522 100644
--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
@@ -34,7 +34,7 @@ describe('mobile auth-server login', () => {
expect(loginSource).toContain('nonAppleProviders.length');
expect(loginSource).not.toContain('react-native-webview');
expect(authSource).toContain(
- 'client.exchangeNativeSocial(action.provider, credential)',
+ 'authClientFor(did, BUILD_AUTH_REGION).exchangeNativeSocial(',
);
expect(authSource).toContain("clientType: 'mobile'");
expect(nativeSource).toContain("import('expo-apple-authentication')");
@@ -140,7 +140,56 @@ describe('mobile auth-server login', () => {
// scheme 派生 2026-07-20 起为三区域查表(cn/global/dev),断言仍锚定
// 「按区域取回调 scheme」这一形状。
expect(envSource).toContain(
- "{ cn: 'cindycn', global: 'cindy', dev: 'cindydev' }[AUTH_REGION]",
+ "{ cn: 'cindycn', global: 'cindy', dev: 'cindydev' }",
+ );
+ expect(envSource).toContain('AUTH_REGION\n];');
+ });
+
+ it('clears a stale organization realm before personal login or a new organization lookup', () => {
+ const authSource = readFileSync(
+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),
+ 'utf8',
+ );
+ expect(authSource).toContain("action.type === 'discover' ||");
+ expect(authSource).toContain("action.type === 'request-code' ||");
+ expect(authSource).toContain("action.type === 'verify-code' ||");
+ expect(authSource).toContain("action.type === 'native-social'");
+ expect(authSource).toContain(
+ 'if (startsBuildRealmFlow) {\n pendingAuthRealmRef.current = null;',
+ );
+
+ const discoveryStart = authSource.indexOf(
+ "if (action.type === 'discover-sso-org') {",
+ );
+ const discoveryBody = authSource.slice(
+ discoveryStart,
+ authSource.indexOf(
+ 'const realmConfig = getMobileEndpointRealmConfig();',
+ discoveryStart,
+ ),
+ );
+ expect(discoveryBody).toContain('pendingAuthRealmRef.current = null;');
+ });
+
+ it('asks for confirmation only when enterprise discovery crosses the build region', () => {
+ const authSource = readFileSync(
+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),
+ 'utf8',
+ );
+
+ expect(authSource).toContain(
+ 'if (discovery.region !== BUILD_AUTH_REGION) {',
+ );
+ expect(authSource).toContain("type: 'realm-switch-required'");
+ expect(authSource).toContain(
+ "if (action.type === 'confirm-sso-realm') {",
+ );
+ expect(authSource).toContain(
+ "if (action.type === 'cancel-sso-realm') {",
+ );
+ expect(authSource).toContain('methods: confirmation.methods');
+ expect(authSource).toContain(
+ "previousState?.step !== 'method-choice' ||",
);
});
diff --git a/apps/mobile/src/__tests__/mobileEnvBootstrap.test.ts b/apps/mobile/src/__tests__/mobileEnvBootstrap.test.ts
index 706544a6b7..b583e4b05b 100644
--- a/apps/mobile/src/__tests__/mobileEnvBootstrap.test.ts
+++ b/apps/mobile/src/__tests__/mobileEnvBootstrap.test.ts
@@ -6,15 +6,17 @@ import {
ensureMobileEnv,
REQUIRED_MOBILE_ENV_KEYS,
} from '../../scripts/ensure-mobile-env.mjs';
-import { mobileClientBuildEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';
+import { mobileClientBundleEnv } from '../../../../scripts/shared/client-endpoint-build-env.mjs';
const roots: string[] = [];
-// 2026-07 端点清单重构后,.env 必填键收缩为构建身份 + 清单自举基址;
+// 2026-07 端点清单重构后,.env 必填键收缩为构建身份 + 本区/对端清单自举基址;
// 业务端点初值 dev 走仓内 config/endpoint.json,不再进 .env 必填集。
const productionEnv = {
EXPO_PUBLIC_CINDY_AUTH_REGION: 'cn',
EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: 'https://hotfix.example.invalid/app',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL:
+ 'https://hotfix-peer.example.invalid/app',
};
afterEach(() => {
@@ -44,6 +46,7 @@ describe('mobile simulator env bootstrap', () => {
'# local overrides',
'EXPO_PUBLIC_CINDY_AUTH_REGION=global',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=',
'EXPO_PUBLIC_XDT_DEV_LOGIN_ENABLED=1',
'',
].join('\n'),
@@ -53,11 +56,17 @@ describe('mobile simulator env bootstrap', () => {
const env = readEnvMap(join(mobileDir, '.env'));
expect(result.created).toBe(false);
- expect(result.addedKeys).toEqual(['EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL']);
+ expect(result.addedKeys).toEqual([
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',
+ ]);
expect(env.EXPO_PUBLIC_CINDY_AUTH_REGION).toBe('global');
expect(env.EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL).toBe(
productionEnv.EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL,
);
+ expect(env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL).toBe(
+ productionEnv.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL,
+ );
expect(env.EXPO_PUBLIC_XDT_DEV_LOGIN_ENABLED).toBe('1');
});
@@ -69,6 +78,7 @@ describe('mobile simulator env bootstrap', () => {
[
'EXPO_PUBLIC_CINDY_AUTH_REGION=',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=""',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=""',
'',
].join('\n'),
);
@@ -92,6 +102,7 @@ describe('mobile simulator env bootstrap', () => {
[
'EXPO_PUBLIC_CINDY_AUTH_REGION=global',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=https://hotfix.user.example.com/app',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=https://hotfix-peer.user.example.com/app',
'EXPO_PUBLIC_CINDY_AUTH_BASE_URL=https://auth.user.example.com',
'EXPO_PUBLIC_XDT_API_BASE_URL=https://api.user.example.com',
'EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL=https://relay.user.example.com',
@@ -116,6 +127,7 @@ describe('mobile simulator env bootstrap', () => {
[
'EXPO_PUBLIC_CINDY_AUTH_REGION="global"',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL="https://hotfix.custom.example.invalid/app"',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL="https://hotfix-peer.custom.example.invalid/app"',
'',
].join('\n'),
);
@@ -128,6 +140,9 @@ describe('mobile simulator env bootstrap', () => {
expect(env.EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL).toBe(
'"https://hotfix.custom.example.invalid/app"',
);
+ expect(env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL).toBe(
+ '"https://hotfix-peer.custom.example.invalid/app"',
+ );
});
it('accepts complete existing env when the inherited EAS profile omits the manifest base', () => {
@@ -139,6 +154,7 @@ describe('mobile simulator env bootstrap', () => {
[
'EXPO_PUBLIC_CINDY_AUTH_REGION=global',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=https://hotfix.global.example.invalid/app',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=https://hotfix.cn.example.invalid/app',
'',
].join('\n'),
);
@@ -149,6 +165,8 @@ describe('mobile simulator env bootstrap', () => {
expect(readEnvMap(join(mobileDir, '.env'))).toMatchObject({
EXPO_PUBLIC_CINDY_AUTH_REGION: 'global',
EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: 'https://hotfix.global.example.invalid/app',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL:
+ 'https://hotfix.cn.example.invalid/app',
});
});
@@ -161,6 +179,7 @@ describe('mobile simulator env bootstrap', () => {
[
'EXPO_PUBLIC_CINDY_AUTH_REGION=cn',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=https://hotfix.cn.example.invalid/app',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=https://hotfix.global.example.invalid/app',
'',
].join('\n'),
);
@@ -169,7 +188,7 @@ describe('mobile simulator env bootstrap', () => {
expect(result.addedKeys).toEqual(REQUIRED_MOBILE_ENV_KEYS);
expect(readEnvMap(join(mobileDir, '.env'))).toMatchObject(
- mobileClientBuildEnv({ authRegion: 'global' }),
+ mobileClientBundleEnv({ authRegion: 'global' }),
);
});
});
@@ -197,6 +216,7 @@ function writeEnvExample(mobileDir: string) {
[
'EXPO_PUBLIC_CINDY_AUTH_REGION=cn',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=',
'',
].join('\n'),
);
diff --git a/apps/mobile/src/__tests__/mobileXcode.test.ts b/apps/mobile/src/__tests__/mobileXcode.test.ts
index 96673dea0a..15af1119b5 100644
--- a/apps/mobile/src/__tests__/mobileXcode.test.ts
+++ b/apps/mobile/src/__tests__/mobileXcode.test.ts
@@ -68,18 +68,23 @@ describe('mobile:xcode env 切换', () => {
'EXPO_PUBLIC_CINDY_AUTH_REGION=cn',
'EXPO_PUBLIC_CINDY_AUTH_REGION=stale',
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=https://cn.example',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=https://global.example',
'EXPO_PUBLIC_CINDY_GOOGLE_WEB_CLIENT_ID=keep-me',
'',
].join('\n');
const next = updateMobileXcodeEnvContent(source, {
EXPO_PUBLIC_CINDY_AUTH_REGION: 'global',
EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: 'https://global.example',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL: 'https://cn.example',
CINDY_USE_LOCAL_REGION_CONFIG: '1',
});
expect(next.match(/EXPO_PUBLIC_CINDY_AUTH_REGION=/g)).toHaveLength(1);
expect(next).toContain('EXPO_PUBLIC_CINDY_AUTH_REGION=global');
expect(next).toContain('EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=https://global.example');
+ expect(next).toContain(
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=https://cn.example',
+ );
expect(next).toContain('CINDY_USE_LOCAL_REGION_CONFIG=1');
expect(next).toContain('EXPO_PUBLIC_CINDY_GOOGLE_WEB_CLIENT_ID=keep-me');
});
diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
index 619ea4aa18..be7ed3e437 100644
--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts
+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts
@@ -14,6 +14,8 @@ const managedEnvKeys = [
'EXPO_PUBLIC_APP_VARIANT',
'EXPO_PUBLIC_BETA_DEV',
'EXPO_PUBLIC_CINDY_AUTH_REGION',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',
'EXPO_PUBLIC_XDT_OTA_SELFHOST',
'EXPO_PUBLIC_XDT_OTA_URL',
'EXPO_PUBLIC_CINDY_GOOGLE_WEB_CLIENT_ID',
@@ -70,6 +72,33 @@ describe('mobile native app config', () => {
);
});
+ it('injects the peer manifest URL into Metro without adding it to the Expo fingerprint', () => {
+ const appJson = JSON.parse(
+ readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),
+ );
+ const buildConfig = require(resolve(process.cwd(), 'app.config.js'));
+
+ const cn = buildConfig({ config: appJson.expo });
+ expect(
+ process.env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL,
+ ).toBe('https://hotfix.cindy.app/cindy');
+ expect(cn.extra.xdtProductionEnv).toEqual({
+ EXPO_PUBLIC_CINDY_AUTH_REGION: 'cn',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL:
+ 'https://hotfix.cindy.com.cn/cindy',
+ });
+ expect(cn.extra.xdtProductionEnv).not.toHaveProperty(
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',
+ );
+ const runtimeEnvSource = readFileSync(
+ resolve(process.cwd(), 'src/config/env.ts'),
+ 'utf8',
+ );
+ expect(runtimeEnvSource).toContain(
+ 'process.env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',
+ );
+ });
+
it('injects EAS owner / projectId / updates from env and omits them when unset', () => {
const appJson = JSON.parse(
readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),
diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
index cd1eb942eb..f04b09eaad 100644
--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts
@@ -226,7 +226,7 @@ describe('native e2e environment', () => {
const cleanupBody = authContext.slice(cleanupStart, authContext.indexOf('}, [', cleanupStart));
const refreshTokenDelete = cleanupBody.indexOf('await serializeRefreshTokenMutation(() =>');
expect(refreshTokenDelete).toBeGreaterThanOrEqual(0);
- expect(cleanupBody).toContain('deleteSecureItem(REFRESH_TOKEN_KEY).catch(() => undefined)');
+ expect(cleanupBody).toContain('deleteSecureItem(AUTH_SESSION_KEY).catch(() => undefined)');
expect(cleanupBody.indexOf('await clearAllMobileVoiceCredentials().catch(() => undefined);')).toBeLessThan(refreshTokenDelete);
expect(cleanupBody.indexOf('await clearAllMobileVoiceInputHistories().catch(() => undefined);')).toBeLessThan(refreshTokenDelete);
const logoutStart = authContext.indexOf('const logout = useCallback(async () => {');
diff --git a/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts b/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts
new file mode 100644
index 0000000000..b9170b08c9
--- /dev/null
+++ b/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts
@@ -0,0 +1,250 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const store = vi.hoisted(() => new Map<string, string>());
+const envState = vi.hoisted(() => ({
+ activeRealm: 'cn' as 'cn' | 'global',
+ endpointByRealm: {
+ cn: 'https://relay.cn.example',
+ global: 'https://relay.global.example',
+ },
+}));
+const mocks = vi.hoisted(() => ({
+ asyncGetItem: vi.fn(async (key: string) => store.get(key) ?? null),
+ loadMobileEndpointsForRealm: vi.fn(async (_realm: 'cn' | 'global') => ({})),
+ getPermissionsAsync: vi.fn(),
+ requestPermissionsAsync: vi.fn(),
+ getDevicePushTokenAsync: vi.fn(),
+}));
+
+vi.mock('@react-native-async-storage/async-storage', () => ({
+ default: {
+ getItem: mocks.asyncGetItem,
+ setItem: vi.fn(async (key: string, value: string) => {
+ store.set(key, value);
+ }),
+ removeItem: vi.fn(async (key: string) => {
+ store.delete(key);
+ }),
+ },
+}));
+
+vi.mock('expo-notifications', () => ({
+ setNotificationHandler: vi.fn(),
+ getPermissionsAsync: mocks.getPermissionsAsync,
+ requestPermissionsAsync: mocks.requestPermissionsAsync,
+ getDevicePushTokenAsync: mocks.getDevicePushTokenAsync,
+}));
+
+vi.mock('react-native', () => ({
+ Platform: { OS: 'ios' },
+}));
+
+vi.mock('@/config/env', () => ({
+ AUTH_REGION: 'cn',
+ BUILD_AUTH_REGION: 'cn',
+ getActiveMobileSessionRealm: () => envState.activeRealm,
+ loadMobileEndpointsForRealm: mocks.loadMobileEndpointsForRealm,
+ getMobileEndpointForRealm: (realm: 'cn' | 'global') =>
+ envState.endpointByRealm[realm],
+}));
+
+import {
+ retryPendingUnregister,
+ syncPushRegistration,
+ unregisterPushTokenBestEffort,
+} from '@/notifications/pushNotifications';
+
+const REGISTERED_KEY = 'cindy.push.registered';
+const PENDING_KEY = 'cindy.push.pendingUnregister';
+
+function setStoredRealms(key: string, realms: Array<'cn' | 'global'>): void {
+ store.set(key, JSON.stringify({ version: 1, realms }));
+}
+
+function readStoredRealms(key: string): string[] {
+ const raw = store.get(key);
+ if (!raw) return [];
+ if (raw === '1') return ['cn'];
+ return (JSON.parse(raw) as { realms: string[] }).realms;
+}
+
+describe('push notification realm routing', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ store.clear();
+ envState.activeRealm = 'cn';
+ mocks.getPermissionsAsync.mockResolvedValue({
+ status: 'granted',
+ canAskAgain: false,
+ });
+ mocks.getDevicePushTokenAsync.mockResolvedValue({
+ data: 'apns-device-token',
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('向当前会话区域注册,但推送构建线仍保持安装包区域', async () => {
+ envState.activeRealm = 'global';
+ const apiFetch = vi.fn().mockResolvedValue({ registered: true });
+
+ await expect(
+ syncPushRegistration({ enabled: true, apiFetch }),
+ ).resolves.toBe('registered');
+
+ expect(apiFetch).toHaveBeenCalledWith(
+ '/api/device-link/push-token',
+ expect.objectContaining({
+ baseUrl: 'https://relay.global.example',
+ method: 'PUT',
+ body: expect.objectContaining({
+ token: 'apns-device-token',
+ appVariant: 'cn',
+ }),
+ }),
+ );
+ expect(apiFetch.mock.calls[0]?.[1]?.body).not.toHaveProperty(
+ 'revocationToken',
+ );
+ expect(readStoredRealms(REGISTERED_KEY)).toEqual(['global']);
+ });
+
+ it('切换区域前用旧 token 向显式冻结的旧区域撤销', async () => {
+ setStoredRealms(REGISTERED_KEY, ['global']);
+ envState.activeRealm = 'cn';
+ const fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 });
+ vi.stubGlobal('fetch', fetch);
+
+ await unregisterPushTokenBestEffort('old-global-token', 'global');
+
+ expect(mocks.loadMobileEndpointsForRealm).toHaveBeenCalledWith('global');
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://relay.global.example/api/device-link/push-token',
+ expect.objectContaining({
+ method: 'DELETE',
+ headers: {
+ Authorization: 'Bearer old-global-token',
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({ token: 'apns-device-token' }),
+ }),
+ );
+ expect(fetch).not.toHaveBeenCalledWith(
+ expect.stringContaining('relay.cn.example'),
+ expect.anything(),
+ );
+ expect(readStoredRealms(REGISTERED_KEY)).toEqual([]);
+ expect(readStoredRealms(PENDING_KEY)).toEqual([]);
+ });
+
+ it('只用当前会话补偿当前区域,另一区域标记保持不动', async () => {
+ setStoredRealms(REGISTERED_KEY, ['cn', 'global']);
+ setStoredRealms(PENDING_KEY, ['cn', 'global']);
+ envState.activeRealm = 'cn';
+ const cnApiFetch = vi.fn().mockResolvedValue({ deleted: true });
+
+ await retryPendingUnregister(cnApiFetch);
+
+ expect(cnApiFetch).toHaveBeenCalledWith(
+ '/api/device-link/push-token',
+ expect.objectContaining({
+ baseUrl: 'https://relay.cn.example',
+ method: 'DELETE',
+ body: { token: 'apns-device-token' },
+ }),
+ );
+ expect(readStoredRealms(PENDING_KEY)).toEqual(['global']);
+ expect(readStoredRealms(REGISTERED_KEY)).toEqual(['global']);
+
+ envState.activeRealm = 'global';
+ const globalApiFetch = vi.fn().mockResolvedValue({ deleted: true });
+ await retryPendingUnregister(globalApiFetch);
+
+ expect(globalApiFetch).toHaveBeenCalledWith(
+ '/api/device-link/push-token',
+ expect.objectContaining({
+ baseUrl: 'https://relay.global.example',
+ }),
+ );
+ expect(readStoredRealms(PENDING_KEY)).toEqual([]);
+ expect(readStoredRealms(REGISTERED_KEY)).toEqual([]);
+ });
+
+ it('旧 token 不可用时不跨区请求,只保留旧区域标记', async () => {
+ setStoredRealms(REGISTERED_KEY, ['global']);
+ envState.activeRealm = 'cn';
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+
+ await unregisterPushTokenBestEffort(null, 'global');
+
+ expect(fetch).not.toHaveBeenCalled();
+ expect(readStoredRealms(REGISTERED_KEY)).toEqual(['global']);
+ expect(readStoredRealms(PENDING_KEY)).toEqual(['global']);
+ });
+
+ it('关闭通知失败时把补偿固定在请求开始时的区域', async () => {
+ setStoredRealms(REGISTERED_KEY, ['global']);
+ envState.activeRealm = 'global';
+ const apiFetch = vi.fn().mockRejectedValue(new Error('offline'));
+
+ await expect(
+ syncPushRegistration({ enabled: false, apiFetch }),
+ ).rejects.toThrow('offline');
+
+ envState.activeRealm = 'cn';
+ expect(readStoredRealms(PENDING_KEY)).toEqual(['global']);
+ });
+
+ it('apiFetch terminal handler 内同步退登不会等待自身', async () => {
+ const fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 });
+ vi.stubGlobal('fetch', fetch);
+ const apiFetch = vi.fn(async () => {
+ await unregisterPushTokenBestEffort('access-token', 'cn');
+ throw new Error('account unavailable');
+ });
+
+ await expect(
+ syncPushRegistration({ enabled: true, apiFetch }),
+ ).rejects.toThrow('account unavailable');
+
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://relay.cn.example/api/device-link/push-token',
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ Authorization: 'Bearer access-token',
+ }),
+ }),
+ );
+ expect(readStoredRealms(PENDING_KEY)).toEqual(['cn']);
+ });
+
+ it('关闭同步读取状态期间若发生退登,不会在旧生命周期发送认证请求', async () => {
+ setStoredRealms(REGISTERED_KEY, ['cn']);
+ const storedRegisteredState = store.get(REGISTERED_KEY) ?? null;
+ let releaseRead: (() => void) | undefined;
+ const readGate = new Promise<void>((resolve) => {
+ releaseRead = resolve;
+ });
+ mocks.asyncGetItem.mockImplementationOnce(async () => {
+ await readGate;
+ return storedRegisteredState;
+ });
+ const apiFetch = vi.fn();
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+
+ const disableSync = syncPushRegistration({ enabled: false, apiFetch });
+ await vi.waitFor(() => {
+ expect(mocks.asyncGetItem).toHaveBeenCalledWith(REGISTERED_KEY);
+ });
+ await unregisterPushTokenBestEffort(null, 'cn');
+ releaseRead?.();
+
+ await expect(disableSync).resolves.toBe('skipped');
+ expect(apiFetch).not.toHaveBeenCalled();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/__tests__/releaseLib.test.ts b/apps/mobile/src/__tests__/releaseLib.test.ts
index 5b4882a8df..c97e03482c 100644
--- a/apps/mobile/src/__tests__/releaseLib.test.ts
+++ b/apps/mobile/src/__tests__/releaseLib.test.ts
@@ -82,6 +82,8 @@ describe('release-lib assertPublicEnv', () => {
const baked = {
EXPO_PUBLIC_CINDY_AUTH_REGION: 'cn',
EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: 'https://cdn.example.com',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL:
+ 'https://cdn-peer.example.com',
EXPO_PUBLIC_XDT_OTA_SELFHOST: '1',
};
@@ -98,7 +100,7 @@ describe('release-lib assertPublicEnv', () => {
{ requiredKeys: SELF_HOST_PUBLIC_ENV_KEYS },
),
).toThrow(
- 'EXPO_PUBLIC_CINDY_AUTH_REGION, EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL, EXPO_PUBLIC_XDT_OTA_SELFHOST',
+ 'EXPO_PUBLIC_CINDY_AUTH_REGION, EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL, EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL, EXPO_PUBLIC_XDT_OTA_SELFHOST',
);
});
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 1158fe1d68..af51528bff 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -13,15 +13,23 @@ import { AppState, Linking } from 'react-native';
import {
AuthApiError,
CindyAuthClient,
+ discoverSsoOrgRealm,
+ parseAccountDeletionReceiptRecord,
+ parseAuthSessionRecord,
reduceAuthFlow,
+ serializeAccountDeletionReceiptRecord,
ssoOrgDiscoveryToMethods,
+ serializeAuthSessionRecord,
type AuthFlowState,
+ type AuthRegion,
+ type AuthSessionRecord,
type AuthMembership,
type AccountDeletionAvailability,
type AccountDeletionChallenge,
type AccountDeletionStatus,
type LoginOutcome,
type SocialProvider,
+ type SsoOrgDiscovery,
type VerificationKind,
} from '@cindy/auth-client';
// dev-only 登录 scenario harness(implementation-plan Step 0 WHAT4):
@@ -36,12 +44,16 @@ import {
type ApiFetchOptions,
} from '@/api/client';
import {
- AUTH_API_BASE_URL,
- AUTH_REGION,
+ activateMobileSessionRealm,
+ BUILD_AUTH_REGION,
+ getMobileEndpointForRealm,
+ getMobileEndpointRealmConfig,
IS_OTA_SELFHOST,
+ loadMobileEndpointsForRealm,
MOBILE_VISUAL_MOCK_ENABLED,
MOBILE_REDIRECT_URL,
OAUTH_BROKER_API_BASE_URL,
+ resetMobileSessionRealm,
} from '@/config/env';
import { syncCanaryChannelAfterAuth } from '@/auth/canaryChannelSync';
import { ensureDeviceId } from '@/auth/deviceId';
@@ -59,7 +71,11 @@ import {
getSecureItem,
setSecureItem,
} from '@/auth/secureStorage';
-import { clearTapdbUser, setTapdbUser, stopMobileTapdbReporting } from '@/analytics/mobileTapdb';
+import {
+ clearTapdbUser,
+ setTapdbUser,
+ stopMobileTapdbReporting,
+} from '@/analytics/mobileTapdb';
import {
clearAnalyticsConsent,
migrateExistingLoginAsConsented,
@@ -83,15 +99,15 @@ import {
WebBrowser.maybeCompleteAuthSession();
-const REFRESH_TOKEN_KEY = 'cindy.mobile.auth.refreshToken';
+const AUTH_SESSION_KEY = 'cindy.mobile.auth.session.v1';
+const LEGACY_RESOURCE_REFRESH_TOKEN_KEY = 'cindy.mobile.auth.refreshToken';
const LEGACY_ACCOUNT_REFRESH_TOKEN_KEY =
'cindy.mobile.auth.accountRefreshToken';
const LEGACY_REFRESH_TOKEN_KEY = 'xdt.mobile.refreshToken';
const USER_PROFILE_KEY = 'cindy.mobile.auth.userProfile';
const LEGACY_USER_PROFILE_KEY = 'xdt.mobile.userProfile';
const PENDING_OAUTH_KEY = 'cindy.mobile.auth.pendingOAuth';
-const ACCOUNT_DELETION_RECEIPT_KEY =
- 'cindy.mobile.auth.accountDeletionReceipt';
+const ACCOUNT_DELETION_RECEIPT_KEY = 'cindy.mobile.auth.accountDeletionReceipt';
const LEGACY_PENDING_OAUTH_KEY = 'xdt.mobile.pendingOAuth';
const PENDING_OAUTH_MAX_AGE_MS = 10 * 60 * 1000;
const AUTH_STARTUP_GATE_TIMEOUT_MS = 20 * 1000;
@@ -115,6 +131,8 @@ export type MobileLoginAction =
| { type: 'reset' }
| { type: 'discover'; email: string }
| { type: 'discover-sso-org'; org: string }
+ | { type: 'confirm-sso-realm' }
+ | { type: 'cancel-sso-realm' }
| { type: 'request-code'; kind: VerificationKind; identifier: string }
| {
type: 'verify-code';
@@ -136,6 +154,7 @@ interface PendingOAuth {
state: string;
createdAt: number;
label: string;
+ realm: AuthRegion;
}
export interface AuthContextValue {
@@ -232,17 +251,22 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const pendingAccountTokenRef = useRef<string | null>(null);
const [user, setUser] = useState<MobileUser | null>(null);
const userRef = useRef<MobileUser | null>(null);
+ // 跨区缓存会话在所属 realm 清单尚未就绪时保持未认证,但仍需后台重试,
+ // 不能复用只由 user 驱动的弱网自愈条件。
+ const [deferredSessionRecovery, setDeferredSessionRecovery] = useState(false);
const [loginState, setLoginState] = useState<AuthFlowState | null>(null);
const loginStateRef = useRef<AuthFlowState | null>(null);
const [authError, setAuthError] = useState<string | null>(null);
const [accountDeletionReceipt, setAccountDeletionReceipt] = useState<
string | null
>(null);
- const [accountDeletionRestored, setAccountDeletionRestored] =
- useState(false);
+ const [accountDeletionRestored, setAccountDeletionRestored] = useState(false);
const pendingLoginTicketRef = useRef<string | null>(null);
const pendingBindTicketRef = useRef<string | null>(null);
const pendingSsoVerificationTicketRef = useRef<string | null>(null);
+ const activeAuthRealmRef = useRef<AuthRegion>(BUILD_AUTH_REGION);
+ const pendingAuthRealmRef = useRef<AuthRegion | null>(null);
+ const accountDeletionReceiptRealmRef = useRef<AuthRegion | null>(null);
const pendingAccountDeletionRestoredRef = useRef(false);
const loginActionInFlightRef = useRef<Promise<boolean> | null>(null);
const browserCompletionRef = useRef<Promise<void> | null>(null);
@@ -255,6 +279,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
>(async () => undefined);
// Logout bumps this generation so a late refresh cannot resurrect the session.
const authGenerationRef = useRef(0);
+ // 用户主动开始新登录后,旧的弱网会话不得再通过定时/前台恢复抢回界面。
+ const sessionRecoverySuspendedRef = useRef(false);
// SecureStore operations are asynchronous. Serialize mutations so logout always
// wins over a refresh/login write that was already inside the native storage call.
const refreshTokenMutationRef = useRef<Promise<void>>(Promise.resolve());
@@ -263,6 +289,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
Promise.resolve(),
);
+ const suspendSessionRecoveryForLogin = useCallback(() => {
+ if (sessionRecoverySuspendedRef.current) return;
+ sessionRecoverySuspendedRef.current = true;
+ authGenerationRef.current += 1;
+ refreshInFlightRef.current = null;
+ setDeferredSessionRecovery(false);
+ }, []);
+
/** 登录态落地后异步刷新灰度标记;失败保留旧值,迟到响应按 auth generation 丢弃。 */
const scheduleCanaryChannelSync = useCallback(
(token: string, expectedAuthGeneration: number) => {
@@ -310,14 +344,22 @@ export function AuthProvider({ children }: { children: ReactNode }) {
);
const persistAccountDeletionReceipt = useCallback(
- async (receiptToken: string | null): Promise<void> => {
+ async (
+ receiptToken: string | null,
+ realm = activeAuthRealmRef.current,
+ ): Promise<void> => {
const operation = async () => {
if (receiptToken) {
- await setSecureItem(ACCOUNT_DELETION_RECEIPT_KEY, receiptToken);
+ await setSecureItem(
+ ACCOUNT_DELETION_RECEIPT_KEY,
+ serializeAccountDeletionReceiptRecord(realm, receiptToken),
+ );
+ accountDeletionReceiptRealmRef.current = realm;
} else {
await deleteSecureItem(ACCOUNT_DELETION_RECEIPT_KEY).catch(
() => undefined,
);
+ accountDeletionReceiptRealmRef.current = null;
}
setAccountDeletionReceipt(receiptToken);
};
@@ -348,6 +390,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// 缓存资料恢复“已登录”视图,token 由后台刷新补齐。
const applyUser = useCallback(
(next: MobileUser | null) => {
+ setDeferredSessionRecovery(false);
userRef.current = next;
setUser(next);
void serializeUserProfileMutation(() => writeCachedUserProfile(next));
@@ -368,7 +411,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
expectedGeneration = authGenerationRef.current,
): Promise<void> => {
// 2026-07 起只拉 auth-server 身份(产品 /api/user/me 已退役)。
- const identityResult = await authClientFor(did)
+ const identityResult = await authClientFor(
+ did,
+ activeAuthRealmRef.current,
+ )
.getMe(token)
.then(
(value) => ({ status: 'fulfilled' as const, value }),
@@ -441,11 +487,27 @@ export function AuthProvider({ children }: { children: ReactNode }) {
outcome.accountDeletionRestored === true ||
pendingAccountDeletionRestoredRef.current;
pendingAccountDeletionRestoredRef.current = false;
+ const committedRealm = pendingAuthRealmRef.current ?? BUILD_AUTH_REGION;
+ const previousAccessToken = accessTokenRef.current;
+ const previousRealm = activeAuthRealmRef.current;
+ const replacesActiveSession =
+ previousAccessToken !== null &&
+ (previousRealm !== committedRealm ||
+ userRef.current?.id !== outcome.membership.id);
+ if (replacesActiveSession) {
+ // 新会话尚未覆盖旧 token / realm;在这一刻撤销旧区推送,失败不能阻断登录。
+ await unregisterPushTokenBestEffort(
+ previousAccessToken,
+ previousRealm,
+ );
+ }
const generation = ++authGenerationRef.current;
refreshInFlightRef.current = null;
+ activateMobileSessionRealm(committedRealm);
+ activeAuthRealmRef.current = committedRealm;
const persisted = await serializeRefreshTokenMutation(async () => {
if (authGenerationRef.current !== generation) return false;
- await setSecureItem(REFRESH_TOKEN_KEY, outcome.refreshToken);
+ await writePersistedAuthSession(outcome.refreshToken, committedRealm);
return authGenerationRef.current === generation;
});
if (!persisted) throw authCodeError('AUTH_FLOW_SUPERSEDED');
@@ -455,10 +517,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
pendingLoginTicketRef.current = null;
pendingBindTicketRef.current = null;
pendingSsoVerificationTicketRef.current = null;
+ pendingAuthRealmRef.current = null;
setToken(outcome.accessToken);
applyUser(
mergeMembershipWithExisting(outcome.membership, userRef.current),
);
+ sessionRecoverySuspendedRef.current = false;
scheduleCanaryChannelSync(outcome.accessToken, generation);
updateLoginState(
reduceAuthFlow(loginStateRef.current, { type: 'outcome', outcome }),
@@ -493,19 +557,26 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const did =
knownDeviceId ?? deviceIdRef.current ?? (await ensureDeviceId());
deviceIdRef.current = did;
- const refreshToken = await serializeRefreshTokenMutation(() =>
- getSecureItem(REFRESH_TOKEN_KEY).catch(() => null),
+ const session = await serializeRefreshTokenMutation(
+ readPersistedAuthSession,
);
- if (!refreshToken) {
+ if (authGenerationRef.current !== generation) return null;
+ if (!session) {
await clearCanaryChannel().catch(() => undefined);
return null;
}
try {
- const pair = await authClientFor(did).refresh(refreshToken);
+ await loadMobileEndpointsForRealm(session.realm);
+ if (authGenerationRef.current !== generation) return null;
+ activateMobileSessionRealm(session.realm);
+ activeAuthRealmRef.current = session.realm;
+ const pair = await authClientFor(did, session.realm).refresh(
+ session.refreshToken,
+ );
if (authGenerationRef.current !== generation) return null;
const persisted = await serializeRefreshTokenMutation(async () => {
if (authGenerationRef.current !== generation) return false;
- await setSecureItem(REFRESH_TOKEN_KEY, pair.refreshToken);
+ await writePersistedAuthSession(pair.refreshToken, session.realm);
return authGenerationRef.current === generation;
});
if (!persisted) return null;
@@ -545,7 +616,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setIsBusy(true);
try {
const did = await ensureDeviceId();
- if (cancelled) return;
+ if (cancelled || sessionRecoverySuspendedRef.current) return;
deviceIdRef.current = did;
setDeviceId(did);
// Old Feishu refresh tokens are not valid in auth-server. Purge them explicitly
@@ -562,21 +633,68 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// 服务模式开关与 BYOK LiteLLM key,防止桌面 key 继续躺在 secure storage。
clearAllMobileVoiceCredentials().catch(() => undefined),
]);
- const [storedRefreshToken, cachedUser, storedDeletionReceipt] =
- await Promise.all([
- getSecureItem(REFRESH_TOKEN_KEY).catch(() => null),
+ let storedSession = await readPersistedAuthSession();
+ if (!storedSession) {
+ const legacyToken = await getSecureItem(
+ LEGACY_RESOURCE_REFRESH_TOKEN_KEY,
+ ).catch(() => null);
+ if (legacyToken) {
+ await writePersistedAuthSession(legacyToken, BUILD_AUTH_REGION);
+ await deleteSecureItem(LEGACY_RESOURCE_REFRESH_TOKEN_KEY).catch(
+ () => undefined,
+ );
+ storedSession = {
+ version: 1,
+ realm: BUILD_AUTH_REGION,
+ refreshToken: legacyToken,
+ };
+ }
+ }
+ const [cachedUser, storedDeletionReceiptRaw] = await Promise.all([
readCachedUserProfile(),
getSecureItem(ACCOUNT_DELETION_RECEIPT_KEY).catch(() => null),
]);
+ const storedDeletionReceipt =
+ parseAccountDeletionReceiptRecord(storedDeletionReceiptRaw) ??
+ (storedDeletionReceiptRaw &&
+ !storedDeletionReceiptRaw.trimStart().startsWith('{')
+ ? {
+ version: 1 as const,
+ realm: BUILD_AUTH_REGION,
+ receiptToken: storedDeletionReceiptRaw,
+ }
+ : null);
if (storedDeletionReceipt) {
- setAccountDeletionReceipt(storedDeletionReceipt);
+ accountDeletionReceiptRealmRef.current = storedDeletionReceipt.realm;
+ setAccountDeletionReceipt(storedDeletionReceipt.receiptToken);
+ // Older builds stored only the opaque receipt; migrate it atomically
+ // with the deterministic build-region interpretation.
+ if (!parseAccountDeletionReceiptRecord(storedDeletionReceiptRaw)) {
+ await setSecureItem(
+ ACCOUNT_DELETION_RECEIPT_KEY,
+ serializeAccountDeletionReceiptRecord(
+ storedDeletionReceipt.realm,
+ storedDeletionReceipt.receiptToken,
+ ),
+ );
+ }
}
- // 弱网冷启动:先用本地会话痕迹恢复已登录视图,再走网络刷新。
- if (storedRefreshToken && cachedUser) {
- userRef.current = cachedUser;
- setUser(cachedUser);
+ // 弱网冷启动只有在会话所属 realm 的业务端点已整体激活后,才发布缓存用户。
+ // 构建 realm 命中启动缓存,不增加网络依赖;跨区清单不可用时保持未认证,
+ // 防止业务调用先捕获构建区 URL、随后 refresh 又把对端 token 发给该 URL。
+ if (storedSession && cachedUser) {
+ try {
+ await loadMobileEndpointsForRealm(storedSession.realm);
+ if (cancelled) return;
+ activateMobileSessionRealm(storedSession.realm);
+ activeAuthRealmRef.current = storedSession.realm;
+ userRef.current = cachedUser;
+ setUser(cachedUser);
+ } catch {
+ if (!cancelled) setDeferredSessionRecovery(true);
+ }
}
- if (!storedRefreshToken)
+ if (!storedSession)
await deleteSecureItem(USER_PROFILE_KEY).catch(() => undefined);
try {
await awaitAuthStartupGate(
@@ -619,34 +737,43 @@ export function AuthProvider({ children }: { children: ReactNode }) {
};
}, [refresh]);
- // 降级会话自愈:有缓存用户但尚未取得 access token 时,以退避节奏和回前台时机重试。
+ // 降级会话自愈:已安全发布的缓存用户,或因跨区清单失败而延迟发布的会话,
+ // 都以退避节奏和回前台时机重试。
useEffect(() => {
- if (!initialized || !user || accessToken) return;
+ const hasRecoverableSession =
+ user !== null || deferredSessionRecovery;
+ if (
+ !initialized ||
+ accessToken ||
+ !hasRecoverableSession ||
+ sessionRecoverySuspendedRef.current
+ )
+ return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | null = null;
let attempt = 0;
const scheduleNext = () => {
- if (cancelled) return;
+ if (cancelled || sessionRecoverySuspendedRef.current) return;
attempt += 1;
const delay = Math.min(5_000 * 2 ** attempt, 60_000);
if (timer) clearTimeout(timer);
timer = setTimeout(() => void tryRefresh(), delay);
};
const tryRefresh = async () => {
- if (cancelled) return;
+ if (cancelled || sessionRecoverySuspendedRef.current) return;
try {
const token = await refresh();
- if (cancelled) return;
+ if (cancelled || sessionRecoverySuspendedRef.current) return;
if (token) return;
- let storedRefreshToken: string | null;
+ let storedSession: AuthSessionRecord | null;
try {
- storedRefreshToken = await getSecureItem(REFRESH_TOKEN_KEY);
+ storedSession = await readPersistedAuthSession();
} catch {
scheduleNext();
return;
}
- if (cancelled) return;
- if (!storedRefreshToken) {
+ if (cancelled || sessionRecoverySuspendedRef.current) return;
+ if (!storedSession) {
applyUser(null);
return;
}
@@ -664,7 +791,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
subscription.remove();
if (timer) clearTimeout(timer);
};
- }, [accessToken, applyUser, initialized, refresh, user]);
+ }, [
+ accessToken,
+ applyUser,
+ deferredSessionRecovery,
+ initialized,
+ refresh,
+ user,
+ ]);
// 存量同意迁移已在冷启动流程里 await 完成(见上方 initialize),这里只负责绑定
// 账号标识 —— initialized 变 true 时迁移必然已经落盘。
@@ -683,6 +817,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const completeOAuthCallback = useCallback(
(callbackUrl: string): Promise<void> => {
if (browserCompletionRef.current) return browserCompletionRef.current;
+ suspendSessionRecoveryForLogin();
const run = (async () => {
setIsBusy(true);
try {
@@ -693,8 +828,19 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const callback = parseOAuthCallbackUrl(callbackUrl);
if (callback.state !== pending.state)
throw authCodeError('STATE_MISMATCH');
+ try {
+ await loadMobileEndpointsForRealm(pending.realm);
+ } catch {
+ throw new AuthApiError(
+ 'ORG_REALM_UNAVAILABLE',
+ 503,
+ 'Unable to load the enterprise auth region manifest',
+ );
+ }
+ pendingAuthRealmRef.current = pending.realm;
const outcome = await authClientFor(
pending.deviceId,
+ pending.realm,
).exchangeAuthorizationCode(callback.code, pending.codeVerifier);
deviceIdRef.current = pending.deviceId;
setDeviceId(pending.deviceId);
@@ -704,6 +850,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const code = authErrorCode(error);
if (code === 'INVALID_AUTH_CODE') {
await deleteSecureItem(PENDING_OAUTH_KEY).catch(() => undefined);
+ pendingAuthRealmRef.current = null;
+ resetMobileSessionRealm();
updateLoginState(null);
}
setAuthError(code);
@@ -725,7 +873,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
);
return run;
},
- [acceptOutcome, updateLoginState],
+ [acceptOutcome, suspendSessionRecoveryForLogin, updateLoginState],
);
// SSO returns through cindycn://auth or cindy://auth. The pending PKCE verifier
@@ -746,6 +894,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const dispatchLoginAction = useCallback(
(action: MobileLoginAction): Promise<boolean> => {
+ suspendSessionRecoveryForLogin();
if (loginActionInFlightRef.current) return loginActionInFlightRef.current;
let run: Promise<boolean>;
const clearIfCurrent = () => {
@@ -759,17 +908,32 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const did = deviceIdRef.current ?? (await ensureDeviceId());
deviceIdRef.current = did;
setDeviceId(did);
- const client = authClientFor(did);
+ const startsBuildRealmFlow =
+ action.type === 'discover' ||
+ action.type === 'request-code' ||
+ action.type === 'verify-code' ||
+ action.type === 'native-social';
+ if (startsBuildRealmFlow) {
+ pendingAuthRealmRef.current = null;
+ resetMobileSessionRealm();
+ }
+ const loginRealm = pendingAuthRealmRef.current ?? BUILD_AUTH_REGION;
+ const client = authClientFor(did, loginRealm);
if (action.type === 'reset') {
pendingAccountTokenRef.current = null;
pendingLoginTicketRef.current = null;
pendingBindTicketRef.current = null;
pendingSsoVerificationTicketRef.current = null;
+ pendingAuthRealmRef.current = null;
+ resetMobileSessionRealm();
pendingAccountDeletionRestoredRef.current = false;
setAccountDeletionRestored(false);
await deleteSecureItem(PENDING_OAUTH_KEY).catch(() => undefined);
- const providers = await client.getProviders();
+ const providers = await authClientFor(
+ did,
+ BUILD_AUTH_REGION,
+ ).getProviders();
updateLoginState(
reduceAuthFlow(loginStateRef.current, {
type: 'providers-loaded',
@@ -778,9 +942,44 @@ export function AuthProvider({ children }: { children: ReactNode }) {
);
return true;
}
+ if (action.type === 'confirm-sso-realm') {
+ const confirmation = loginStateRef.current;
+ if (
+ confirmation?.step !== 'realm-confirmation' ||
+ pendingAuthRealmRef.current !== confirmation.targetRegion
+ ) {
+ throw authCodeError('INVALID_AUTH_ACTION');
+ }
+ updateLoginState(
+ reduceAuthFlow(confirmation, {
+ type: 'discovery-loaded',
+ email: '',
+ methods: confirmation.methods,
+ }),
+ );
+ return true;
+ }
+ if (action.type === 'cancel-sso-realm') {
+ const confirmation = loginStateRef.current;
+ if (confirmation?.step !== 'realm-confirmation') {
+ throw authCodeError('INVALID_AUTH_ACTION');
+ }
+ pendingAuthRealmRef.current = null;
+ resetMobileSessionRealm();
+ updateLoginState(
+ reduceAuthFlow(confirmation, {
+ type: 'providers-loaded',
+ providers: confirmation.providers,
+ }),
+ );
+ return true;
+ }
if (action.type === 'discover') {
const email = action.email.trim().toLowerCase();
- const methods = await client.discover(email);
+ const methods = await authClientFor(
+ did,
+ BUILD_AUTH_REGION,
+ ).discover(email);
updateLoginState(
reduceAuthFlow(loginStateRef.current, {
type: 'discovery-loaded',
@@ -793,21 +992,72 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// 企业 SSO 入口(按组织 ID/slug/已验证域名):结果映射进 method-choice,
// 复用连接选择 UI 与 start-sso 流程。
if (action.type === 'discover-sso-org') {
- const discovery = await client.discoverSsoOrg(
- action.org.trim().toLowerCase(),
- );
- updateLoginState(
- reduceAuthFlow(loginStateRef.current, {
- type: 'discovery-loaded',
- email: '',
- methods: ssoOrgDiscoveryToMethods(discovery),
- }),
- );
+ 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'),
+ ]);
+ } 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'),
+ });
+ pendingAuthRealmRef.current = selected.region;
+ discovery = selected.discovery;
+ } else {
+ pendingAuthRealmRef.current = BUILD_AUTH_REGION;
+ discovery = await authClientFor(
+ did,
+ BUILD_AUTH_REGION,
+ ).discoverSsoOrg(org);
+ }
+ const methods = ssoOrgDiscoveryToMethods(discovery);
+ const currentState = loginStateRef.current;
+ if (discovery.region !== BUILD_AUTH_REGION) {
+ if (currentState?.step !== 'identifier') {
+ throw authCodeError('INVALID_AUTH_ACTION');
+ }
+ updateLoginState(
+ reduceAuthFlow(currentState, {
+ type: 'realm-switch-required',
+ targetRegion: discovery.region,
+ providers: currentState.providers,
+ methods,
+ }),
+ );
+ } else {
+ updateLoginState(
+ reduceAuthFlow(currentState, {
+ type: 'discovery-loaded',
+ email: '',
+ methods,
+ }),
+ );
+ }
return true;
}
if (action.type === 'request-code') {
const identifier = action.identifier.trim();
- await client.requestCode(action.kind, identifier);
+ await authClientFor(did, BUILD_AUTH_REGION).requestCode(
+ action.kind,
+ identifier,
+ );
updateLoginState(
reduceAuthFlow(loginStateRef.current, {
type: 'code-requested',
@@ -819,7 +1069,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
if (action.type === 'verify-code') {
await acceptOutcome(
- await client.verifyCode(
+ await authClientFor(did, BUILD_AUTH_REGION).verifyCode(
action.kind,
action.identifier.trim(),
action.code,
@@ -833,13 +1083,26 @@ export function AuthProvider({ children }: { children: ReactNode }) {
action.provider,
);
await acceptOutcome(
- await client.exchangeNativeSocial(action.provider, credential),
+ await authClientFor(did, BUILD_AUTH_REGION).exchangeNativeSocial(
+ action.provider,
+ credential,
+ ),
did,
);
return true;
}
if (action.type === 'start-sso') {
const previousState = loginStateRef.current;
+ if (
+ previousState?.step !== 'method-choice' ||
+ !previousState.methods.some(
+ (method) =>
+ method.type === 'sso' &&
+ method.connectionId === action.connectionId,
+ )
+ ) {
+ throw authCodeError('INVALID_AUTH_ACTION');
+ }
const { codeVerifier, codeChallenge } = await createPkcePair();
const state = createState();
await setSecureItem(
@@ -850,6 +1113,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
state,
createdAt: Date.now(),
label: action.label,
+ realm: loginRealm,
} satisfies PendingOAuth),
);
updateLoginState(
@@ -874,7 +1138,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return true;
}
await deleteSecureItem(PENDING_OAUTH_KEY).catch(() => undefined);
- updateLoginState(previousState);
+ pendingAuthRealmRef.current = null;
+ updateLoginState(null);
throw authCodeError('USER_CANCELLED');
}
if (action.type === 'select-account') {
@@ -964,12 +1229,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
code === 'INVALID_SSO_VERIFICATION_TICKET' ||
code === 'INVALID_TOKEN' ||
code === 'TOKEN_EXPIRED' ||
- code === 'AUTH_FLOW_SUPERSEDED'
+ code === 'AUTH_FLOW_SUPERSEDED' ||
+ code === 'USER_CANCELLED'
) {
pendingAccountTokenRef.current = null;
pendingLoginTicketRef.current = null;
pendingBindTicketRef.current = null;
pendingSsoVerificationTicketRef.current = null;
+ pendingAuthRealmRef.current = null;
pendingAccountDeletionRestoredRef.current = false;
setAccountDeletionRestored(false);
updateLoginState(null);
@@ -984,7 +1251,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
run.then(clearIfCurrent, clearIfCurrent);
return run;
},
- [acceptOutcome, completeOAuthCallback, updateLoginState],
+ [
+ acceptOutcome,
+ completeOAuthCallback,
+ suspendSessionRecoveryForLogin,
+ updateLoginState,
+ ],
);
const clearLocalSession = useCallback(async () => {
@@ -992,7 +1264,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// 都先 best-effort 注销移动推送 token —— 只挂在 logout 会漏掉终止路径,设备会
// 继续收到旧账号的任务通知。token 此刻可能已失效(账号不可用),失败静默,
// 残留由 server 侧 APNs 410 回收与换账号重注册的让位逻辑兜底。
- await unregisterPushTokenBestEffort(accessTokenRef.current);
+ await unregisterPushTokenBestEffort(
+ accessTokenRef.current,
+ activeAuthRealmRef.current,
+ );
authGenerationRef.current += 1;
refreshInFlightRef.current = null;
setToken(null);
@@ -1003,6 +1278,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
pendingLoginTicketRef.current = null;
pendingBindTicketRef.current = null;
pendingSsoVerificationTicketRef.current = null;
+ pendingAuthRealmRef.current = null;
+ activeAuthRealmRef.current = BUILD_AUTH_REGION;
+ resetMobileSessionRealm();
pendingAccountDeletionRestoredRef.current = false;
// 覆盖历史穿透凭据、服务模式与 BYOK key 三类存量存储键(功能已删除)。
await clearAllMobileVoiceCredentials().catch(() => undefined);
@@ -1022,13 +1300,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
await stopMobileTapdbReporting().catch(() => undefined);
await clearAnalyticsConsent().catch(() => undefined);
await serializeRefreshTokenMutation(() =>
- deleteSecureItem(REFRESH_TOKEN_KEY).catch(() => undefined),
+ deleteSecureItem(AUTH_SESSION_KEY).catch(() => undefined),
);
await Promise.all([
serializeUserProfileMutation(() =>
deleteSecureItem(USER_PROFILE_KEY).catch(() => undefined),
),
deleteSecureItem(LEGACY_REFRESH_TOKEN_KEY).catch(() => undefined),
+ deleteSecureItem(LEGACY_RESOURCE_REFRESH_TOKEN_KEY).catch(
+ () => undefined,
+ ),
deleteSecureItem(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY).catch(() => undefined),
deleteSecureItem(PENDING_OAUTH_KEY).catch(() => undefined),
deleteSecureItem(LEGACY_PENDING_OAUTH_KEY).catch(() => undefined),
@@ -1074,13 +1355,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const logout = useCallback(async () => {
const token = accessTokenRef.current;
const did = deviceIdRef.current;
+ const realm = activeAuthRealmRef.current;
// 移动推送 token 的注销收口在 clearLocalSession(覆盖 logout 与全部终止路径)。
// 普通登出代表放弃尚未确认的 challenge;确认注销走 clearLocalSession 直达,
// 不调用本函数,因此已确认请求的 receipt 仍会保留供登录页查询。
await persistAccountDeletionReceipt(null);
await clearLocalSession();
if (token && did)
- await authClientFor(did)
+ await authClientFor(did, realm)
.logout(token)
.catch(() => undefined);
}, [clearLocalSession, persistAccountDeletionReceipt]);
@@ -1112,7 +1394,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const did = deviceIdRef.current ?? (await ensureDeviceId());
deviceIdRef.current = did;
return runProtectedAuthRequest(() =>
- authClientFor(did).getAccountDeletionAvailability(token),
+ authClientFor(
+ did,
+ activeAuthRealmRef.current,
+ ).getAccountDeletionAvailability(token),
);
}, [getAccessToken, runProtectedAuthRequest]);
@@ -1122,11 +1407,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const did = deviceIdRef.current ?? (await ensureDeviceId());
deviceIdRef.current = did;
const challenge = await runProtectedAuthRequest(() =>
- authClientFor(did).requestAccountDeletionChallenge(token),
+ authClientFor(
+ did,
+ activeAuthRealmRef.current,
+ ).requestAccountDeletionChallenge(token),
);
// 先持久化查询凭证,再把 challenge 交给 UI。即使确认成功后的响应丢失,
// 下一次冷启动仍能查询注销状态。
- await persistAccountDeletionReceipt(challenge.receiptToken);
+ await persistAccountDeletionReceipt(
+ challenge.receiptToken,
+ activeAuthRealmRef.current,
+ );
return challenge;
}, [getAccessToken, persistAccountDeletionReceipt, runProtectedAuthRequest]);
@@ -1140,7 +1431,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
if (!token) throw authCodeError('UNAUTHENTICATED');
const did = deviceIdRef.current ?? (await ensureDeviceId());
deviceIdRef.current = did;
- const client = authClientFor(did);
+ const client = authClientFor(did, activeAuthRealmRef.current);
let status: AccountDeletionStatus;
try {
status = await runProtectedAuthRequest(() =>
@@ -1174,10 +1465,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const getAccountDeletionStatus = useCallback(async () => {
const receiptToken = accountDeletionReceipt;
- if (!receiptToken) return null;
+ const realm = accountDeletionReceiptRealmRef.current;
+ if (!receiptToken || !realm) return null;
const did = deviceIdRef.current ?? (await ensureDeviceId());
deviceIdRef.current = did;
- return authClientFor(did).getAccountDeletionStatus(receiptToken);
+ await loadMobileEndpointsForRealm(realm);
+ return authClientFor(did, realm).getAccountDeletionStatus(receiptToken);
}, [accountDeletionReceipt]);
const clearAccountDeletionReceipt = useCallback(
@@ -1297,10 +1590,12 @@ export function useAuth(): AuthContextValue {
return context;
}
-function authClientFor(deviceId: string): CindyAuthClient {
- // auth 协议只有 cn/global 两条线;dev 目标行为语义归 cn 系(实际连的
- // dev-auth 服务器由 AUTH_API_BASE_URL 决定,与线别参数正交)。
- const region = AUTH_REGION === 'global' ? 'global' : 'cn';
+function authClientFor(
+ deviceId: string,
+ region: AuthRegion = BUILD_AUTH_REGION,
+): CindyAuthClient {
+ // auth 协议只有 cn/global 两条线;dev 构建语义归 cn 系,实际基址仍来自
+ // 已解析的 endpoint manifest。
// 登录 scenario harness 注入点(仅 client 构造参数;implementation-plan Step 0
// WHAT4)。guard:__DEV__ + EXPO_PUBLIC_LOGIN_SCENARIO(值域见附录 A);
// 生产构建由 metro resolveRequest 把 fixtures 整模块替换为空 stub 双保险。
@@ -1310,7 +1605,7 @@ function authClientFor(deviceId: string): CindyAuthClient {
region,
});
return new CindyAuthClient({
- baseUrl: AUTH_API_BASE_URL,
+ baseUrl: getMobileEndpointForRealm(region, 'authApiBaseUrl'),
region,
deviceId,
clientType: 'mobile',
@@ -1401,6 +1696,22 @@ function authCodeError(code: string): Error & { code: string } {
return Object.assign(new Error(code), { code });
}
+async function readPersistedAuthSession(): Promise<AuthSessionRecord | null> {
+ return parseAuthSessionRecord(
+ await getSecureItem(AUTH_SESSION_KEY).catch(() => null),
+ );
+}
+
+async function writePersistedAuthSession(
+ refreshToken: string,
+ realm: AuthRegion,
+): Promise<void> {
+ await setSecureItem(
+ AUTH_SESSION_KEY,
+ serializeAuthSessionRecord(realm, refreshToken),
+ );
+}
+
async function readCachedUserProfile(): Promise<MobileUser | null> {
try {
const raw = await getSecureItem(USER_PROFILE_KEY);
@@ -1441,7 +1752,8 @@ async function readPendingOAuth(): Promise<PendingOAuth> {
typeof parsed.deviceId !== 'string' ||
typeof parsed.state !== 'string' ||
typeof parsed.createdAt !== 'number' ||
- typeof parsed.label !== 'string'
+ typeof parsed.label !== 'string' ||
+ (parsed.realm !== 'cn' && parsed.realm !== 'global')
)
throw authCodeError('INVALID_AUTH_CODE');
if (Date.now() - parsed.createdAt > PENDING_OAUTH_MAX_AGE_MS) {
diff --git a/apps/mobile/src/auth/__tests__/loginConsent.test.ts b/apps/mobile/src/auth/__tests__/loginConsent.test.ts
index eef20d6043..3515dfbfbc 100644
--- a/apps/mobile/src/auth/__tests__/loginConsent.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginConsent.test.ts
@@ -232,5 +232,10 @@ describe('LoginSkinControls 接线(源码断言)', () => {
expect(controlsSource).toContain('login.overlaySecondaryPressed');
// 弹窗 = stage 内全屏遮罩 + 680×380 设计坐标系整层缩放(与登录组同口径)
expect(controlsSource).toMatch(/LOGIN_CONSENT_DIALOG[\s\S]*transform: \[\{ scale \}\]/);
+ // 区域确认与协议确认共用设计标准正文 26/40,不允许按文案临时缩字号。
+ expect(controlsSource).toContain('fontSize={D.body.font}');
+ expect(controlsSource).toContain('lineHeight={D.body.lineHeight}');
+ expect(controlsSource).not.toContain('compactBody');
+ expect(loginSource).not.toContain('compactBody');
});
});
diff --git a/apps/mobile/src/auth/__tests__/loginMessages.test.ts b/apps/mobile/src/auth/__tests__/loginMessages.test.ts
index 9fca60137b..4933f6f38d 100644
--- a/apps/mobile/src/auth/__tests__/loginMessages.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginMessages.test.ts
@@ -21,6 +21,7 @@ import {
resolveLoginLocale,
type LoginLocale,
} from '@/auth/loginMessages';
+import { LOGIN_CONSENT_DIALOG } from '@/auth/loginSkinLayout';
const LOCALES: LoginLocale[] = ['zh-CN', 'en', 'ja', 'ko'];
@@ -64,6 +65,34 @@ describe('loginMessages 4 语 catalog', () => {
expect(loginMessages.ko.phonePlaceholder).toBe('휴대전화 번호');
});
+ it('区域确认正文按标准 26/40 固定两行,4 语每行均无需二次折行', () => {
+ const maxEstimatedUnits =
+ (LOGIN_CONSENT_DIALOG.body.width * 0.95 * 3) /
+ LOGIN_CONSENT_DIALOG.body.font;
+ const estimatedUnits = (value: string) =>
+ [...value].reduce(
+ (sum, character) =>
+ sum + ((character.codePointAt(0) ?? 0) <= 0xff ? 0.5 : 1),
+ 0,
+ );
+ for (const locale of LOCALES) {
+ const messages = loginMessages[locale];
+ for (const body of [
+ messages.realmConsentBodyCn,
+ messages.realmConsentBodyGlobal,
+ ]) {
+ const lines = body.split('\n');
+ expect(lines, `locale=${locale}: ${body}`).toHaveLength(2);
+ for (const line of lines) {
+ expect(
+ estimatedUnits(line),
+ `locale=${locale}: ${line}`,
+ ).toBeLessThanOrEqual(maxEstimatedUnits / 3);
+ }
+ }
+ }
+ });
+
it('登录错误码 4 语齐全且非空', () => {
const codes = Object.keys(authErrorMessages);
expect(codes.length).toBeGreaterThan(0);
diff --git a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
index 6b9f3e4bc5..d02746263a 100644
--- a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
@@ -168,10 +168,12 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {
expect(loginSource).toContain('setSsoOrgMode(false);');
});
- it('sso-org-filled:企业 ID 提交接线(discover-sso-org dispatch verbatim)', () => {
- expect(loginSource).toContain(
- "void auth.dispatchLoginAction({ type: 'discover-sso-org', org: value })",
- );
+ it('sso-org-filled:企业 ID 直接发现,仅在状态机判定跨区后确认', () => {
+ expect(loginSource).toContain("type: 'discover-sso-org'");
+ expect(loginSource).toContain("auth.loginState?.step === 'realm-confirmation'");
+ expect(loginSource).toContain("type: 'confirm-sso-realm'");
+ expect(loginSource).toContain("type: 'cancel-sso-realm'");
+ expect(loginSource).not.toContain('crossRegionConsent');
expect(loginSource).toContain('testID="login.ssoOrgContinueButton"');
expect(loginSource).toContain('disabled={disabled || !ssoOrg.trim()}');
});
diff --git a/apps/mobile/src/auth/loginMessages.ts b/apps/mobile/src/auth/loginMessages.ts
index aa9779f0c0..148c1ce277 100644
--- a/apps/mobile/src/auth/loginMessages.ts
+++ b/apps/mobile/src/auth/loginMessages.ts
@@ -31,9 +31,11 @@ const messages = {
emailCode: '发送邮箱验证码',
ssoRequired: '该组织要求使用企业 SSO 登录。',
ssoEntry: '使用企业 SSO 登录',
- consentStatement: '我已阅读并同意 <terms>服务条款</terms> 和 <privacy>隐私协议</privacy>',
+ consentStatement:
+ '我已阅读并同意 <terms>服务条款</terms> 和 <privacy>隐私协议</privacy>',
consentDialogTitle: '服务条款和隐私协议',
- consentDialogBody: '请阅读并同意 Cindy 的以下协议后继续:<terms>服务条款</terms>、<privacy>隐私协议</privacy>',
+ consentDialogBody:
+ '请阅读并同意 Cindy 的以下协议后继续:<terms>服务条款</terms>、<privacy>隐私协议</privacy>',
consentAgree: '同意',
consentDisagree: '暂不同意',
ssoOrgTitle: '企业 SSO 登录',
@@ -41,6 +43,11 @@ const messages = {
ssoOrgPlaceholder: '企业 ID、slug 或域名',
ssoOrgHint: '不知道企业登录标识?请联系企业管理员。',
ssoOrgDetected: '选择企业「{org}」的单点登录方式',
+ realmConsentTitle: '连接企业所在区域',
+ realmConsentBodyCn: '你的企业位于中国大陆区。\n继续后,Cindy 会连接该区域。',
+ realmConsentBodyGlobal: '你的企业位于国际区。\n继续后,Cindy 会连接该区域。',
+ realmConsentAgree: '继续登录',
+ realmConsentDisagree: '取消',
ssoVerificationTitle: '验证企业联系方式',
ssoVerificationSubtitle:
'首次登录需要验证身份提供方返回的联系方式 {target}。',
@@ -146,6 +153,13 @@ const messages = {
ssoOrgHint:
"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',
+ realmConsentBodyCn:
+ 'Your enterprise is in Mainland China.\nContinue to connect Cindy to this region.',
+ realmConsentBodyGlobal:
+ 'Your enterprise is in the Global region.\nContinue to connect Cindy to this region.',
+ realmConsentAgree: 'Continue sign-in',
+ realmConsentDisagree: 'Cancel',
ssoVerificationTitle: 'Verify your work identity',
ssoVerificationSubtitle:
'First-time sign-in requires verification of the contact returned by your identity provider: {target}.',
@@ -260,10 +274,19 @@ const messages = {
ssoOrgSubtitle:
'会社 ID、組織 slug、または確認済みドメインを入力すると、所属組織のシングルサインオンに進みます。',
ssoOrgPlaceholder: '会社 ID、slug、またはドメイン',
- ssoOrgHint: '企業のログイン識別子が不明な場合は、管理者にお問い合わせください。',
+ ssoOrgHint:
+ '企業のログイン識別子が不明な場合は、管理者にお問い合わせください。',
ssoOrgDetected: '組織「{org}」のシングルサインオン方法を選択',
+ realmConsentTitle: '企業のリージョンに接続',
+ realmConsentBodyCn:
+ 'この企業は中国本土リージョンにあります。\n続行すると Cindy はこの地域に接続します。',
+ realmConsentBodyGlobal:
+ 'この企業はグローバルリージョンにあります。\n続行すると Cindy はこの地域に接続します。',
+ realmConsentAgree: 'ログインを続ける',
+ realmConsentDisagree: 'キャンセル',
ssoVerificationTitle: '企業の連絡先を確認',
- ssoVerificationSubtitle: '初回ログイン時、IdP が返した連絡先 {target} の確認が必要です。',
+ ssoVerificationSubtitle:
+ '初回ログイン時、IdP が返した連絡先 {target} の確認が必要です。',
enterCode: '認証コードを入力',
codeSentTo: '認証コードの送信先:',
codePlaceholder: '6桁の認証コード',
@@ -298,9 +321,11 @@ const messages = {
accountDeletionScreenTitle: 'アカウントを削除',
accountDeletionLoading: 'アカウントの状態を確認しています…',
accountDeletionUnavailableTitle: 'この操作は現在利用できません',
- accountDeletionUnavailableCopy: '設定画面に戻って、後でもう一度お試しください。',
+ accountDeletionUnavailableCopy:
+ '設定画面に戻って、後でもう一度お試しください。',
accountDeletionVerifyTitle: 'アカウントの所有権を確認',
- accountDeletionCodeSent: '認証コードを {target} に送信しました。10 分間有効です。',
+ accountDeletionCodeSent:
+ '認証コードを {target} に送信しました。10 分間有効です。',
accountDeletionAcknowledgeA11y: 'アカウント削除の影響を理解したことを確認',
accountDeletionAcknowledgeCopy:
'理解しています:この端末はすぐにログアウトします。他のクライアントはログイン状態が無効になった後にログアウトします。30 日以内に再ログインすれば取り消せます。期限が過ぎると Cindy ログインアカウントは完全に削除され、復元できません。',
@@ -323,8 +348,10 @@ const messages = {
'認証コードが正しくないか、有効期限が切れています。確認して再試行してください。',
accountDeletionErrorAttempts:
'認証の試行回数が多すぎます。認証コードを再送信してください。',
- accountDeletionErrorRate: '操作が頻繁すぎます。しばらくしてからお試しください。',
- accountDeletionErrorPending: 'アカウントはすでに削除待機期間に入っています。',
+ accountDeletionErrorRate:
+ '操作が頻繁すぎます。しばらくしてからお試しください。',
+ accountDeletionErrorPending:
+ 'アカウントはすでに削除待機期間に入っています。',
accountDeletionErrorProcessing: 'アカウントの削除処理はすでに進行中です。',
accountDeletionErrorUnavailable: 'この操作は現在利用できません。',
accountDeletionErrorNetwork:
@@ -367,12 +394,21 @@ const messages = {
consentAgree: '동의',
consentDisagree: '동의 안 함',
ssoOrgTitle: '기업 SSO 로그인',
- ssoOrgSubtitle: '회사 ID, 조직 slug 또는 인증된 도메인을 입력하면 소속 조직의 SSO 로그인으로 이동합니다.',
+ ssoOrgSubtitle:
+ '회사 ID, 조직 slug 또는 인증된 도메인을 입력하면 소속 조직의 SSO 로그인으로 이동합니다.',
ssoOrgPlaceholder: '회사 ID, slug 또는 도메인',
ssoOrgHint: '기업 로그인 식별자를 모르시나요? 관리자에게 문의하세요.',
ssoOrgDetected: '"{org}" 조직의 SSO 연결을 선택하세요',
+ realmConsentTitle: '기업 지역에 연결',
+ realmConsentBodyCn:
+ '이 기업은 중국 본토 지역에 있습니다.\n계속하면 Cindy가 해당 지역에 연결됩니다.',
+ realmConsentBodyGlobal:
+ '이 기업은 글로벌 지역에 있습니다.\n계속하면 Cindy가 해당 지역에 연결됩니다.',
+ realmConsentAgree: '로그인 계속',
+ realmConsentDisagree: '취소',
ssoVerificationTitle: '기업 신원 확인',
- ssoVerificationSubtitle: '최초 로그인 시 ID 공급자가 반환한 연락처 {target} 확인이 필요합니다.',
+ ssoVerificationSubtitle:
+ '최초 로그인 시 ID 공급자가 반환한 연락처 {target} 확인이 필요합니다.',
enterCode: '인증 코드 입력',
codeSentTo: '인증 코드 전송 대상:',
codePlaceholder: '6자리 인증 코드',
@@ -406,9 +442,11 @@ const messages = {
accountDeletionScreenTitle: '계정 삭제',
accountDeletionLoading: '계정 상태를 확인하는 중…',
accountDeletionUnavailableTitle: '현재 이 작업을 사용할 수 없습니다',
- accountDeletionUnavailableCopy: '설정 화면으로 돌아가 나중에 다시 시도해 주세요.',
+ accountDeletionUnavailableCopy:
+ '설정 화면으로 돌아가 나중에 다시 시도해 주세요.',
accountDeletionVerifyTitle: '계정 소유권 확인',
- accountDeletionCodeSent: '인증 코드를 {target}(으)로 보냈습니다. 10분간 유효합니다.',
+ accountDeletionCodeSent:
+ '인증 코드를 {target}(으)로 보냈습니다. 10분간 유효합니다.',
accountDeletionAcknowledgeA11y: '계정 삭제의 영향을 이해했음을 확인',
accountDeletionAcknowledgeCopy:
'이해합니다: 이 기기는 즉시 로그아웃됩니다. 다른 클라이언트는 로그인 상태가 무효화된 후 로그아웃됩니다. 30일 이내에 다시 로그인하면 취소할 수 있습니다. 기한이 지나면 Cindy 로그인 계정은 영구적으로 삭제되며 복구할 수 없습니다.',
@@ -431,7 +469,8 @@ const messages = {
'인증 코드가 올바르지 않거나 만료되었습니다. 확인 후 다시 시도해 주세요.',
accountDeletionErrorAttempts:
'인증 시도가 너무 많습니다. 인증 코드를 다시 보내주세요.',
- accountDeletionErrorRate: '요청이 너무 잦습니다. 잠시 후 다시 시도해 주세요.',
+ accountDeletionErrorRate:
+ '요청이 너무 잦습니다. 잠시 후 다시 시도해 주세요.',
accountDeletionErrorPending: '계정이 이미 삭제 대기 기간에 들어갔습니다.',
accountDeletionErrorProcessing: '계정 삭제가 이미 진행 중입니다.',
accountDeletionErrorUnavailable: '현재 이 작업을 사용할 수 없습니다.',
@@ -477,7 +516,10 @@ export function resolveLoginLocale(
/** 生效语言:设置里的手动选择优先,未选择时跟随系统语言(4 语主干)。 */
export function getLoginLanguage(): LoginLocale {
- return getManualLocaleOverride() ?? resolveLoginLocale(getLocales()[0]?.languageTag);
+ return (
+ getManualLocaleOverride() ??
+ resolveLoginLocale(getLocales()[0]?.languageTag)
+ );
}
/**
@@ -587,6 +629,18 @@ export const authErrorMessages: Record<string, Record<LoginLocale, string>> = {
ja: '会社が見つからないか、SSO ログインが有効になっていません。',
ko: '회사를 찾을 수 없거나 SSO 로그인이 활성화되어 있지 않습니다.',
},
+ ORG_REALM_AMBIGUOUS: {
+ 'zh-CN': '该企业标识同时存在于两个区域,请联系企业管理员处理。',
+ en: 'This enterprise identifier exists in both regions. Contact your administrator.',
+ ja: 'この企業識別子は両方の地域に存在します。管理者にお問い合わせください。',
+ ko: '이 기업 식별자가 두 지역에 모두 존재합니다. 관리자에게 문의하세요.',
+ },
+ ORG_REALM_UNAVAILABLE: {
+ 'zh-CN': '暂时无法确认企业所在区域,请检查网络后重试。',
+ en: 'Cindy cannot verify the enterprise region right now. Check your connection and retry.',
+ ja: '企業の地域を現在確認できません。ネットワークを確認して再試行してください。',
+ ko: '현재 기업 지역을 확인할 수 없습니다. 네트워크를 확인한 후 다시 시도하세요.',
+ },
SSO_EMAIL_REQUIRED: {
'zh-CN': '该企业身份未提供有效邮箱,请联系企业管理员检查 IdP 配置。',
en: 'Your work identity did not provide a valid email. Ask your admin to check the IdP configuration.',
diff --git a/apps/mobile/src/config/clientEndpointStartup.ts b/apps/mobile/src/config/clientEndpointStartup.ts
index b17c0d82f4..437b9266f9 100644
--- a/apps/mobile/src/config/clientEndpointStartup.ts
+++ b/apps/mobile/src/config/clientEndpointStartup.ts
@@ -23,7 +23,11 @@ import {
type ClientEndpointMap,
} from '@cindy/maker-shared/client-endpoints';
-import { ENDPOINT_MANIFEST_BASE_URL, applyResolvedClientEndpoints } from './env';
+import {
+ BUILD_AUTH_REGION,
+ ENDPOINT_MANIFEST_BASE_URL,
+ applyResolvedClientEndpoints,
+} from './env';
const MANIFEST_RELATIVE_PATH = '/endpoint.json';
/** 单次请求的网络超时——超时即阻断启动,不是无限等待。 */
@@ -98,6 +102,7 @@ export interface StartupEndpointResolveDeps {
apply?: (resolved: ClientEndpointMap & {
reviewVersion: string | null;
isTestFlight: boolean;
+ region: 'cn' | 'global' | null;
}) => void;
timeoutMs?: number;
/** 自动重试节奏,默认 AUTO_RETRY_DELAYS_MS;传 `[]` 关闭(单次尝试)。 */
@@ -171,6 +176,13 @@ export async function runStartupEndpointResolve(
// 拿到正文:解析/校验不过 = 线上清单配置错,重试同一份内容没有意义,直接阻断。
const result = resolveClientEndpointsStrict(fetched.text);
if (!result.ok) return { ok: false, reason: result.reason };
+ // 老清单缺 region 时保持兼容;一旦自报 region,就必须与安装包构建区域一致。
+ if (result.region !== null && result.region !== BUILD_AUTH_REGION) {
+ return {
+ ok: false,
+ reason: `region-mismatch:${BUILD_AUTH_REGION}:${result.region}`,
+ };
+ }
// 分发环境识别失败不能把 endpoint 闸门变成启动故障;降级为非 TestFlight,
// 保留既有 review 行为。真实 iOS 路径由 useStartupEndpointGate 注入 StoreKit 实现。
@@ -181,7 +193,12 @@ export async function runStartupEndpointResolve(
isTestFlight = false;
}
- apply({ ...result.endpoints, reviewVersion: result.reviewVersion, isTestFlight });
+ apply({
+ ...result.endpoints,
+ reviewVersion: result.reviewVersion,
+ isTestFlight,
+ region: result.region,
+ });
return { ok: true, source: 'cdn' };
} catch {
return { ok: false, reason: 'internal-error' };
diff --git a/apps/mobile/src/config/env.ts b/apps/mobile/src/config/env.ts
index 241ebd56ea..89fe4fe946 100644
--- a/apps/mobile/src/config/env.ts
+++ b/apps/mobile/src/config/env.ts
@@ -1,6 +1,13 @@
import Constants from 'expo-constants';
-import { parseClientEndpointManifest } from '@cindy/maker-shared/client-endpoints';
+import {
+ CLIENT_ENDPOINT_KEYS,
+ parseClientEndpointManifest,
+ type ClientEndpointKey,
+ type ClientEndpointMap,
+ type ClientEndpointRegion,
+ type RealmManifestBaseUrls,
+} from '@cindy/maker-shared/client-endpoints';
import type { LoginMessageKey } from '@/auth/loginMessages';
@@ -12,17 +19,16 @@ export interface MobileGoogleConfig {
iosUrlScheme: string;
}
-const configuredExpoExtra = (Constants.expoConfig?.extra as {
- xdtProductionEnv?: Record<string, string>;
- cindy?: {
- regionConfigSource?: string;
- google?: Partial<MobileGoogleConfig>;
- };
-} | null) ?? {};
-const configuredBuildEnv = (configuredExpoExtra.xdtProductionEnv ?? {}) as Record<
- string,
- string
->;
+const configuredExpoExtra =
+ (Constants.expoConfig?.extra as {
+ xdtProductionEnv?: Record<string, string>;
+ cindy?: {
+ regionConfigSource?: string;
+ google?: Partial<MobileGoogleConfig>;
+ };
+ } | null) ?? {};
+const configuredBuildEnv = (configuredExpoExtra.xdtProductionEnv ??
+ {}) as Record<string, string>;
const configuredRegionGoogle = configuredExpoExtra.cindy?.google;
function configuredValue(key: string): string {
@@ -33,7 +39,11 @@ export const AUTH_REGION: CindyAuthRegion = (() => {
const value = configuredValue('EXPO_PUBLIC_CINDY_AUTH_REGION');
return value === 'global' ? 'global' : value === 'dev' ? 'dev' : 'cn';
})();
-export const APP_SCHEME = { cn: 'cindycn', global: 'cindy', dev: 'cindydev' }[AUTH_REGION];
+export const BUILD_AUTH_REGION: ClientEndpointRegion =
+ AUTH_REGION === 'global' ? 'global' : 'cn';
+export const APP_SCHEME = { cn: 'cindycn', global: 'cindy', dev: 'cindydev' }[
+ AUTH_REGION
+];
export const MOBILE_REDIRECT_URL = `${APP_SCHEME}://auth`;
// __DEV__ 端点初值来源:metro 构建期按 AUTH_REGION 把仓内
@@ -59,13 +69,31 @@ const DEV_MANIFEST_PARSED = (() => {
require('../../../../config/endpoint.dev.json')
: // eslint-disable-next-line @typescript-eslint/no-require-imports
require('../../../../config/endpoint.json');
- const parsed = parseClientEndpointManifest(JSON.stringify(raw), { allowHttp: true });
+ const parsed = parseClientEndpointManifest(JSON.stringify(raw), {
+ allowHttp: true,
+ });
if (!parsed.ok) {
- throw new Error(`${manifestPath} invalid (${parsed.reason}) — dev 端点正本必须能过客户端 parser`);
+ throw new Error(
+ `${manifestPath} invalid (${parsed.reason}) — dev 端点正本必须能过客户端 parser`,
+ );
}
return parsed;
})();
-const DEV_MANIFEST: Partial<Record<string, string>> = DEV_MANIFEST_PARSED?.endpoints ?? {};
+const DEV_MANIFEST: Partial<Record<string, string>> =
+ DEV_MANIFEST_PARSED?.endpoints ?? {};
+
+let buildEndpointMap: ClientEndpointMap | null =
+ DEV_MANIFEST_PARSED?.endpoints ?? null;
+let endpointManifestRegion: ClientEndpointRegion | null =
+ DEV_MANIFEST_PARSED?.region ?? null;
+let activeSessionRealm: ClientEndpointRegion = BUILD_AUTH_REGION;
+const realmEndpointCache = new Map<ClientEndpointRegion, ClientEndpointMap>();
+if (buildEndpointMap) {
+ realmEndpointCache.set(
+ endpointManifestRegion ?? BUILD_AUTH_REGION,
+ buildEndpointMap,
+ );
+}
// 显式 env 优先,dev 回落仓内正本;prod 为空串(闸门回填,见上)。
export const DEFAULT_DEVICE_LINK_API_BASE_URL =
@@ -84,7 +112,10 @@ export interface MobileConfigIssue {
messageKey: LoginMessageKey;
}
-export function normalizeBaseUrlWithDefault(value: string | undefined, fallback: string): string {
+export function normalizeBaseUrlWithDefault(
+ value: string | undefined,
+ fallback: string,
+): string {
const trimmed = value?.trim();
return trimmed ? trimmed.replace(/\/$/, '') : fallback;
}
@@ -94,7 +125,9 @@ export function normalizeBaseUrlWithDefault(value: string | undefined, fallback:
// EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL。
export function resolveDeviceLinkApiBaseUrl(value: string | undefined): string {
const trimmed = value?.trim();
- return trimmed ? trimmed.replace(/\/$/, '') : DEFAULT_DEVICE_LINK_API_BASE_URL;
+ return trimmed
+ ? trimmed.replace(/\/$/, '')
+ : DEFAULT_DEVICE_LINK_API_BASE_URL;
}
export function deviceLinkWsUrl(apiBaseUrl = DEVICE_LINK_API_BASE_URL): string {
@@ -110,9 +143,8 @@ export const DEV_LOGIN_ENABLED = resolveEnvFlag(
process.env.EXPO_PUBLIC_XDT_DEV_LOGIN_ENABLED,
);
-export const MOBILE_VISUAL_MOCK_ENABLED = __DEV__ && resolveEnvFlag(
- process.env.EXPO_PUBLIC_CINDY_MOBILE_VISUAL_MOCK,
-);
+export const MOBILE_VISUAL_MOCK_ENABLED =
+ __DEV__ && resolveEnvFlag(process.env.EXPO_PUBLIC_CINDY_MOBILE_VISUAL_MOCK);
export const MOBILE_VISUAL_MOCK_REALDATA_URL = __DEV__
? process.env.EXPO_PUBLIC_CINDY_MOBILE_REALDATA_URL?.trim() || ''
@@ -153,8 +185,8 @@ function isHttpUrl(value: string): boolean {
// 新值(消费点全部是调用时读取,无模块顶层捕获——新增顶层派生前先想清楚)。
// 初始值即构建期烘焙值;__DEV__ 下闸门不拉取,行为与现状完全一致。
-// auth 不分 cn/global 字段:dev 读所选 region 正本(默认 global);prod 由 region 化
-// 清单回填。显式 env 覆写仍最高优先。
+// 默认 auth 来自构建区域清单;组织 SSO 登录时会把 token 消费端点整体切到
+// session realm。显式 env 覆写仍只影响 dev/构建区域初值。
export let AUTH_API_BASE_URL = normalizeBaseUrlWithDefault(
configuredValue('EXPO_PUBLIC_CINDY_AUTH_BASE_URL'),
DEV_MANIFEST.authApiBaseUrl ?? '',
@@ -216,11 +248,32 @@ export let VOICE_API_BASE_URL = normalizeBaseUrlWithDefault(
DEV_MANIFEST.voiceApiBaseUrl ?? '',
);
+function syncBuildTokenEndpointCache(): void {
+ if (!buildEndpointMap) return;
+ const buildRealm = endpointManifestRegion ?? BUILD_AUTH_REGION;
+ buildEndpointMap = {
+ ...buildEndpointMap,
+ authApiBaseUrl: AUTH_API_BASE_URL,
+ oauthBrokerApiBaseUrl: OAUTH_BROKER_API_BASE_URL,
+ deviceLinkApiBaseUrl: DEVICE_LINK_API_BASE_URL,
+ voiceApiBaseUrl: VOICE_API_BASE_URL,
+ };
+ realmEndpointCache.set(buildRealm, buildEndpointMap);
+}
+
+// __DEV__ 的显式 EXPO_PUBLIC_* 覆写必须同时进入构建区域缓存。认证客户端和
+// logout/reset 现在从 realm cache 取值;只改 live binding 会导致首次登录看似
+// 命中本地服务,后续 realm 激活却悄悄退回仓内正本。
+syncBuildTokenEndpointCache();
+
// 二进制版本号:审核模式匹配基准。优先原生层版本(iOS CFBundleShortVersionString /
// Android versionName,OTA 热更后不漂移),expoConfig.version 兜底(dev / 测试环境
// 拿不到原生值)。与 mobileTapdb 的版本上报取值口径一致。
-export const APP_BINARY_VERSION =
- (Constants.nativeAppVersion ?? Constants.expoConfig?.version ?? '').trim();
+export const APP_BINARY_VERSION = (
+ Constants.nativeAppVersion ??
+ Constants.expoConfig?.version ??
+ ''
+).trim();
// 运行平台标识:只会是 'ios' / 'android' / ''(拿不到)。审核模式的平台门控要在 env.ts
// 顶层就能判定,而这里不能引 react-native 的 Platform:env.ts 被 node 环境单测直接
@@ -299,23 +352,41 @@ export let REVIEW_MODE = isReviewModeActive(
// 非 live binding(清单不再承载语音网关地址,启动闸门无覆写路径):env 覆写为空时
// 即空串。生产语音输入走 VOICE_API_BASE_URL 的托管路径,本值仅供本地 e2e / dev。
-export const MOBILE_VOICE_LITELLM_BASE_URL = DEFAULT_MOBILE_VOICE_LITELLM_BASE_URL
- ? normalizeBaseUrlWithDefault(DEFAULT_MOBILE_VOICE_LITELLM_BASE_URL, '')
- : '';
-
-// 端点清单(endpoint.json)的自举拉取基址(启动闸门专用),按 region 构建期二选一
-// 烘焙(EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL ← region 对应 endpoint*.json 的
-// cdnBaseUrl)。**烘焙常量、不接受远程覆盖**——拉清单的
-// 地址若吃清单自己的字段,配错一次就把自己锁死(与 desktop 同则)。这是客户端
-// 唯一"有感"的烘焙远程 URL。
+export const MOBILE_VOICE_LITELLM_BASE_URL =
+ DEFAULT_MOBILE_VOICE_LITELLM_BASE_URL
+ ? normalizeBaseUrlWithDefault(DEFAULT_MOBILE_VOICE_LITELLM_BASE_URL, '')
+ : '';
+
+// 本区与对端 endpoint.json 的自举拉取基址,均由构建期从两份仓内清单的
+// cdnBaseUrl 注入。**烘焙常量、不接受远程覆盖**——区域身份由受信任地址表
+// 决定,远端清单只提供该区域的业务端点。
export const ENDPOINT_MANIFEST_BASE_URL = configuredValue(
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL',
).replace(/\/+$/, '');
+export const ENDPOINT_MANIFEST_PEER_BASE_URL = (
+ // Expo/Metro 只内联静态属性访问;不能改回 configuredValue(dynamicKey)。
+ process.env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL?.trim() ||
+ configuredBuildEnv.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL?.trim() ||
+ ''
+).replace(/\/+$/, '');
+
+function trustedMobileRealmManifestBaseUrls(): RealmManifestBaseUrls {
+ return BUILD_AUTH_REGION === 'global'
+ ? {
+ cn: ENDPOINT_MANIFEST_PEER_BASE_URL,
+ global: ENDPOINT_MANIFEST_BASE_URL,
+ }
+ : {
+ cn: ENDPOINT_MANIFEST_BASE_URL,
+ global: ENDPOINT_MANIFEST_PEER_BASE_URL,
+ };
+}
/**
* 启动闸门拉到远程端点清单后回写运行期端点。`undefined` 表示调用方未提供、
- * 不修改;空串表示清单缺失/留空后的权威结果,必须清空旧值。auth 字段不分
- * region——国内/海外两条 CDN 各发各的清单,无脑取。
+ * 不修改;空串表示清单缺失/留空后的权威结果,必须清空旧值。启动清单写入
+ * 构建区域默认值;跨区域组织会话由 activateMobileSessionRealm 整体切换
+ * token 消费端点。
*/
export function applyResolvedClientEndpoints(resolved: {
authApiBaseUrl?: string;
@@ -327,12 +398,19 @@ export function applyResolvedClientEndpoints(resolved: {
reviewVersion?: string | null;
/** iOS StoreKit 分发环境;TestFlight 保留 OTA、禁用整包外跳。 */
isTestFlight?: boolean;
+ region?: ClientEndpointRegion | null;
}): void {
if (resolved.authApiBaseUrl !== undefined) {
- AUTH_API_BASE_URL = normalizeBaseUrlWithDefault(resolved.authApiBaseUrl, '');
+ AUTH_API_BASE_URL = normalizeBaseUrlWithDefault(
+ resolved.authApiBaseUrl,
+ '',
+ );
}
if (resolved.oauthBrokerApiBaseUrl !== undefined) {
- OAUTH_BROKER_API_BASE_URL = normalizeBaseUrlWithDefault(resolved.oauthBrokerApiBaseUrl, '');
+ OAUTH_BROKER_API_BASE_URL = normalizeBaseUrlWithDefault(
+ resolved.oauthBrokerApiBaseUrl,
+ '',
+ );
}
if (resolved.deviceLinkApiBaseUrl !== undefined) {
DEVICE_LINK_API_BASE_URL = resolved.deviceLinkApiBaseUrl.replace(/\/$/, '');
@@ -340,6 +418,9 @@ export function applyResolvedClientEndpoints(resolved: {
if (resolved.voiceApiBaseUrl !== undefined) {
VOICE_API_BASE_URL = resolved.voiceApiBaseUrl.replace(/\/$/, '');
}
+ // partial apply 也必须保持构建缓存与 live binding 一致;测试、dev 热重载和
+ // 未来的局部配置刷新都不能在下一次 realm reset 时退回旧值。
+ syncBuildTokenEndpointCache();
// 仅自建变体吃清单覆写,保住「非自建 ⇒ OTA_SERVER_BASE_URL 恒空串」不变量
// (调用点虽都有 IS_OTA_SELFHOST 门控,这里再挡一层,变体身份始终由烧包决定)。
if (resolved.mobileUpdateBaseUrl !== undefined && IS_OTA_SELFHOST) {
@@ -351,13 +432,112 @@ export function applyResolvedClientEndpoints(resolved: {
if (resolved.isTestFlight !== undefined) {
IS_TESTFLIGHT_BUILD = resolved.isTestFlight;
}
- if (resolved.reviewVersion !== undefined || resolved.isTestFlight !== undefined) {
+ if (
+ resolved.reviewVersion !== undefined ||
+ resolved.isTestFlight !== undefined
+ ) {
REVIEW_MODE = isReviewModeActive(
resolvedReviewVersion,
APP_BINARY_VERSION,
IS_TESTFLIGHT_BUILD,
);
}
+
+ const hasCompleteEndpointMap = CLIENT_ENDPOINT_KEYS.every(
+ (key) => typeof (resolved as Partial<ClientEndpointMap>)[key] === 'string',
+ );
+ if (hasCompleteEndpointMap) {
+ buildEndpointMap = resolved as ClientEndpointMap;
+ endpointManifestRegion = resolved.region ?? null;
+ activeSessionRealm = endpointManifestRegion ?? BUILD_AUTH_REGION;
+ realmEndpointCache.clear();
+ realmEndpointCache.set(activeSessionRealm, buildEndpointMap);
+ }
+}
+
+export function getMobileEndpointRealmConfig(): {
+ buildRegion: ClientEndpointRegion;
+ manifestRegion: ClientEndpointRegion | null;
+ crossRealmOrgLoginEnabled: boolean;
+ realmManifestBaseUrls: RealmManifestBaseUrls;
+} {
+ return {
+ buildRegion: BUILD_AUTH_REGION,
+ manifestRegion: endpointManifestRegion,
+ crossRealmOrgLoginEnabled: AUTH_REGION !== 'dev',
+ realmManifestBaseUrls: trustedMobileRealmManifestBaseUrls(),
+ };
+}
+
+const MOBILE_REALM_MANIFEST_TIMEOUT_MS = 10_000;
+
+/** 当前登录态消费业务请求的区域;与安装包/更新通道所在区域相互独立。 */
+export function getActiveMobileSessionRealm(): ClientEndpointRegion {
+ return activeSessionRealm;
+}
+
+export async function loadMobileEndpointsForRealm(
+ region: ClientEndpointRegion,
+): Promise<ClientEndpointMap> {
+ const cached = realmEndpointCache.get(region);
+ if (cached) return cached;
+ const baseUrl = trustedMobileRealmManifestBaseUrls()[region];
+ if (!baseUrl) {
+ throw new Error('realm-manifest-url-unavailable');
+ }
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () => controller.abort(),
+ MOBILE_REALM_MANIFEST_TIMEOUT_MS,
+ );
+ try {
+ const response = await fetch(`${baseUrl}/endpoint.json?t=${Date.now()}`, {
+ signal: controller.signal,
+ });
+ if (!response.ok) throw new Error(`http-${response.status}`);
+ const parsed = parseClientEndpointManifest(await response.text());
+ if (!parsed.ok) throw new Error(parsed.reason);
+ if (parsed.region !== null && parsed.region !== region) {
+ throw new Error(`region-mismatch:${region}:${parsed.region}`);
+ }
+ realmEndpointCache.set(region, parsed.endpoints);
+ return parsed.endpoints;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+export function getMobileEndpointForRealm(
+ region: ClientEndpointRegion,
+ key: ClientEndpointKey,
+): string {
+ const endpoints = realmEndpointCache.get(region);
+ if (!endpoints)
+ throw new Error(`mobile endpoints for realm '${region}' not loaded`);
+ return endpoints[key];
+}
+
+/** 只切 token 消费端点;mobileUpdate/review/更新身份仍由构建清单控制。 */
+export function activateMobileSessionRealm(region: ClientEndpointRegion): void {
+ const endpoints = realmEndpointCache.get(region);
+ if (!endpoints)
+ throw new Error(`mobile endpoints for realm '${region}' not loaded`);
+ activeSessionRealm = region;
+ AUTH_API_BASE_URL = endpoints.authApiBaseUrl;
+ OAUTH_BROKER_API_BASE_URL = endpoints.oauthBrokerApiBaseUrl;
+ DEVICE_LINK_API_BASE_URL = endpoints.deviceLinkApiBaseUrl;
+ VOICE_API_BASE_URL = endpoints.voiceApiBaseUrl;
+}
+
+export function resetMobileSessionRealm(): void {
+ const buildRealm = endpointManifestRegion ?? BUILD_AUTH_REGION;
+ const endpoints = realmEndpointCache.get(buildRealm) ?? buildEndpointMap;
+ activeSessionRealm = buildRealm;
+ if (!endpoints) return;
+ AUTH_API_BASE_URL = endpoints.authApiBaseUrl;
+ OAUTH_BROKER_API_BASE_URL = endpoints.oauthBrokerApiBaseUrl;
+ DEVICE_LINK_API_BASE_URL = endpoints.deviceLinkApiBaseUrl;
+ VOICE_API_BASE_URL = endpoints.voiceApiBaseUrl;
}
// 自建分发服务基址,唯一来源是 endpoint.json 的 mobileUpdateBaseUrl:
diff --git a/apps/mobile/src/notifications/PushNotificationsBridge.tsx b/apps/mobile/src/notifications/PushNotificationsBridge.tsx
index a36329b0f1..6d813d5e3f 100644
--- a/apps/mobile/src/notifications/PushNotificationsBridge.tsx
+++ b/apps/mobile/src/notifications/PushNotificationsBridge.tsx
@@ -41,7 +41,7 @@ export function PushNotificationsBridge() {
if (!auth.initialized || !auth.isAuthenticated) return;
let cancelled = false;
void (async () => {
- // 先补偿上次登出/终止时失败的注销,再按当前开关同步注册状态
+ // 只用当前会话补偿当前区域的注销,再按本机开关同步注册状态。
await retryPendingUnregister(apiFetchRef.current).catch(() => undefined);
if (cancelled) return;
const enabled = await readPushEnabled();
@@ -51,7 +51,7 @@ export function PushNotificationsBridge() {
return () => {
cancelled = true;
};
- }, [auth.initialized, auth.isAuthenticated]);
+ }, [auth.initialized, auth.isAuthenticated, auth.user]);
// APNs token 轮换 → 重新上报(仅开关开启且已登录时)
useEffect(() => {
diff --git a/apps/mobile/src/notifications/pushNotifications.ts b/apps/mobile/src/notifications/pushNotifications.ts
index d1f79fdcf9..ca692d5d60 100644
--- a/apps/mobile/src/notifications/pushNotifications.ts
+++ b/apps/mobile/src/notifications/pushNotifications.ts
@@ -1,8 +1,15 @@
import * as Notifications from 'expo-notifications';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Platform } from 'react-native';
+import type { ClientEndpointRegion } from '@cindy/maker-shared/client-endpoints';
import type { ApiFetchOptions } from '@/api/client';
-import { AUTH_REGION, DEVICE_LINK_API_BASE_URL } from '@/config/env';
+import {
+ AUTH_REGION,
+ BUILD_AUTH_REGION,
+ getActiveMobileSessionRealm,
+ getMobileEndpointForRealm,
+ loadMobileEndpointsForRealm,
+} from '@/config/env';
import { buildPushTokenRegistrationBody } from './pushRegistrationModel';
/**
@@ -10,22 +17,178 @@ import { buildPushTokenRegistrationBody } from './pushRegistrationModel';
*
* - 开关持久化在本机(AsyncStorage),默认关闭;打开时才请求系统通知权限。
* - 注册目标是 device-link server 的 PUT /push-token(Bearer 鉴权与 WS 同源);
- * 关闭开关 / 登出时注销(DELETE,幂等)。
+ * 关闭开关 / 登出 / 换账号或区域时注销(DELETE,幂等)。
* - 仅 iOS(APNs):Android 需 FCM / 国内厂商通道,二期接入(server 侧已预留
* provider='fcm' 字段)。
* - App 在前台时压掉系统横幅(WS 活着,会话本来就在实时刷新)。
*/
const PUSH_ENABLED_KEY = 'cindy.push.enabled';
-/** 是否成功注册过 token:避免从未注册的设备在每次启动时都打一发 DELETE。 */
+/** 成功或可能成功注册过 token 的区域集合,避免把注销请求发到错误区域。 */
const PUSH_REGISTERED_KEY = 'cindy.push.registered';
/**
- * 登出/终止时注销失败的待补偿标记:离线登出会吞掉 DELETE 失败,未登录态又拿不到
- * token 重试——留标记,下次任意账号登录后补一发注销(换账号场景另有 server 侧
- * 同 token 让位逻辑兜底)。
+ * 注销失败的区域集合。只允许在以后重新持有同一区域登录态时补偿,
+ * 不会用 CN token 请求 Global,也不会用 Global token 请求 CN。
*/
const PUSH_PENDING_UNREGISTER_KEY = 'cindy.push.pendingUnregister';
const PUSH_TOKEN_PATH = '/api/device-link/push-token';
+const PUSH_REALM_STATE_VERSION = 1;
+const PUSH_DEVICE_TOKEN_MAX_LENGTH = 512;
+const PUSH_UNREGISTER_TIMEOUT_MS = 3_000;
+
+interface PushRealmState {
+ version: typeof PUSH_REALM_STATE_VERSION;
+ realms: ClientEndpointRegion[];
+}
+
+/** React effects / token listener / 设置页可能同时触发,串行化避免注册与撤销倒序。 */
+let pushMutationTail: Promise<void> = Promise.resolve();
+/**
+ * 终止登录不能排在 apiFetch 后面等待,否则 apiFetch 的 terminal handler 正在
+ * await 注销时会形成环。注销递增 generation,使旧生命周期的排队操作失效。
+ */
+let pushLifecycleGeneration = 0;
+
+function runPushMutation<T>(operation: () => Promise<T>): Promise<T> {
+ const result = pushMutationTail.then(operation, operation);
+ pushMutationTail = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+}
+
+function isClientEndpointRegion(value: unknown): value is ClientEndpointRegion {
+ return value === 'cn' || value === 'global';
+}
+
+/**
+ * v1 以前两个 key 都是 '0'/'1'。旧版没有区域字段:由仍持有登录上下文的
+ * 调用方提供迁移区域,避免把历史状态错误归到安装包区域。
+ */
+async function readPushRealms(
+ key: string,
+ legacyRealm: ClientEndpointRegion = BUILD_AUTH_REGION,
+): Promise<Set<ClientEndpointRegion>> {
+ try {
+ const raw = await AsyncStorage.getItem(key);
+ if (!raw || raw === '0') return new Set();
+ if (raw === '1') return new Set([legacyRealm]);
+ const parsed: unknown = JSON.parse(raw);
+ if (
+ typeof parsed !== 'object' ||
+ parsed === null ||
+ (parsed as { version?: unknown }).version !== PUSH_REALM_STATE_VERSION ||
+ !Array.isArray((parsed as { realms?: unknown }).realms)
+ ) {
+ return new Set();
+ }
+ return new Set(
+ (parsed as PushRealmState).realms.filter(isClientEndpointRegion),
+ );
+ } catch {
+ return new Set();
+ }
+}
+
+async function writePushRealms(
+ key: string,
+ realms: ReadonlySet<ClientEndpointRegion>,
+): Promise<void> {
+ if (realms.size === 0) {
+ await AsyncStorage.removeItem(key);
+ return;
+ }
+ const state: PushRealmState = {
+ version: PUSH_REALM_STATE_VERSION,
+ realms: (['cn', 'global'] as const).filter((realm) => realms.has(realm)),
+ };
+ await AsyncStorage.setItem(key, JSON.stringify(state));
+}
+
+async function addPushRealm(
+ key: string,
+ realm: ClientEndpointRegion,
+ legacyRealm: ClientEndpointRegion = realm,
+): Promise<void> {
+ const realms = await readPushRealms(key, legacyRealm);
+ realms.add(realm);
+ await writePushRealms(key, realms);
+}
+
+async function removePushRealm(
+ key: string,
+ realm: ClientEndpointRegion,
+ legacyRealm: ClientEndpointRegion = realm,
+): Promise<void> {
+ const realms = await readPushRealms(key, legacyRealm);
+ realms.delete(realm);
+ await writePushRealms(key, realms);
+}
+
+function normalizeDeviceToken(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const token = value.trim();
+ if (token.length === 0 || token.length > PUSH_DEVICE_TOKEN_MAX_LENGTH) {
+ return null;
+ }
+ return token;
+}
+
+async function getNativeDeviceTokenBestEffort(): Promise<string | null> {
+ try {
+ const deviceToken = await Notifications.getDevicePushTokenAsync();
+ return normalizeDeviceToken(deviceToken.data);
+ } catch {
+ return null;
+ }
+}
+
+function deviceLinkBaseForRealm(realm: ClientEndpointRegion): string {
+ return getMobileEndpointForRealm(realm, 'deviceLinkApiBaseUrl');
+}
+
+function pushDeleteBody(token: string | null): { token: string } | undefined {
+ return token ? { token } : undefined;
+}
+
+/**
+ * 清理登录态时不能走 apiFetch:401 terminal handler 可能正在等待当前清理,
+ * 形成自等待。调用方必须在切换 realm / 清空旧 access token 前进入此函数。
+ */
+async function deletePushTokenWithAccessToken(
+ realm: ClientEndpointRegion,
+ accessToken: string,
+): Promise<void> {
+ await loadMobileEndpointsForRealm(realm);
+ const deviceToken = await getNativeDeviceTokenBestEffort();
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () => controller.abort(),
+ PUSH_UNREGISTER_TIMEOUT_MS,
+ );
+ try {
+ const response = await fetch(
+ deviceLinkBaseForRealm(realm) + PUSH_TOKEN_PATH,
+ {
+ method: 'DELETE',
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ ...(deviceToken ? { 'content-type': 'application/json' } : {}),
+ },
+ ...(deviceToken
+ ? { body: JSON.stringify({ token: deviceToken }) }
+ : {}),
+ signal: controller.signal,
+ },
+ );
+ if (!response.ok) {
+ throw new Error(`unregister failed: ${response.status}`);
+ }
+ } finally {
+ clearTimeout(timer);
+ }
+}
export function isPushSupported(): boolean {
return Platform.OS === 'ios';
@@ -72,33 +235,54 @@ export type AuthedApiFetch = <T>(
) => Promise<T>;
/**
- * 把本机开关状态同步到 server 注册表。开 → 请求权限 + 拿 APNs token + PUT;
- * 关 → 曾注册过才 DELETE。调用方决定时机(开关翻转 / 登录后启动 / token 轮换)。
+ * 把本机开关状态同步到当前会话区域的 server 注册表。开 → 请求权限 + 拿 APNs
+ * token + PUT;关 → 曾在当前区域注册过才 DELETE。
*/
-export async function syncPushRegistration(opts: {
- enabled: boolean;
- apiFetch: AuthedApiFetch;
-}): Promise<PushSyncResult> {
+async function syncPushRegistrationInternal(
+ opts: {
+ enabled: boolean;
+ apiFetch: AuthedApiFetch;
+ },
+ lifecycleGeneration: number,
+): Promise<PushSyncResult> {
if (!isPushSupported()) return 'unsupported';
+ if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
+ const realm = getActiveMobileSessionRealm();
+ const baseUrl = deviceLinkBaseForRealm(realm);
if (!opts.enabled) {
- const wasRegistered = (await AsyncStorage.getItem(PUSH_REGISTERED_KEY)) === '1';
- if (!wasRegistered) return 'skipped';
- await opts.apiFetch(PUSH_TOKEN_PATH, {
- baseUrl: DEVICE_LINK_API_BASE_URL,
- method: 'DELETE',
- });
- await AsyncStorage.setItem(PUSH_REGISTERED_KEY, '0');
+ const registeredRealms = await readPushRealms(PUSH_REGISTERED_KEY, realm);
+ if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
+ if (!registeredRealms.has(realm)) return 'skipped';
+ const token = await getNativeDeviceTokenBestEffort();
+ if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
+ try {
+ await opts.apiFetch(PUSH_TOKEN_PATH, {
+ baseUrl,
+ method: 'DELETE',
+ ...(token ? { body: pushDeleteBody(token) } : {}),
+ });
+ } catch (error) {
+ await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm).catch(
+ () => undefined,
+ );
+ throw error;
+ }
+ await removePushRealm(PUSH_REGISTERED_KEY, realm);
+ await removePushRealm(PUSH_PENDING_UNREGISTER_KEY, realm);
return 'unregistered';
}
let permission = await Notifications.getPermissionsAsync();
+ if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
if (permission.status !== 'granted' && permission.canAskAgain) {
permission = await Notifications.requestPermissionsAsync();
+ if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
}
if (permission.status !== 'granted') return 'permission-denied';
const deviceToken = await Notifications.getDevicePushTokenAsync();
+ if (lifecycleGeneration !== pushLifecycleGeneration) return 'skipped';
const body = buildPushTokenRegistrationBody({
token: typeof deviceToken.data === 'string' ? deviceToken.data : '',
region: AUTH_REGION,
@@ -106,73 +290,114 @@ export async function syncPushRegistration(opts: {
});
if (!body) return 'skipped';
- await opts.apiFetch(PUSH_TOKEN_PATH, {
- baseUrl: DEVICE_LINK_API_BASE_URL,
- method: 'PUT',
- body,
- });
- await AsyncStorage.setItem(PUSH_REGISTERED_KEY, '1');
+ // PUT 响应丢失时无法判断服务端是否提交,发出前即标记“可能已注册”;
+ // 后续只能在该区域持有有效会话时做幂等 DELETE。
+ await addPushRealm(PUSH_REGISTERED_KEY, realm);
+ if (lifecycleGeneration !== pushLifecycleGeneration) {
+ await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm);
+ return 'skipped';
+ }
+ try {
+ await opts.apiFetch(PUSH_TOKEN_PATH, {
+ baseUrl,
+ method: 'PUT',
+ body,
+ });
+ } catch (error) {
+ if (lifecycleGeneration !== pushLifecycleGeneration) {
+ await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm).catch(
+ () => undefined,
+ );
+ }
+ throw error;
+ }
+ if (lifecycleGeneration !== pushLifecycleGeneration) {
+ await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm);
+ return 'skipped';
+ }
+ await removePushRealm(PUSH_PENDING_UNREGISTER_KEY, realm);
return 'registered';
}
+export function syncPushRegistration(opts: {
+ enabled: boolean;
+ apiFetch: AuthedApiFetch;
+}): Promise<PushSyncResult> {
+ const lifecycleGeneration = pushLifecycleGeneration;
+ return runPushMutation(() =>
+ syncPushRegistrationInternal(opts, lifecycleGeneration),
+ );
+}
+
/**
- * 登出/终止前的 best-effort 注销。**不走 apiFetchRaw**:清理流程中若响应
- * 401 ACCOUNT_UNAVAILABLE,apiFetchRaw 会 await 全局 terminal handler →
- * terminateSession 单飞返回「正在等待本函数」的同一个 promise → 死锁。
- * 这里用裸 fetch,任何失败(含 401)都只落补偿标记。
+ * 登出、终止或换账号/区域前的 best-effort 注销。realm 与 access token 都在
+ * 调用开始时冻结,因此后续端点切换不会把旧 token 发到新区域。
*/
-export async function unregisterPushTokenBestEffort(accessToken: string | null): Promise<void> {
+async function unregisterPushTokenBestEffortInternal(
+ realm: ClientEndpointRegion,
+ accessToken: string | null,
+): Promise<void> {
if (!isPushSupported()) return;
try {
- if ((await AsyncStorage.getItem(PUSH_REGISTERED_KEY)) !== '1') return;
- if (!accessToken) {
- // 已注册却拿不到 token(终止路径的竞态):留待补偿标记
- await AsyncStorage.setItem(PUSH_PENDING_UNREGISTER_KEY, '1');
- return;
- }
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), 3_000);
- try {
- const res = await fetch(DEVICE_LINK_API_BASE_URL + PUSH_TOKEN_PATH, {
- method: 'DELETE',
- headers: { Authorization: `Bearer ${accessToken}` },
- signal: controller.signal,
- });
- if (!res.ok) throw new Error(`unregister failed: ${res.status}`);
- } finally {
- clearTimeout(timer);
- }
- await AsyncStorage.setItem(PUSH_REGISTERED_KEY, '0');
- await AsyncStorage.removeItem(PUSH_PENDING_UNREGISTER_KEY);
+ const registeredRealms = await readPushRealms(PUSH_REGISTERED_KEY, realm);
+ if (!registeredRealms.has(realm)) return;
+
+ await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm);
+ if (!accessToken) return;
+
+ await deletePushTokenWithAccessToken(realm, accessToken);
+ await removePushRealm(PUSH_REGISTERED_KEY, realm);
+ await removePushRealm(PUSH_PENDING_UNREGISTER_KEY, realm);
} catch {
- // 注销失败(离线/超时/服务端错):登出流程不能被卡住,但留标记,
- // 下次登录后由 retryPendingUnregister 补偿;server 侧 DELETE 按物理设备清理
- // (跨账号),换账号登录补偿同样能清掉旧账号残留行。
- await AsyncStorage.setItem(PUSH_PENDING_UNREGISTER_KEY, '1').catch(() => undefined);
+ // 离线/超时/旧 token 失效不能阻断退出或切换。标记只在以后登录同一区域时
+ // 重试,绝不引入服务端互信或客户端跨区 token 发送。
+ await addPushRealm(PUSH_PENDING_UNREGISTER_KEY, realm).catch(
+ () => undefined,
+ );
}
}
-/** 用户关闭开关但注销请求失败时排队补偿(opt-out 先落盘,注销之后补)。 */
-export async function markPendingUnregister(): Promise<void> {
- await AsyncStorage.setItem(PUSH_PENDING_UNREGISTER_KEY, '1');
+export function unregisterPushTokenBestEffort(
+ accessToken: string | null,
+ realm: ClientEndpointRegion = getActiveMobileSessionRealm(),
+): Promise<void> {
+ pushLifecycleGeneration += 1;
+ // 不进入 pushMutationTail:当前 tail 可能正在 apiFetch → terminal handler →
+ // clearLocalSession → 本函数。等待 tail 会形成自等待死锁。
+ return unregisterPushTokenBestEffortInternal(realm, accessToken);
}
/**
- * 补偿上次登出/终止时失败的注销(登录态就绪后调用)。
- * 同账号重登:补一发 DELETE(随后若开关开启会重新注册,语义各自独立);
- * 换账号:DELETE 只动本设备行,旧账号残留由 server 侧同 token 让位逻辑处理。
+ * 只补偿“当前会话区域”的注销。历史上另一区域的标记保持不动,直到用户再次
+ * 登录该区域;当前 token 永远不会被发送给 peer endpoint。
*/
-export async function retryPendingUnregister(apiFetch: AuthedApiFetch): Promise<void> {
+async function retryPendingUnregisterInternal(
+ apiFetch: AuthedApiFetch,
+): Promise<void> {
if (!isPushSupported()) return;
+ const realm = getActiveMobileSessionRealm();
+ const pendingRealms = await readPushRealms(
+ PUSH_PENDING_UNREGISTER_KEY,
+ realm,
+ );
+ if (!pendingRealms.has(realm)) return;
+
try {
- if ((await AsyncStorage.getItem(PUSH_PENDING_UNREGISTER_KEY)) !== '1') return;
+ const token = await getNativeDeviceTokenBestEffort();
await apiFetch(PUSH_TOKEN_PATH, {
- baseUrl: DEVICE_LINK_API_BASE_URL,
+ baseUrl: deviceLinkBaseForRealm(realm),
method: 'DELETE',
+ ...(token ? { body: pushDeleteBody(token) } : {}),
});
- await AsyncStorage.removeItem(PUSH_PENDING_UNREGISTER_KEY);
- await AsyncStorage.setItem(PUSH_REGISTERED_KEY, '0');
+ await removePushRealm(PUSH_PENDING_UNREGISTER_KEY, realm);
+ await removePushRealm(PUSH_REGISTERED_KEY, realm);
} catch {
- // 仍失败:标记保留,下次启动继续补偿
+ // 仍失败:保留当前区域标记,下次同区登录继续补偿。
}
}
+
+export function retryPendingUnregister(
+ apiFetch: AuthedApiFetch,
+): Promise<void> {
+ return runPushMutation(() => retryPendingUnregisterInternal(apiFetch));
+}
diff --git a/apps/mobile/vitest.config.ts b/apps/mobile/vitest.config.ts
index 3474568735..1da1cf3fd5 100644
--- a/apps/mobile/vitest.config.ts
+++ b/apps/mobile/vitest.config.ts
@@ -46,6 +46,10 @@ export default defineConfig({
env: {
EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL: 'https://relay.example.invalid',
EXPO_PUBLIC_XDT_MOBILE_VOICE_LITELLM_BASE_URL: 'https://gateway.example.invalid',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL:
+ 'https://manifest.cn.example.invalid/app',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL:
+ 'https://manifest.global.example.invalid/app',
},
},
});
diff --git a/docs/README.md b/docs/README.md
index 74e2b6c3e9..0506f48086 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -31,6 +31,7 @@
| [development-workflow.md](./dev-rules/development-workflow.md) | 开发工作流 | authoritative | worktree dogfooding 契约、提 PR/直推 main 门禁、Review P0/P1/P2 口径 | — |
| [plugin-setup-runtime.md](./plugin-setup-runtime.md) | 技术设计 | 参考 | `ghost_list` / `ghost_call` 插件配置前置检查、Ask-shell Setup 卡片、配置变更回调与原调用恢复 | — |
| [desktop-login-hosted-callback.md](./desktop-login-hosted-callback.md) | 跨仓契约 | 参考 | Desktop 系统浏览器登录的托管回调链路:auth-server 路由契约、结果页模板交付、灰度开关与回滚 | — |
+| [auth-realm-routing.md](./auth-realm-routing.md) | 跨仓契约 | 参考 | 组织 SSO 双区域发现、会话区域持久化与 token 消费端点路由 | — |
| [legal/README.md](./legal/README.md) | 法律/合规索引 | authoritative | 法律合规资料归档边界与固定路径例外 | — |
| [legal/wechat-open-sdk-compliance.md](./legal/wechat-open-sdk-compliance.md) | 合规记录 | restricted-review-required | Mobile 微信 Open SDK 版本、隐私披露和发布前签核 | — |
| [legal/notices/README.md](./legal/notices/README.md) | 第三方许可/SBOM | generated | `pnpm licenses:generate`、Desktop/Mobile 随包声明 | — |
diff --git a/docs/auth-realm-routing.md b/docs/auth-realm-routing.md
new file mode 100644
index 0000000000..955db10ee5
--- /dev/null
+++ b/docs/auth-realm-routing.md
@@ -0,0 +1,93 @@
+# 组织登录区域路由
+
+Cindy 的中国大陆版与国际版仍是两个独立的安装包和更新通道。组织 SSO 登录可以在
+用户提交企业标识后自动发现组织所在的 auth 区域,并让本次登录会话使用该区域的完整
+服务端点。
+
+## 两类区域状态
+
+- `buildRegion`:由安装包决定,控制 App ID、URL scheme、品牌、法律链接、网站、
+ CDN 与更新通道;运行期不可切换。
+- `sessionRealm`:`cn | global`,控制 auth、device-link、oauth-broker、OSS、
+ heartbeat、model-access、voice、GitHub、SkillHub、plugin 与 hook 等所有使用
+ 登录令牌的服务;组织登录成功后一直保留到登出。
+
+两者可以不同。例如,中国大陆安装包可以登录位于 `global` 的组织;它的更新仍来自
+中国大陆安装包通道,但组织数据与带 Bearer token 的业务请求全部走 `global`。
+
+## 端点清单契约
+
+区域身份不由远端清单自报,而由构建时注入的受信任地址表决定:
+
+- `*.cindy.com.cn` 对应中国大陆区域;
+- `*.cindy.app` 对应国际区域。
+
+构建脚本分别读取 `config/endpoint.json` 与 `config/endpoint.global.json` 的
+`cdnBaseUrl`,把当前区域和对端区域的两个清单基址烘焙进客户端。远端
+`endpoint.json` 继续使用原有 `schemaVersion: 1` 与业务端点字段,不要求
+`region`、`crossRealmOrgLoginEnabled` 或 `realmManifestBaseUrls`。
+
+客户端从某个受信任地址加载到清单后,就把它归入该地址对应的区域,并使用其中的
+`authApiBaseUrl` 调用该区 auth-server。discovery 响应仍必须包含 `region`,且必须与
+请求的区域一致;这可以防止 CDN 或 auth-server 配错后把组织路由到错误数据面。
+
+## 发现与失败规则
+
+用户提交企业 ID、组织 slug 或已验证域名后,客户端直接并行加载两区清单,分别取出
+各自的 `authApiBaseUrl`,再并行调用两区 `POST /api/auth/sso/discovery`。服务端响应
+包含自报的 `region`。
+
+- 一区成功、另一区明确返回 `ORG_SSO_NOT_FOUND`:选择成功区域。
+- 两区都成功:`ORG_REALM_AMBIGUOUS`,不自动猜测。
+- 两区都明确未找到:保留 `ORG_SSO_NOT_FOUND`。
+- 任一区超时、不可达、响应非法或区域不匹配:`ORG_REALM_UNAVAILABLE`;即使另一区
+ 成功也 fail closed。
+
+发现结果与 `buildRegion` 相同时直接进入连接选择,不显示额外确认。发现结果与
+`buildRegion` 不同时,客户端显示目标区域,并说明继续后 Cindy 将连接该区域;用户
+确认后才进入连接选择并继续 SSO,取消或 reset 会丢弃临时区域。安装包及更新通道仍由
+`buildRegion` 固定,无需在确认文案中重复说明。选中的临时区域用于本次 SSO
+authorize、callback、授权码兑换、联系方式验证与身份选择。
+
+## 会话持久化与恢复
+
+Desktop safeStorage 和 Mobile SecureStore 都只保存一个加密的原子记录:
+
+```json
+{ "version": 1, "realm": "global", "refreshToken": "…" }
+```
+
+旧版裸 refresh token 只在一次性迁移时按 `buildRegion` 解释。冷启动先加载并核验记录中
+区域的端点清单,再向该区域 refresh;对端清单暂不可用时保留记录供重试,禁止退回
+`buildRegion` 发送 token。登出会清除记录和 `sessionRealm`,业务端点恢复安装包区域。
+
+Mobile 的 Pending OAuth 同时保存 `realm`,但 redirect scheme 始终使用当前安装包的
+scheme。个人验证码和社交登录不做跨区域发现,也不合并两区 passport。
+
+## Mobile 推送撤销
+
+Mobile 按 `sessionRealm` 分别保存推送注册与待注销状态。登出、换账号或换区域时,
+客户端会在替换 Access Token 和业务端点之前,用旧 Token 向旧区域现有的鉴权接口
+`DELETE /api/device-link/push-token` 发起 best-effort 撤销;请求同时携带本机 APNs token,
+便于同一区域内清理同一安装留下的旧账号记录。
+
+撤销失败不能阻断退出或登录。待注销标记仍绑定原区域,并且只会在客户端以后重新持有
+该区域登录态时重试;CN Token 不会发送到 Global 端点,Global Token 也不会发送到 CN
+端点。两区 device-link-server 不互相信任、不互查数据,也不需要新增跨区鉴权端点、
+数据库字段、密钥或环境变量。
+
+## 上线与回滚
+
+按以下顺序发布:
+
+1. 先升级中国大陆和国际 `auth-server`,确保 discovery 响应都包含正确的 `region`。
+2. 确认两区 `endpoint.json` 均可公网访问,且各自 `authApiBaseUrl` 指向同区域的
+ auth-server。
+3. 发布包含双区域可信清单地址的 Desktop 与 Mobile 客户端;device-link-server 无需
+ 为区域路由增加部署步骤。
+4. 用同区组织和跨区组织各验证一次发现、确认、登录、冷启动恢复与登出;Mobile 还需
+ 验证换账号或区域时,旧区域在新会话提交前收到推送撤销请求。
+
+需要紧急回滚新的组织发现能力时,应通过客户端版本回滚或客户端级开关处理,不能删除
+任一区域清单;已建立的跨区会话仍需要按保存的 `sessionRealm` 加载原区域端点并刷新
+token。
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 59526e5ce7..8fdc64e55a 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -124,6 +124,14 @@
**注意别指望 `--update-baseline` 帮你收尾。** `proposed` 存在的理由正是「已知有存量不一致」,改成 `decided` 的那一刻这些告警会变成阻断违规;而 `--update-baseline` 只删不加,遇到 baseline 里没有的指纹会直接拒绝。所以裁决时只有两条路:要么把命中逐条读语境改掉,要么先人工把已 review 过的指纹写进 `i18n/glossary-baseline.json` 冻结存量,之后再用 `--update-baseline` 做修剪。
+### Global region
+
+企业认证与业务服务所在区域的用户可见名称,用于组织登录检测到 Global 服务区域时的确认文案;它描述连接的服务区域,不是对当前安装版本的标签,也不同于项目配置里的 generic global scope。先按现有四语文案登记为 proposed。
+
+### Mainland China
+
+企业认证与业务服务所在区域的用户可见名称,用于组织登录检测到中国大陆服务区域时的确认文案;它描述连接的服务区域,不代表当前安装的是中国大陆版。先按现有四语文案登记为 proposed,避免后续出现“中国区/国内区/China region”等多套说法。
+
### Cindy Codex home
远端主机上由 Cindy 管理的 Codex 凭证目录(~/.xdt-server/v1/codex-home/),与用户本机 ~/.codex 相区分。四语统一保留英文原词(home 小写),避免各语言自造「Codex 主目录」等不同说法;syncAuth 与 codexAuthMissing 等远端登录态文案使用。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index 1c1f41239b..4a49c4c938 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -65,6 +65,28 @@
},
"note": "桌面登录页标题旁的品牌红胶囊(DESIGN.md §16.3),指徽标这个 UI 元素本身。徽标上的标签值另立条目(region-code-cn / region-code-dev)——本条 en 为 Region badge、各语言译文均非英文原词,caseStandardFor 天然返回 null,所以本条约束不到标签值,也无需写 checkCase。作为待产品裁决术语登记:尚未拍板是否改为可译文案(如「中国大陆版 / Mainland China」),先登记以免后续界面自造“国内版/中国版/开发版”等多套说法。"
},
+ {
+ "id": "auth-region-mainland-china",
+ "status": "proposed",
+ "en": "Mainland China",
+ "translations": {
+ "zh-CN": "中国大陆区",
+ "ja": "中国本土リージョン",
+ "ko": "중국 본토 지역"
+ },
+ "note": "企业认证与业务服务所在区域的用户可见名称,用于组织登录检测到中国大陆服务区域时的确认文案;它描述连接的服务区域,不代表当前安装的是中国大陆版。先按现有四语文案登记为 proposed,避免后续出现“中国区/国内区/China region”等多套说法。"
+ },
+ {
+ "id": "auth-region-global",
+ "status": "proposed",
+ "en": "Global region",
+ "translations": {
+ "zh-CN": "国际区",
+ "ja": "グローバルリージョン",
+ "ko": "글로벌 지역"
+ },
+ "note": "企业认证与业务服务所在区域的用户可见名称,用于组织登录检测到 Global 服务区域时的确认文案;它描述连接的服务区域,不是对当前安装版本的标签,也不同于项目配置里的 generic global scope。先按现有四语文案登记为 proposed。"
+ },
{
"id": "region-code-cn",
"status": "proposed",
diff --git a/packages/auth-client/fixtures/loginScenarios.ts b/packages/auth-client/fixtures/loginScenarios.ts
index b43f28c58f..4efd4e2932 100644
--- a/packages/auth-client/fixtures/loginScenarios.ts
+++ b/packages/auth-client/fixtures/loginScenarios.ts
@@ -258,12 +258,15 @@ function discoveryFor(scenario: ParsedLoginScenario): unknown {
return { methods: [{ type: "email_code" }] };
}
-function ssoOrgDiscoveryFor(scenario: ParsedLoginScenario): unknown {
+function ssoOrgDiscoveryFor(
+ scenario: ParsedLoginScenario,
+ region: AuthRegion,
+): unknown {
const connections =
scenario.kind === "sso" && scenario.variant === "multi"
? [SSO_CONNECTION_A, SSO_CONNECTION_B]
: [SSO_CONNECTION_A];
- return { orgName: SSO_ORG_NAME, connections };
+ return { region, orgName: SSO_ORG_NAME, connections };
}
/** verify-code / callback exchange 的 outcome(附录 A outcome:* 场景)。 */
@@ -317,7 +320,7 @@ export function createScenarioFetch(
case "discover":
return jsonResponse(200, discoveryFor(scenario));
case "sso-discovery":
- return jsonResponse(200, ssoOrgDiscoveryFor(scenario));
+ return jsonResponse(200, ssoOrgDiscoveryFor(scenario, region));
case "request-code":
case "request-binding-code":
return jsonResponse(200, { status: "sent" });
diff --git a/packages/auth-client/src/__tests__/client.test.ts b/packages/auth-client/src/__tests__/client.test.ts
index 9620f8c6e8..304006c0d9 100644
--- a/packages/auth-client/src/__tests__/client.test.ts
+++ b/packages/auth-client/src/__tests__/client.test.ts
@@ -1,9 +1,15 @@
import { describe, expect, it, vi } from "vitest";
import {
+ AuthApiError,
CindyAuthClient,
+ discoverSsoOrgRealm,
+ parseAccountDeletionReceiptRecord,
+ parseAuthSessionRecord,
reduceAuthFlow,
+ serializeAccountDeletionReceiptRecord,
ssoOrgDiscoveryToMethods,
+ serializeAuthSessionRecord,
type AuthFetch,
type AuthFetchResponse,
} from "../index.js";
@@ -178,7 +184,8 @@ describe("CindyAuthClient", () => {
await expect(
auth.getAccountDeletionAvailability("access-token"),
).resolves.toMatchObject({ available: true });
- const challenge = await auth.requestAccountDeletionChallenge("access-token");
+ const challenge =
+ await auth.requestAccountDeletionChallenge("access-token");
await expect(
auth.confirmAccountDeletion("access-token", {
challengeId: challenge.challengeId,
@@ -271,6 +278,7 @@ describe("CindyAuthClient", () => {
it("discovers enterprise SSO connections by org id and maps to login methods", async () => {
const fetch = vi.fn(async () =>
response(200, {
+ region: "cn",
orgName: "Disco Corp",
connections: [
{ connectionId: "conn-1", protocol: "saml", connectionName: "Okta" },
@@ -296,13 +304,45 @@ describe("CindyAuthClient", () => {
it("maps an empty SSO connection list to the precise ORG_SSO_NOT_FOUND error", async () => {
const fetch = vi.fn(async () =>
- response(200, { orgName: "Empty Corp", connections: [] }),
+ response(200, { region: "cn", orgName: "Empty Corp", connections: [] }),
);
await expect(
client(fetch).discoverSsoOrg("empty-corp"),
).rejects.toMatchObject({ code: "ORG_SSO_NOT_FOUND" });
});
+ it("fails closed when SSO discovery responds from the wrong region", async () => {
+ const fetch = vi.fn(async () =>
+ response(200, {
+ region: "global",
+ orgName: "Disco Corp",
+ connections: [
+ { connectionId: "conn-1", protocol: "saml", connectionName: "Okta" },
+ ],
+ }),
+ );
+ await expect(
+ client(fetch).discoverSsoOrg("disco-corp"),
+ ).rejects.toMatchObject({
+ code: "REGION_MISMATCH",
+ });
+ });
+
+ it("checks the response region before treating an empty connection list as not found", async () => {
+ const fetch = vi.fn(async () =>
+ response(200, {
+ region: "global",
+ orgName: "Misrouted Corp",
+ connections: [],
+ }),
+ );
+ await expect(
+ client(fetch).discoverSsoOrg("misrouted-corp"),
+ ).rejects.toMatchObject({
+ code: "REGION_MISMATCH",
+ });
+ });
+
it("builds PKCE authorize URLs for social and SSO", () => {
const auth = client();
const url = new URL(
@@ -320,7 +360,159 @@ describe("CindyAuthClient", () => {
});
});
+describe("discoverSsoOrgRealm", () => {
+ const discovery = (region: "cn" | "global") => ({
+ region,
+ orgName: `${region} Corp`,
+ connections: [
+ {
+ connectionId: `${region}-1`,
+ protocol: "oidc" as const,
+ connectionName: "SSO",
+ },
+ ],
+ });
+ const found = (region: "cn" | "global") => ({
+ discoverSsoOrg: vi.fn(async () => discovery(region)),
+ });
+ const notFound = () => ({
+ discoverSsoOrg: vi.fn(async () => {
+ throw new AuthApiError("ORG_SSO_NOT_FOUND", 404, "not found");
+ }),
+ });
+ const unavailable = () => ({
+ discoverSsoOrg: vi.fn(async () => {
+ throw new AuthApiError("NETWORK_ERROR", 0, "offline");
+ }),
+ });
+
+ it.each([
+ ["cn", found("cn"), notFound()],
+ ["global", notFound(), found("global")],
+ ] as const)(
+ "selects %s only when the peer explicitly reports not found",
+ async (region, cn, global) => {
+ await expect(
+ discoverSsoOrgRealm("corp", { cn, global }),
+ ).resolves.toMatchObject({
+ region,
+ discovery: { region },
+ });
+ },
+ );
+
+ it("rejects an identifier present in both regions as ambiguous", async () => {
+ await expect(
+ discoverSsoOrgRealm("corp", { cn: found("cn"), global: found("global") }),
+ ).rejects.toMatchObject({ code: "ORG_REALM_AMBIGUOUS" });
+ });
+
+ it("preserves not-found only when both regions explicitly report it", async () => {
+ await expect(
+ discoverSsoOrgRealm("corp", { cn: notFound(), global: notFound() }),
+ ).rejects.toMatchObject({ code: "ORG_SSO_NOT_FOUND" });
+ });
+
+ it("fails closed when either region is unavailable, even if the other succeeds", async () => {
+ await expect(
+ discoverSsoOrgRealm("corp", { cn: found("cn"), global: unavailable() }),
+ ).rejects.toMatchObject({ code: "ORG_REALM_UNAVAILABLE" });
+ });
+});
+
+describe("auth session realm record", () => {
+ it("round-trips realm and refresh token as one versioned record", () => {
+ const raw = serializeAuthSessionRecord("global", "refresh-secret");
+ expect(parseAuthSessionRecord(raw)).toEqual({
+ version: 1,
+ realm: "global",
+ refreshToken: "refresh-secret",
+ });
+ });
+
+ it.each([
+ null,
+ "not-json",
+ JSON.stringify({ version: 2, realm: "cn", refreshToken: "token" }),
+ JSON.stringify({ version: 1, realm: "us", refreshToken: "token" }),
+ JSON.stringify({ version: 1, realm: "cn", refreshToken: "" }),
+ ])("rejects malformed records without throwing", (raw) => {
+ expect(parseAuthSessionRecord(raw)).toBeNull();
+ });
+
+ it("keeps an account-deletion receipt bound to its realm after logout", () => {
+ const raw = serializeAccountDeletionReceiptRecord(
+ "global",
+ "receipt-secret",
+ "passport-1",
+ );
+ expect(parseAccountDeletionReceiptRecord(raw)).toEqual({
+ version: 2,
+ realm: "global",
+ receiptToken: "receipt-secret",
+ authIdentity: "passport-1",
+ });
+ expect(
+ parseAccountDeletionReceiptRecord(
+ serializeAccountDeletionReceiptRecord("cn", "legacy-receipt"),
+ ),
+ ).toEqual({
+ version: 1,
+ realm: "cn",
+ receiptToken: "legacy-receipt",
+ });
+ expect(parseAccountDeletionReceiptRecord("legacy-receipt")).toBeNull();
+ });
+});
+
describe("reduceAuthFlow", () => {
+ it("keeps a cross-region discovery pending until the user confirms", () => {
+ const providers = {
+ region: "global" as const,
+ attribution: "email" as const,
+ email: true,
+ phone: false,
+ social: [],
+ };
+ const methods = [
+ {
+ type: "sso" as const,
+ connectionId: "cn-sso",
+ protocol: "oidc" as const,
+ orgName: "CN Corp",
+ connectionName: "Enterprise SSO",
+ ssoRequired: false,
+ },
+ ];
+ const confirmation = reduceAuthFlow(null, {
+ type: "realm-switch-required",
+ targetRegion: "cn",
+ providers,
+ methods,
+ });
+ expect(confirmation).toEqual({
+ step: "realm-confirmation",
+ targetRegion: "cn",
+ providers,
+ methods,
+ });
+ if (confirmation.step !== "realm-confirmation") {
+ throw new Error("expected realm confirmation");
+ }
+
+ expect(
+ reduceAuthFlow(confirmation, {
+ type: "discovery-loaded",
+ email: "",
+ methods: confirmation.methods,
+ }),
+ ).toEqual({
+ step: "method-choice",
+ email: "",
+ methods,
+ });
+ });
+
it("projects secret-bearing outcomes into public states", () => {
const state = reduceAuthFlow(null, {
type: "outcome",
diff --git a/packages/auth-client/src/client.ts b/packages/auth-client/src/client.ts
index 5fe0f2c9e1..7307bac35a 100644
--- a/packages/auth-client/src/client.ts
+++ b/packages/auth-client/src/client.ts
@@ -127,9 +127,17 @@ export class CindyAuthClient {
ssoOrgDiscoverySchema,
{ org },
);
+ if (discovery.region !== this.options.region) {
+ throw new AuthApiError(
+ "REGION_MISMATCH",
+ 0,
+ `Queried ${this.options.region} auth deployment returned ${discovery.region}`,
+ );
+ }
// 企业存在但未启用任何 SSO 连接(服务端可能以 200 + connections:[] 表达):
// 映射成精确的 ORG_SSO_NOT_FOUND(其文案已覆盖「未启用 SSO」语义),
// 避免落到 INVALID_RESPONSE 的通用错误,也拦住空 methods 进入 method-choice。
+ // 必须在 region 核对之后判断,不能把错误部署返回的空列表伪装成明确未找到。
if (discovery.connections.length === 0) {
throw new AuthApiError(
"ORG_SSO_NOT_FOUND",
diff --git a/packages/auth-client/src/index.ts b/packages/auth-client/src/index.ts
index 94521a4db9..74fdf5caff 100644
--- a/packages/auth-client/src/index.ts
+++ b/packages/auth-client/src/index.ts
@@ -1,10 +1,28 @@
export { AuthApiError, CindyAuthClient } from "./client.js";
+export { discoverSsoOrgRealm } from "./orgRealmDiscovery.js";
+export {
+ accountDeletionReceiptRecordSchema,
+ authSessionRecordSchema,
+ parseAccountDeletionReceiptRecord,
+ parseAuthSessionRecord,
+ serializeAccountDeletionReceiptRecord,
+ serializeAuthSessionRecord,
+} from "./sessionRealm.js";
export { isValidEmail } from "./email.js";
export type {
AuthClientOptions,
AuthFetch,
AuthFetchResponse,
} from "./client.js";
+export type {
+ SsoOrgDiscoveryClient,
+ SsoOrgRealmClients,
+ SsoOrgRealmDiscovery,
+} from "./orgRealmDiscovery.js";
+export type {
+ AccountDeletionReceiptRecord,
+ AuthSessionRecord,
+} from "./sessionRealm.js";
export {
accountDeletionAvailabilitySchema,
accountDeletionChallengeSchema,
diff --git a/packages/auth-client/src/orgRealmDiscovery.ts b/packages/auth-client/src/orgRealmDiscovery.ts
new file mode 100644
index 0000000000..0163a59eeb
--- /dev/null
+++ b/packages/auth-client/src/orgRealmDiscovery.ts
@@ -0,0 +1,73 @@
+import { AuthApiError } from "./client.js";
+import type { AuthRegion, SsoOrgDiscovery } from "./types.js";
+
+export interface SsoOrgDiscoveryClient {
+ discoverSsoOrg(org: string): Promise<SsoOrgDiscovery>;
+}
+
+export type SsoOrgRealmClients = Record<AuthRegion, SsoOrgDiscoveryClient>;
+
+export interface SsoOrgRealmDiscovery {
+ region: AuthRegion;
+ discovery: SsoOrgDiscovery;
+}
+
+function isNotFound(reason: unknown): boolean {
+ return reason instanceof AuthApiError && reason.code === "ORG_SSO_NOT_FOUND";
+}
+
+/**
+ * 同时探测国内与国际 auth-server,并以 fail-closed 规则选择企业所在区域。
+ *
+ * 只有「一侧成功、另一侧明确 ORG_SSO_NOT_FOUND」可以继续。任一侧网络失败、
+ * 超时、响应非法或 region 不匹配都不能拿另一侧的成功结果猜测,避免故障期间
+ * 把同名企业路由到错误数据面。
+ */
+export async function discoverSsoOrgRealm(
+ org: string,
+ clients: SsoOrgRealmClients,
+): Promise<SsoOrgRealmDiscovery> {
+ const [cn, global] = await Promise.allSettled([
+ clients.cn.discoverSsoOrg(org),
+ clients.global.discoverSsoOrg(org),
+ ]);
+
+ if (cn.status === "fulfilled" && global.status === "fulfilled") {
+ throw new AuthApiError(
+ "ORG_REALM_AMBIGUOUS",
+ 409,
+ "Enterprise identifier exists in both auth regions",
+ );
+ }
+ if (
+ cn.status === "fulfilled" &&
+ global.status === "rejected" &&
+ isNotFound(global.reason)
+ ) {
+ return { region: "cn", discovery: cn.value };
+ }
+ if (
+ global.status === "fulfilled" &&
+ cn.status === "rejected" &&
+ isNotFound(cn.reason)
+ ) {
+ return { region: "global", discovery: global.value };
+ }
+ if (
+ cn.status === "rejected" &&
+ global.status === "rejected" &&
+ isNotFound(cn.reason) &&
+ isNotFound(global.reason)
+ ) {
+ throw new AuthApiError(
+ "ORG_SSO_NOT_FOUND",
+ 404,
+ "Enterprise SSO configuration was not found in either auth region",
+ );
+ }
+ throw new AuthApiError(
+ "ORG_REALM_UNAVAILABLE",
+ 503,
+ "Unable to verify the enterprise auth region",
+ );
+}
diff --git a/packages/auth-client/src/sessionRealm.ts b/packages/auth-client/src/sessionRealm.ts
new file mode 100644
index 0000000000..f24a5964d6
--- /dev/null
+++ b/packages/auth-client/src/sessionRealm.ts
@@ -0,0 +1,105 @@
+import { z } from "zod";
+
+import { authRegionSchema, type AuthRegion } from "./types.js";
+
+export const authSessionRecordSchema = z.object({
+ version: z.literal(1),
+ realm: authRegionSchema,
+ refreshToken: z.string().min(1),
+});
+
+export interface AuthSessionRecord {
+ version: 1;
+ realm: AuthRegion;
+ refreshToken: string;
+}
+
+const accountDeletionReceiptRecordV1Schema = z.object({
+ version: z.literal(1),
+ realm: authRegionSchema,
+ receiptToken: z.string().min(1),
+});
+
+const accountDeletionReceiptRecordV2Schema = z.object({
+ version: z.literal(2),
+ realm: authRegionSchema,
+ receiptToken: z.string().min(1),
+ authIdentity: z.string().min(1),
+});
+
+export const accountDeletionReceiptRecordSchema = z.discriminatedUnion(
+ 'version',
+ [accountDeletionReceiptRecordV1Schema, accountDeletionReceiptRecordV2Schema],
+);
+
+export interface AccountDeletionReceiptRecordV1 {
+ version: 1;
+ realm: AuthRegion;
+ receiptToken: string;
+}
+
+export interface AccountDeletionReceiptRecordV2 {
+ version: 2;
+ realm: AuthRegion;
+ receiptToken: string;
+ /** Passport identity (membership fallback for legacy claims) that requested the challenge. */
+ authIdentity: string;
+}
+
+export type AccountDeletionReceiptRecord =
+ AccountDeletionReceiptRecordV1 | AccountDeletionReceiptRecordV2;
+
+/** Parse an encrypted-storage plaintext without throwing or logging credentials. */
+export function parseAuthSessionRecord(
+ raw: string | null,
+): AuthSessionRecord | null {
+ if (!raw) return null;
+ try {
+ const parsed = authSessionRecordSchema.safeParse(JSON.parse(raw));
+ return parsed.success ? parsed.data : null;
+ } catch {
+ return null;
+ }
+}
+
+export function serializeAuthSessionRecord(
+ realm: AuthRegion,
+ refreshToken: string,
+): string {
+ return JSON.stringify(
+ authSessionRecordSchema.parse({ version: 1, realm, refreshToken }),
+ );
+}
+
+/**
+ * Account-deletion receipts outlive the authenticated session, so their realm
+ * must travel with the credential after logout resets the active session realm.
+ */
+export function parseAccountDeletionReceiptRecord(
+ raw: string | null,
+): AccountDeletionReceiptRecord | null {
+ if (!raw) return null;
+ try {
+ const parsed = accountDeletionReceiptRecordSchema.safeParse(
+ JSON.parse(raw),
+ );
+ return parsed.success ? parsed.data : null;
+ } catch {
+ return null;
+ }
+}
+
+export function serializeAccountDeletionReceiptRecord(
+ realm: AuthRegion,
+ receiptToken: string,
+ authIdentity?: string,
+): string {
+ return JSON.stringify(
+ accountDeletionReceiptRecordSchema.parse({
+ version: authIdentity ? 2 : 1,
+ realm,
+ receiptToken,
+ ...(authIdentity ? { authIdentity } : {}),
+ }),
+ );
+}
diff --git a/packages/auth-client/src/types.ts b/packages/auth-client/src/types.ts
index f3eacfb742..d78b508aef 100644
--- a/packages/auth-client/src/types.ts
+++ b/packages/auth-client/src/types.ts
@@ -42,6 +42,7 @@ export const ssoOrgConnectionSchema = z.object({
export type SsoOrgConnection = z.infer<typeof ssoOrgConnectionSchema>;
export const ssoOrgDiscoverySchema = z.object({
+ region: authRegionSchema,
orgName: z.string(),
// 不设 min(1):服务端对「企业存在但未启用 SSO」可能返回 200 + connections:[]。
// 让空数组通过 schema 校验,由 CindyAuthClient.discoverSsoOrg 显式映射成精确的
@@ -214,6 +215,12 @@ export type SsoVerificationChannel = "email" | "sms";
export type AuthFlowState =
| { step: "identifier"; providers: ProviderConfig }
+ | {
+ step: "realm-confirmation";
+ targetRegion: AuthRegion;
+ providers: ProviderConfig;
+ methods: LoginMethod[];
+ }
| { step: "method-choice"; email: string; methods: LoginMethod[] }
| { step: "verification-code"; kind: VerificationKind; identifier: string }
| { step: "browser-redirect"; label: string }
@@ -239,6 +246,12 @@ export type AuthFlowState =
export type AuthFlowAction =
| { type: "providers-loaded"; providers: ProviderConfig }
+ | {
+ type: "realm-switch-required";
+ targetRegion: AuthRegion;
+ providers: ProviderConfig;
+ methods: LoginMethod[];
+ }
| { type: "discovery-loaded"; email: string; methods: LoginMethod[] }
| { type: "code-requested"; kind: VerificationKind; identifier: string }
| { type: "browser-started"; label: string }
@@ -267,6 +280,13 @@ export function reduceAuthFlow(
switch (action.type) {
case "providers-loaded":
return { step: "identifier", providers: action.providers };
+ case "realm-switch-required":
+ return {
+ step: "realm-confirmation",
+ targetRegion: action.targetRegion,
+ providers: action.providers,
+ methods: action.methods,
+ };
case "discovery-loaded":
return {
step: "method-choice",
diff --git a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts b/packages/maker-shared/src/__tests__/clientEndpoints.test.ts
index b49939f4e0..6492175349 100644
--- a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts
+++ b/packages/maker-shared/src/__tests__/clientEndpoints.test.ts
@@ -8,6 +8,7 @@ import {
const VALID_MANIFEST = {
schemaVersion: 1,
+ region: 'cn',
apiBaseUrl: 'https://api.example.com',
authApiBaseUrl: 'https://auth.example.com',
authDesktopCallbackUrl: 'https://auth.example.com/api/auth/desktop/callback',
@@ -36,9 +37,50 @@ describe('parseClientEndpointManifest(字段可按 region 缺省)', () => {
if (!result.ok) throw new Error('unreachable');
expect(result.endpoints.authApiBaseUrl).toBe('https://auth.example.com');
expect(result.endpoints.slackHookWsUrl).toBe('wss://slack-hook.example.com');
+ expect(result.region).toBe('cn');
expect(Object.keys(result.endpoints).sort()).toEqual([...CLIENT_ENDPOINT_KEYS].sort());
});
+ it('清单缺少 region 时保持兼容,由可信清单地址确定区域', () => {
+ const legacy: Record<string, unknown> = { ...VALID_MANIFEST };
+ delete legacy.region;
+ const result = parseClientEndpointManifest(JSON.stringify(legacy));
+ expect(result).toMatchObject({
+ ok: true,
+ region: null,
+ });
+ });
+
+ it.each([
+ [
+ '区域非法',
+ { region: 'us' },
+ undefined,
+ 'invalid-field:region',
+ ],
+ [
+ '期望区域不匹配',
+ { region: 'global' },
+ { expectedRegion: 'cn' as const },
+ 'region-mismatch:cn:global',
+ ],
+ ])('拒绝区域诊断元数据配置错误:%s', (_label, patch, options, reason) => {
+ expect(
+ parseClientEndpointManifest(JSON.stringify({ ...VALID_MANIFEST, ...patch }), options),
+ ).toEqual({ ok: false, reason });
+ });
+
+ it('忽略旧跨区字段,区域路由不依赖远端清单', () => {
+ const result = parseClientEndpointManifest(
+ JSON.stringify({
+ ...VALID_MANIFEST,
+ crossRealmOrgLoginEnabled: 'invalid-but-ignored',
+ realmManifestBaseUrls: 'invalid-but-ignored',
+ }),
+ );
+ expect(result).toMatchObject({ ok: true });
+ });
+
it('忽略未知字段(向前兼容)', () => {
const result = parseClientEndpointManifest(
JSON.stringify({ ...VALID_MANIFEST, futureKey: 'x', _note: '正本内注释' }),
diff --git a/packages/maker-shared/src/__tests__/clientEndpointsManifestFile.test.ts b/packages/maker-shared/src/__tests__/clientEndpointsManifestFile.test.ts
index 6bfea78d2c..baa275d32e 100644
--- a/packages/maker-shared/src/__tests__/clientEndpointsManifestFile.test.ts
+++ b/packages/maker-shared/src/__tests__/clientEndpointsManifestFile.test.ts
@@ -5,11 +5,11 @@
* 发布方式是人肉上传各自 region 的 hotfix CDN(`<base>/endpoint.json`,暂无发布
* 脚本),这条测试是上传前的唯一自动防线:改 CDN 前必须先改仓内正本并让本测试
* 通过。客户端仍会在清单原文无法解析时阻断,所以这里保证正本永远能被客户端
- * parser 接受;region 不适用的 endpoint 字段允许缺失或留空。
+ * parser 接受;region 不适用的 endpoint 字段允许缺失或留空。区域身份和两区清单
+ * 地址由客户端构建配置提供,不写进远端清单。
*
* 构建期自举 CDN 基址直接读取同一份清单的 cdnBaseUrl,不再维护第二份镜像。
- * 清单即唯一事实源:parser 会把缺失/空白 endpoint 归一为空串,不把 region 差异
- * 当成全量启动事故。
+ * 清单即业务端点唯一事实源:parser 会把缺失/空白 endpoint 归一为空串。
*
* `_` 前缀键约定为正本内注释(JSON 无注释语法;客户端 parser 按未知字段忽略),
* 未知字段检查对其豁免。
diff --git a/packages/maker-shared/src/clientEndpoints.ts b/packages/maker-shared/src/clientEndpoints.ts
index f36015a7ee..17d672fffe 100644
--- a/packages/maker-shared/src/clientEndpoints.ts
+++ b/packages/maker-shared/src/clientEndpoints.ts
@@ -14,8 +14,9 @@
* - **没有缓存回退、没有超时后静默继续、没有逐字段烘焙回退**——任何本地兜底
* 都会把非空 CDN 配置错误静默掩盖成"部分端点漂移",这里要的是非法值立刻暴露;
* desktop 与 mobile 正式包均遵守本条严格语义。
- * - 客户端唯一烘焙的远程 URL 是拉清单用的 CDN 基址(自举必需,且防"清单配错
- * CDN 把自己锁死");**更新/hotfix 链的 CDN base 也来自清单**(cdnBaseUrl)
+ * - 客户端只烘焙 CN/Global 两份清单的 CDN 基址(自举与组织区域发现必需,
+ * 且防"清单配错 CDN 把自己锁死");**更新/hotfix 链的 CDN base 也来自清单**
+ * (cdnBaseUrl)
* ——清单阻断在一切更新检查之前,更新链拿到的一定是已解析的清单值,
* 无鸡生蛋问题;
* - dev(desktop 未打包 / mobile __DEV__)默认不走 CDN,改读仓内正本文件
@@ -69,8 +70,8 @@ export const CLIENT_ENDPOINT_KEYS = [
// SlackIM→slack-hook / GitHub 反馈→githubApiBaseUrl / Skillhub→
// skillhubApiBaseUrl)。退役时清单体系尚无已发布的 packaged/mobile 消费者,
// 正本(=CDN 上传源)已同步删值,无兼容包袱(同 cdnInternalBaseUrl 先例)。
- // auth 不分 cn/global:国内/海外是两条 CDN 各发各的清单,清单本身已 region 化,
- // 客户端无脑取本字段即可。
+ // 每份清单只描述自身 region 的 auth/业务端点。默认会话读取构建清单;
+ // 跨区域组织登录会先加载目标 region 清单,再整体切换 token 消费端点。
'authApiBaseUrl',
// desktop 系统浏览器登录的**服务端托管回调**地址(auth-server 路由,精确值需与
// 服务端 redirect_uri allowlist 逐字符一致)。非空 = 走托管回调链路:回调页停在
@@ -114,6 +115,13 @@ export type ClientEndpointKey = (typeof CLIENT_ENDPOINT_KEYS)[number];
/** 解析成功后的端点全集(全 key 存在;清单缺失/空白的字段值为 `''`)。 */
export type ClientEndpointMap = Record<ClientEndpointKey, string>;
+/** auth-server 的物理部署区域;与 App 包体的品牌/更新区域是两个独立概念。 */
+export type ClientEndpointRegion = 'cn' | 'global';
+
+export type RealmManifestBaseUrls = Readonly<
+ Record<ClientEndpointRegion, string>
+>;
+
/**
* 可选字符串字段:`review` = 手机版审核模式的**送审版本号**(App 审核期间填
* 送审构建的二进制版本号,如 "1.4.0")。mobile 启动时用它与自身二进制版本号
@@ -162,6 +170,8 @@ const FIELD_PROTOCOLS: Record<ClientEndpointKey, readonly string[]> = {
export interface ParseClientEndpointManifestOptions {
/** true 时 https-only 字段追加接受 http:、wss 字段追加 ws:(localhost 场景)。 */
allowHttp?: boolean;
+ /** 加载指定区域的清单时必须提供;清单自报区域不一致或缺失会整份拒绝。 */
+ expectedRegion?: ClientEndpointRegion;
}
// 去尾部斜杠。不用 /\/+$/ 正则——超长 '/' 串上会 O(n²) 回溯(CodeQL js/polynomial-redos)。
@@ -171,7 +181,10 @@ function trimTrailingSlashes(s: string): string {
return s.slice(0, end);
}
-function allowedProtocols(key: ClientEndpointKey, allowHttp: boolean): readonly string[] {
+function allowedProtocols(
+ key: ClientEndpointKey,
+ allowHttp: boolean,
+): readonly string[] {
const base = FIELD_PROTOCOLS[key];
if (!allowHttp) return base;
const relaxed = [...base];
@@ -181,7 +194,13 @@ function allowedProtocols(key: ClientEndpointKey, allowHttp: boolean): readonly
}
export type ParseClientEndpointManifestResult =
- | { ok: true; endpoints: ClientEndpointMap; reviewVersion: string | null }
+ | {
+ ok: true;
+ endpoints: ClientEndpointMap;
+ reviewVersion: string | null;
+ /** 可选诊断元数据;缺失时由受信任清单地址确定区域。 */
+ region: ClientEndpointRegion | null;
+ }
| { ok: false; reason: string };
/**
@@ -234,7 +253,9 @@ export function parseClientEndpointManifest(
} catch {
return { ok: false, reason: `invalid-field:${key}` };
}
- if (!allowedProtocols(key, options?.allowHttp === true).includes(url.protocol)) {
+ if (
+ !allowedProtocols(key, options?.allowHttp === true).includes(url.protocol)
+ ) {
return { ok: false, reason: `invalid-protocol:${key}` };
}
if (url.username || url.password) {
@@ -250,11 +271,36 @@ export function parseClientEndpointManifest(
const reviewVersion =
typeof rawReview === 'string' && rawReview.trim() ? rawReview.trim() : null;
- return { ok: true, endpoints, reviewVersion };
+ const rawRegion = record.region;
+ const region =
+ rawRegion === undefined
+ ? null
+ : rawRegion === 'cn' || rawRegion === 'global'
+ ? rawRegion
+ : null;
+ if (rawRegion !== undefined && region === null) {
+ return { ok: false, reason: 'invalid-field:region' };
+ }
+ if (
+ options?.expectedRegion !== undefined &&
+ region !== options.expectedRegion
+ ) {
+ return {
+ ok: false,
+ reason: `region-mismatch:${options.expectedRegion}:${region ?? 'missing'}`,
+ };
+ }
+
+ return {
+ ok: true,
+ endpoints,
+ reviewVersion,
+ region,
+ };
}
export type ResolveClientEndpointsResult =
- | { ok: true; endpoints: ClientEndpointMap; reviewVersion: string | null }
+ | Extract<ParseClientEndpointManifestResult, { ok: true }>
| { ok: false; reason: string };
/**
diff --git a/scripts/__tests__/client-endpoint-build-env.test.mjs b/scripts/__tests__/client-endpoint-build-env.test.mjs
index 3c2b053a23..29d78e8db8 100644
--- a/scripts/__tests__/client-endpoint-build-env.test.mjs
+++ b/scripts/__tests__/client-endpoint-build-env.test.mjs
@@ -7,6 +7,8 @@ import { afterEach, test } from 'node:test';
import {
desktopClientBuildEnv,
loadEndpointManifestBaseUrl,
+ loadPeerEndpointManifestBaseUrl,
+ mobileClientBundleEnv,
mobileClientBuildEnv,
} from '../shared/client-endpoint-build-env.mjs';
import { resolveReleaseCdnBaseUrl } from '../shared/release-env.mjs';
@@ -30,6 +32,7 @@ test('desktop/mobile 构建从 region 清单的 cdnBaseUrl 生成自举环境变
assert.deepEqual(desktopClientBuildEnv({ allowEnvOverride: false, repoRoot }), {
VITE_CINDY_AUTH_REGION: 'global',
VITE_ENDPOINT_MANIFEST_BASE_URL: 'https://hotfix-global.example.invalid/app',
+ VITE_ENDPOINT_MANIFEST_PEER_BASE_URL: 'https://hotfix-cn.example.invalid/app',
});
assert.equal(
Object.hasOwn(desktopClientBuildEnv({ allowEnvOverride: false, repoRoot }), 'VITE_FEISHU_APP_ID'),
@@ -39,6 +42,15 @@ test('desktop/mobile 构建从 region 清单的 cdnBaseUrl 生成自举环境变
EXPO_PUBLIC_CINDY_AUTH_REGION: 'global',
EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: 'https://hotfix-global.example.invalid/app',
});
+ assert.deepEqual(mobileClientBundleEnv({ authRegion: 'global', repoRoot }), {
+ EXPO_PUBLIC_CINDY_AUTH_REGION: 'global',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL: 'https://hotfix-global.example.invalid/app',
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL: 'https://hotfix-cn.example.invalid/app',
+ });
+ assert.equal(
+ loadPeerEndpointManifestBaseUrl({ authRegion: 'cn', repoRoot }),
+ 'https://hotfix-global.example.invalid/app',
+ );
});
test('端点清单自举基址缺失、非法协议或携带凭据时 fail closed', () => {
diff --git a/scripts/__tests__/endpoint-consistency.test.mjs b/scripts/__tests__/endpoint-consistency.test.mjs
index e44f228aa6..f632d0b270 100644
--- a/scripts/__tests__/endpoint-consistency.test.mjs
+++ b/scripts/__tests__/endpoint-consistency.test.mjs
@@ -16,6 +16,7 @@ test('提交的 EAS build profiles 不包含生产端点 env(含 extends)',
assert.equal(env.EXPO_PUBLIC_XDT_DEVICE_LINK_API_BASE_URL, undefined, profileName);
assert.equal(env.EXPO_PUBLIC_XDT_MOBILE_VOICE_LITELLM_BASE_URL, undefined, profileName);
assert.equal(env.EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL, undefined, profileName);
+ assert.equal(env.EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL, undefined, profileName);
}
assert.equal(resolveEasBuildProfileEnv(eas.build, 'testflight').EXPO_PUBLIC_CINDY_AUTH_REGION, 'cn');
});
diff --git a/scripts/check-endpoint-literals.mjs b/scripts/check-endpoint-literals.mjs
index d3aa2e5ca6..10ee1cd074 100644
--- a/scripts/check-endpoint-literals.mjs
+++ b/scripts/check-endpoint-literals.mjs
@@ -13,8 +13,9 @@ import { fileURLToPath } from 'node:url';
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const EAS_ENDPOINT_ENV_KEYS = Object.freeze([
'EXPO_PUBLIC_FEISHU_APP_ID',
- // 现役:端点清单自举基址(唯一烘焙远程 URL,由发版脚本临时注入)。
+ // 现役:本区与对端的两份清单自举基址,由发版脚本临时注入。
'EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL',
+ 'EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL',
// 以下为已退役键(2026-07 端点清单重构后不再注入)——保留在名单里防复活。
'EXPO_PUBLIC_CINDY_AUTH_BASE_URL',
'EXPO_PUBLIC_XDT_API_BASE_URL',
diff --git a/scripts/shared/client-endpoint-build-env.mjs b/scripts/shared/client-endpoint-build-env.mjs
index 8e9ac78514..4b26278f50 100644
--- a/scripts/shared/client-endpoint-build-env.mjs
+++ b/scripts/shared/client-endpoint-build-env.mjs
@@ -1,9 +1,9 @@
/**
* 客户端构建期端点自举配置。
*
- * 运行期业务端点的唯一事实源是 region 对应的 config/endpoint*.json;构建期只需
- * 烘焙 region 与“去哪里拉这份清单”的 CDN 基址。该基址直接取同一份仓内正本的
- * cdnBaseUrl,避免再维护一份 production-endpoints.json 镜像。
+ * 运行期业务端点的唯一事实源是 region 对应的 config/endpoint*.json;构建期烘焙
+ * region 与 CN/Global 两份清单的 CDN 基址。基址直接取仓内正本的 cdnBaseUrl,
+ * 避免再维护一份 production-endpoints.json 镜像。
*/
import fs from 'node:fs';
import path from 'node:path';
@@ -72,6 +72,18 @@ export function loadEndpointManifestBaseUrl(options = {}) {
return normalized;
}
+/**
+ * 返回当前构建区域之外的另一份受信任清单基址。CN/Global 互为对端;
+ * dev 以 CN 身份运行,仍只把 Global 作为对端。
+ */
+export function loadPeerEndpointManifestBaseUrl(options = {}) {
+ const region = resolveClientBuildRegion(options.authRegion);
+ return loadEndpointManifestBaseUrl({
+ authRegion: region === 'global' ? 'cn' : 'global',
+ repoRoot: options.repoRoot,
+ });
+}
+
/** Desktop 正式构建所需的公开 Vite 变量。 */
export function desktopClientBuildEnv({ allowEnvOverride = true, authRegion, repoRoot } = {}) {
const region = resolveClientBuildRegion(
@@ -82,10 +94,15 @@ export function desktopClientBuildEnv({ allowEnvOverride = true, authRegion, rep
const override = allowEnvOverride
? process.env.VITE_ENDPOINT_MANIFEST_BASE_URL?.trim()
: '';
+ const peerOverride = allowEnvOverride
+ ? process.env.VITE_ENDPOINT_MANIFEST_PEER_BASE_URL?.trim()
+ : '';
return {
VITE_CINDY_AUTH_REGION: region,
VITE_ENDPOINT_MANIFEST_BASE_URL:
override || loadEndpointManifestBaseUrl({ authRegion: region, repoRoot }),
+ VITE_ENDPOINT_MANIFEST_PEER_BASE_URL:
+ peerOverride || loadPeerEndpointManifestBaseUrl({ authRegion: region, repoRoot }),
};
}
@@ -102,3 +119,18 @@ export function mobileClientBuildEnv({ authRegion, repoRoot } = {}) {
}),
};
}
+
+/**
+ * Mobile JS bundle 额外需要对端区域清单基址。与 mobileClientBuildEnv 分开,
+ * 避免把这个纯 JS 变量加入 app.config 的既有 Expo extra / runtime fingerprint。
+ */
+export function mobileClientBundleEnv(options = {}) {
+ const buildEnv = mobileClientBuildEnv(options);
+ return {
+ ...buildEnv,
+ EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL: loadPeerEndpointManifestBaseUrl({
+ authRegion: buildEnv.EXPO_PUBLIC_CINDY_AUTH_REGION,
+ repoRoot: options.repoRoot,
+ }),
+ };
+}