Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): CAS desktop cold-start credentials
xd-bobo6497e7e9bdcf
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex bd58382ad0..00e10a46d3 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -360,13 +360,23 @@ describe('auth login-flow reset', () => {const coldStart = source.indexOf('async function runColdStartRefreshFlow(');const coldEnd = source.indexOf('\n}\n\nasync function loadLoginProviders()', coldStart);const coldBody = source.slice(coldStart, coldEnd);+ const coldCredentialCommit = coldBody.indexOf(+ 'await commitDesktopRefreshCredentials(',+ );const coldPolicyGuard = coldBody.indexOf('!canRestoreAuthSessionForMembership(');const coldRealmActivation = coldBody.indexOf('activateClientEndpointRealm(storedRealm);');+ expect(coldCredentialCommit).toBeGreaterThan(-1);expect(coldPolicyGuard).toBeGreaterThan(-1);+ expect(coldCredentialCommit).toBeLessThan(coldPolicyGuard);expect(coldRealmActivation).toBeGreaterThan(coldPolicyGuard);- expect(coldBody).toContain('writePersistedAuthSession(refreshData.refreshToken, storedRealm);');- expect(coldBody).toContain("epochChanged('before-cold-start-vault-write')");- expect(coldBody).toContain("'Cold-start Resource session write was superseded'");+ expect(coldBody).toContain('requestedToken,');+ expect(coldBody).toContain('allowUnclaimedVault: true');+ expect(coldBody).toContain("epochChanged('before-cold-start-credential-commit')");+ expect(coldBody).toContain("credentialCommit !== 'active'");+ expect(coldBody).not.toContain(+ 'writePersistedAuthSession(refreshData.refreshToken, storedRealm)',+ );+ expect(coldBody).not.toContain('rememberResourceSession(refreshData');const refreshStart = source.indexOf('export async function refresh(): Promise<boolean> {');const refreshEnd = source.indexOf('\n}\n\nexport async function logout()', refreshStart);@@ -377,7 +387,7 @@ describe('auth login-flow reset', () => {);expect(runtimePolicyGuard).toBeGreaterThan(-1);expect(runtimeRealmActivation).toBeGreaterThan(runtimePolicyGuard);- expect(refreshBody).toContain('await commitDesktopRuntimeRefreshCredentials(');+ expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');expect(refreshBody).toContain("await expireRuntimeAuth(currentUser.id, 'replaced-elsewhere', {",);@@ -435,10 +445,13 @@ describe('auth login-flow reset', () => {expect(refreshBody).toContain('latestSession.refreshToken === requestedToken');expect(refreshBody).toContain("credentialCommit !== 'active'");- const helperStart = source.indexOf('async function commitDesktopRuntimeRefreshCredentials(');+ const helperStart = source.indexOf('async function commitDesktopRefreshCredentials(');const helperEnd = source.indexOf('\n}\n\n/** Persist a rotated Passport', helperStart);const helperBody = source.slice(helperStart, helperEnd);expect(helperBody).toContain('vault.activeAccountKey === key');+ expect(helperBody).toContain('options.validateBeforeWrite?.()');+ expect(helperBody).toContain('canClaimUninitializedVault');+ expect(helperBody).toContain('Object.keys(vault.resources).length === 0');expect(helperBody).toContain('readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY)');expect(helperBody).toContain('markActive: stillOwnsActiveSession');expect(helperBody).toContain("if (commit === 'active') {");@@ -451,7 +464,7 @@ describe('auth login-flow reset', () => {const refreshBody = source.slice(refreshStart, refreshEnd);expect(refreshBody).toContain('const authRealmChanged = refreshRealm !== activeAuthRealm;');- expect(refreshBody).toContain('await commitDesktopRuntimeRefreshCredentials(');+ expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');expect(refreshBody).toContain('activeAuthRealm = refreshRealm;');expect(refreshBody).toContain('const membershipKindChanged = previousMembershipKind !== nextUser.membershipKind;',diff --git a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.tsindex f40a46428c..b6dc330896 100644--- a/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts+++ b/apps/desktop/src/main/__tests__/authSessionExpiredDetection.test.ts@@ -157,10 +157,10 @@ describe('desktop auth session-expiry detection', () => {expect(authSource).toContain('withGhostSkillProjectionOwnerCommit,');expect(authSource).toContain("from './authBoundaryQuarantine.js';");- expect(refreshBody).toContain('await commitDesktopRuntimeRefreshCredentials(');+ expect(refreshBody).toContain('await commitDesktopRefreshCredentials(');expect(refreshBody).toContain('await withCloudOwnerCommit({');expect(refreshBody).toContain('nextOwnerId: nextUser.id');- expect(refreshBody.indexOf('await commitDesktopRuntimeRefreshCredentials(')).toBeLessThan(+ expect(refreshBody.indexOf('await commitDesktopRefreshCredentials(')).toBeLessThan(refreshBody.indexOf('await withCloudOwnerCommit({'),);});diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex cb55a4efc9..fa230d1737 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -1041,22 +1041,33 @@ function assertPassportReplacementStored(result: PassportSessionReplacementResul);}-type RuntimeRefreshCredentialCommit = 'active' | 'inactive' | 'discarded';+type ActiveRefreshCredentialCommit = 'active' | 'inactive' | 'discarded';-async function commitDesktopRuntimeRefreshCredentials(+async function commitDesktopRefreshCredentials(pair: AuthTokenPair,realm: AuthRegion,requestedRefreshToken: string,-): Promise<RuntimeRefreshCredentialCommit> {+ options: {+ allowUnclaimedVault?: boolean;+ validateBeforeWrite?: () => void;+ } = {},+): Promise<ActiveRefreshCredentialCommit> {return transactAuthAccountVault((vault) => {+ options.validateBeforeWrite?.();const key = accountVaultKey(realm, pair.membership.id);const latestSession = readPersistedAuthSession();const requestedTokenStillStored =(latestSession?.realm === realm && latestSession.refreshToken === requestedRefreshToken) ||(realm === AUTH_REGION &&readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY) === requestedRefreshToken);- const stillOwnsActiveSession = requestedTokenStillStored && vault.activeAccountKey === key;+ const canClaimUninitializedVault =+ options.allowUnclaimedVault === true &&+ vault.activeAccountKey === null &&+ Object.keys(vault.resources).length === 0;+ const stillOwnsActiveSession =+ requestedTokenStillStored &&+ (vault.activeAccountKey === key || canClaimUninitializedVault);const passportId = pair.membership.passportId;if (passportId && (stillOwnsActiveSession || vault.resources[key])) {// A passive stale refresh may still rotate account A's resource token@@ -3711,6 +3722,7 @@ async function runColdStartRefreshFlow(attempts,failureAction,rejectedTokens,+ requestedToken,} = await runAuthRefreshWithReplacementRetry(storedToken, {phase: 'cold-start',realm: storedRealm,@@ -3774,34 +3786,41 @@ async function runColdStartRefreshFlow(}const refreshData = refreshResult.data as RefreshResponse;+ const credentialCommit = await commitDesktopRefreshCredentials(+ refreshData,+ storedRealm,+ requestedToken,+ {+ allowUnclaimedVault: true,+ validateBeforeWrite: () => {+ if (epochChanged('before-cold-start-credential-commit')) {+ throw new AuthApiError(+ 'AUTH_FLOW_SUPERSEDED',+ 409,+ 'Cold-start credential commit was superseded',+ );+ }+ },+ },+ );+ if (credentialCommit !== 'active') {+ log.warn(+ `cold-start refresh lost active credential ownership (${credentialCommit}); preserved only the still-saved account token`,+ );+ return finishColdStartSignedOut('cold-start-credential-ownership-lost');+ }+ lastAcceptedRefreshToken = refreshData.refreshToken;if (!canRestoreAuthSessionForMembership(AUTH_REGION, storedRealm, refreshData.membership.kind)) {- // refresh token 可能已由 auth-server 轮换。即使当前构建不能接受这枚个人- // 会话,也必须把新 token 写回原 realm,供拥有该 realm 的实例继续使用。- writePersistedAuthSession(refreshData.refreshToken, storedRealm);+ // The credential transaction above already preserved the rotated token+ // in its issuing realm. This process must not publish that identity.resetActiveAuthRealmToBuild();log.warn(`cold-start refresh rejected cross-realm personal session realm=${storedRealm} buildRegion=${AUTH_REGION}`,);return finishColdStartSignedOut('cold-start-incompatible-membership');}- // Refresh is token-rotating. Preserve the server-issued replacement before- // the cross-process projection gate can reject or defer the owner commit.- writePersistedAuthSession(refreshData.refreshToken, storedRealm);- await rememberResourceSession(refreshData, storedRealm, {- markActive: true,- validateBeforeWrite: () => {- if (epochChanged('before-cold-start-vault-write')) {- throw new AuthApiError(- 'AUTH_FLOW_SUPERSEDED',- 409,- 'Cold-start Resource session write was superseded',- );- }- },- });- lastAcceptedRefreshToken = refreshData.refreshToken;const previousSession = getActiveAppSession();await withCloudOwnerCommit({previousOwnerId: previousSession.dataOwnerId,@@ -4623,7 +4642,7 @@ export async function refresh(): Promise<boolean> {const authRealmChanged = refreshRealm !== activeAuthRealm;const data = result.data as RefreshResponse;- const credentialCommit = await commitDesktopRuntimeRefreshCredentials(+ const credentialCommit = await commitDesktopRefreshCredentials(data,refreshRealm,requestedToken,