Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
新增会话区域恢复校验
DavidShen5d69fc99e0ba
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex 834964e7c4..a5ae27743a 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -160,6 +160,38 @@ describe('auth login-flow reset', () => {expect(initializeBody.slice(localGuard, refreshTokenRead)).toContain('return snapshotAuthState();');});+ it('activates a restored realm only after the refreshed membership passes build policy', () => {+ const initializeStart = source.indexOf('export async function initialize(');+ const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);+ const initializeBody = source.slice(initializeStart, initializeEnd);+ expect(initializeBody).toContain('await loadClientEndpointsForRealm(persistedSession.realm);');+ expect(initializeBody).not.toContain('activateClientEndpointRealm(persistedSession.realm);');++ const coldStart = source.indexOf('async function runColdStartRefreshFlow(');+ const coldEnd = source.indexOf('\n}\n\nasync function loadLoginProviders()', coldStart);+ const coldBody = source.slice(coldStart, coldEnd);+ const coldPolicyGuard = coldBody.indexOf('!canRestoreAuthSessionForMembership(');+ const coldRealmActivation = coldBody.indexOf('activateClientEndpointRealm(storedRealm);');+ expect(coldPolicyGuard).toBeGreaterThan(-1);+ expect(coldRealmActivation).toBeGreaterThan(coldPolicyGuard);+ expect(coldBody).toContain('writePersistedAuthSession(refreshData.refreshToken, storedRealm);');++ 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);+ const runtimePolicyGuard = refreshBody.indexOf('!canRestoreAuthSessionForMembership(');+ const runtimeRealmActivation = refreshBody.indexOf(+ 'activateClientEndpointRealm(refreshRealm);',+ );+ expect(runtimePolicyGuard).toBeGreaterThan(-1);+ expect(runtimeRealmActivation).toBeGreaterThan(runtimePolicyGuard);+ expect(refreshBody).toContain('writePersistedAuthSession(data.refreshToken, refreshRealm);');+ expect(refreshBody).toContain(+ "await expireRuntimeAuth(currentUser.id, 'replaced-elsewhere', {",+ );+ expect(refreshBody).toContain('preservePersistedRefreshToken: true');+ });+it('drops a runtime refresh result after logout or a newer login changes auth generation', () => {const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);diff --git a/apps/desktop/src/main/__tests__/authRealmPolicy.test.ts b/apps/desktop/src/main/__tests__/authRealmPolicy.test.tsnew file mode 100644index 0000000000..d5702c275d--- /dev/null+++ b/apps/desktop/src/main/__tests__/authRealmPolicy.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';+import { canRestoreAuthSessionForMembership } from '../authRealmPolicy';++describe('canRestoreAuthSessionForMembership', () => {+ it.each([+ ['cn', 'cn'],+ ['global', 'global'],+ ] as const)('allows a personal session in its build realm (%s)', (buildRegion, sessionRealm) => {+ expect(canRestoreAuthSessionForMembership(buildRegion, sessionRealm, 'personal')).toBe(true);+ });++ it.each([+ ['cn', 'global'],+ ['global', 'cn'],+ ] as const)(+ 'rejects a personal session outside its build realm (%s build, %s session)',+ (buildRegion, sessionRealm) => {+ expect(canRestoreAuthSessionForMembership(buildRegion, sessionRealm, 'personal')).toBe(false);+ },+ );++ it.each([+ ['cn', 'cn'],+ ['cn', 'global'],+ ['global', 'cn'],+ ['global', 'global'],+ ] as const)(+ 'allows an organization session to follow its realm (%s build, %s session)',+ (buildRegion, sessionRealm) => {+ expect(canRestoreAuthSessionForMembership(buildRegion, sessionRealm, 'org')).toBe(true);+ },+ );+});diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 3223fbdb51..3c79c7fb4a 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -56,6 +56,7 @@ import {} from './authRefreshFailure';import { awaitWithStartupTimeout } from './authStartupGate';import { syncCanaryFlagAfterAuth } from './canaryFlagSync';+import { canRestoreAuthSessionForMembership } from './authRealmPolicy';import {createAuthBrowserAuthorizationSlot,createAuthLoopbackDevBridgeSlot,@@ -1876,8 +1877,6 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A}try {await loadClientEndpointsForRealm(persistedSession.realm);- activateClientEndpointRealm(persistedSession.realm);- activeAuthRealm = persistedSession.realm;} catch (error) {// 对端区域清单暂不可用时保留原子凭据;退回构建区 refresh 会把有效 token// 当成非法凭据,因此本次仅以未登录放行 UI,下一次 initialize/重启可重试。@@ -2024,6 +2023,19 @@ async function runColdStartRefreshFlow(}const refreshData = refreshResult.data as RefreshResponse;+ if (+ !canRestoreAuthSessionForMembership(AUTH_REGION, storedRealm, refreshData.membership.kind)+ ) {+ // refresh token 可能已由 auth-server 轮换。即使当前构建不能接受这枚个人+ // 会话,也必须把新 token 写回原 realm,供拥有该 realm 的实例继续使用。+ writePersistedAuthSession(refreshData.refreshToken, storedRealm);+ resetActiveAuthRealmToBuild();+ log.warn(+ `cold-start refresh rejected cross-realm personal session realm=${storedRealm} buildRegion=${AUTH_REGION}`,+ );+ commitActiveAppSession('signed-out');+ return snapshotLoggedOutAuthState();+ }if (accountSwitchTeardown) {// Cold-start refresh may outlive initialize()'s startup timeout. Keep// the owner boundary held for the entire late commit sequence so stale@@ -2046,7 +2058,11 @@ async function runColdStartRefreshFlow(releaseBoundary = null;return snapshotAuthState();}- writePersistedAuthSession(refreshData.refreshToken);+ if (storedRealm !== activeAuthRealm) {+ activateClientEndpointRealm(storedRealm);+ activeAuthRealm = storedRealm;+ }+ writePersistedAuthSession(refreshData.refreshToken, storedRealm);lastAcceptedRefreshToken = refreshData.refreshToken;accessToken = refreshData.accessToken;@@ -2090,6 +2106,7 @@ async function runColdStartRefreshFlow(clearTimeout(refreshTimer);refreshTimer = null;}+ resetActiveAuthRealmToBuild();}releaseBoundary?.();releaseBoundary = null;@@ -2716,6 +2733,23 @@ export async function refresh(): Promise<boolean> {const authRealmChanged = refreshRealm !== activeAuthRealm;const data = result.data as RefreshResponse;+ if (!canRestoreAuthSessionForMembership(AUTH_REGION, refreshRealm, data.membership.kind)) {+ // Preserve a rotated token in the realm that issued it, but never publish+ // the incompatible personal identity or activate that realm's business endpoints.+ writePersistedAuthSession(data.refreshToken, refreshRealm);+ log.warn(+ `runtime refresh rejected cross-realm personal session realm=${refreshRealm} buildRegion=${AUTH_REGION}`,+ );+ if (currentUser !== null) {+ await expireRuntimeAuth(currentUser.id, 'replaced-elsewhere', {+ preservePersistedRefreshToken: true,+ });+ } else {+ resetActiveAuthRealmToBuild();+ commitActiveAppSession('signed-out');+ }+ return false;+ }const needsIdentityCheck =replacementRetries > 0 ||persistedRefreshTokenNeedsIdentityCheck ||diff --git a/apps/desktop/src/main/authRealmPolicy.ts b/apps/desktop/src/main/authRealmPolicy.tsnew file mode 100644index 0000000000..18f13fa0aa--- /dev/null+++ b/apps/desktop/src/main/authRealmPolicy.ts@@ -0,0 +1,13 @@+import type { AuthMembership, AuthRegion } from '@cindy/auth-client';++/**+ * Organization sessions may follow their server-side realm, while personal+ * accounts remain scoped to the installed build region.+ */+export function canRestoreAuthSessionForMembership(+ buildRegion: AuthRegion,+ sessionRealm: AuthRegion,+ membershipKind: AuthMembership['kind'],+): boolean {+ return membershipKind === 'org' || sessionRealm === buildRegion;+}diff --git a/docs/auth-realm-routing.md b/docs/auth-realm-routing.mdindex 955db10ee5..c9cbf897f0 100644--- a/docs/auth-realm-routing.md+++ b/docs/auth-realm-routing.md@@ -59,7 +59,11 @@ Desktop safeStorage 和 Mobile SecureStore 都只保存一个加密的原子记旧版裸 refresh token 只在一次性迁移时按 `buildRegion` 解释。冷启动先加载并核验记录中区域的端点清单,再向该区域 refresh;对端清单暂不可用时保留记录供重试,禁止退回-`buildRegion` 发送 token。登出会清除记录和 `sessionRealm`,业务端点恢复安装包区域。+`buildRegion` 发送 token。Desktop 在 refresh 返回组织 membership 后才允许激活跨区业务+端点;个人 membership 只有在 `sessionRealm === buildRegion` 时才能恢复。跨区个人+session 被拒绝时,Desktop 仍把轮换后的 refresh token 写回原 realm,但保持未登录且不+删除记录,避免破坏共享 userData 中另一实例仍在使用的会话。登出会清除记录和+`sessionRealm`,业务端点恢复安装包区域。Mobile 的 Pending OAuth 同时保存 `realm`,但 redirect scheme 始终使用当前安装包的scheme。个人验证码和社交登录不做跨区域发现,也不合并两区 passport。