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): persist desktop logout tombstone

xd-bobofb82ecea2536
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index cd02e4cc5a..ac03d64af3 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -383,6 +383,88 @@ describe('auth login-flow reset', () => {
expect(refreshAt).toBeGreaterThan(reconcileAt);
});
+ it('keeps logout-all durable across a crash between vault and session cleanup', () => {
+ expect(source).toContain('signedOutAt?: number;');
+
+ const clearStart = source.indexOf('async function clearAuthAccountVault(');
+ const clearEnd = source.indexOf(
+ '\n}\n\nfunction metadataFromMembership',
+ clearStart,
+ );
+ const clearBody = source.slice(clearStart, clearEnd);
+ expect(clearBody).toContain('withCrossProcessLock(');
+ expect(clearBody).toContain("label: 'auth-account-vault-clear'");
+ expect(clearBody).toContain('const vault = emptyAuthAccountVault();');
+ expect(clearBody).toContain('vault.activeAccountKey = null;');
+ expect(clearBody).toContain('vault.resources = {};');
+ expect(clearBody).toContain('vault.passports = {};');
+ expect(clearBody).toContain('vault.signedOutAt = Date.now();');
+ expect(clearBody.indexOf('writeAuthAccountVaultOrThrow(vault);')).toBeLessThan(
+ clearBody.indexOf('await afterPersist();'),
+ );
+
+ const reconcileStart = source.indexOf(
+ 'async function reconcileDesktopActiveAuthSession()',
+ );
+ const reconcileEnd = source.indexOf(
+ '\n}\n\nfunction readPersistedRefreshToken',
+ reconcileStart,
+ );
+ const reconcileBody = source.slice(reconcileStart, reconcileEnd);
+ const tombstoneGuard = reconcileBody.indexOf(
+ "typeof vault.signedOutAt === 'number'",
+ );
+ expect(tombstoneGuard).toBeGreaterThan(-1);
+ expect(reconcileBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(
+ tombstoneGuard,
+ );
+ expect(reconcileBody.indexOf('return null;')).toBeGreaterThan(tombstoneGuard);
+ expect(reconcileBody.indexOf('writePersistedAuthSessionOrThrow(')).toBeGreaterThan(
+ tombstoneGuard,
+ );
+
+ const refreshCommitStart = source.indexOf(
+ 'async function commitDesktopRefreshCredentials(',
+ );
+ const refreshCommitEnd = source.indexOf(
+ '\n}\n\n/**\n * Account refresh tokens',
+ refreshCommitStart,
+ );
+ expect(source.slice(refreshCommitStart, refreshCommitEnd)).toContain(
+ "typeof vault.signedOutAt !== 'number'",
+ );
+
+ const resourceWriteStart = source.indexOf('function writeResourceSessionToVault(');
+ const resourceWriteEnd = source.indexOf(
+ '\n}\n\nasync function rememberPassportSession',
+ resourceWriteStart,
+ );
+ const resourceWriteBody = source.slice(resourceWriteStart, resourceWriteEnd);
+ expect(resourceWriteBody).toContain('if (options.markActive !== false) {');
+ expect(resourceWriteBody).toContain('delete vault.signedOutAt;');
+
+ const loginCommitStart = source.indexOf('async function commitDesktopLoginSessions(');
+ const loginCommitEnd = source.indexOf(
+ '\n}\n\n/** Persist a rotated Passport',
+ loginCommitStart,
+ );
+ const loginCommitBody = source.slice(loginCommitStart, loginCommitEnd);
+ expect(loginCommitBody).toContain('if (!input.passportId) {');
+ expect(loginCommitBody).toContain('delete vault.signedOutAt;');
+
+ const logoutStart = source.indexOf('export async function logout(): Promise<void> {');
+ const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);
+ const logoutBody = source.slice(logoutStart, logoutEnd);
+ const tombstoneCommit = logoutBody.indexOf('await clearAuthAccountVault(() => {');
+ const ownerTeardown = logoutBody.indexOf('await withAccountFreeOwnerCommit({');
+ expect(tombstoneCommit).toBeGreaterThan(-1);
+ expect(logoutBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(
+ tombstoneCommit,
+ );
+ expect(ownerTeardown).toBeGreaterThan(tombstoneCommit);
+ expect(logoutBody).toContain('preservePersistedRefreshToken: true');
+ });
+
it('activates a restored realm only after the refreshed membership passes build policy', () => {
const initializeStart = source.indexOf('export async function initialize(');
const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 4a4f815020..1d4f79953b 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -232,6 +232,12 @@ interface AuthAccountVault {
activeAccountKey: string | null;
resources: Record<string, StoredResourceSession>;
passports: Record<string, StoredPassportSession>;
+ /**
+ * Durable logout-all marker. The vault is the crash-consistent owner record,
+ * so this must win over a compatibility session left behind by an interrupted
+ * logout until a new explicit login commits an active Resource.
+ */
+ signedOutAt?: number;
}
export interface AuthState {
@@ -664,7 +670,8 @@ function readAuthAccountVault(options: { allowUnreadable?: boolean } = {}): Auth
Array.isArray(parsed.resources) ||
!parsed.passports ||
typeof parsed.passports !== 'object' ||
- Array.isArray(parsed.passports)
+ Array.isArray(parsed.passports) ||
+ (parsed.signedOutAt !== undefined && typeof parsed.signedOutAt !== 'number')
) {
throw new Error('unsupported auth account vault');
}
@@ -719,6 +726,9 @@ function readAuthAccountVault(options: { allowUnreadable?: boolean } = {}): Auth
typeof parsed.activeAccountKey === 'string' ? parsed.activeAccountKey : null,
resources,
passports,
+ ...(typeof parsed.signedOutAt === 'number'
+ ? { signedOutAt: parsed.signedOutAt }
+ : {}),
};
} catch (error) {
log.warn('encrypted auth account vault is invalid; ignoring it without deleting', error);
@@ -806,13 +816,24 @@ async function mutateAuthAccountVault<T>(
return transactAuthAccountVault(operation);
}
-async function clearAuthAccountVault(): Promise<void> {
+async function clearAuthAccountVault(
+ afterPersist: () => void | Promise<void> = () => undefined,
+): Promise<void> {
await withCrossProcessLock(
authAccountVaultLockPath(),
{ label: 'auth-account-vault-clear', waitMs: 5_000 },
async (status) => {
if (!status.held) throw accountVaultLockError(status.reason);
- removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);
+ // Explicit logout must remain available even if an old vault is
+ // undecryptable. Replace it with a fresh fail-closed owner record rather
+ // than reading or deleting it first.
+ const vault = emptyAuthAccountVault();
+ vault.activeAccountKey = null;
+ vault.resources = {};
+ vault.passports = {};
+ vault.signedOutAt = Date.now();
+ writeAuthAccountVaultOrThrow(vault);
+ await afterPersist();
},
);
}
@@ -912,7 +933,10 @@ function writeResourceSessionToVault(
metadata: metadataFromMembership(pair.membership, passportId),
lastUsedAt: options.lastUsedAt ?? Date.now(),
};
- if (options.markActive !== false) vault.activeAccountKey = key;
+ if (options.markActive !== false) {
+ delete vault.signedOutAt;
+ vault.activeAccountKey = key;
+ }
}
async function rememberPassportSession(input: {
@@ -967,7 +991,13 @@ async function commitDesktopLoginSessions(
commitTransition: () => void | Promise<void>,
): Promise<void> {
await transactAuthAccountVault((vault) => {
- if (!input.passportId) return;
+ if (!input.passportId) {
+ // Legacy login responses may only be able to persist the compatibility
+ // session. They are still an explicit login and must supersede a prior
+ // logout-all tombstone so cold start can migrate the Resource later.
+ delete vault.signedOutAt;
+ return;
+ }
writeResourceSessionToVault(vault, input.pair, input.realm, input.passportId);
if (input.accountRefreshToken) {
writePassportSessionToVault(vault, {
@@ -1064,6 +1094,7 @@ async function commitDesktopRefreshCredentials(
const canClaimUninitializedVault =
options.allowUnclaimedVault === true &&
vault.activeAccountKey === null &&
+ typeof vault.signedOutAt !== 'number' &&
Object.keys(vault.resources).length === 0;
const stillOwnsActiveSession =
requestedTokenStillStored &&
@@ -1318,6 +1349,16 @@ async function reconcileDesktopActiveAuthSession(): Promise<
if (!status.held) throw accountVaultLockError(status.reason);
const vault = readAuthAccountVault();
const session = readPersistedAuthSession();
+ if (typeof vault.signedOutAt === 'number') {
+ // Logout-all persists this owner tombstone before removing the
+ // compatibility projection. If the process stopped between those
+ // writes, finish the projection cleanup without ever refreshing it.
+ removeSafe(AUTH_SESSION_KEY);
+ removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);
+ removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);
+ removeSafe(LEGACY_REFRESH_TOKEN_KEY);
+ return null;
+ }
const activeResource = vault.activeAccountKey
? vault.resources[vault.activeAccountKey]
: undefined;
@@ -4894,7 +4935,15 @@ export async function logout(): Promise<void> {
const currentAccountKey = currentUser
? accountVaultKey(activeAuthRealm, currentUser.id)
: savedVault.activeAccountKey;
- await clearAuthAccountVault();
+ await clearAuthAccountVault(() => {
+ // Publish the durable signed-out owner before clearing compatibility
+ // records. The vault lock remains held across both writes, and startup
+ // reconciliation completes this cleanup if the process dies in between.
+ removeSafe(AUTH_SESSION_KEY);
+ removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);
+ removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);
+ removeSafe(LEGACY_REFRESH_TOKEN_KEY);
+ });
// The shared projection state machine owns the full teardown and only then
// publishes the signed-out owner. The bootstrap IPC handler must not wrap a
// second independent boundary around this transition.
@@ -4916,6 +4965,7 @@ export async function logout(): Promise<void> {
reason: 'logout',
nextMode: 'signed-out',
clearOnFailure: true,
+ preservePersistedRefreshToken: true,
});
} catch (error) {
localTransitionError = error;