🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(auth): coalesce concurrent rotating-token refresh attempts
Rudy Celekli87f9c11b75a1
diff --git a/v3/@claude-flow/cli/__tests__/auth-token-refresh.test.ts b/v3/@claude-flow/cli/__tests__/auth-token-refresh.test.tsindex 6fd26957d9..a5d520c54a 100644--- a/v3/@claude-flow/cli/__tests__/auth-token-refresh.test.ts+++ b/v3/@claude-flow/cli/__tests__/auth-token-refresh.test.ts@@ -147,6 +147,52 @@ describe('getValidAccessToken', () => {});});+describe('concurrent access-token refresh', () => {+ it('shares one rotating credential across overlapping proxy refresh calls', async () => {+ const name = profileName('concurrent-proxy');+ writeProfile(name, name);+ secrets.set(name, 'one-use-refresh');+ let spent = false;+ refreshTokenMock.mockImplementation(async () => {+ if (spent) throw new Error('refresh token reuse detected');+ spent = true;+ await new Promise(resolve => setImmediate(resolve));+ return { access_token: 'shared-access', refresh_token: 'rotated', expires_in: 900 };+ });+ const { refreshInjectedToken } = await import('../src/proxy/token-bridge.js');+ expect(await Promise.all([refreshInjectedToken(), refreshInjectedToken()])).toEqual([true, true]);+ expect(refreshTokenMock).toHaveBeenCalledTimes(1);+ expect(setSecretMock).toHaveBeenCalledTimes(1);+ expect(getSessionToken(name)).toBe('shared-access');+ clearSessionToken(name);+ });++ it('shares a failed attempt but allows a later demand-driven retry', async () => {+ const name = profileName('retry-flight');+ writeProfile(name, name);+ secrets.set(name, 'unspent-refresh');+ refreshTokenMock.mockRejectedValue(new Error('temporary transport failure'));+ const failures = await Promise.allSettled([getValidAccessToken(name), getValidAccessToken(name)]);+ expect(failures.map(result => result.status)).toEqual(['rejected', 'rejected']);+ expect(refreshTokenMock).toHaveBeenCalledTimes(1);+ expect(getSessionToken(name)).toBeNull();+ refreshTokenMock.mockResolvedValue({ access_token: 'retried', expires_in: 900 });+ await expect(getValidAccessToken(name)).resolves.toBe('retried');+ expect(refreshTokenMock).toHaveBeenCalledTimes(2);+ clearSessionToken(name);+ });++ it('does not share credentials between different profiles', async () => {+ const names = [profileName('independent-a'), profileName('independent-b')];+ for (const name of names) { writeProfile(name, name); secrets.set(name, name); }+ refreshTokenMock.mockImplementation(async (token: string) => ({ access_token: token + '-access', expires_in: 900 }));+ expect(await Promise.all(names.map(name => getValidAccessToken(name))))+ .toEqual(names.map(name => name + '-access'));+ expect(refreshTokenMock).toHaveBeenCalledTimes(2);+ names.forEach(clearSessionToken);+ });+});+describe('auth status --check consumer', () => {it('uses the demand-driven accessor without exposing the token', async () => {const name = profileName('status-check');diff --git a/v3/@claude-flow/cli/src/auth/client.ts b/v3/@claude-flow/cli/src/auth/client.tsindex c8e06d9cbb..edf4682c5b 100644--- a/v3/@claude-flow/cli/src/auth/client.ts+++ b/v3/@claude-flow/cli/src/auth/client.ts@@ -22,6 +22,9 @@ import { domainForScope } from './scopes.js';/** Refresh before there is less than one minute left on the access token. */export const ACCESS_TOKEN_REFRESH_WINDOW_MS = 60_000;+// A rotating refresh credential may be spent only once per process attempt.+const pendingRefreshes = new Map<string, Promise<string>>();+export interface LoginResult {tokens: OAuthTokenResponse;method: 'pkce' | 'device' | 'token-stdin';@@ -250,28 +253,40 @@ export async function getValidAccessToken(profileName = 'default'): Promise<striif (cached) return cached;if (!profile.keychainRef) throw new SessionOnlyExpiredError(profileName);- const sec = await loadSecurityOAuth();- const keychain = await sec.createKeychainAdapter();- const refreshTokenValue = await keychain.getSecret(KEYCHAIN_SERVICE, profile.keychainRef);- if (!refreshTokenValue) throw new SessionOnlyExpiredError(profileName);-- const refreshed = await refreshAccessToken(refreshTokenValue);- if (!refreshed.access_token) throw new Error('Cognitum refresh response did not contain an access token');-- // Cognitum rotates refresh tokens with reuse detection. Commit the rotated- // credential first; if this write fails, do not publish/cache the access- // token and do not retry the already-spent old refresh token here.- if (refreshed.refresh_token) {- await keychain.setSecret(KEYCHAIN_SERVICE, profile.keychainRef, refreshed.refresh_token);- }+ const refreshKey = JSON.stringify([profileName, profile.keychainRef]);+ const pending = pendingRefreshes.get(refreshKey);+ if (pending) return pending;- const expiresAtMs = Date.now() + Math.max(0, refreshed.expires_in ?? 0) * 1000;- setSessionToken(profileName, refreshed.access_token, expiresAtMs);- setProfile(profileName, {- ...profile,- accountId: refreshed.account_email ?? profile.accountId,- accessTokenExpiresAt: new Date(expiresAtMs).toISOString(),- linkedAt: new Date().toISOString(),- });- return refreshed.access_token;+ const refresh = (async () => {+ const sec = await loadSecurityOAuth();+ const keychain = await sec.createKeychainAdapter();+ const refreshTokenValue = await keychain.getSecret(KEYCHAIN_SERVICE, profile.keychainRef);+ if (!refreshTokenValue) throw new SessionOnlyExpiredError(profileName);++ const refreshed = await refreshAccessToken(refreshTokenValue);+ if (!refreshed.access_token) throw new Error('Cognitum refresh response did not contain an access token');++ // Cognitum rotates refresh tokens with reuse detection. Commit the rotated+ // credential first; if this write fails, do not publish/cache the access+ // token and do not retry the already-spent old refresh token here.+ if (refreshed.refresh_token) {+ await keychain.setSecret(KEYCHAIN_SERVICE, profile.keychainRef, refreshed.refresh_token);+ }++ const expiresAtMs = Date.now() + Math.max(0, refreshed.expires_in ?? 0) * 1000;+ setSessionToken(profileName, refreshed.access_token, expiresAtMs);+ setProfile(profileName, {+ ...profile,+ accountId: refreshed.account_email ?? profile.accountId,+ accessTokenExpiresAt: new Date(expiresAtMs).toISOString(),+ linkedAt: new Date().toISOString(),+ });+ return refreshed.access_token;+ })();+ pendingRefreshes.set(refreshKey, refresh);+ try {+ return await refresh;+ } finally {+ pendingRefreshes.delete(refreshKey);+ }}