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(desktop): preserve add-account auth realm

xd-bobo3e3da8b27c73
diff --git a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts b/apps/desktop/src/main/__tests__/authHostedCallback.test.ts
index d486dfb4ec..4dd80a4902 100644
--- a/apps/desktop/src/main/__tests__/authHostedCallback.test.ts
+++ b/apps/desktop/src/main/__tests__/authHostedCallback.test.ts
@@ -267,7 +267,9 @@ describe('openSystemBrowserAuthorization 分流', () => {
expect(start).toBeGreaterThan(-1);
const body = source.slice(start, source.indexOf('\n}', start));
- expect(body).toContain('pendingAuthRealm ?? activeAuthRealm');
+ expect(body).toContain('client: CindyAuthClient');
+ expect(body).toContain('loginRealm: AuthRegion');
+ expect(body).not.toContain('pendingAuthRealm ?? activeAuthRealm');
expect(body).toContain(
"getClientEndpointForRealm(loginRealm, 'authDesktopCallbackUrl')",
);
@@ -276,6 +278,33 @@ describe('openSystemBrowserAuthorization 分流', () => {
expect(body).toContain(': openLoopbackBrowserAuthorization(');
});
+ it('authorize、callback 与轮询复用 action 冻结的 auth client', () => {
+ const hostedStart = source.indexOf('async function openHostedBrowserAuthorization(');
+ const hostedBody = source.slice(hostedStart, source.indexOf('\n}\n', hostedStart));
+ const loopbackStart = source.indexOf('async function openLoopbackBrowserAuthorization(');
+ const loopbackBody = source.slice(
+ loopbackStart,
+ source.indexOf('\n}\n\n// ── Refresh scheduling', loopbackStart),
+ );
+ const actionStart = source.indexOf('async function runLoginAction(action: DesktopLoginAction)');
+ const actionBody = source.slice(
+ actionStart,
+ source.indexOf('\n}\n\nexport async function dispatchLoginAction', actionStart),
+ );
+
+ expect(hostedBody).toContain('client: CindyAuthClient');
+ expect(hostedBody).toContain('client.buildAuthorizeUrl(');
+ expect(hostedBody).not.toContain('createAuthClient()');
+ expect(loopbackBody).toContain('client: CindyAuthClient');
+ expect(loopbackBody).toContain('client.buildAuthorizeUrl(');
+ expect(loopbackBody).not.toContain('createAuthClient()');
+ expect(actionBody).toContain('const client = createAuthClient(loginRealm);');
+ expect(actionBody).toContain(
+ 'openSystemBrowserAuthorization(\n client,\n loginRealm,',
+ );
+ expect(actionBody).toContain('client.exchangeAuthorizationCode(');
+ });
+
/**
* 取回凭据必须与走浏览器的 state 分离。写回 input.state 会让任何能读浏览历史的
* 扩展 / 同机进程抢先消费掉一次性结果,把真实客户端顶成 expired。
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index 50b873f532..5458d3a9fe 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -83,7 +83,7 @@ describe('auth login-flow reset', () => {
expect(confirmBody).not.toContain("type: 'start-browser'");
});
- it('clears stale organization realm state before personal login and a new discovery', () => {
+ it('pins personal login to the build realm and clears stale realm before organization discovery', () => {
const discoveryStart = source.indexOf('async function discoverOrganizationRealm(');
const discoveryBody = source.slice(discoveryStart, source.indexOf('\n}', discoveryStart));
expect(discoveryBody).toContain('pendingAuthRealm = null;');
@@ -97,7 +97,16 @@ describe('auth login-flow reset', () => {
expect(actionPreamble).toContain("action.type === 'request-code'");
expect(actionPreamble).toContain("action.type === 'verify-code'");
expect(actionPreamble).toContain("action.type === 'start-browser' && action.kind === 'social'");
- expect(actionPreamble).toContain('if (startsBuildRealmFlow) pendingAuthRealm = null;');
+ expect(actionPreamble).toContain('? AUTH_REGION');
+ expect(actionPreamble).toContain('const client = createAuthClient(loginRealm);');
+
+ const personalActionSetup = source.slice(
+ source.indexOf('if (!providerConfig) await loadLoginProviders', actionStart),
+ source.indexOf("if (action.type === 'discover')", actionStart),
+ );
+ expect(personalActionSetup).toContain(
+ 'if (startsBuildRealmFlow) pendingAuthRealm = loginRealm;',
+ );
});
it('does not leave expired private tickets on a screen that can only reuse them', () => {
@@ -201,9 +210,7 @@ describe('auth login-flow reset', () => {
const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);
const readBody = source.slice(readStart, readEnd);
- expect(readBody).toContain(
- 'if (options.allowUnreadable || options.recoverInvalid) continue;',
- );
+ expect(readBody).toContain('if (options.allowUnreadable || options.recoverInvalid) continue;');
expect(readBody).toContain("throw new Error('invalid saved resource credential')");
expect(readBody).toContain("throw new Error('invalid saved Passport credential')");
expect(readBody).toContain("throw new Error('invalid saved Passport membership')");
@@ -229,23 +236,16 @@ describe('auth login-flow reset', () => {
);
const transactionBody = source.slice(transactionStart, transactionEnd);
expect(transactionBody).toContain('recoverInvalidForExplicitLogin?: boolean');
- expect(transactionBody).toContain(
- 'recoverInvalid: options.recoverInvalidForExplicitLogin',
- );
+ expect(transactionBody).toContain('recoverInvalid: options.recoverInvalidForExplicitLogin');
const loginStart = source.indexOf('async function commitDesktopLoginSessions(');
- const loginEnd = source.indexOf(
- '\n}\n\n/** Persist a rotated Passport',
- loginStart,
- );
+ const loginEnd = source.indexOf('\n}\n\n/** Persist a rotated Passport', loginStart);
const loginBody = source.slice(loginStart, loginEnd);
expect(loginBody).toContain('recoverInvalidForExplicitLogin: true');
expect(loginBody).toContain('waitWhileBusyAfterRotation: true');
const transitionCommit = loginBody.indexOf('await transition.commit();');
const transitionRollback = loginBody.indexOf('await transition.rollback();');
- expect(transitionCommit).toBeGreaterThan(
- loginBody.indexOf('await transactAuthAccountVault('),
- );
+ expect(transitionCommit).toBeGreaterThan(loginBody.indexOf('await transactAuthAccountVault('));
expect(transitionRollback).toBeGreaterThan(transitionCommit);
expect(transitionRollback).toBeLessThan(
loginBody.indexOf('recoverInvalidForExplicitLogin: true'),
@@ -272,7 +272,10 @@ describe('auth login-flow reset', () => {
it('waits through a busy vault lock after the server has rotated a credential', () => {
const rotatedCredentialHelpers = [
['async function rememberResourceSession(', '\n}\n\ntype ResourceSessionReplacementResult'],
- ['async function replaceResourceSessionIfCurrent(', '\n}\n\ntype RejectedResourceSessionRemovalResult'],
+ [
+ 'async function replaceResourceSessionIfCurrent(',
+ '\n}\n\ntype RejectedResourceSessionRemovalResult',
+ ],
['async function replacePassportSessionIfCurrent(', '\n}\n\n/** Delete a rejected Passport'],
['async function commitDesktopRefreshCredentials(', '\n}\n\n/**\n * Account refresh tokens'],
] as const;
@@ -281,9 +284,7 @@ describe('auth login-flow reset', () => {
const start = source.indexOf(startMarker);
const end = source.indexOf(endMarker, start);
expect(start).toBeGreaterThan(-1);
- expect(source.slice(start, end)).toContain(
- 'waitWhileBusyAfterRotation: true',
- );
+ expect(source.slice(start, end)).toContain('waitWhileBusyAfterRotation: true');
}
});
@@ -307,7 +308,7 @@ describe('auth login-flow reset', () => {
);
});
- it('invalidates every pending add-account action when its surface closes', () => {
+ it('invalidates pending add-account actions without cancelling an accepted login commit', () => {
const runStart = source.indexOf('async function runLoginAction(action: DesktopLoginAction)');
const runEnd = source.indexOf('\n}\n\nexport async function dispatchLoginAction', runStart);
const runBody = source.slice(runStart, runEnd);
@@ -320,6 +321,10 @@ describe('auth login-flow reset', () => {
const completeBody = source.slice(completeStart, completeEnd);
expect(completeBody).toContain('expectedLoginFlowEpoch = loginFlowEpoch');
expect(completeBody).toContain('loginFlowEpoch !== expectedLoginFlowEpoch');
+ expect(completeBody).toContain(
+ 'const releaseLoginFlowCommit = sealLoginFlowCommit(expectedLoginFlowEpoch);',
+ );
+ expect(completeBody).toContain('releaseLoginFlowCommit();');
const vaultTransaction = completeBody.indexOf('await commitDesktopLoginSessions(');
const durableSession = completeBody.indexOf('writePersistedAuthSessionOrThrow(');
const teardown = completeBody.indexOf('await accountSwitchTeardown(');
@@ -329,8 +334,13 @@ describe('auth login-flow reset', () => {
expect(completeBody).toContain('restorePersistedAuthSessionIfCurrent(');
const cancelStart = source.indexOf('export function cancelAddAccountLogin(): void {');
- const cancelEnd = source.indexOf('\n}', cancelStart);
- expect(source.slice(cancelStart, cancelEnd)).toContain('loginFlowEpoch += 1;');
+ const cancelEnd = source.indexOf('\n}\n\nexport function getCurrentDataOwnerId', cancelStart);
+ const cancelBody = source.slice(cancelStart, cancelEnd);
+ expect(cancelBody).toContain('if (isLoginFlowCommitSealed(loginFlowEpoch))');
+ expect(cancelBody).toContain('loginFlowEpoch += 1;');
+ expect(cancelBody.indexOf('isLoginFlowCommitSealed')).toBeLessThan(
+ cancelBody.indexOf('loginFlowEpoch += 1;'),
+ );
});
it('single-flights Passport refresh and rejects cross-realm personal account switching', () => {
@@ -411,9 +421,7 @@ describe('auth login-flow reset', () => {
const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);
const initializeBody = source.slice(initializeStart, initializeEnd);
const localGuard = initializeBody.indexOf("getActiveAppSession().mode === 'local'");
- const refreshTokenRead = initializeBody.indexOf(
- 'await reconcileDesktopActiveAuthSession()',
- );
+ const refreshTokenRead = initializeBody.indexOf('await reconcileDesktopActiveAuthSession()');
expect(localGuard).toBeGreaterThan(-1);
expect(refreshTokenRead).toBeGreaterThan(localGuard);
@@ -423,13 +431,8 @@ describe('auth login-flow reset', () => {
});
it('preserves compatibility and vault generations before cold-start refresh', () => {
- const helperStart = source.indexOf(
- 'async function reconcileDesktopActiveAuthSession()',
- );
- const helperEnd = source.indexOf(
- '\n}\n\nfunction readPersistedRefreshToken',
- helperStart,
- );
+ const helperStart = source.indexOf('async function reconcileDesktopActiveAuthSession()');
+ const helperEnd = source.indexOf('\n}\n\nfunction readPersistedRefreshToken', helperStart);
const helperBody = source.slice(helperStart, helperEnd);
expect(helperBody).toContain('authAccountVaultLockPath()');
expect(helperBody).toContain("label: 'auth-account-vault-reconcile'");
@@ -438,9 +441,7 @@ describe('auth login-flow reset', () => {
expect(helperBody).toContain('writePersistedAuthSessionOrThrow(');
expect(helperBody).toContain('return session;');
- const candidatesStart = source.indexOf(
- 'function readStoredRefreshTokenCandidates',
- );
+ const candidatesStart = source.indexOf('function readStoredRefreshTokenCandidates');
const candidatesEnd = source.indexOf(
'\n}\n\nfunction readPersistedAccountDeletionReceipt',
candidatesStart,
@@ -450,9 +451,7 @@ describe('auth login-flow reset', () => {
expect(candidatesBody).toContain('vault.resources[vault.activeAccountKey]');
expect(candidatesBody).toContain('activeResource.refreshToken');
- const commitStart = source.indexOf(
- 'async function commitDesktopRefreshCredentials',
- );
+ const commitStart = source.indexOf('async function commitDesktopRefreshCredentials');
const commitEnd = source.indexOf(
'\n}\n\n/**\n * Account refresh tokens have no replay grace.',
commitStart,
@@ -460,13 +459,8 @@ describe('auth login-flow reset', () => {
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 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)');
@@ -474,24 +468,16 @@ describe('auth login-flow reset', () => {
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 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(
- '\n}\n\n/**\n * 冷启动 refresh 流程本体',
- initializeStart,
- );
+ const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);
const initializeBody = source.slice(initializeStart, initializeEnd);
- const reconcileAt = initializeBody.indexOf(
- 'await reconcileDesktopActiveAuthSession()',
- );
+ const reconcileAt = initializeBody.indexOf('await reconcileDesktopActiveAuthSession()');
const refreshAt = initializeBody.indexOf(
'runColdStartRefreshFlow(storedToken, persistedSession.realm)',
);
@@ -503,10 +489,7 @@ describe('auth login-flow reset', () => {
expect(source).toContain('signedOutAt?: number;');
const clearStart = source.indexOf('async function clearAuthAccountVault(');
- const clearEnd = source.indexOf(
- '\n}\n\nfunction metadataFromMembership',
- clearStart,
- );
+ 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'");
@@ -519,29 +502,21 @@ describe('auth login-flow reset', () => {
clearBody.indexOf('await afterPersist();'),
);
- const reconcileStart = source.indexOf(
- 'async function reconcileDesktopActiveAuthSession()',
- );
+ 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'",
- );
+ const tombstoneGuard = reconcileBody.indexOf("typeof vault.signedOutAt === 'number'");
expect(tombstoneGuard).toBeGreaterThan(-1);
- expect(reconcileBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(
- tombstoneGuard,
- );
+ 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 refreshCommitStart = source.indexOf('async function commitDesktopRefreshCredentials(');
const refreshCommitEnd = source.indexOf(
'\n}\n\n/**\n * Account refresh tokens',
refreshCommitStart,
@@ -574,9 +549,7 @@ describe('auth login-flow reset', () => {
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(logoutBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(tombstoneCommit);
expect(ownerTeardown).toBeGreaterThan(tombstoneCommit);
expect(logoutBody).toContain('preservePersistedRefreshToken: true');
});
@@ -591,9 +564,7 @@ describe('auth login-flow reset', () => {
const coldStart = source.indexOf('async function runColdStartRefreshFlow(');
const coldEnd = source.indexOf('\n}\n\nasync function loadLoginProviders()', coldStart);
const coldBody = source.slice(coldStart, coldEnd);
- const coldCredentialCommit = coldBody.indexOf(
- 'await commitDesktopRefreshCredentials(',
- );
+ const coldCredentialCommit = coldBody.indexOf('await commitDesktopRefreshCredentials(');
const coldPolicyGuard = coldBody.indexOf('!canRestoreAuthSessionForMembership(');
const coldRealmActivation = coldBody.indexOf('activateClientEndpointRealm(storedRealm);');
expect(coldCredentialCommit).toBeGreaterThan(-1);
@@ -609,10 +580,7 @@ describe('auth login-flow reset', () => {
'readActiveVaultRefreshCandidate()',
inactiveCommit,
);
- const ownershipRetry = coldBody.indexOf(
- 'return runColdStartRefreshFlow(',
- activeCandidateRead,
- );
+ const ownershipRetry = coldBody.indexOf('return runColdStartRefreshFlow(', activeCandidateRead);
expect(activeCandidateRead).toBeGreaterThan(inactiveCommit);
expect(ownershipRetry).toBeGreaterThan(activeCandidateRead);
expect(coldBody.slice(inactiveCommit, ownershipRetry)).toContain(
@@ -819,9 +787,7 @@ describe('auth login-flow reset', () => {
serializedRepairStart,
);
const serializedRepairBody = source.slice(serializedRepairStart, serializedRepairEnd);
- expect(serializedRepairBody).toContain(
- 'withStableOwnerBoundaryMutation(ownerId',
- );
+ expect(serializedRepairBody).toContain('withStableOwnerBoundaryMutation(ownerId');
expect(serializedRepairBody).toContain(
'repairStableCloudOwnerDataReservationsWhileLocked(ownerId)',
);
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index 628caf0777..4b744336fe 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -344,7 +344,10 @@ let accessToken: string | null = null;
let currentUser: CurrentUser | null = null;
/** 已登录会话区域;安装包区域 AUTH_REGION 始终不变。 */
let activeAuthRealm: AuthRegion = AUTH_REGION;
-/** 企业发现成功后冻结到整次 SSO 流程,reset/cancel/失败回收时清除。 */
+/**
+ * 当前登录流使用的区域。个人登录固定为安装包区域,企业发现后改为组织区域;
+ * 账号选择、绑定等后续步骤继续复用,reset/cancel/失败回收时清除。
+ */
let pendingAuthRealm: AuthRegion | null = null;
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
let refreshPromise: Promise<boolean> | null = null;
@@ -390,6 +393,12 @@ let loginActionPromiseEpoch: number | null = null;
// Separate from authStateEpoch: closing an add-account surface must invalidate
// its requests without expiring the still-active account's runtime refresh.
let loginFlowEpoch = 0;
+// Once an accepted login starts its durable owner transaction, renderer teardown
+// may unmount the add-account route as part of the boundary-pending projection.
+// That lifecycle cleanup must not supersede the transaction it just triggered.
+// A depth map keeps the guard correct even if two same-epoch commits briefly
+// overlap before authStateEpoch rejects the stale one.
+const sealedLoginFlowCommitDepths = new Map<number, number>();
// `accountDeletionRestored` may arrive before membership selection. Keep it
// main-only until the final resource-token login commits.
let pendingAccountDeletionRestored = false;
@@ -809,16 +818,13 @@ function readAuthAccountVault(
memberships,
};
}
- const active =
- typeof parsed.activeAccountKey === 'string' ? parsed.activeAccountKey : null;
+ const active = typeof parsed.activeAccountKey === 'string' ? parsed.activeAccountKey : null;
return {
version: 1,
activeAccountKey: active && resources[active] ? active : null,
resources,
passports,
- ...(typeof parsed.signedOutAt === 'number'
- ? { signedOutAt: parsed.signedOutAt }
- : {}),
+ ...(typeof parsed.signedOutAt === 'number' ? { signedOutAt: parsed.signedOutAt } : {}),
};
} catch (error) {
if (options.recoverInvalid) {
@@ -905,7 +911,10 @@ async function transactAuthAccountVault<T>(
} catch (error) {
if (previousWasAbsent) {
removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);
- } else if (previousRaw !== null && !writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, previousRaw)) {
+ } else if (
+ previousRaw !== null &&
+ !writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, previousRaw)
+ ) {
throw new AuthApiError(
'CREDENTIAL_STORE_UNAVAILABLE',
503,
@@ -1249,8 +1258,7 @@ async function commitDesktopRefreshCredentials(
typeof vault.signedOutAt !== 'number' &&
Object.keys(vault.resources).length === 0;
const stillOwnsActiveSession =
- requestedTokenStillStored &&
- (vault.activeAccountKey === key || canClaimUninitializedVault);
+ requestedTokenStillStored && (vault.activeAccountKey === key || canClaimUninitializedVault);
const passportId = pair.membership.passportId;
if (passportId && (stillOwnsActiveSession || vault.resources[key])) {
// A passive stale refresh may still rotate account A's resource token
@@ -1524,10 +1532,7 @@ async function reconcileDesktopActiveAuthSession(): Promise<
: undefined;
if (!activeResource) return session;
if (!session) {
- writePersistedAuthSessionOrThrow(
- activeResource.refreshToken,
- activeResource.realm,
- );
+ writePersistedAuthSessionOrThrow(activeResource.refreshToken, activeResource.realm);
return {
version: 1,
realm: activeResource.realm,
@@ -2532,6 +2537,7 @@ function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
* 这里另生成一对凭据,只把哈希后的 clientState 交给 authorize。
*/
async function openHostedBrowserAuthorization(
+ client: CindyAuthClient,
input: BrowserAuthorizationInput,
redirectUri: string,
signal: AbortSignal,
@@ -2539,7 +2545,6 @@ async function openHostedBrowserAuthorization(
if (signal.aborted) return { error: 'USER_CANCELLED' };
const { clientState, pollSecret } = createDesktopPollCredentials();
- const client = createAuthClient();
const authUrl = client.buildAuthorizeUrl({ ...input, state: clientState, redirectUri });
// 整次尝试共用一个截止时间:唤起浏览器与随后的轮询都从这份预算里花,和 loopback
@@ -2587,17 +2592,19 @@ async function openHostedBrowserAuthorization(
/** 按端点清单分流到托管回调或 loopback(语义见本节顶部注释)。 */
async function openSystemBrowserAuthorization(
+ client: CindyAuthClient,
+ loginRealm: AuthRegion,
input: BrowserAuthorizationInput,
signal: AbortSignal,
): Promise<{ code: string } | { error: string }> {
- const loginRealm = pendingAuthRealm ?? activeAuthRealm;
const hostedCallbackUrl = getClientEndpointForRealm(loginRealm, 'authDesktopCallbackUrl');
return hostedCallbackUrl
- ? openHostedBrowserAuthorization(input, hostedCallbackUrl, signal)
- : openLoopbackBrowserAuthorization(input, signal);
+ ? openHostedBrowserAuthorization(client, input, hostedCallbackUrl, signal)
+ : openLoopbackBrowserAuthorization(client, input, signal);
}
async function openLoopbackBrowserAuthorization(
+ client: CindyAuthClient,
input: BrowserAuthorizationInput,
signal: AbortSignal,
): Promise<{ code: string } | { error: string }> {
@@ -2672,7 +2679,7 @@ async function openLoopbackBrowserAuthorization(
}
const address = server.address() as AddressInfo;
const redirectUri = `http://127.0.0.1:${address.port}/auth/callback`;
- const authUrl = createAuthClient().buildAuthorizeUrl({ ...input, redirectUri });
+ const authUrl = client.buildAuthorizeUrl({ ...input, redirectUri });
// dev bridge 挂接(packaged no-op):fixture 触发与真实回调走同一渲染/finish。
authLoopbackDevBridgeSlot.attach(finish, renderCallbackPage);
timeout = setTimeout(() => finish({ error: 'USER_CANCELLED' }), BROWSER_AUTH_TIMEOUT_MS);
@@ -3171,6 +3178,25 @@ function assertLoginFlowCurrent(expectedEpoch: number): void {
);
}
+function sealLoginFlowCommit(expectedEpoch: number): () => void {
+ sealedLoginFlowCommitDepths.set(
+ expectedEpoch,
+ (sealedLoginFlowCommitDepths.get(expectedEpoch) ?? 0) + 1,
+ );
+ return () => {
+ const depth = sealedLoginFlowCommitDepths.get(expectedEpoch) ?? 0;
+ if (depth <= 1) {
+ sealedLoginFlowCommitDepths.delete(expectedEpoch);
+ return;
+ }
+ sealedLoginFlowCommitDepths.set(expectedEpoch, depth - 1);
+ };
+}
+
+function isLoginFlowCommitSealed(expectedEpoch: number): boolean {
+ return (sealedLoginFlowCommitDepths.get(expectedEpoch) ?? 0) > 0;
+}
+
function resetActiveAuthRealmToBuild(): void {
activeAuthRealm = AUTH_REGION;
resetClientEndpointRealm();
@@ -3634,6 +3660,10 @@ export async function beginAddAccountLogin(): Promise<DesktopLoginActionResult>
}
export function cancelAddAccountLogin(): void {
+ if (isLoginFlowCommitSealed(loginFlowEpoch)) {
+ log.info('add-account close ignored after accepted login commit began');
+ return;
+ }
loginFlowEpoch += 1;
browserAuthorizationSlot.cancelActive();
resetLoginFlowState();
@@ -4534,115 +4564,120 @@ async function completeLogin(
}
};
assertTransitionCurrent();
+ const releaseLoginFlowCommit = sealLoginFlowCommit(expectedLoginFlowEpoch);
- const committedRealm = pendingAuthRealm ?? AUTH_REGION;
- const accountRefreshToken = outcome.accountRefreshToken ?? pendingAccountRefreshToken;
- let previousPersistedSession: ReturnType<typeof readPersistedAuthSession> = null;
- let activeSessionWritten = false;
- await commitDesktopLoginSessions(
- {
- pair: outcome,
- realm: committedRealm,
- passportId: nextUser.passportId || undefined,
- accountRefreshToken,
- memberships:
- pendingAccountMemberships.length > 0 ? pendingAccountMemberships : [outcome.membership],
- },
- {
- commit: 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();
- // 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: () =>
- commitWithClearedAccountDeletionReceipt(() => {
+ try {
+ const committedRealm = pendingAuthRealm ?? AUTH_REGION;
+ const accountRefreshToken = outcome.accountRefreshToken ?? pendingAccountRefreshToken;
+ let previousPersistedSession: ReturnType<typeof readPersistedAuthSession> = null;
+ let activeSessionWritten = false;
+ await commitDesktopLoginSessions(
+ {
+ pair: outcome,
+ realm: committedRealm,
+ passportId: nextUser.passportId || undefined,
+ accountRefreshToken,
+ memberships:
+ pendingAccountMemberships.length > 0 ? pendingAccountMemberships : [outcome.membership],
+ },
+ {
+ commit: 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();
+ // 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();
- 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()) {
- clearReloginFlag();
- }
- accountDeletionRestoredNoticePending = deletionWasRestored;
- // 显式登录解除本进程登出墓碑(passive / foreign-device)。
- passiveLocalSignOut = false;
- foreignDeviceLocalSignOut = false;
- currentUser = nextUser;
- commitCloudAppSession(currentUser.id);
- if (!isPassiveSharedUserDataInstance()) {
- canaryFlagStore.clear();
+ if (!accountSwitchTeardown) {
+ throw new Error('login cloud owner transition requires a teardown hook');
}
- pendingAuthRealm = null;
- }),
- });
- },
- rollback: () => {
- if (!activeSessionWritten) return;
- restorePersistedAuthSessionIfCurrent(
- outcome.refreshToken,
- committedRealm,
- previousPersistedSession,
- );
+ await accountSwitchTeardown({
+ previousUserId: previousSession.dataOwnerId ?? previousSession.mode,
+ nextUserId: nextUser.id,
+ });
+ assertTransitionCurrent();
+ },
+ prepareCommit: async () => {
+ assertTransitionCurrent();
+ await claimLegacyNamespaceForVerifiedUser(nextUser.id);
+ assertTransitionCurrent();
+ },
+ commit: () =>
+ commitWithClearedAccountDeletionReceipt(() => {
+ assertTransitionCurrent();
+ 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()) {
+ clearReloginFlag();
+ }
+ accountDeletionRestoredNoticePending = deletionWasRestored;
+ // 显式登录解除本进程登出墓碑(passive / foreign-device)。
+ passiveLocalSignOut = false;
+ foreignDeviceLocalSignOut = false;
+ currentUser = nextUser;
+ commitCloudAppSession(currentUser.id);
+ if (!isPassiveSharedUserDataInstance()) {
+ canaryFlagStore.clear();
+ }
+ pendingAuthRealm = null;
+ }),
+ });
+ },
+ rollback: () => {
+ if (!activeSessionWritten) return;
+ restorePersistedAuthSessionIfCurrent(
+ outcome.refreshToken,
+ committedRealm,
+ previousPersistedSession,
+ );
+ },
},
- },
- );
- await migrateLocalProviderBindingsAfterCloudCommit(nextUser.id);
- scheduleCanaryFlagSync({
- token: outcome.accessToken,
- expectedAuthEpoch: loginEpoch,
- expectedUserId: nextUser.id,
- });
- scheduleXdOrgBetaDefault({
- expectedAuthEpoch: loginEpoch,
- expectedUserId: nextUser.id,
- });
- scheduleRefresh(outcome.accessToken);
- getProviderSecretStore().reconcileOwner(outcome.membership.id);
- pendingLoginTicket = null;
- pendingBindTicket = null;
- pendingSsoVerificationTicket = null;
- loginFlowState = reduceAuthFlow(loginFlowState, { type: 'outcome', outcome });
- notifyRenderer();
- notifyAuthListeners();
- return loginFlowState;
+ );
+ await migrateLocalProviderBindingsAfterCloudCommit(nextUser.id);
+ scheduleCanaryFlagSync({
+ token: outcome.accessToken,
+ expectedAuthEpoch: loginEpoch,
+ expectedUserId: nextUser.id,
+ });
+ scheduleXdOrgBetaDefault({
+ expectedAuthEpoch: loginEpoch,
+ expectedUserId: nextUser.id,
+ });
+ scheduleRefresh(outcome.accessToken);
+ getProviderSecretStore().reconcileOwner(outcome.membership.id);
+ pendingLoginTicket = null;
+ pendingBindTicket = null;
+ pendingSsoVerificationTicket = null;
+ loginFlowState = reduceAuthFlow(loginFlowState, { type: 'outcome', outcome });
+ notifyRenderer();
+ notifyAuthListeners();
+ return loginFlowState;
+ } finally {
+ releaseLoginFlowCommit();
+ }
}
async function acceptLoginOutcome(
@@ -4693,10 +4728,8 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA
action.type === 'request-code' ||
action.type === 'verify-code' ||
(action.type === 'start-browser' && action.kind === 'social');
- if (startsBuildRealmFlow) pendingAuthRealm = null;
- const client = createAuthClient(
- startsBuildRealmFlow ? AUTH_REGION : (pendingAuthRealm ?? activeAuthRealm),
- );
+ const loginRealm = startsBuildRealmFlow ? AUTH_REGION : (pendingAuthRealm ?? activeAuthRealm);
+ const client = createAuthClient(loginRealm);
const stateBeforeAction = loginFlowState?.step === 'error' ? null : loginFlowState;
try {
// Cancellation is intercepted by dispatchLoginAction so it can settle the
@@ -4745,6 +4778,10 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA
return { success: true, state: loginFlowState };
}
if (!providerConfig) await loadLoginProviders(actionLoginFlowEpoch);
+ // loadLoginProviders clears transient login state. Pin a new personal login
+ // afterwards so account selection and binding cannot inherit the active
+ // organization's realm. The active account remains untouched until commit.
+ if (startsBuildRealmFlow) pendingAuthRealm = loginRealm;
if (action.type === 'discover') {
const email = action.email.trim().toLowerCase();
@@ -4853,6 +4890,8 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA
const deactivateCancellation = browserAuthorizationSlot.activate(() => cancellation.abort());
try {
const callback = await openSystemBrowserAuthorization(
+ client,
+ loginRealm,
{
kind: action.kind,
providerOrConnectionId: action.providerOrConnectionId,