Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/auth/linearPkce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:ht
import { randomBytes, createHash } from 'node:crypto';
import { AuthProfileStore, type AuthProfile } from './oauthStore.js';
import { openBrowser } from './openBrowser.js';
import { PkceSettlement, TOKEN_EXCHANGE_TIMEOUT_MS } from './pkceSettlement.js';
import { endSupersededCallback, PkceSettlement, TOKEN_EXCHANGE_TIMEOUT_MS } from './pkceSettlement.js';
import { parseTokenResponse } from './tokenResponse.js';

// ----- Constants -----
Expand Down Expand Up @@ -194,14 +194,20 @@ export async function runLinearPkceFlow(options: LinearFlowOptions = {}): Promis

const result = parseLinearTokenResponse(await tokenRes.json());

if (!settlement.finish()) return;
if (!settlement.finish()) {
endSupersededCallback(res);
return;
}
clearTimeout(timeout);
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(successHtml());
server.close();
resolve(result);
} catch (err) {
if (!settlement.finish()) return;
if (!settlement.finish()) {
endSupersededCallback(res);
return;
}
clearTimeout(timeout);
res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(errorHtml(String(err)));
Expand Down
135 changes: 135 additions & 0 deletions src/auth/oauthPkce.flow.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { createServer, request } from 'node:http';
import type { AddressInfo } from 'node:net';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

const opened: string[] = [];
vi.mock('./openBrowser.js', () => ({
openBrowser: (url: string) => {
opened.push(url);
},
}));

const { runOAuthPkceFlow } = await import('./oauthPkce.js');

async function freePort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = createServer();
probe.once('error', reject);
probe.listen(0, '127.0.0.1', () => {
const { port } = probe.address() as AddressInfo;
probe.close(() => resolve(port));
});
});
}

async function waitForAuthUrl(): Promise<URL> {
for (let i = 0; i < 200; i++) {
if (opened.length > 0) return new URL(opened[0]);
await new Promise((r) => setTimeout(r, 5));
}
throw new Error('flow never opened the browser');
}

interface CallbackReply {
status: number;
body: string;
}

function hitCallback(port: number, query: string): Promise<CallbackReply> {
return new Promise((resolve, reject) => {
const req = request(
{ host: '127.0.0.1', port, path: `/auth/callback?${query}`, method: 'GET' },
(res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk: string) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
},
);
req.on('error', reject);
req.end();
});
}

function fakeJwt(payload: Record<string, unknown>): string {
const enc = (v: unknown) => Buffer.from(JSON.stringify(v)).toString('base64url');
return `${enc({ alg: 'none' })}.${enc(payload)}.sig`;
}

describe('runOAuthPkceFlow callback response', () => {
beforeEach(() => {
opened.length = 0;
vi.spyOn(console, 'log').mockImplementation(() => {});
});

afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});

it('ends the held callback response when the login timeout wins during the exchange', async () => {
// The token request never answers on its own; it only fails when the flow aborts it.
vi.stubGlobal(
'fetch',
vi.fn(
(_url: string, init: { signal: AbortSignal }) =>
new Promise((_resolve, reject) => {
init.signal.addEventListener('abort', () => reject(init.signal.reason), { once: true });
}),
),
);

const port = await freePort();
const flow = runOAuthPkceFlow({ port, timeoutMs: 300 });
const flowOutcome = flow.then(
() => 'resolved',
(err: Error) => err.message,
);
const state = (await waitForAuthUrl()).searchParams.get('state');

const reply = await hitCallback(port, `code=abc&state=${state}`);

expect(reply.status).toBe(410);
expect(reply.body).toContain('already ended');
expect(await flowOutcome).toMatch(/timed out/);
});

it('still answers 200 once and resolves when the exchange wins', async () => {
const access = fakeJwt({ 'https://api.openai.com/auth': { chatgpt_account_id: 'acct_1' } });
const fetchMock = vi.fn(async () =>
new Response(JSON.stringify({ access_token: access, refresh_token: 'r1', expires_in: 3600 }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
);
vi.stubGlobal('fetch', fetchMock);

const port = await freePort();
const flow = runOAuthPkceFlow({ port, timeoutMs: 5_000 });
const state = (await waitForAuthUrl()).searchParams.get('state');

const reply = await hitCallback(port, `code=abc&state=${state}`);
const result = await flow;

expect(reply.status).toBe(200);
expect(result.accountId).toBe('acct_1');
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it('answers 500 once and rejects when the exchange fails before any timeout', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 400 })));

const port = await freePort();
const flow = runOAuthPkceFlow({ port, timeoutMs: 5_000 });
const flowOutcome = flow.then(
() => 'resolved',
(err: Error) => err.message,
);
const state = (await waitForAuthUrl()).searchParams.get('state');

const reply = await hitCallback(port, `code=abc&state=${state}`);

expect(reply.status).toBe(500);
expect(await flowOutcome).toMatch(/Token exchange failed \(400\)/);
});
});
17 changes: 13 additions & 4 deletions src/auth/oauthPkce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { isIP } from 'node:net';
import { randomBytes, createHash } from 'node:crypto';
import { AuthProfileStore, type AuthProfile } from './oauthStore.js';
import { openBrowser } from './openBrowser.js';
import { PkceSettlement, TOKEN_EXCHANGE_TIMEOUT_MS } from './pkceSettlement.js';
import { endSupersededCallback, PkceSettlement, TOKEN_EXCHANGE_TIMEOUT_MS } from './pkceSettlement.js';
import { parseTokenResponse } from './tokenResponse.js';

// Constants
Expand Down Expand Up @@ -75,6 +75,8 @@ export interface OAuthFlowOptions {
clientId?: string;
port?: number;
scopes?: string;
/** Login timeout; defaults to two minutes. Tests shorten it. */
timeoutMs?: number;
}

/**
Expand All @@ -86,6 +88,7 @@ export async function runOAuthPkceFlow(options: OAuthFlowOptions = {}): Promise<
clientId = DEFAULT_OPENAI_CLIENT_ID,
port = DEFAULT_CALLBACK_PORT,
scopes = DEFAULT_SCOPES,
timeoutMs = LOGIN_TIMEOUT_MS,
} = options;
// Must be exactly "http://localhost:1455/auth/callback" — this is the value
// registered on the public Codex OAuth client. Using 127.0.0.1 instead
Expand Down Expand Up @@ -125,7 +128,7 @@ export async function runOAuthPkceFlow(options: OAuthFlowOptions = {}): Promise<
server.close();
reject(new Error('OAuth login timed out (120s). 다시 시도하세요.'));
}
}, LOGIN_TIMEOUT_MS);
}, timeoutMs);

const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
if (settlement.settled) {
Expand Down Expand Up @@ -247,14 +250,20 @@ export async function runOAuthPkceFlow(options: OAuthFlowOptions = {}): Promise<
accountId,
};

if (!settlement.finish()) return;
if (!settlement.finish()) {
endSupersededCallback(res);
return;
}
clearTimeout(timeout);
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(successHtml());
server.close();
resolve(result);
} catch (err) {
if (!settlement.finish()) return;
if (!settlement.finish()) {
endSupersededCallback(res);
return;
}
clearTimeout(timeout);
res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(errorHtml(String(err)));
Expand Down
12 changes: 9 additions & 3 deletions src/auth/openrouterPkce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:ht
import { randomBytes, createHash } from 'node:crypto';
import { AuthProfileStore, type AuthProfile } from './oauthStore.js';
import { openBrowser } from './openBrowser.js';
import { PkceSettlement, TOKEN_EXCHANGE_TIMEOUT_MS } from './pkceSettlement.js';
import { endSupersededCallback, PkceSettlement, TOKEN_EXCHANGE_TIMEOUT_MS } from './pkceSettlement.js';

// ----- Constants -----

Expand Down Expand Up @@ -164,14 +164,20 @@ export async function runOpenRouterPkceFlow(
userId: payload.user_id ?? undefined,
};

if (!settlement.finish()) return;
if (!settlement.finish()) {
endSupersededCallback(res);
return;
}
clearTimeout(timeout);
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(successHtml());
server.close();
resolve(result);
} catch (err) {
if (!settlement.finish()) return;
if (!settlement.finish()) {
endSupersededCallback(res);
return;
}
clearTimeout(timeout);
res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(errorHtml(String(err)));
Expand Down
40 changes: 39 additions & 1 deletion src/auth/pkceSettlement.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { PkceSettlement } from './pkceSettlement.js';
import { endSupersededCallback, PkceSettlement } from './pkceSettlement.js';

describe('PkceSettlement', () => {
it('allows exactly one callback to claim an exchange', () => {
Expand All @@ -11,3 +11,41 @@ describe('PkceSettlement', () => {
expect(settlement.settled).toBe(true);
});
});

describe('endSupersededCallback', () => {
function fakeRes(init: { headersSent?: boolean; writableEnded?: boolean } = {}) {
const calls: string[] = [];
const res = {
headersSent: init.headersSent ?? false,
writableEnded: init.writableEnded ?? false,
writeHead(status: number, headers?: Record<string, string>) {
calls.push(`head:${status}:${headers?.Connection ?? ''}`);
res.headersSent = true;
},
end(body?: string) {
calls.push(`end:${body ? 'body' : ''}`);
res.writableEnded = true;
},
};
return { res, calls };
}

it('answers 410 with Connection: close and ends the response once', () => {
const { res, calls } = fakeRes();
endSupersededCallback(res);
endSupersededCallback(res);
expect(calls).toEqual(['head:410:close', 'end:body']);
});

it('only ends a response whose headers were already sent', () => {
const { res, calls } = fakeRes({ headersSent: true });
endSupersededCallback(res);
expect(calls).toEqual(['end:body']);
});

it('leaves an already-ended response alone', () => {
const { res, calls } = fakeRes({ headersSent: true, writableEnded: true });
endSupersededCallback(res);
expect(calls).toEqual([]);
});
});
30 changes: 30 additions & 0 deletions src/auth/pkceSettlement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,33 @@ export class PkceSettlement {
}

export const TOKEN_EXCHANGE_TIMEOUT_MS = 30_000;

/** Minimal response surface the superseded-callback helper needs. */
export interface CallbackResponse {
readonly headersSent: boolean;
readonly writableEnded: boolean;
writeHead(statusCode: number, headers?: Record<string, string>): unknown;
end(body?: string): unknown;
}

/**
* End a callback response whose exchange lost the settlement race.
*
* A callback that claimed the exchange holds an open response while the token
* request runs. If the login timeout or a server error settles the flow first,
* the handler must not resolve or reject again, but the browser still waits on
* this response. Returning without ending it left the tab loading and the
* socket open. This answers exactly once with 410 Gone and `Connection: close`
* so the socket is released; a response that already ended is left alone.
*/
export function endSupersededCallback(res: CallbackResponse): void {
if (res.writableEnded) return;
if (!res.headersSent) {
res.writeHead(410, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' });
}
res.end(
'<!DOCTYPE html><html><head><meta charset="utf-8"><title>OpenSwarm Auth</title></head>' +
'<body><p>This login attempt already ended (timed out or was cancelled). ' +
'Close this tab and start the login again.</p></body></html>',
);
}
Loading