Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): harden account switch persistence
xd-boboafb845c9eb71
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex 886bd8eaef..8722f0e96b 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -42,7 +42,9 @@ describe('auth login-flow reset', () => {const completeStart = source.indexOf('async function completeLogin(');const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);const completeBody = source.slice(completeStart, completeEnd);- expect(completeBody).toContain('if (authStateEpoch !== loginEpoch)');+ expect(completeBody).toContain(+ 'if (authStateEpoch !== loginEpoch || loginFlowEpoch !== expectedLoginFlowEpoch)',+ );expect(completeBody).toContain('notifyRenderer();');// 防复活:主机飞书 token 链已随 refresh-feishu 退役(2026-07-17),// authManager 不得再接 FeishuTokenManager(飞书授权归 xd-feishu 意识@@ -114,7 +116,7 @@ describe('auth login-flow reset', () => {expect(source).toContain("const AUTH_ACCOUNT_VAULT_KEY = 'cindy_auth_accounts_v1';");expect(source).toContain('client.refreshAccount(current.accountRefreshToken)');expect(source).toContain('client.logoutAccount(pair.accountToken)');- expect(source).toContain('writeSafe(AUTH_ACCOUNT_VAULT_KEY');+ expect(source).toContain('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY');expect(source).not.toContain('writeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY');expect(source).not.toContain('accountToken: accountAccessToken');@@ -183,6 +185,23 @@ describe('auth login-flow reset', () => {}});+ it('atomically replaces the aggregate saved-account vault', () => {+ const writeStart = source.indexOf('function writeAtomicSafe(');+ const writeEnd = source.indexOf('\n}\n\nfunction removeAtomicSafeOrThrow', writeStart);+ const writeBody = source.slice(writeStart, writeEnd);+ expect(writeBody).toContain('atomicWriteFileSync(');+ expect(writeBody).toContain("safeStorage.encryptString(value).toString('base64')");++ const readStart = source.indexOf('function readAtomicSafe(');+ const readEnd = source.indexOf('\n}\n\nfunction isAtomicPersistedSecretAbsent', readStart);+ expect(source.slice(readStart, readEnd)).toContain('fs.readFileSync(`${filepath}.bak`');++ const clearStart = source.indexOf('function removeAtomicSafeOrThrow(');+ const clearEnd = source.indexOf('\n}\n\nfunction removeSafe(', clearStart);+ const clearBody = source.slice(clearStart, clearEnd);+ expect(clearBody.indexOf('`${filepath}.bak`')).toBeLessThan(clearBody.indexOf('filepath])'));+ });+it('fails a Desktop account switch before owner teardown when session persistence fails', () => {const completeStart = source.indexOf('async function completeLogin(');const completeEnd = source.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);@@ -209,6 +228,14 @@ describe('auth login-flow reset', () => {const completeBody = source.slice(completeStart, completeEnd);expect(completeBody).toContain('expectedLoginFlowEpoch = loginFlowEpoch');expect(completeBody).toContain('loginFlowEpoch !== expectedLoginFlowEpoch');+ const resourceStored = completeBody.indexOf('await rememberResourceSession(');+ const resourceRecheck = completeBody.indexOf('assertTransitionCurrent();', resourceStored);+ const durableSession = completeBody.indexOf('writePersistedAuthSessionOrThrow(');+ const teardown = completeBody.indexOf('await accountSwitchTeardown(');+ expect(resourceRecheck).toBeGreaterThan(resourceStored);+ expect(durableSession).toBeGreaterThan(resourceRecheck);+ expect(completeBody.lastIndexOf('assertTransitionCurrent();', teardown)).toBeLessThan(teardown);+ expect(completeBody).toContain('restorePersistedAuthSessionIfCurrent(');const cancelStart = source.indexOf('export function cancelAddAccountLogin(): void {');const cancelEnd = source.indexOf('\n}', cancelStart);diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 7b35e1809c..620c356793 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -87,6 +87,7 @@ import {} from './authBoundaryQuarantine.js';import { buildFocusDeepLink } from './deepLink';import { getResolvedMainLocale, t } from './i18n';+import { atomicWriteFileSync } from './utils/atomicWriteFile.js';import {activateClientEndpointRealm,getClientEndpoint,@@ -524,6 +525,87 @@ function writeSafe(key: string, value: string): boolean {}}+/**+ * The aggregate account vault needs atomic replacement because one partial+ * write would otherwise discard every saved resource and Passport session.+ * During the Windows backup-swap fallback, readers use the old backup rather+ * than trying to restore it while the writer still owns the vault lock.+ */+function readAtomicSafe(key: string): string | null {+ try {+ if (!safeStorage.isEncryptionAvailable()) {+ logSafeStorageIssueOnce('encryption unavailable (atomic read)', key);+ return null;+ }+ const filepath = path.join(SAFE_STORAGE_DIR(), `${key}.enc`);+ let content: string;+ try {+ content = fs.readFileSync(filepath, 'utf-8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error;+ content = fs.readFileSync(`${filepath}.bak`, 'utf-8');+ }+ return safeStorage.decryptString(Buffer.from(content, 'base64'));+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return null;+ logSafeStorageIssueOnce('atomic decrypt failed', key, err);+ return null;+ }+}++function isAtomicPersistedSecretAbsent(key: string): boolean {+ if (!safeStorage.isEncryptionAvailable()) return false;+ const filepath = path.join(SAFE_STORAGE_DIR(), `${key}.enc`);+ for (const candidate of [filepath, `${filepath}.bak`]) {+ try {+ fs.accessSync(candidate, fs.constants.F_OK);+ return false;+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') return false;+ }+ }+ return true;+}++function writeAtomicSafe(key: string, value: string): boolean {+ try {+ if (!safeStorage.isEncryptionAvailable()) {+ logSafeStorageIssueOnce('encryption unavailable (atomic write)', key);+ return false;+ }+ atomicWriteFileSync(+ path.join(SAFE_STORAGE_DIR(), `${key}.enc`),+ safeStorage.encryptString(value).toString('base64'),+ );+ return true;+ } catch (err) {+ logSafeStorageIssueOnce('atomic encrypt/persist failed', key, err);+ return false;+ }+}++function removeAtomicSafeOrThrow(key: string): void {+ const filepath = path.join(SAFE_STORAGE_DIR(), `${key}.enc`);+ try {+ // Remove the backup first so deleting the main file cannot resurrect an+ // older vault on the next atomic write.+ for (const candidate of [`${filepath}.bak`, filepath]) {+ try {+ fs.unlinkSync(candidate);+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error;+ }+ }+ } catch (error) {+ logSafeStorageIssueOnce('atomic delete failed', key, error);+ throw new AuthApiError(+ 'CREDENTIAL_STORE_UNAVAILABLE',+ 503,+ 'Could not clear saved account credentials',+ );+ }+}+function removeSafe(key: string): void {try {fs.unlinkSync(path.join(SAFE_STORAGE_DIR(), `${key}.enc`));@@ -562,9 +644,9 @@ function isStoredAccountMetadata(value: unknown): value is StoredAccountMetadata}function readAuthAccountVault(options: { allowUnreadable?: boolean } = {}): AuthAccountVault {- const raw = readSafe(AUTH_ACCOUNT_VAULT_KEY);+ const raw = readAtomicSafe(AUTH_ACCOUNT_VAULT_KEY);if (raw === null) {- if (isPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY)) return emptyAuthAccountVault();+ if (isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY)) return emptyAuthAccountVault();log.warn('encrypted auth account vault exists but is temporarily unreadable');if (options.allowUnreadable) return emptyAuthAccountVault();throw new AuthApiError(@@ -636,7 +718,7 @@ function readAuthAccountVault(options: { allowUnreadable?: boolean } = {}): Auth}function writeAuthAccountVault(vault: AuthAccountVault): boolean {- return writeSafe(AUTH_ACCOUNT_VAULT_KEY, JSON.stringify(vault));+ return writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, JSON.stringify(vault));}function writeAuthAccountVaultOrThrow(vault: AuthAccountVault): void {@@ -688,7 +770,7 @@ async function clearAuthAccountVault(): Promise<void> {{ label: 'auth-account-vault-clear', waitMs: 5_000 },async (status) => {if (!status.held) throw accountVaultLockError(status.reason);- removeSafe(AUTH_ACCOUNT_VAULT_KEY);+ removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);},);}@@ -970,6 +1052,25 @@ function writePersistedAuthSessionOrThrow(refreshToken: string, realm = activeAu);}+function restorePersistedAuthSessionIfCurrent(+ expectedRefreshToken: string,+ expectedRealm: AuthRegion,+ previousSession: ReturnType<typeof readPersistedAuthSession>,+): void {+ const expected = serializeAuthSessionRecord(expectedRealm, expectedRefreshToken);+ if (readSafe(AUTH_SESSION_KEY) !== expected) return;+ if (previousSession) {+ if (!writePersistedAuthSession(previousSession.refreshToken, previousSession.realm)) {+ log.warn('failed to restore the previous persisted auth session after login rollback');+ }+ return;+ }+ const removed = removeSafeIfUnchanged(AUTH_SESSION_KEY, expected);+ if (removed === 'deleted' && expectedRealm === AUTH_REGION) {+ removeSafeIfUnchanged(LEGACY_RESOURCE_REFRESH_TOKEN_KEY, expectedRefreshToken);+ }+}+/*** 过渡期镜像:把轮换出的新 refresh token 同步回写 legacy 凭证文件。*@@ -3578,13 +3679,16 @@ async function completeLogin(outcome.accountDeletionRestored === true || pendingAccountDeletionRestored;const nextUser = mapMembershipToAuthUser(outcome.membership);const previousSession = getActiveAppSession();- if (authStateEpoch !== loginEpoch) {- throw new AuthApiError(- 'AUTH_FLOW_SUPERSEDED',- 409,- 'Login was superseded by a newer auth action',- );- }+ const assertTransitionCurrent = (): void => {+ if (authStateEpoch !== loginEpoch || loginFlowEpoch !== expectedLoginFlowEpoch) {+ throw new AuthApiError(+ 'AUTH_FLOW_SUPERSEDED',+ 409,+ 'Login was superseded by a newer auth action',+ );+ }+ };+ assertTransitionCurrent();const committedRealm = pendingAuthRealm ?? AUTH_REGION;const accountRefreshToken = outcome.accountRefreshToken ?? pendingAccountRefreshToken;@@ -3592,6 +3696,7 @@ async function completeLogin(// target session before tearing down the current owner so a later local// boundary failure cannot strand the newly authenticated account.await rememberResourceSession(outcome, committedRealm, { markActive: true });+ assertTransitionCurrent();if (accountRefreshToken && nextUser.passportId) {await rememberPassportSession({realm: committedRealm,@@ -3600,71 +3705,73 @@ async function completeLogin(memberships:pendingAccountMemberships.length > 0 ? pendingAccountMemberships : [outcome.membership],});+ assertTransitionCurrent();}// Switching is not committed until the compatibility active-session record// is durable. Failing here keeps the old owner and its runtimes intact;// ignoring this write would report success only in memory and lose the// selected account on restart.+ assertTransitionCurrent();+ const previousPersistedSession = readPersistedAuthSession();writePersistedAuthSessionOrThrow(outcome.refreshToken, committedRealm);- await withCloudOwnerCommit({- previousOwnerId: previousSession.dataOwnerId,- nextOwnerId: nextUser.id,- prepareTransition: async () => {- if (!accountSwitchTeardown) {- throw new Error('login cloud owner transition requires a teardown hook');- }- await accountSwitchTeardown({- previousUserId: previousSession.dataOwnerId ?? previousSession.mode,- nextUserId: nextUser.id,- });- },- prepareCommit: async () => {- if (authStateEpoch !== loginEpoch || loginFlowEpoch !== expectedLoginFlowEpoch) {- throw new AuthApiError(- 'AUTH_FLOW_SUPERSEDED',- 409,- 'Login was superseded by a newer auth action',- );- }- await claimLegacyNamespaceForVerifiedUser(nextUser.id);- if (authStateEpoch !== loginEpoch || loginFlowEpoch !== expectedLoginFlowEpoch) {- throw new AuthApiError(- 'AUTH_FLOW_SUPERSEDED',- 409,- 'Login was superseded by a newer auth action',- );- }- },- commit: () => {- pendingAccountToken = null;- pendingAccountRefreshToken = null;- pendingAccountMemberships = [];- pendingAccountDeletionRestored = false;- accessToken = outcome.accessToken;- persistedRefreshTokenNeedsIdentityCheck = false;- clearReplacementIntegrationReloadTimers();- activateClientEndpointRealm(committedRealm);- activeAuthRealm = committedRealm;- if (!isPassiveSharedUserDataInstance()) {- removeSafe(LEGACY_REFRESH_TOKEN_KEY);- }- lastAcceptedRefreshToken = outcome.refreshToken;- if (!isPassiveSharedUserDataInstance()) {- removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);- clearReloginFlag();- }- accountDeletionRestoredNoticePending = deletionWasRestored;- // 显式登录解除本进程登出墓碑(passive / foreign-device)。- passiveLocalSignOut = false;- foreignDeviceLocalSignOut = false;- currentUser = nextUser;- commitCloudAppSession(currentUser.id);- if (!isPassiveSharedUserDataInstance()) {- canaryFlagStore.clear();- }- pendingAuthRealm = null;- },- });+ try {+ await withCloudOwnerCommit({+ previousOwnerId: previousSession.dataOwnerId,+ nextOwnerId: nextUser.id,+ prepareTransition: async () => {+ assertTransitionCurrent();+ if (!accountSwitchTeardown) {+ throw new Error('login cloud owner transition requires a teardown hook');+ }+ await accountSwitchTeardown({+ previousUserId: previousSession.dataOwnerId ?? previousSession.mode,+ nextUserId: nextUser.id,+ });+ assertTransitionCurrent();+ },+ prepareCommit: async () => {+ assertTransitionCurrent();+ await claimLegacyNamespaceForVerifiedUser(nextUser.id);+ assertTransitionCurrent();+ },+ commit: () => {+ pendingAccountToken = null;+ pendingAccountRefreshToken = null;+ pendingAccountMemberships = [];+ pendingAccountDeletionRestored = false;+ accessToken = outcome.accessToken;+ persistedRefreshTokenNeedsIdentityCheck = false;+ clearReplacementIntegrationReloadTimers();+ activateClientEndpointRealm(committedRealm);+ activeAuthRealm = committedRealm;+ if (!isPassiveSharedUserDataInstance()) {+ removeSafe(LEGACY_REFRESH_TOKEN_KEY);+ }+ lastAcceptedRefreshToken = outcome.refreshToken;+ if (!isPassiveSharedUserDataInstance()) {+ removeSafe(ACCOUNT_DELETION_RECEIPT_KEY);+ clearReloginFlag();+ }+ accountDeletionRestoredNoticePending = deletionWasRestored;+ // 显式登录解除本进程登出墓碑(passive / foreign-device)。+ passiveLocalSignOut = false;+ foreignDeviceLocalSignOut = false;+ currentUser = nextUser;+ commitCloudAppSession(currentUser.id);+ if (!isPassiveSharedUserDataInstance()) {+ canaryFlagStore.clear();+ }+ pendingAuthRealm = null;+ },+ });+ } catch (error) {+ restorePersistedAuthSessionIfCurrent(+ outcome.refreshToken,+ committedRealm,+ previousPersistedSession,+ );+ throw error;+ }scheduleCanaryFlagSync({token: outcome.accessToken,expectedAuthEpoch: loginEpoch,diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.tsindex 2b1e8d67d8..5ea9583494 100644--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts@@ -417,7 +417,7 @@ describe('mobile auth-server login', () => {targetWrite,);const rollbackWrite = switchBody.indexOf(- 'previousSession.refreshToken,',+ 'await restorePersistedAuthSession(previousSession);',activeVaultCommit,);@@ -429,6 +429,43 @@ describe('mobile auth-server login', () => {expect(switchBody).not.toContain('const oldSession = initialVault');});+ it('durably commits an added account before clearing the previous runtime', () => {+ const authSource = readFileSync(+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),+ 'utf8',+ );+ const acceptStart = authSource.indexOf('const acceptOutcome = useCallback');+ const acceptBody = authSource.slice(+ acceptStart,+ authSource.indexOf('const refresh = useCallback', acceptStart),+ );+ const serialized = acceptBody.indexOf(+ 'const persisted = await serializeRefreshTokenMutation(async () => {',+ );+ const targetWrite = acceptBody.indexOf(+ 'await writePersistedAuthSession(outcome.refreshToken, committedRealm);',+ serialized,+ );+ const activeVaultCommit = acceptBody.indexOf(+ 'await mutateMobileAccountVault((vault) => {',+ targetWrite,+ );+ const rollback = acceptBody.indexOf(+ 'await restorePersistedAuthSession(previousPersistedSession);',+ activeVaultCommit,+ );+ const runtimeClear = acceptBody.indexOf(+ 'await clearAccountScopedRuntimeForSwitch();',+ rollback,+ );++ expect(serialized).toBeGreaterThan(-1);+ expect(targetWrite).toBeGreaterThan(serialized);+ expect(activeVaultCommit).toBeGreaterThan(targetWrite);+ expect(rollback).toBeGreaterThan(activeVaultCommit);+ expect(runtimeClear).toBeGreaterThan(rollback);+ });+it('clears the previous owner canary flag before best-effort sync', () => {const authSource = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'),diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex 03ddcf1d5f..3b604ec849 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -918,12 +918,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {userRef.current !== null &&(previousRealm !== committedRealm ||userRef.current?.id !== outcome.membership.id);- if (replacesActiveSession) {- await clearAccountScopedRuntimeForSwitch();- assertLoginFlowCurrent(expectedLoginFlowEpoch);- }const generation = ++authGenerationRef.current;refreshInFlightRef.current = null;+ const nextAccountKey = passportId+ ? accountVaultKey(committedRealm, outcome.membership.id)+ : null;const persisted = await serializeRefreshTokenMutation(async () => {if (authGenerationRef.current !== generation ||@@ -931,11 +930,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {) {return false;}+ const previousPersistedSession = await readPersistedAuthSessionStrict();await writePersistedAuthSession(outcome.refreshToken, committedRealm);- return (- authGenerationRef.current === generation &&- loginFlowEpochRef.current === expectedLoginFlowEpoch- );+ try {+ if (nextAccountKey) {+ await mutateMobileAccountVault((vault) => {+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ if (vault.resources[nextAccountKey]) {+ vault.activeAccountKey = nextAccountKey;+ }+ });+ }+ if (+ authGenerationRef.current !== generation ||+ loginFlowEpochRef.current !== expectedLoginFlowEpoch+ ) {+ throw authCodeError('AUTH_FLOW_SUPERSEDED');+ }+ return true;+ } catch (error) {+ await restorePersistedAuthSession(previousPersistedSession);+ throw error;+ }});if (!persisted) throw authCodeError('AUTH_FLOW_SUPERSEDED');if (@@ -943,17 +959,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {loginFlowEpochRef.current !== expectedLoginFlowEpoch)throw authCodeError('AUTH_FLOW_SUPERSEDED');- if (passportId) {- const nextAccountKey = accountVaultKey(- committedRealm,- outcome.membership.id,- );- await mutateMobileAccountVault((vault) => {- assertLoginFlowCurrent(expectedLoginFlowEpoch);- if (vault.resources[nextAccountKey]) {- vault.activeAccountKey = nextAccountKey;- }- });+ if (replacesActiveSession) {+ await clearAccountScopedRuntimeForSwitch();assertLoginFlowCurrent(expectedLoginFlowEpoch);}activateMobileSessionRealm(committedRealm);@@ -2112,14 +2119,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {vault.activeAccountKey = accountKey;});} catch (error) {- if (previousSession) {- await writePersistedAuthSession(- previousSession.refreshToken,- previousSession.realm,- );- } else {- await deleteSecureItem(AUTH_SESSION_KEY);- }+ await restorePersistedAuthSession(previousSession);throw error;}});@@ -2756,6 +2756,16 @@ async function writePersistedAuthSession();}+async function restorePersistedAuthSession(+ session: AuthSessionRecord | null,+): Promise<void> {+ if (session) {+ await writePersistedAuthSession(session.refreshToken, session.realm);+ } else {+ await deleteSecureItem(AUTH_SESSION_KEY);+ }+}+async function readCachedUserProfile(): Promise<MobileUser | null> {try {const raw = await getSecureItem(USER_PROFILE_KEY);