diff --git a/src/auth/linearPkce.ts b/src/auth/linearPkce.ts index 5fd8f481..7518a90a 100644 --- a/src/auth/linearPkce.ts +++ b/src/auth/linearPkce.ts @@ -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 ----- @@ -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))); diff --git a/src/auth/oauthPkce.flow.test.ts b/src/auth/oauthPkce.flow.test.ts new file mode 100644 index 00000000..5419f811 --- /dev/null +++ b/src/auth/oauthPkce.flow.test.ts @@ -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 { + 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 { + 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 { + 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 { + 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\)/); + }); +}); diff --git a/src/auth/oauthPkce.ts b/src/auth/oauthPkce.ts index 86a765c1..4178009c 100644 --- a/src/auth/oauthPkce.ts +++ b/src/auth/oauthPkce.ts @@ -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 @@ -75,6 +75,8 @@ export interface OAuthFlowOptions { clientId?: string; port?: number; scopes?: string; + /** Login timeout; defaults to two minutes. Tests shorten it. */ + timeoutMs?: number; } /** @@ -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 @@ -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) { @@ -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))); diff --git a/src/auth/openrouterPkce.ts b/src/auth/openrouterPkce.ts index 8f35c06e..ab1dbe14 100644 --- a/src/auth/openrouterPkce.ts +++ b/src/auth/openrouterPkce.ts @@ -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 ----- @@ -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))); diff --git a/src/auth/pkceSettlement.test.ts b/src/auth/pkceSettlement.test.ts index fdf99293..2f2f6922 100644 --- a/src/auth/pkceSettlement.test.ts +++ b/src/auth/pkceSettlement.test.ts @@ -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', () => { @@ -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) { + 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([]); + }); +}); diff --git a/src/auth/pkceSettlement.ts b/src/auth/pkceSettlement.ts index 23d75ab4..cf3c6cd6 100644 --- a/src/auth/pkceSettlement.ts +++ b/src/auth/pkceSettlement.ts @@ -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): 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( + 'OpenSwarm Auth' + + '

This login attempt already ended (timed out or was cancelled). ' + + 'Close this tab and start the login again.

', + ); +}