Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(auth): recover the active saved account

xd-bobob2b83c041c18
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index f7249dd9eb..291b33bb3e 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -578,6 +578,20 @@ describe('auth login-flow reset', () => {
expect(coldBody).toContain('allowUnclaimedVault: true');
expect(coldBody).toContain("epochChanged('before-cold-start-credential-commit')");
expect(coldBody).toContain("credentialCommit !== 'active'");
+ const inactiveCommit = coldBody.indexOf("credentialCommit !== 'active'");
+ const activeCandidateRead = coldBody.indexOf(
+ 'readActiveVaultRefreshCandidate()',
+ inactiveCommit,
+ );
+ const ownershipRetry = coldBody.indexOf(
+ 'return runColdStartRefreshFlow(',
+ activeCandidateRead,
+ );
+ expect(activeCandidateRead).toBeGreaterThan(inactiveCommit);
+ expect(ownershipRetry).toBeGreaterThan(activeCandidateRead);
+ expect(coldBody.slice(inactiveCommit, ownershipRetry)).toContain(
+ '!attemptedOwnershipTokens.has(nextActiveCandidate.refreshToken)',
+ );
expect(coldBody).not.toContain(
'writePersistedAuthSession(refreshData.refreshToken, storedRealm)',
);
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index eaedcf227c..eee4cd3445 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -1698,6 +1698,19 @@ function readStoredRefreshTokenCandidates(realm: AuthRegion): readonly (string |
];
}
+function readActiveVaultRefreshCandidate(): {
+ accountKey: string;
+ realm: AuthRegion;
+ refreshToken: string;
+} | null {
+ const vault = readAuthAccountVault();
+ const accountKey = vault.activeAccountKey;
+ const resource = accountKey ? vault.resources[accountKey] : undefined;
+ return accountKey && resource
+ ? { accountKey, realm: resource.realm, refreshToken: resource.refreshToken }
+ : null;
+}
+
function readPersistedAccountDeletionReceipt() {
const raw = readSafe(ACCOUNT_DELETION_RECEIPT_KEY);
const record = parseAccountDeletionReceiptRecord(raw);
@@ -3915,7 +3928,14 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
async function runColdStartRefreshFlow(
storedToken: string,
storedRealm: AuthRegion,
+ ownershipRecovery: {
+ attemptedTokens?: ReadonlySet<string>;
+ expectedActiveVaultAccountKey?: string;
+ hopsRemaining?: number;
+ } = {},
): Promise<AuthState> {
+ const attemptedOwnershipTokens = new Set(ownershipRecovery.attemptedTokens);
+ attemptedOwnershipTokens.add(storedToken);
const epochAtStart = authStateEpoch;
const epochChanged = (point: string): boolean => {
if (authStateEpoch === epochAtStart) return false;
@@ -3956,7 +3976,11 @@ async function runColdStartRefreshFlow(
return snapshotAuthState();
}
const latestSession = readPersistedAuthSession();
- if (latestSession && latestSession.realm !== storedRealm) {
+ if (
+ latestSession &&
+ latestSession.realm !== storedRealm &&
+ !ownershipRecovery.expectedActiveVaultAccountKey
+ ) {
// 共享 userData 的另一个实例已切到其它区域。旧区域请求无论成功失败都不能
// 覆盖/删除新原子记录;本实例本次以未登录返回,后续 initialize 可加载新清单。
log.warn('cold-start auth realm changed on disk; discarding stale refresh result');
@@ -4003,6 +4027,7 @@ async function runColdStartRefreshFlow(
}
const refreshData = refreshResult.data as RefreshResponse;
+ attemptedOwnershipTokens.add(requestedToken);
const credentialCommit = await commitDesktopRefreshCredentials(
refreshData,
storedRealm,
@@ -4024,6 +4049,26 @@ async function runColdStartRefreshFlow(
log.warn(
`cold-start refresh lost active credential ownership (${credentialCommit}); preserved only the still-saved account token`,
);
+ const nextActiveCandidate = readActiveVaultRefreshCandidate();
+ const hopsRemaining = ownershipRecovery.hopsRemaining ?? 3;
+ if (
+ nextActiveCandidate &&
+ hopsRemaining > 0 &&
+ !attemptedOwnershipTokens.has(nextActiveCandidate.refreshToken)
+ ) {
+ log.info(
+ 'cold-start refresh preserved a non-active rotation; continuing with the vault active account',
+ );
+ return runColdStartRefreshFlow(
+ nextActiveCandidate.refreshToken,
+ nextActiveCandidate.realm,
+ {
+ attemptedTokens: attemptedOwnershipTokens,
+ expectedActiveVaultAccountKey: nextActiveCandidate.accountKey,
+ hopsRemaining: hopsRemaining - 1,
+ },
+ );
+ }
return finishColdStartSignedOut('cold-start-credential-ownership-lost');
}
lastAcceptedRefreshToken = refreshData.refreshToken;
diff --git a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
index df6c757e0c..d2c3206bb3 100644
--- a/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
+++ b/apps/mobile/src/__tests__/authWeakNetworkBootstrap.test.ts
@@ -151,7 +151,7 @@ describe('auth weak-network bootstrap', () => {
emptyCandidatesAt,
);
const requestRefreshAt = refreshBody.indexOf(
- 'candidatePair = await authClientFor(did, candidate.realm).refresh(',
+ 'pair = await authClientFor(did, candidate.realm).refresh(',
loadRealmAt,
);
const activateRealmAt = refreshBody.indexOf(
diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
index 4bdea30da2..e6ee33f939 100644
--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
@@ -321,23 +321,36 @@ describe('mobile auth-server login', () => {
'clearPersistedSession: () => deleteSecureItem(AUTH_SESSION_KEY)',
);
const resourceVaultWrite = refreshBody.indexOf(
- 'await commitMobileRuntimeResourceSession({',
+ 'commitMobileRuntimeResourceSession({',
);
const publishAccessToken = refreshBody.indexOf(
'setToken(pair.accessToken);',
resourceVaultWrite,
);
+ const inactiveCommit = refreshBody.indexOf(
+ "if (resourceCommit === 'inactive') {",
+ resourceVaultWrite,
+ );
+ const selectActivePair = refreshBody.indexOf(
+ 'selectedSession = candidate;',
+ inactiveCommit,
+ );
expect(resourceVaultWrite).toBeGreaterThan(-1);
+ expect(inactiveCommit).toBeGreaterThan(resourceVaultWrite);
+ expect(selectActivePair).toBeGreaterThan(inactiveCommit);
expect(publishAccessToken).toBeGreaterThan(resourceVaultWrite);
expect(refreshBody.slice(resourceVaultWrite, publishAccessToken)).not.toContain(
'.catch(',
);
- expect(refreshBody).toMatch(
- /if \(authGenerationRef\.current !== generation\) return null;\s+const passportId =[\s\S]*?expectedRefreshToken: session\.refreshToken,[\s\S]*?if \(authGenerationRef\.current !== generation\) return null;\s+setToken\(pair\.accessToken\);/,
+ expect(refreshBody).toContain(
+ 'expectedRefreshToken: candidate.refreshToken',
+ );
+ expect(refreshBody.slice(inactiveCommit, selectActivePair)).toContain(
+ 'continue;',
);
expect(refreshBody).toContain('removeMobileResourceSessionIfCurrent({');
expect(refreshBody).toContain(
- 'expectedRefreshToken: session.refreshToken',
+ 'expectedRefreshToken:\n activeResourceAtStart!.resource!.refreshToken',
);
expect(refreshBody).toContain("error.code === 'DEVICE_MISMATCH'");
expect(refreshBody).not.toContain('removeMobileSavedAccount(');
@@ -432,6 +445,8 @@ describe('mobile auth-server login', () => {
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("if (resourceCommit === 'inactive') {");
+ expect(refreshBody).toContain('selectedSession = candidate;');
expect(refreshBody).toContain(
'rejectedRefreshTokens.includes(\n activeResourceAtStart.resource.refreshToken,',
);
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 7b472c6ef7..be5426e94a 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -1134,18 +1134,18 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return null;
}
let selectedSession: AuthSessionRecord | null = null;
- let candidatePair: Awaited<ReturnType<CindyAuthClient['refresh']>> | null = null;
+ let selectedPair: Awaited<ReturnType<CindyAuthClient['refresh']>> | null = null;
+ let selectedPassportId: string | undefined;
const rejectedRefreshTokens: string[] = [];
try {
for (const [index, candidate] of refreshCandidates.entries()) {
- selectedSession = candidate;
+ let pair: Awaited<ReturnType<CindyAuthClient['refresh']>>;
try {
await loadMobileEndpointsForRealm(candidate.realm);
if (authGenerationRef.current !== generation) return null;
- candidatePair = await authClientFor(did, candidate.realm).refresh(
+ pair = await authClientFor(did, candidate.realm).refresh(
candidate.refreshToken,
);
- break;
} catch (candidateError) {
const rejected = isRejectedRefresh(candidateError);
const deviceMismatch =
@@ -1161,61 +1161,91 @@ export function AuthProvider({ children }: { children: ReactNode }) {
) {
throw candidateError;
}
+ continue;
}
- }
- if (!selectedSession || !candidatePair) return null;
- const session = selectedSession;
- const pair = candidatePair;
- activateMobileSessionRealm(session.realm);
- activeAuthRealmRef.current = session.realm;
- if (authGenerationRef.current !== generation) return null;
- const passportId =
- pair.membership.passportId ??
- (userRef.current?.id === pair.membership.id
- ? userRef.current.passportId
- : undefined);
- const persisted = await serializeRefreshTokenMutation(async () => {
- if (authGenerationRef.current !== generation) return false;
- if (!passportId) {
- 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,
- validateBeforeWrite: () => {
- if (authGenerationRef.current !== generation) {
- throw authCodeError('AUTH_FLOW_SUPERSEDED');
- }
- },
- afterPersist: async () => {
- if (authGenerationRef.current !== generation) {
- throw authCodeError('AUTH_FLOW_SUPERSEDED');
+
+ if (authGenerationRef.current !== generation) return null;
+ const candidateAccountKey = accountVaultKey(
+ candidate.realm,
+ pair.membership.id,
+ );
+ const passportId =
+ pair.membership.passportId ??
+ persistedVault.resources[candidateAccountKey]?.metadata
+ .passportId ??
+ (userRef.current?.id === pair.membership.id
+ ? userRef.current.passportId
+ : undefined);
+ const resourceCommit = await serializeRefreshTokenMutation(
+ async () => {
+ if (authGenerationRef.current !== generation) return 'stale';
+ if (!passportId) {
+ if (
+ persistedVault.activeAccountKey &&
+ persistedVault.activeAccountKey !== candidateAccountKey
+ ) {
+ return 'inactive';
}
await writePersistedAuthSession(
pair.refreshToken,
- session.realm,
+ candidate.realm,
);
- if (authGenerationRef.current !== generation) {
- throw authCodeError('AUTH_FLOW_SUPERSEDED');
- }
- },
- });
- return (
- resourceCommit === 'stored' &&
- authGenerationRef.current === generation
+ return authGenerationRef.current === generation
+ ? 'active'
+ : 'stale';
+ }
+ return commitMobileRuntimeResourceSession({
+ expectedRefreshToken: candidate.refreshToken,
+ compatibilityRefreshTokens: refreshCandidates
+ .filter(
+ (refreshCandidate) =>
+ refreshCandidate.realm === candidate.realm,
+ )
+ .map(
+ (refreshCandidate) => refreshCandidate.refreshToken,
+ ),
+ pair,
+ realm: candidate.realm,
+ passportId,
+ validateBeforeWrite: () => {
+ if (authGenerationRef.current !== generation) {
+ throw authCodeError('AUTH_FLOW_SUPERSEDED');
+ }
+ },
+ afterPersist: async () => {
+ if (authGenerationRef.current !== generation) {
+ throw authCodeError('AUTH_FLOW_SUPERSEDED');
+ }
+ await writePersistedAuthSession(
+ pair.refreshToken,
+ candidate.realm,
+ );
+ if (authGenerationRef.current !== generation) {
+ throw authCodeError('AUTH_FLOW_SUPERSEDED');
+ }
+ },
+ });
+ },
);
- });
- if (!persisted) return null;
+ if (resourceCommit === 'stale') return null;
+ if (resourceCommit === 'inactive') {
+ // A successful refresh rotates the token even when this is only
+ // the stale compatibility account. Its replacement is durable;
+ // continue until the vault's active account wins the CAS.
+ refreshSavedAccountsSnapshotBestEffort();
+ continue;
+ }
+ selectedSession = candidate;
+ selectedPair = pair;
+ selectedPassportId = passportId;
+ break;
+ }
+ if (!selectedSession || !selectedPair) return null;
+ const session = selectedSession;
+ const pair = selectedPair;
+ const passportId = selectedPassportId;
+ activateMobileSessionRealm(session.realm);
+ activeAuthRealmRef.current = session.realm;
if (authGenerationRef.current !== generation) return null;
setToken(pair.accessToken);
applyUser(
diff --git a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
index fdfb20faa0..6b7ffa0b90 100644
--- a/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
+++ b/apps/mobile/src/auth/__tests__/mobileAccountVault.test.ts
@@ -377,7 +377,7 @@ describe('mobile account vault', () => {
).toBe('resource-new');
});
- it('commits a runtime refresh only for its active Resource owner and token generation', async () => {
+ it('preserves an inactive refresh without letting it reclaim the active account', async () => {
const accountKey = JSON.stringify(['global', metadata.membershipId]);
const otherAccountKey = JSON.stringify(['global', 'membership-2']);
const afterPersist = vi.fn(async () => undefined);
@@ -425,10 +425,10 @@ describe('mobile account vault', () => {
passportId: metadata.passportId,
afterPersist,
}),
- ).resolves.toBe('stale');
+ ).resolves.toBe('inactive');
const vault = parseMobileAccountVault(secureStorage.value);
expect(vault.activeAccountKey).toBe(otherAccountKey);
- expect(vault.resources[accountKey]?.refreshToken).toBe('resource-old');
+ expect(vault.resources[accountKey]?.refreshToken).toBe('resource-late');
expect(vault.resources[otherAccountKey]?.refreshToken).toBe(
'resource-new-login',
);
@@ -483,7 +483,7 @@ describe('mobile account vault', () => {
passportId: metadata.passportId,
afterPersist,
}),
- ).resolves.toBe('stored');
+ ).resolves.toBe('active');
expect(
parseMobileAccountVault(secureStorage.value).resources[accountKey]
?.refreshToken,
@@ -531,7 +531,7 @@ describe('mobile account vault', () => {
realm: 'global',
passportId: metadata.passportId,
}),
- ).resolves.toBe('stored');
+ ).resolves.toBe('active');
expect(
parseMobileAccountVault(secureStorage.value).resources[accountKey]
?.refreshToken,
diff --git a/apps/mobile/src/auth/mobileAccountVault.ts b/apps/mobile/src/auth/mobileAccountVault.ts
index d662df6874..a542948ed4 100644
--- a/apps/mobile/src/auth/mobileAccountVault.ts
+++ b/apps/mobile/src/auth/mobileAccountVault.ts
@@ -362,9 +362,11 @@ export type MobileResourceSessionReplacementResult =
| 'missing';
/**
- * Commit an active runtime session refresh only while it still owns the active
- * Resource token generation. A missing entry is accepted solely for the
- * one-time legacy migration where no vault account has been activated yet.
+ * Commit a runtime refresh only while it still owns that Resource generation.
+ * A non-active compatibility account keeps its rotated replacement without
+ * reclaiming `activeAccountKey`; only an active result publishes the
+ * compatibility session in `afterPersist`. A missing entry may be recreated
+ * after a proved refresh unless a logout-all tombstone forbids every write.
*/
export async function commitMobileRuntimeResourceSession(input: {
expectedRefreshToken: string;
@@ -374,32 +376,30 @@ export async function commitMobileRuntimeResourceSession(input: {
passportId: string;
validateBeforeWrite?: () => void;
afterPersist?: () => void | Promise<void>;
-}): Promise<'stored' | 'stale'> {
+}): Promise<'active' | 'inactive' | 'stale'> {
const key = accountVaultKey(input.realm, input.pair.membership.id);
return transactMobileAccountVault(
(vault) => {
input.validateBeforeWrite?.();
const current = vault.resources[key];
+ const acceptedPreviousTokens = new Set([
+ input.expectedRefreshToken,
+ ...(input.compatibilityRefreshTokens ?? []),
+ ]);
if (current) {
- const acceptedPreviousTokens = new Set([
- input.expectedRefreshToken,
- ...(input.compatibilityRefreshTokens ?? []),
- ]);
if (
- vault.activeAccountKey !== key ||
current.realm !== input.realm ||
!acceptedPreviousTokens.has(current.refreshToken)
) {
return 'stale';
}
- } else if (
- vault.activeAccountKey !== null ||
- typeof vault.signedOutAt === 'number'
- ) {
+ } else if (typeof vault.signedOutAt === 'number') {
return 'stale';
}
- delete vault.signedOutAt;
+ const ownsActiveAccount = vault.activeAccountKey === key;
+ const canClaimUninitializedVault =
+ !current && vault.activeAccountKey === null;
vault.resources[key] = {
realm: input.realm,
refreshToken: input.pair.refreshToken,
@@ -409,11 +409,19 @@ export async function commitMobileRuntimeResourceSession(input: {
),
lastUsedAt: Date.now(),
};
- vault.activeAccountKey = key;
- return 'stored';
+ if (ownsActiveAccount || canClaimUninitializedVault) {
+ delete vault.signedOutAt;
+ vault.activeAccountKey = key;
+ return 'active';
+ }
+ // A compatibility candidate can belong to a saved but non-active
+ // account after an interrupted switch. Preserve its rotated token while
+ // leaving the vault's active owner untouched; the caller must continue
+ // until another candidate commits as active.
+ return 'inactive';
},
async (result) => {
- if (result === 'stored') await input.afterPersist?.();
+ if (result === 'active') await input.afterPersist?.();
},
);
}