Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): close account transition transaction
xd-bobo4b8981f6e82b
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex 8722f0e96b..b3e89d912f 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -155,9 +155,9 @@ describe('auth login-flow reset', () => {});it('serializes saved-account vault mutations across shared-userData processes', () => {- const mutationStart = source.indexOf('async function mutateAuthAccountVault');+ const mutationStart = source.indexOf('async function transactAuthAccountVault');const mutationEnd = source.indexOf(- '\n}\n\nasync function clearAuthAccountVault',+ '\n}\n\nasync function mutateAuthAccountVault',mutationStart,);const mutationBody = source.slice(mutationStart, mutationEnd);@@ -169,6 +169,11 @@ describe('auth login-flow reset', () => {expect(mutationBody.indexOf('writeAuthAccountVaultOrThrow(vault);')).toBeGreaterThan(mutationBody.indexOf('await operation(vault);'),);+ expect(mutationBody.indexOf('await afterPersist(result);')).toBeGreaterThan(+ mutationBody.indexOf('writeAuthAccountVaultOrThrow(vault);'),+ );+ expect(mutationBody).toContain('removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);');+ expect(mutationBody).toContain('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, previousRaw)');for (const helper of ['async function rememberResourceSession(',@@ -206,10 +211,16 @@ 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);+ const vaultTransaction = completeBody.indexOf('await commitDesktopLoginSessions(');const durableSession = completeBody.indexOf('writePersistedAuthSessionOrThrow(');const ownerCommit = completeBody.indexOf('await withCloudOwnerCommit({');+ expect(vaultTransaction).toBeGreaterThan(-1);+ expect(durableSession).toBeGreaterThan(vaultTransaction);expect(durableSession).toBeGreaterThan(-1);expect(ownerCommit).toBeGreaterThan(durableSession);+ expect(completeBody.indexOf('restorePersistedAuthSessionIfCurrent(')).toBeGreaterThan(+ ownerCommit,+ );expect(completeBody.slice(ownerCommit)).not.toContain('writePersistedAuthSession(outcome.refreshToken',);diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 620c356793..9684f11f66 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -748,22 +748,50 @@ function accountVaultLockError(reason: 'busy' | 'unavailable'): AuthApiError {* in-process queue alone cannot prevent it from overwriting a primary* instance's concurrently added account or rotated Passport.*/-async function mutateAuthAccountVault<T>(+async function transactAuthAccountVault<T>(operation: (vault: AuthAccountVault) => T | Promise<T>,+ afterPersist: (result: T) => void | Promise<void> = () => undefined,): Promise<T> {return withCrossProcessLock(authAccountVaultLockPath(),{ label: 'auth-account-vault', waitMs: 5_000 },async (status) => {if (!status.held) throw accountVaultLockError(status.reason);+ const previousRaw = readAtomicSafe(AUTH_ACCOUNT_VAULT_KEY);+ const previousWasAbsent =+ previousRaw === null && isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY);const vault = readAuthAccountVault();const result = await operation(vault);writeAuthAccountVaultOrThrow(vault);- return result;+ try {+ // Keep the shared-userData lock through the active-session write,+ // runtime teardown and final owner commit. Cancellation or any local+ // boundary failure restores the complete pre-transition vault before+ // another process can observe or extend the partial account switch.+ await afterPersist(result);+ return result;+ } catch (error) {+ if (previousWasAbsent) {+ removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);+ } else if (previousRaw !== null && !writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, previousRaw)) {+ throw new AuthApiError(+ 'CREDENTIAL_STORE_UNAVAILABLE',+ 503,+ 'Could not restore saved account credentials after a failed account switch',+ );+ }+ throw error;+ }},);}+async function mutateAuthAccountVault<T>(+ operation: (vault: AuthAccountVault) => T | Promise<T>,+): Promise<T> {+ return transactAuthAccountVault(operation);+}+async function clearAuthAccountVault(): Promise<void> {await withCrossProcessLock(authAccountVaultLockPath(),@@ -803,18 +831,28 @@ async function rememberResourceSession(log.warn('resource session omitted passportId; keeping only the active compatibility record');return;}- const key = accountVaultKey(realm, pair.membership.id);await mutateAuthAccountVault((vault) => {- vault.resources[key] = {- realm,- refreshToken: pair.refreshToken,- metadata: metadataFromMembership(pair.membership, passportId),- lastUsedAt: options.lastUsedAt ?? Date.now(),- };- if (options.markActive !== false) vault.activeAccountKey = key;+ writeResourceSessionToVault(vault, pair, realm, passportId, options);});}+function writeResourceSessionToVault(+ vault: AuthAccountVault,+ pair: AuthTokenPair,+ realm: AuthRegion,+ passportId: string,+ options: { markActive?: boolean; lastUsedAt?: number } = {},+): void {+ const key = accountVaultKey(realm, pair.membership.id);+ vault.resources[key] = {+ realm,+ refreshToken: pair.refreshToken,+ metadata: metadataFromMembership(pair.membership, passportId),+ lastUsedAt: options.lastUsedAt ?? Date.now(),+ };+ if (options.markActive !== false) vault.activeAccountKey = key;+}+async function rememberPassportSession(input: {realm: AuthRegion;passportId: string;@@ -856,6 +894,30 @@ function writePassportSessionToVault(});}+async function commitDesktopLoginSessions(+ input: {+ pair: AuthTokenPair;+ realm: AuthRegion;+ passportId?: string;+ accountRefreshToken?: string | null;+ memberships: readonly (AuthMembership | AccountMembership | StoredAccountMetadata)[];+ },+ commitTransition: () => void | Promise<void>,+): Promise<void> {+ await transactAuthAccountVault((vault) => {+ if (!input.passportId) return;+ writeResourceSessionToVault(vault, input.pair, input.realm, input.passportId);+ if (input.accountRefreshToken) {+ writePassportSessionToVault(vault, {+ realm: input.realm,+ passportId: input.passportId,+ accountRefreshToken: input.accountRefreshToken,+ memberships: input.memberships,+ });+ }+ }, commitTransition);+}+/** Persist a rotated Passport only while the request still owns the token it consumed. */type PassportSessionReplacementResult = 'stored' | 'stale' | 'write-failed';@@ -3692,84 +3754,91 @@ async function completeLogin(const committedRealm = pendingAuthRealm ?? AUTH_REGION;const accountRefreshToken = outcome.accountRefreshToken ?? pendingAccountRefreshToken;- // Resource and Account refresh endpoints rotate credentials. Persist the new- // 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,- passportId: nextUser.passportId,- accountRefreshToken,- 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);+ let previousPersistedSession: ReturnType<typeof readPersistedAuthSession> = null;+ let activeSessionWritten = false;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();+ await commitDesktopLoginSessions(+ {+ pair: outcome,+ realm: committedRealm,+ passportId: nextUser.passportId || undefined,+ accountRefreshToken,+ memberships:+ pendingAccountMemberships.length > 0 ? pendingAccountMemberships : [outcome.membership],},- prepareCommit: async () => {+ async () => {+ // The aggregate account vault, compatibility active session, old-owner+ // teardown and final owner publication are one epoch-owned transaction.+ // Any cancellation before commit restores both durable records while+ // the cross-process vault lock is still held.assertTransitionCurrent();- await claimLegacyNamespaceForVerifiedUser(nextUser.id);+ // Capture the compatibility session only after entering the same+ // cross-process ownership window as the vault write. A concurrent+ // passive refresh may have rotated it while this login waited on the+ // lock; rollback must restore that latest generation, not a stale one.+ previousPersistedSession = readPersistedAuthSession();+ writePersistedAuthSessionOrThrow(outcome.refreshToken, committedRealm);+ activeSessionWritten = true;assertTransitionCurrent();+ 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;+ },+ });},- 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,);+ } catch (error) {+ if (activeSessionWritten) {+ restorePersistedAuthSessionIfCurrent(+ outcome.refreshToken,+ committedRealm,+ previousPersistedSession,+ );+ }throw error;}scheduleCanaryFlagSync({diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.tsindex e4cbd2a20b..62df5d38d8 100644--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts@@ -413,23 +413,34 @@ describe('mobile auth-server login', () => {latestRead,);const activeVaultCommit = switchBody.indexOf(- 'await mutateMobileAccountVault((vault) => {',+ 'await commitMobileSavedAccountActivation(',+ latestRead,+ );+ const runtimeClear = switchBody.indexOf(+ 'await clearAccountScopedRuntimeForSwitch();',targetWrite,);const rollbackWrite = switchBody.indexOf('await restorePersistedAuthSession(previousSession);',- activeVaultCommit,+ runtimeClear,);expect(serialized).toBeGreaterThan(-1);expect(latestRead).toBeGreaterThan(serialized);- expect(targetWrite).toBeGreaterThan(latestRead);- expect(activeVaultCommit).toBeGreaterThan(targetWrite);- expect(rollbackWrite).toBeGreaterThan(activeVaultCommit);+ expect(activeVaultCommit).toBeGreaterThan(latestRead);+ expect(targetWrite).toBeGreaterThan(activeVaultCommit);+ expect(runtimeClear).toBeGreaterThan(targetWrite);+ expect(rollbackWrite).toBeGreaterThan(runtimeClear);+ expect(switchBody.slice(runtimeClear, rollbackWrite)).toContain(+ 'activateMobileSessionRealm(realm!);',+ );+ expect(switchBody.slice(rollbackWrite)).toContain(+ 'activateMobileSessionRealm(previousRealm);',+ );expect(switchBody).not.toContain('const oldSession = initialVault');});- it('durably commits an added account before clearing the previous runtime', () => {+ it('keeps the added-account vault transaction through runtime cleanup and owner commit', () => {const authSource = readFileSync(resolve(process.cwd(), 'src/auth/AuthContext.tsx'),'utf8',@@ -450,20 +461,28 @@ describe('mobile auth-server login', () => {'await writePersistedAuthSession(',vaultTransaction,);- const rollback = acceptBody.indexOf(- 'await restorePersistedAuthSession(previousPersistedSession);',- targetWrite,- );const runtimeClear = acceptBody.indexOf('await clearAccountScopedRuntimeForSwitch();',- rollback,+ targetWrite,+ );+ const ownerCommit = acceptBody.indexOf(+ 'activateMobileSessionRealm(committedRealm);',+ runtimeClear,+ );+ const rollback = acceptBody.indexOf(+ 'await restorePersistedAuthSession(previousPersistedSession);',+ ownerCommit,);expect(serialized).toBeGreaterThan(-1);expect(vaultTransaction).toBeGreaterThan(serialized);expect(targetWrite).toBeGreaterThan(vaultTransaction);- expect(rollback).toBeGreaterThan(targetWrite);- expect(runtimeClear).toBeGreaterThan(rollback);+ expect(runtimeClear).toBeGreaterThan(targetWrite);+ expect(ownerCommit).toBeGreaterThan(runtimeClear);+ expect(rollback).toBeGreaterThan(ownerCommit);+ expect(acceptBody.slice(rollback)).toContain(+ 'activateMobileSessionRealm(previousRealm);',+ );});it('durably clears saved credentials before publishing mobile logout', () => {diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex 8e8b298188..9a7f0a7a0d 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -88,6 +88,7 @@ import {import {clearMobileAccountVault,commitMobileLoginSessions,+ commitMobileSavedAccountActivation,listMobileSavedAccounts,mutateMobileAccountVault,patchMobileAccountMetadata,@@ -906,6 +907,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {userRef.current?.id !== outcome.membership.id);const generation = ++authGenerationRef.current;refreshInFlightRef.current = null;+ let runtimeCleanupStarted = false;const persisted = await serializeRefreshTokenMutation(async () => {if (authGenerationRef.current !== generation ||@@ -933,54 +935,72 @@ export function AuthProvider({ children }: { children: ReactNode }) {throw authCodeError('AUTH_FLOW_SUPERSEDED');}assertLoginFlowCurrent(expectedLoginFlowEpoch);+ if (replacesActiveSession) {+ runtimeCleanupStarted = true;+ await clearAccountScopedRuntimeForSwitch();+ if (authGenerationRef.current !== generation) {+ throw authCodeError('AUTH_FLOW_SUPERSEDED');+ }+ assertLoginFlowCurrent(expectedLoginFlowEpoch);+ }++ // No await is allowed between the final cancellation check and+ // publishing the new in-memory owner. The vault transaction stays+ // owned through runtime cleanup and this synchronous commit, so a+ // cancelled Add Account flow restores both durable records.+ activateMobileSessionRealm(committedRealm);+ activeAuthRealmRef.current = committedRealm;+ pendingLoginTicketRef.current = null;+ pendingAccountTokenRef.current = null;+ pendingAccountRefreshTokenRef.current = null;+ pendingAccountMembershipsRef.current = [];+ pendingBindTicketRef.current = null;+ pendingSsoVerificationTicketRef.current = null;+ pendingAuthRealmRef.current = null;+ setToken(outcome.accessToken);+ applyUser(+ mergeMembershipWithExisting(+ outcome.membership,+ userRef.current,+ passportId || undefined,+ ),+ );+ additionalLoginRef.current = false;+ sessionRecoverySuspendedRef.current = false;+ setAccountGeneration((value) => value + 1);+ updateLoginState(+ reduceAuthFlow(loginStateRef.current, {+ type: 'outcome',+ outcome,+ }),+ );+ // 只有 resource token、用户资料与 refresh token 全部落地后才发布恢复提示。+ setAccountDeletionRestored(deletionWasRestored);},);return true;} catch (error) {await restorePersistedAuthSession(previousPersistedSession);+ if (+ runtimeCleanupStarted &&+ authGenerationRef.current === generation+ ) {+ // Runtime cleanup is rebuildable rather than durable. If the login+ // is cancelled while push/cache cleanup is in flight, republish the+ // old owner and advance its generation after cleanup settles so+ // account-scoped effects reconnect from the restored session.+ activateMobileSessionRealm(previousRealm);+ setMobileAuthOwner(userRef.current?.id ?? null);+ setAccountGeneration((value) => value + 1);+ }throw error;}});if (!persisted) throw authCodeError('AUTH_FLOW_SUPERSEDED');- if (- authGenerationRef.current !== generation ||- loginFlowEpochRef.current !== expectedLoginFlowEpoch- )- throw authCodeError('AUTH_FLOW_SUPERSEDED');- if (replacesActiveSession) {- await clearAccountScopedRuntimeForSwitch();- assertLoginFlowCurrent(expectedLoginFlowEpoch);- }- activateMobileSessionRealm(committedRealm);- activeAuthRealmRef.current = committedRealm;-- pendingLoginTicketRef.current = null;- pendingAccountTokenRef.current = null;- pendingAccountRefreshTokenRef.current = null;- pendingAccountMembershipsRef.current = [];- pendingBindTicketRef.current = null;- pendingSsoVerificationTicketRef.current = null;- pendingAuthRealmRef.current = null;- setToken(outcome.accessToken);- applyUser(- mergeMembershipWithExisting(- outcome.membership,- userRef.current,- passportId || undefined,- ),- );- additionalLoginRef.current = false;- sessionRecoverySuspendedRef.current = false;- setAccountGeneration((value) => value + 1);void refreshSavedAccountsSnapshot();void clearCanaryChannel().catch(() => undefined);scheduleCanaryChannelSync(outcome.accessToken, generation);scheduleXdOrgBetaDefault(outcome.accessToken, generation);- updateLoginState(- reduceAuthFlow(loginStateRef.current, { type: 'outcome', outcome }),- );- // 只有 resource token、用户资料与 refresh token 全部落地后才发布恢复提示。- setAccountDeletionRestored(deletionWasRestored);// Identity is already durable. Product preferences/profile hydration is best effort// and must not turn a successful login into an error on a transient downstream outage.void loadMe(outcome.accessToken, did, generation).catch(() => undefined);@@ -2119,6 +2139,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {const generation = ++authGenerationRef.current;refreshInFlightRef.current = null;+ const previousRealm = activeAuthRealmRef.current;+ let runtimeCleanupStarted = false;try {await serializeRefreshTokenMutation(async () => {if (authGenerationRef.current !== generation) {@@ -2129,16 +2151,48 @@ export function AuthProvider({ children }: { children: ReactNode }) {// must roll back to a concurrently persisted T1, never its stale// initial vault snapshot.const previousSession = await readPersistedAuthSessionStrict();- await writePersistedAuthSession(pair!.refreshToken, realm!);try {- await mutateMobileAccountVault((vault) => {- if (!vault.resources[accountKey]) {- throw authCodeError('SAVED_ACCOUNT_NOT_FOUND');- }- vault.activeAccountKey = accountKey;- });+ await commitMobileSavedAccountActivation(+ accountKey,+ async () => {+ await writePersistedAuthSession(pair!.refreshToken, realm!);+ if (authGenerationRef.current !== generation) {+ throw authCodeError('AUTH_FLOW_SUPERSEDED');+ }+ runtimeCleanupStarted = true;+ await clearAccountScopedRuntimeForSwitch();+ if (authGenerationRef.current !== generation) {+ throw authCodeError('AUTH_FLOW_SUPERSEDED');+ }++ // Publish the new owner synchronously while the vault+ // transaction still owns activeAccountKey and AUTH_SESSION_KEY.+ activateMobileSessionRealm(realm!);+ activeAuthRealmRef.current = realm!;+ pendingAuthRealmRef.current = null;+ setToken(pair!.accessToken);+ applyUser(+ mergeMembershipWithExisting(+ pair!.membership,+ null,+ metadata.passportId,+ ),+ );+ sessionRecoverySuspendedRef.current = false;+ updateLoginState(null);+ setAccountGeneration((value) => value + 1);+ },+ );} catch (error) {await restorePersistedAuthSession(previousSession);+ if (+ runtimeCleanupStarted &&+ authGenerationRef.current === generation+ ) {+ activateMobileSessionRealm(previousRealm);+ setMobileAuthOwner(userRef.current?.id ?? null);+ setAccountGeneration((value) => value + 1);+ }throw error;}});@@ -2147,25 +2201,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {throw error;}- await clearAccountScopedRuntimeForSwitch();- if (authGenerationRef.current !== generation) {- throw authCodeError('AUTH_FLOW_SUPERSEDED');- }- activateMobileSessionRealm(realm);- activeAuthRealmRef.current = realm;- pendingAuthRealmRef.current = null;- setToken(pair.accessToken);- applyUser(- mergeMembershipWithExisting(- pair.membership,- null,- metadata.passportId,- ),- );- sessionRecoverySuspendedRef.current = false;- updateLoginState(null);- setAccountGeneration((value) => value + 1);- await refreshSavedAccountsSnapshot();+ void refreshSavedAccountsSnapshot().catch(() => undefined);void clearCanaryChannel().catch(() => undefined);scheduleCanaryChannelSync(pair.accessToken, generation);scheduleXdOrgBetaDefault(pair.accessToken, generation);diff --git a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.tsindex 8f9ab8b3d6..2c5d582951 100644--- a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts+++ b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts@@ -23,6 +23,7 @@ vi.mock('../secureStorage', () => ({import {clearMobileAccountVault,commitMobileLoginSessions,+ commitMobileSavedAccountActivation,listMobileSavedAccounts,mutateMobileAccountVault,parseMobileAccountVault,@@ -282,6 +283,40 @@ describe('mobile account vault', () => {expect(secureStorage.set).toHaveBeenCalledTimes(1);});+ it('restores the previous active account when runtime commit is superseded', async () => {+ const oldKey = JSON.stringify(['global', metadata.membershipId]);+ const targetKey = JSON.stringify(['global', 'membership-2']);+ const original = JSON.stringify({+ version: 1,+ activeAccountKey: oldKey,+ resources: {+ [oldKey]: {+ realm: 'global',+ refreshToken: 'old-refresh',+ metadata,+ lastUsedAt: 10,+ },+ [targetKey]: {+ realm: 'global',+ refreshToken: 'target-refresh',+ metadata: { ...metadata, membershipId: 'membership-2' },+ lastUsedAt: 20,+ },+ },+ passports: {},+ });+ secureStorage.value = original;++ await expect(+ commitMobileSavedAccountActivation(targetKey, async () => {+ throw new Error('AUTH_FLOW_SUPERSEDED');+ }),+ ).rejects.toThrow('AUTH_FLOW_SUPERSEDED');++ expect(secureStorage.value).toBe(original);+ expect(secureStorage.set).toHaveBeenCalledTimes(2);+ });+it('keeps a signed-out tombstone and restores the vault if session deletion fails', async () => {const original = JSON.stringify({version: 1,diff --git a/apps/mobile/src/auth/mobileAccountVault.ts b/apps/mobile/src/auth/mobileAccountVault.tsindex fe8b4ac404..5b58eb159f 100644--- a/apps/mobile/src/auth/mobileAccountVault.ts+++ b/apps/mobile/src/auth/mobileAccountVault.ts@@ -311,6 +311,23 @@ export async function commitMobileLoginSessions();}+export async function commitMobileSavedAccountActivation(+ accountKey: string,+ commitTransition: () => void | Promise<void>,+): Promise<void> {+ await transactMobileAccountVault(+ (vault) => {+ if (!vault.resources[accountKey]) {+ throw Object.assign(new Error('SAVED_ACCOUNT_NOT_FOUND'), {+ code: 'SAVED_ACCOUNT_NOT_FOUND',+ });+ }+ vault.activeAccountKey = accountKey;+ },+ commitTransition,+ );+}+/*** Store a rotated Passport only while the vault still contains the token that* started the request. Logout and concurrent refreshes therefore win over a