Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): reconcile saved credential generations
xd-bobo61e5392bf98c
diff --git a/apps/desktop/src/main/__tests__/authLegacyTokenMirror.test.ts b/apps/desktop/src/main/__tests__/authLegacyTokenMirror.test.tsindex 9a103d61e9..e1eda04c3a 100644--- a/apps/desktop/src/main/__tests__/authLegacyTokenMirror.test.ts+++ b/apps/desktop/src/main/__tests__/authLegacyTokenMirror.test.ts@@ -155,15 +155,19 @@ describe('legacy → v1 refresh token migration window', () => {expect(guardCalls.length).toBe(2);});- it('读侧:交出 v1 与 legacy 两个来源且不在此折叠,v1 排前', () => {+ it('读侧:交出 compatibility、vault 与 legacy 三个来源且不在此折叠', () => {const body = sliceBody('function readStoredRefreshTokenCandidates(', '\n}\n');const v1Idx = body.indexOf('readPersistedRefreshToken(realm)');+ const vaultIdx = body.indexOf('activeResource.refreshToken');const legacyIdx = body.indexOf('readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY)');expect(v1Idx).toBeGreaterThan(-1);+ expect(vaultIdx).toBeGreaterThan(-1);expect(legacyIdx).toBeGreaterThan(-1);- // v1 带 realm、是本版本权威记录,必须排在 legacy 之前。- expect(v1Idx).toBeLessThan(legacyIdx);+ // compatibility 先覆盖回滚版本刚轮换的代次,vault 再覆盖新版本中断写留下的代次;+ // legacy 裸 token 风险最高,只作为构建区的最后兜底。+ expect(v1Idx).toBeLessThan(vaultIdx);+ expect(vaultIdx).toBeLessThan(legacyIdx);// legacy 同样只在与安装包区域一致时可解释。expect(body).toContain('realm === AUTH_REGION ? readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY) : null',diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex 13da101735..8d840c2e5a 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -386,7 +386,7 @@ describe('auth login-flow reset', () => {);});- it('repairs an interrupted active-session projection before cold-start refresh', () => {+ it('preserves compatibility and vault generations before cold-start refresh', () => {const helperStart = source.indexOf('async function reconcileDesktopActiveAuthSession()',);@@ -398,8 +398,54 @@ describe('auth login-flow reset', () => {expect(helperBody).toContain('authAccountVaultLockPath()');expect(helperBody).toContain("label: 'auth-account-vault-reconcile'");expect(helperBody).toContain('vault.resources[vault.activeAccountKey]');- expect(helperBody).toContain('session.refreshToken !== activeResource.refreshToken');+ expect(helperBody).toContain('if (!session)');expect(helperBody).toContain('writePersistedAuthSessionOrThrow(');+ expect(helperBody).toContain('return session;');++ const candidatesStart = source.indexOf(+ 'function readStoredRefreshTokenCandidates',+ );+ const candidatesEnd = source.indexOf(+ '\n}\n\nfunction readPersistedAccountDeletionReceipt',+ candidatesStart,+ );+ const candidatesBody = source.slice(candidatesStart, candidatesEnd);+ expect(candidatesBody).toContain('readPersistedRefreshToken(realm)');+ expect(candidatesBody).toContain('vault.resources[vault.activeAccountKey]');+ expect(candidatesBody).toContain('activeResource.refreshToken');++ const commitStart = source.indexOf(+ 'async function commitDesktopRefreshCredentials',+ );+ const commitEnd = source.indexOf(+ '\n}\n\n/**\n * Account refresh tokens have no replay grace.',+ commitStart,+ );+ const commitBody = source.slice(commitStart, commitEnd);+ expect(commitBody).toContain('vault.resources[key]?.refreshToken === requestedRefreshToken');++ const deadStart = source.indexOf(+ 'async function clearConfirmedDeadRefreshTokens',+ );+ const deadEnd = source.indexOf(+ '\n}\n\n/**\n * replacement-retry',+ deadStart,+ );+ const deadBody = source.slice(deadStart, deadEnd);+ expect(deadBody).toContain('await mutateAuthAccountVault((vault) => {');+ expect(deadBody).toContain('deadTokens.includes(activeResource.refreshToken)');+ expect(deadBody).toContain('delete vault.resources[activeKey];');+ expect(deadBody).toContain('vault.activeAccountKey = null;');++ const listStart = source.indexOf('export function listSavedAccounts()');+ const listEnd = source.indexOf(+ '\n}\n\nexport async function syncSavedAccounts',+ listStart,+ );+ const listBody = source.slice(listStart, listEnd);+ expect(listBody).toContain(+ 'const activeKey = currentUser ? accountVaultKey(activeAuthRealm, currentUser.id) : null;',+ );const initializeStart = source.indexOf('export async function initialize(');const initializeEnd = source.indexOf(diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 8c43eaa0a8..962272d087 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -1174,6 +1174,9 @@ async function commitDesktopRefreshCredentials(const latestSession = readPersistedAuthSession();const requestedTokenStillStored =(latestSession?.realm === realm && latestSession.refreshToken === requestedRefreshToken) ||+ (vault.activeAccountKey === key &&+ vault.resources[key]?.realm === realm &&+ vault.resources[key]?.refreshToken === requestedRefreshToken) ||(realm === AUTH_REGION &&readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY) === requestedRefreshToken);const canClaimUninitializedVault =@@ -1420,9 +1423,10 @@ function readPersistedAuthSession() {}/**- * The aggregate vault is the crash-consistent owner record. Repair its- * compatibility session projection under the same cross-process lock before- * cold start can send a refresh request with a consumed token generation.+ * Repair a missing compatibility projection from the aggregate vault. When+ * both exist but diverge, preserve both: a rollback build can rotate only the+ * compatibility session, while an interrupted new-build commit can leave the+ * vault newer. The refresh retry path asks the server which one is stale.*/async function reconcileDesktopActiveAuthSession(): Promise<ReturnType<typeof readPersistedAuthSession>@@ -1448,20 +1452,21 @@ async function reconcileDesktopActiveAuthSession(): Promise<? vault.resources[vault.activeAccountKey]: undefined;if (!activeResource) return session;- if (- session?.realm !== activeResource.realm ||- session.refreshToken !== activeResource.refreshToken- ) {+ if (!session) {writePersistedAuthSessionOrThrow(activeResource.refreshToken,activeResource.realm,);+ return {+ version: 1,+ realm: activeResource.realm,+ refreshToken: activeResource.refreshToken,+ };}- return {- version: 1,- realm: activeResource.realm,- refreshToken: activeResource.refreshToken,- };+ // A rollback build can rotate only the compatibility session. When the+ // two durable projections disagree, preserve both as refresh candidates;+ // the server's definitive response decides which generation is stale.+ return session;},);}@@ -1569,8 +1574,8 @@ function mirrorLegacyResourceRefreshToken(refreshToken: string, realm: AuthRegio}/**- * 确定性失效后清掉磁盘上所有「已确认死掉」的 refresh token —— v1 权威记录与 legacy- * 从属副本各清一次。+ * 确定性失效后清掉磁盘上所有「已确认死掉」的 refresh token —— account vault、+ * v1 兼容记录与 legacy 从属副本各清一次。** `deadTokens` 是本轮被服务端拒过的全部 token(按首次尝试顺序)。必须逐一比对而不是只* 认最初那一枚:本轮一旦从另一个来源追赶过,磁盘上现存的就是清单里较晚的那一枚,只拿@@ -1584,7 +1589,30 @@ function mirrorLegacyResourceRefreshToken(refreshToken: string, realm: AuthRegio* 运行期 `clearAuth` 已经会删这两个文件(那是显式登出 / 会话过期的整体清理),所以这里* 只补冷启动确定性失效这一条路径;passive 实例的守卫在调用点。*/-function clearConfirmedDeadRefreshTokens(realm: AuthRegion, deadTokens: readonly string[]): void {+async function clearConfirmedDeadRefreshTokens(+ realm: AuthRegion,+ deadTokens: readonly string[],+): Promise<void> {+ try {+ await mutateAuthAccountVault((vault) => {+ const activeKey = vault.activeAccountKey;+ const activeResource = activeKey ? vault.resources[activeKey] : undefined;+ if (+ !activeKey ||+ activeResource?.realm !== realm ||+ !deadTokens.includes(activeResource.refreshToken)+ ) {+ return;+ }+ delete vault.resources[activeKey];+ vault.activeAccountKey = null;+ });+ } catch (error) {+ log.error(+ 'cold-start refresh: failed to remove the confirmed-dead active Resource from the account vault',+ error,+ );+ }let sessionOutcome: RemoveIfUnchangedResult = 'changed';for (const token of deadTokens) {sessionOutcome = removeSafeIfUnchanged(@@ -1645,8 +1673,13 @@ function clearConfirmedDeadRefreshTokens(realm: AuthRegion, deadTokens: readonly* 的 token 挤掉 legacy 里真正有效的那枚,最终以确定性失效收场并连带删掉有效凭证。*/function readStoredRefreshTokenCandidates(realm: AuthRegion): readonly (string | null)[] {+ const vault = readAuthAccountVault();+ const activeResource = vault.activeAccountKey+ ? vault.resources[vault.activeAccountKey]+ : undefined;return [readPersistedRefreshToken(realm),+ activeResource?.realm === realm ? activeResource.refreshToken : null,realm === AUTH_REGION ? readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY) : null,];}@@ -3145,9 +3178,7 @@ export function listSavedAccounts(): DesktopAccountSwitcherSnapshot {if (!byKey.has(key)) byKey.set(key, membership);}}- const activeKey = currentUser- ? accountVaultKey(activeAuthRealm, currentUser.id)- : vault.activeAccountKey;+ const activeKey = currentUser ? accountVaultKey(activeAuthRealm, currentUser.id) : null;const accounts = [...byKey.entries()].map(([key, metadata]) => accountSummaryFromMetadata(key, metadata, activeKey)).sort((left, right) => {@@ -3937,7 +3968,7 @@ async function runColdStartRefreshFlow(// 的 token 做 compare-and-delete 会一律 changed,把已确认失效的凭证留在盘上,// 只读 legacy 的旧版实例继续拿它撞 INVALID_REFRESH_TOKEN 被强制重登。const confirmedDeadTokens = rejectedTokens.length > 0 ? rejectedTokens : [storedToken];- clearConfirmedDeadRefreshTokens(storedRealm, confirmedDeadTokens);+ await clearConfirmedDeadRefreshTokens(storedRealm, confirmedDeadTokens);}resetActiveAuthRealmToBuild();} else if (action.kind === 'foreign-device') {diff --git a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.tsindex bf136d01bf..df6c757e0c 100644--- a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts+++ b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts@@ -138,16 +138,25 @@ describe('auth weak-network bootstrap', () => {const reconcileAt = refreshBody.indexOf('reconcileMobileActiveAuthSession({',);- const readSessionAt = refreshBody.indexOf(- 'const session = reconciledAuth.session;',+ const readCandidatesAt = refreshBody.indexOf(+ 'const refreshCandidates = reconciledAuth.refreshCandidates;',reconcileAt,);- const emptySessionAt = refreshBody.indexOf('if (!session) {');+ const emptyCandidatesAt = refreshBody.indexOf(+ 'if (refreshCandidates.length === 0) {',+ readCandidatesAt,+ );const loadRealmAt = refreshBody.indexOf(- 'await loadMobileEndpointsForRealm(session.realm);',+ 'await loadMobileEndpointsForRealm(candidate.realm);',+ emptyCandidatesAt,+ );+ const requestRefreshAt = refreshBody.indexOf(+ 'candidatePair = await authClientFor(did, candidate.realm).refresh(',+ loadRealmAt,);const activateRealmAt = refreshBody.indexOf('activateMobileSessionRealm(session.realm);',+ requestRefreshAt,);const guards = [...refreshBody.matchAll(@@ -156,14 +165,17 @@ describe('auth weak-network bootstrap', () => {].map((match) => match.index);expect(reconcileAt).toBeGreaterThanOrEqual(0);- expect(readSessionAt).toBeGreaterThan(reconcileAt);+ expect(readCandidatesAt).toBeGreaterThan(reconcileAt);expect(- guards.some((index) => index > readSessionAt && index < emptySessionAt),+ guards.some(+ (index) => index > readCandidatesAt && index < emptyCandidatesAt,+ ),).toBe(true);- expect(loadRealmAt).toBeGreaterThan(emptySessionAt);+ expect(loadRealmAt).toBeGreaterThan(emptyCandidatesAt);expect(- guards.some((index) => index > loadRealmAt && index < activateRealmAt),+ guards.some((index) => index > loadRealmAt && index < requestRefreshAt),).toBe(true);+ expect(activateRealmAt).toBeGreaterThan(requestRefreshAt);});it('换账号或区域时先用旧会话撤销旧区域推送,再激活新区域', () => {diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.tsindex b22897ac48..4bdea30da2 100644--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts@@ -415,6 +415,39 @@ describe('mobile auth-server login', () => {expect(resourceStored).toBeGreaterThan(-1);expect(regionGuard).toBeGreaterThan(resourceStored);expect(switchBody).toContain("throw authCodeError('REGION_MISMATCH')");+ expect(switchBody).toContain('const runtimeActiveAccountKey = userRef.current');+ expect(switchBody).toContain('if (runtimeActiveAccountKey === accountKey) return;');+ });++ it('tries both compatibility and vault Resource generations before expiring auth', () => {+ const authSource = readFileSync(+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),+ 'utf8',+ );+ const refreshStart = authSource.indexOf('const refresh = useCallback');+ const refreshEnd = authSource.indexOf('\n useEffect(() => {', refreshStart);+ const refreshBody = authSource.slice(refreshStart, refreshEnd);++ expect(refreshBody).toContain('const refreshCandidates = reconciledAuth.refreshCandidates;');+ expect(refreshBody).toContain('for (const [index, candidate] of refreshCandidates.entries())');+ expect(refreshBody).toContain('rejectedRefreshTokens.push(candidate.refreshToken);');+ expect(refreshBody).toContain('compatibilityRefreshTokens: refreshCandidates');+ expect(refreshBody).toContain(+ 'rejectedRefreshTokens.includes(\n activeResourceAtStart.resource.refreshToken,',+ );++ const snapshotStart = authSource.indexOf(+ 'const refreshSavedAccountsSnapshot = useCallback',+ );+ const snapshotEnd = authSource.indexOf(+ '\n\n const refreshSavedAccountsSnapshotBestEffort',+ snapshotStart,+ );+ const snapshotBody = authSource.slice(snapshotStart, snapshotEnd);+ expect(snapshotBody).toContain('const runtimeActiveAccountKey = userRef.current');+ expect(snapshotBody).toContain(+ 'listMobileSavedAccounts(vault, runtimeActiveAccountKey)',+ );});it('rolls a failed account switch back to the latest serialized session', () => {diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsxindex 2d618d59ee..7b472c6ef7 100644--- a/apps/mobile/src/auth/AuthContext.tsx+++ b/apps/mobile/src/auth/AuthContext.tsx@@ -822,7 +822,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {const refreshSavedAccountsSnapshot = useCallback(async () => {const vault = await readMobileAccountVault();- setSavedAccounts(listMobileSavedAccounts(vault));+ const runtimeActiveAccountKey = userRef.current+ ? accountVaultKey(activeAuthRealmRef.current, userRef.current.id)+ : null;+ setSavedAccounts(listMobileSavedAccounts(vault, runtimeActiveAccountKey));}, []);const refreshSavedAccountsSnapshotBestEffort = useCallback((): void => {@@ -1124,20 +1127,47 @@ export function AuthProvider({ children }: { children: ReactNode }) {await clearCanaryChannel().catch(() => undefined);return null;}- const session = reconciledAuth.session;+ const refreshCandidates = reconciledAuth.refreshCandidates;if (authGenerationRef.current !== generation) return null;- if (!session) {+ if (refreshCandidates.length === 0) {await clearCanaryChannel().catch(() => undefined);return null;}+ let selectedSession: AuthSessionRecord | null = null;+ let candidatePair: Awaited<ReturnType<CindyAuthClient['refresh']>> | null = null;+ const rejectedRefreshTokens: string[] = [];try {- await loadMobileEndpointsForRealm(session.realm);- if (authGenerationRef.current !== generation) return null;+ for (const [index, candidate] of refreshCandidates.entries()) {+ selectedSession = candidate;+ try {+ await loadMobileEndpointsForRealm(candidate.realm);+ if (authGenerationRef.current !== generation) return null;+ candidatePair = await authClientFor(did, candidate.realm).refresh(+ candidate.refreshToken,+ );+ break;+ } catch (candidateError) {+ const rejected = isRejectedRefresh(candidateError);+ const deviceMismatch =+ candidateError instanceof AuthApiError &&+ candidateError.code === 'DEVICE_MISMATCH';+ if (rejected && !deviceMismatch) {+ rejectedRefreshTokens.push(candidate.refreshToken);+ }+ if (+ !rejected ||+ deviceMismatch ||+ index === refreshCandidates.length - 1+ ) {+ throw candidateError;+ }+ }+ }+ if (!selectedSession || !candidatePair) return null;+ const session = selectedSession;+ const pair = candidatePair;activateMobileSessionRealm(session.realm);activeAuthRealmRef.current = session.realm;- const pair = await authClientFor(did, session.realm).refresh(- session.refreshToken,- );if (authGenerationRef.current !== generation) return null;const passportId =pair.membership.passportId ??@@ -1147,12 +1177,18 @@ export function AuthProvider({ children }: { children: ReactNode }) {const persisted = await serializeRefreshTokenMutation(async () => {if (authGenerationRef.current !== generation) return false;if (!passportId) {- await writePersistedAuthSession(pair.refreshToken, session.realm);+ await writePersistedAuthSession(+ pair.refreshToken,+ session.realm,+ );return authGenerationRef.current === generation;}const resourceCommit =await commitMobileRuntimeResourceSession({expectedRefreshToken: session.refreshToken,+ compatibilityRefreshTokens: refreshCandidates+ .filter((candidate) => candidate.realm === session.realm)+ .map((candidate) => candidate.refreshToken),pair,realm: session.realm,passportId,@@ -1192,15 +1228,18 @@ export function AuthProvider({ children }: { children: ReactNode }) {refreshSavedAccountsSnapshotBestEffort();scheduleCanaryChannelSync(pair.accessToken, generation);scheduleXdOrgBetaDefault(pair.accessToken, generation);- void loadMe(pair.accessToken, did, generation).catch(() => undefined);+ void loadMe(pair.accessToken, did, generation).catch(+ () => undefined,+ );return pair.accessToken;} catch (error) {if (authGenerationRef.current !== generation) return null;if (isRejectedRefresh(error)) {const rejectedAccountKey =- activeResourceAtStart?.resource?.realm === session.realm &&- activeResourceAtStart.resource.refreshToken ===- session.refreshToken+ activeResourceAtStart?.resource &&+ rejectedRefreshTokens.includes(+ activeResourceAtStart.resource.refreshToken,+ )? activeResourceAtStart.accountKey: null;if (@@ -1213,7 +1252,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {try {const removal = await removeMobileResourceSessionIfCurrent({accountKey: rejectedAccountKey,- expectedRefreshToken: session.refreshToken,+ expectedRefreshToken:+ activeResourceAtStart!.resource!.refreshToken,validateBeforeWrite: () => {if (authGenerationRef.current !== generation) {throw authCodeError('AUTH_FLOW_SUPERSEDED');@@ -2192,7 +2232,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {async (accountKey: string): Promise<void> => {const generationAtStart = authGenerationRef.current;const initialVault = await readMobileAccountVault();- if (initialVault.activeAccountKey === accountKey) return;+ const runtimeActiveAccountKey = userRef.current+ ? accountVaultKey(activeAuthRealmRef.current, userRef.current.id)+ : null;+ if (runtimeActiveAccountKey === accountKey) return;const resource = initialVault.resources[accountKey];let metadata = resource?.metadata ?? null;let realm = resource?.realm ?? null;diff --git a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.tsindex 927c5cb4ea..fdfb20faa0 100644--- a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts+++ b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts@@ -119,9 +119,12 @@ describe('mobile account vault', () => {orgLogoUrl: 'https://example.com/org.png',}),]);+ expect(listMobileSavedAccounts(parseMobileAccountVault(raw), null)).toEqual([+ expect.objectContaining({ accountKey, isCurrent: false }),+ ]);});- it('repairs an interrupted compatibility-session write from the active vault before refresh', async () => {+ it('preserves divergent compatibility and vault generations as refresh candidates', async () => {const accountKey = JSON.stringify(['global', metadata.membershipId]);secureStorage.value = JSON.stringify({version: 1,@@ -161,12 +164,13 @@ describe('mobile account vault', () => {expect(reconciled.session).toEqual({version: 1,realm: 'global',- refreshToken: 'resource-new',+ refreshToken: 'resource-old',});- expect(writePersistedSession).toHaveBeenCalledWith(- 'resource-new',- 'global',- );+ expect(reconciled.refreshCandidates).toEqual([+ { version: 1, realm: 'global', refreshToken: 'resource-old' },+ { version: 1, realm: 'global', refreshToken: 'resource-new' },+ ]);+ expect(writePersistedSession).not.toHaveBeenCalled();expect(clearPersistedSession).not.toHaveBeenCalled();expect(secureStorage.set).not.toHaveBeenCalled();@@ -187,6 +191,49 @@ describe('mobile account vault', () => {expect(clearPersistedSession).toHaveBeenCalledTimes(1);});+ it('repairs a missing compatibility projection from the active vault', async () => {+ const accountKey = JSON.stringify(['global', metadata.membershipId]);+ secureStorage.value = JSON.stringify({+ version: 1,+ activeAccountKey: accountKey,+ resources: {+ [accountKey]: {+ realm: 'global',+ refreshToken: 'resource-new',+ metadata,+ lastUsedAt: 10,+ },+ },+ passports: {},+ });+ const writePersistedSession = vi.fn(async () => undefined);++ await expect(+ reconcileMobileActiveAuthSession({+ readPersistedSession: async () => null,+ writePersistedSession,+ clearPersistedSession: vi.fn(async () => undefined),+ }),+ ).resolves.toMatchObject({+ session: {+ version: 1,+ realm: 'global',+ refreshToken: 'resource-new',+ },+ refreshCandidates: [+ {+ version: 1,+ realm: 'global',+ refreshToken: 'resource-new',+ },+ ],+ });+ expect(writePersistedSession).toHaveBeenCalledWith(+ 'resource-new',+ 'global',+ );+ });+it('does not trust an active key whose resource credential is missing', () => {const raw = JSON.stringify({version: 1,@@ -444,6 +491,53 @@ describe('mobile account vault', () => {expect(afterPersist).toHaveBeenCalledTimes(1);});+ it('commits a refresh that proves a newer compatibility generation', async () => {+ const accountKey = JSON.stringify(['global', metadata.membershipId]);+ const pair = {+ accessToken: 'access-latest',+ refreshToken: 'resource-latest',+ membership: {+ id: metadata.membershipId,+ passportId: metadata.passportId,+ displayName: metadata.displayName,+ email: metadata.email,+ avatarUrl: metadata.avatarUrl,+ kind: metadata.kind,+ role: metadata.role,+ orgId: metadata.orgId,+ orgName: metadata.orgName,+ orgLogoUrl: metadata.orgLogoUrl,+ },+ };+ secureStorage.value = JSON.stringify({+ version: 1,+ activeAccountKey: accountKey,+ resources: {+ [accountKey]: {+ realm: 'global',+ refreshToken: 'vault-older',+ metadata,+ lastUsedAt: 10,+ },+ },+ passports: {},+ });++ await expect(+ commitMobileRuntimeResourceSession({+ expectedRefreshToken: 'compatibility-newer',+ compatibilityRefreshTokens: ['vault-older'],+ pair,+ realm: 'global',+ passportId: metadata.passportId,+ }),+ ).resolves.toBe('stored');+ expect(+ parseMobileAccountVault(secureStorage.value).resources[accountKey]+ ?.refreshToken,+ ).toBe('resource-latest');+ });+it('does not recreate a runtime Resource after a signed-out tombstone', async () => {const pair = {accessToken: 'access-late',diff --git a/apps/mobile/src/auth/mobileAccountVault.ts b/apps/mobile/src/auth/mobileAccountVault.tsindex 7aa9c93824..d662df6874 100644--- a/apps/mobile/src/auth/mobileAccountVault.ts+++ b/apps/mobile/src/auth/mobileAccountVault.ts@@ -195,13 +195,15 @@ export function transactMobileAccountVault<T>(export interface ReconciledMobileAuthState {vault: MobileAccountVault;session: AuthSessionRecord | null;+ refreshCandidates: AuthSessionRecord[];}/**- * Repair the compatibility auth session from the crash-consistent active- * Resource record before any refresh request can consume a stale generation.- * The vault queue remains owned through the repair so an account transition- * cannot interleave between the snapshot and the projection write.+ * Reconcile the compatibility session with the active Resource record before+ * refresh. A missing projection is repaired from the vault, but divergent+ * generations are both returned: rollback builds can rotate only the legacy+ * projection, while an interrupted new-build commit can leave the vault newer.+ * Only a definitive server response can identify the stale generation.*/export function reconcileMobileActiveAuthSession(input: {readPersistedSession: () => Promise<AuthSessionRecord | null>;@@ -218,29 +220,38 @@ export function reconcileMobileActiveAuthSession(input: {if (typeof vault.signedOutAt === 'number') {if (session) await input.clearPersistedSession();- return { vault, session: null };+ return { vault, session: null, refreshCandidates: [] };}const activeResource = vault.activeAccountKey? vault.resources[vault.activeAccountKey]: undefined;- if (!activeResource) return { vault, session };-- if (- session?.realm !== activeResource.realm ||- session.refreshToken !== activeResource.refreshToken- ) {+ const activeSession: AuthSessionRecord | null = activeResource+ ? {+ version: 1,+ realm: activeResource.realm,+ refreshToken: activeResource.refreshToken,+ }+ : null;+ if (!session && activeSession) {await input.writePersistedSession(- activeResource.refreshToken,- activeResource.realm,+ activeSession.refreshToken,+ activeSession.realm,);- session = {- version: 1,- realm: activeResource.realm,- refreshToken: activeResource.refreshToken,- };+ session = activeSession;+ }+ const refreshCandidates = session ? [session] : [];+ if (+ activeSession &&+ !refreshCandidates.some(+ (candidate) =>+ candidate.realm === activeSession.realm &&+ candidate.refreshToken === activeSession.refreshToken,+ )+ ) {+ refreshCandidates.push(activeSession);}- return { vault, session };+ return { vault, session, refreshCandidates };});}@@ -289,14 +300,17 @@ export async function clearMobileLoginCredentialsForLogout(input: {});}-export function listMobileSavedAccounts(vault: MobileAccountVault): MobileSavedAccount[] {+export function listMobileSavedAccounts(+ vault: MobileAccountVault,+ activeAccountKey = vault.activeAccountKey,+): MobileSavedAccount[] {const byKey = new Map<string, MobileSavedAccount>();for (const [key, resource] of Object.entries(vault.resources)) {byKey.set(key, {...resource.metadata,accountKey: key,realm: resource.realm,- isCurrent: key === vault.activeAccountKey,+ isCurrent: key === activeAccountKey,lastUsedAt: resource.lastUsedAt,});}@@ -308,7 +322,7 @@ export function listMobileSavedAccounts(vault: MobileAccountVault): MobileSavedA...metadata,accountKey: key,realm: passport.realm,- isCurrent: key === vault.activeAccountKey,+ isCurrent: key === activeAccountKey,lastUsedAt: 0,});}@@ -354,6 +368,7 @@ export type MobileResourceSessionReplacementResult =*/export async function commitMobileRuntimeResourceSession(input: {expectedRefreshToken: string;+ compatibilityRefreshTokens?: readonly string[];pair: AuthTokenPair;realm: AuthRegion;passportId: string;@@ -366,10 +381,14 @@ export async function commitMobileRuntimeResourceSession(input: {input.validateBeforeWrite?.();const current = vault.resources[key];if (current) {+ const acceptedPreviousTokens = new Set([+ input.expectedRefreshToken,+ ...(input.compatibilityRefreshTokens ?? []),+ ]);if (vault.activeAccountKey !== key ||current.realm !== input.realm ||- current.refreshToken !== input.expectedRefreshToken+ !acceptedPreviousTokens.has(current.refreshToken)) {return 'stale';}