🌊 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(oauth): retain early callbacks and ignore unrelated requests
Rudy Celekli3a013b31eb7c
diff --git a/v3/@claude-flow/cli/__tests__/auth-browser-callback.test.ts b/v3/@claude-flow/cli/__tests__/auth-browser-callback.test.tsnew file mode 100644index 0000000000..f362e65f32--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/auth-browser-callback.test.ts@@ -0,0 +1,34 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { CallbackServer } from '../../security/src/oauth/callback-server.js';+const exchangeCode = vi.hoisted(() => vi.fn());+const scenario = vi.hoisted(() => ({ state: 'expected' }));+vi.mock('../src/auth/security-bridge.js', () => ({+ loadSecurityOAuth: async () => ({+ CallbackServer: { bind: async () => {+ const server = await CallbackServer.bind();+ return { redirectUri: server.redirectUri, awaitCallback: () => server.awaitCallback(200) };+ } },+ generatePkce: () => ({ state: 'expected', codeChallenge: 'challenge', codeVerifier: 'verifier' }),+ authorizeUrl: (redirect: string) => redirect,+ openBrowser: async (url: string) => {+ // Complete the real loopback callback before openBrowser returns.+ const response = await fetch(`${url}?code=received&state=${scenario.state}`, { signal: AbortSignal.timeout(100) });+ await response.text();+ },+ exchangeCode,+ }),+}));+import { browserLogin, StateMismatchError } from '../src/auth/client.js';+beforeEach(() => { exchangeCode.mockReset(); scenario.state = 'expected'; });+describe('browser login callback boundary', () => {+ it('exchanges an early callback only after validating its state', async () => {+ exchangeCode.mockResolvedValue({ access_token: 'access', token_type: 'Bearer' });+ await expect(browserLogin(() => {})).resolves.toEqual({ tokens: { access_token: 'access', token_type: 'Bearer' }, method: 'pkce' });+ expect(exchangeCode).toHaveBeenCalledWith('received', 'verifier', expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback$/));+ });+ it('rejects a mismatched callback state without exchanging its code', async () => {+ scenario.state = 'mismatched';+ await expect(browserLogin(() => {})).rejects.toBeInstanceOf(StateMismatchError);+ expect(exchangeCode).not.toHaveBeenCalled();+ });+});diff --git a/v3/@claude-flow/security/__tests__/oauth-callback-routing.test.ts b/v3/@claude-flow/security/__tests__/oauth-callback-routing.test.tsnew file mode 100644index 0000000000..60d1beacae--- /dev/null+++ b/v3/@claude-flow/security/__tests__/oauth-callback-routing.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';+import { request } from 'node:http';+import { CallbackServer, CallbackTimeoutError } from '../src/oauth/callback-server.js';++function send(url: string, method = 'GET'): Promise<number> {+ return new Promise((resolve, reject) => {+ const req = request(url, { method, agent: false }, res => {+ res.resume();+ res.on('end', () => resolve(res.statusCode!));+ });+ req.setTimeout(100, () => req.destroy(new Error('request timed out')));+ req.on('error', reject);+ req.end();+ });+}++describe('OAuth loopback callback routing', () => {+ for (const [path, method, status] of [['/favicon.ico', 'GET', 404], ['/oauth/callback', 'POST', 405]] as const) {+ it(`ignores ${method} ${path} and still receives the OAuth callback`, async () => {+ const server = await CallbackServer.bind();+ const result = server.awaitCallback(300).catch(error => error);+ try {+ expect(await send(`http://127.0.0.1:${server.port}${path}`, method)).toBe(status);+ expect(await send(`${server.redirectUri}?code=legitimate&state=expected`)).toBe(200);+ expect(await result).toEqual({ code: 'legitimate', state: 'expected', error: null });+ } finally { await result; }+ });+ }+ it('retains a callback received before awaitCallback is called', async () => {+ const server = await CallbackServer.bind();+ try {+ expect(await send(`${server.redirectUri}?code=early&state=original`)).toBe(200);+ expect(await server.awaitCallback(30)).toEqual({ code: 'early', state: 'original', error: null });+ } finally { await server.awaitCallback(30).catch(() => {}); }+ });+ it('still times out when no callback arrives', async () => {+ const server = await CallbackServer.bind();+ await expect(server.awaitCallback(10)).rejects.toBeInstanceOf(CallbackTimeoutError);+ });+});diff --git a/v3/@claude-flow/security/src/oauth/callback-server.ts b/v3/@claude-flow/security/src/oauth/callback-server.tsindex c16be47500..ce91bf1c32 100644--- a/v3/@claude-flow/security/src/oauth/callback-server.ts+++ b/v3/@claude-flow/security/src/oauth/callback-server.ts@@ -1,6 +1,6 @@/*** Ephemeral-port localhost callback server for the browser-based OAuth flow- * (ADR-306). A minimal single-request HTTP server — deliberately not a full+ * (ADR-306). A minimal single-callback HTTP server — deliberately not a full* framework for one GET route that lives for one request and then shuts* down. A TypeScript port of meta-proxy's `src/oauth/callback_server.rs`.*@@ -37,11 +37,56 @@ export class CallbackTimeoutError extends Error {}export class CallbackServer {+ private readonly callback: Promise<CallbackResult>;private constructor(private readonly server: Server,public readonly redirectUri: string,public readonly port: number,- ) {}+ ) {+ // Install the listener before bind() returns: opening the browser can+ // deliver a callback before the caller reaches awaitCallback().+ this.callback = new Promise((resolve) => {+ let received = false;+ this.server.on('request', (req, res) => {+ let url: URL;+ try {+ url = new URL(req.url ?? '/', 'http://127.0.0.1');+ } catch {+ res.writeHead(400, { connection: 'close' });+ res.end();+ return;+ }+ if (url.pathname !== '/oauth/callback') {+ res.writeHead(404, { connection: 'close' });+ res.end();+ return;+ }+ if (req.method !== 'GET') {+ res.writeHead(405, { allow: 'GET', connection: 'close' });+ res.end();+ return;+ }+ if (received) {+ res.writeHead(409, { connection: 'close' });+ res.end();+ return;+ }+ received = true;+ const result: CallbackResult = {+ code: url.searchParams.get('code'),+ state: url.searchParams.get('state'),+ error: url.searchParams.get('error'),+ };+ res.writeHead(200, {+ 'content-type': 'text/html; charset=utf-8',+ connection: 'close',+ });+ res.end(SUCCESS_PAGE);+ this.server.close();+ resolve(result);+ });+ });+ }/*** Binds `127.0.0.1:0` (OS-assigned ephemeral port) and returns the server@@ -75,22 +120,9 @@ export class CallbackServer {reject(new CallbackTimeoutError());}, waitForMs);- this.server.once('request', (req, res) => {+ this.callback.then((result) => {clearTimeout(timer);- const url = new URL(req.url ?? '/oauth/callback', 'http://127.0.0.1');- const result: CallbackResult = {- code: url.searchParams.get('code'),- state: url.searchParams.get('state'),- error: url.searchParams.get('error'),- };- res.writeHead(200, {- 'content-type': 'text/html; charset=utf-8',- connection: 'close',- });- res.end(SUCCESS_PAGE, () => {- this.server.close();- resolve(result);- });+ resolve(result);});});}