@bastani/pi-ai 0.9.24 → 0.9.25-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/NOTICE.md +1 -1
  3. package/README.md +17 -6
  4. package/dist/api/cloudflare-workers-ai-system-one.js +2 -2
  5. package/dist/api/cloudflare-workers-ai-system-one.js.map +1 -1
  6. package/dist/api/openai-codex-responses.d.ts +2 -2
  7. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  8. package/dist/api/openai-codex-responses.js +8 -28
  9. package/dist/api/openai-codex-responses.js.map +1 -1
  10. package/dist/api/openai-responses-shared.d.ts +25 -6
  11. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  12. package/dist/api/openai-responses-shared.js +66 -19
  13. package/dist/api/openai-responses-shared.js.map +1 -1
  14. package/dist/api/openai-responses.d.ts +2 -1
  15. package/dist/api/openai-responses.d.ts.map +1 -1
  16. package/dist/api/openai-responses.js +21 -32
  17. package/dist/api/openai-responses.js.map +1 -1
  18. package/dist/api/system-one-shared.d.ts +2 -2
  19. package/dist/api/system-one-shared.d.ts.map +1 -1
  20. package/dist/api/system-one-shared.js +26 -1
  21. package/dist/api/system-one-shared.js.map +1 -1
  22. package/dist/api/typesafe-system-one.js +2 -2
  23. package/dist/api/typesafe-system-one.js.map +1 -1
  24. package/dist/auth/helpers.js +1 -1
  25. package/dist/auth/helpers.js.map +1 -1
  26. package/dist/auth/oauth/anthropic.d.ts.map +1 -1
  27. package/dist/auth/oauth/anthropic.js +19 -128
  28. package/dist/auth/oauth/anthropic.js.map +1 -1
  29. package/dist/auth/oauth/callback-server.d.ts +31 -0
  30. package/dist/auth/oauth/callback-server.d.ts.map +1 -0
  31. package/dist/auth/oauth/callback-server.js +138 -0
  32. package/dist/auth/oauth/callback-server.js.map +1 -0
  33. package/dist/auth/oauth/load.d.ts +2 -0
  34. package/dist/auth/oauth/load.d.ts.map +1 -1
  35. package/dist/auth/oauth/load.js +5 -0
  36. package/dist/auth/oauth/load.js.map +1 -1
  37. package/dist/auth/oauth/oauth-page.js +1 -1
  38. package/dist/auth/oauth/oauth-page.js.map +1 -1
  39. package/dist/auth/oauth/openai-chatgpt.d.ts +3 -0
  40. package/dist/auth/oauth/openai-chatgpt.d.ts.map +1 -0
  41. package/dist/auth/oauth/openai-chatgpt.js +250 -0
  42. package/dist/auth/oauth/openai-chatgpt.js.map +1 -0
  43. package/dist/auth/oauth/openai-codex.d.ts +1 -1
  44. package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
  45. package/dist/auth/oauth/openai-codex.js +20 -124
  46. package/dist/auth/oauth/openai-codex.js.map +1 -1
  47. package/dist/auth/oauth/openrouter.d.ts +1 -1
  48. package/dist/auth/oauth/openrouter.d.ts.map +1 -1
  49. package/dist/auth/oauth/openrouter.js +19 -138
  50. package/dist/auth/oauth/openrouter.js.map +1 -1
  51. package/dist/auth/oauth/radius.d.ts +1 -1
  52. package/dist/auth/oauth/radius.d.ts.map +1 -1
  53. package/dist/auth/oauth/radius.js +21 -89
  54. package/dist/auth/oauth/radius.js.map +1 -1
  55. package/dist/auth/types.d.ts +6 -1
  56. package/dist/auth/types.d.ts.map +1 -1
  57. package/dist/auth/types.js.map +1 -1
  58. package/dist/bun-oauth.d.ts.map +1 -1
  59. package/dist/bun-oauth.js +2 -0
  60. package/dist/bun-oauth.js.map +1 -1
  61. package/dist/cli.js +2 -1
  62. package/dist/cli.js.map +1 -1
  63. package/dist/models.d.ts +5 -3
  64. package/dist/models.d.ts.map +1 -1
  65. package/dist/models.js +6 -2
  66. package/dist/models.js.map +1 -1
  67. package/dist/providers/data/.manifest.json +1 -1
  68. package/dist/providers/data/amazon-bedrock.json +1 -1
  69. package/dist/providers/data/azure-openai-responses.json +1 -1
  70. package/dist/providers/data/baseten.json +1 -1
  71. package/dist/providers/data/cerebras.json +1 -1
  72. package/dist/providers/data/github-copilot.json +1 -1
  73. package/dist/providers/data/openai-codex.json +1 -1
  74. package/dist/providers/data/openai.json +1 -1
  75. package/dist/providers/data/opencode.json +1 -1
  76. package/dist/providers/data/openrouter.json +1 -1
  77. package/dist/providers/data/radius.json +1 -1
  78. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  79. package/dist/providers/openai-codex.js +1 -1
  80. package/dist/providers/openai-codex.js.map +1 -1
  81. package/dist/providers/openai.d.ts.map +1 -1
  82. package/dist/providers/openai.js +11 -2
  83. package/dist/providers/openai.js.map +1 -1
  84. package/dist/providers/opencode.d.ts +3 -1
  85. package/dist/providers/opencode.d.ts.map +1 -1
  86. package/dist/providers/opencode.js +4 -2
  87. package/dist/providers/opencode.js.map +1 -1
  88. package/dist/providers/vercel-ai-gateway.d.ts.map +1 -1
  89. package/dist/providers/vercel-ai-gateway.js +4 -2
  90. package/dist/providers/vercel-ai-gateway.js.map +1 -1
  91. package/dist/types.d.ts +40 -1
  92. package/dist/types.d.ts.map +1 -1
  93. package/dist/types.js.map +1 -1
  94. package/dist/utils/oauth-page.d.ts +2 -0
  95. package/dist/utils/oauth-page.d.ts.map +1 -0
  96. package/dist/utils/oauth-page.js +2 -0
  97. package/dist/utils/oauth-page.js.map +1 -0
  98. package/dist/utils/retry.d.ts.map +1 -1
  99. package/dist/utils/retry.js +3 -0
  100. package/dist/utils/retry.js.map +1 -1
  101. package/dist/utils/validation.d.ts +1 -0
  102. package/dist/utils/validation.d.ts.map +1 -1
  103. package/dist/utils/validation.js +3 -0
  104. package/dist/utils/validation.js.map +1 -1
  105. package/package.json +6 -2
@@ -0,0 +1,250 @@
1
+ /** Direct OpenAI Responses API token sharing through Sign in with ChatGPT. */
2
+ import { randomBytes } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import { oauthErrorHtml, oauthSuccessHtml } from "../../utils/oauth-page.js";
5
+ import { getProviderEnvValue } from "../../utils/provider-env.js";
6
+ import { generatePKCE } from "./pkce.js";
7
+ const DYNAMIC_CLIENT_ID = "dynamic_agent_client";
8
+ const AGENT_NAME_HINT = "Atomic";
9
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ const AUTHORIZE_URL = "https://auth.openai.com/api/accounts/authorize";
11
+ const TOKEN_URL = "https://auth.openai.com/api/accounts/oauth/token";
12
+ const RESOURCE = "https://api.openai.com/v1";
13
+ const CALLBACK_HOST = getProviderEnvValue("PI_OAUTH_CALLBACK_HOST") || "127.0.0.1";
14
+ const CALLBACK_PORT = 1455;
15
+ const CALLBACK_PATH = "/auth/callback";
16
+ const REDIRECT_URI = `http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`;
17
+ const DIRECT_TOKEN_SCOPE = "chatgpt.tokens.use.direct";
18
+ const SCOPE = `openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`;
19
+ const EXPIRY_MARGIN_MS = 3 * 60 * 1000;
20
+ function randomValue() {
21
+ return randomBytes(32).toString("base64url");
22
+ }
23
+ function authorizationResultFromCallback(url, expectedState) {
24
+ const code = url.searchParams.get("code");
25
+ if (!code)
26
+ throw new Error("Missing authorization code");
27
+ const state = url.searchParams.get("state");
28
+ if (!state)
29
+ throw new Error("Missing OAuth state");
30
+ if (state !== expectedState)
31
+ throw new Error("OAuth state mismatch");
32
+ const clientId = url.searchParams.get("client_id")?.trim();
33
+ if (!clientId)
34
+ throw new Error("OpenAI OAuth registration callback did not contain an issued client ID");
35
+ return { code, clientId };
36
+ }
37
+ function authorizationResultFromManualInput(input, expectedState) {
38
+ let url;
39
+ try {
40
+ url = new URL(input.trim());
41
+ }
42
+ catch {
43
+ throw new Error("Paste the full callback URL from the browser");
44
+ }
45
+ const expected = new URL(REDIRECT_URI);
46
+ if (url.origin !== expected.origin || url.pathname !== expected.pathname) {
47
+ throw new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);
48
+ }
49
+ const error = url.searchParams.get("error");
50
+ if (error)
51
+ throw new Error(`ChatGPT authorization failed: ${error}`);
52
+ return authorizationResultFromCallback(url, expectedState);
53
+ }
54
+ function sendHtml(response, status, body) {
55
+ response.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
56
+ response.end(body);
57
+ }
58
+ function startCallbackServer(expectedState) {
59
+ return new Promise((resolve, reject) => {
60
+ let resolveResult;
61
+ let rejectResult;
62
+ const result = new Promise((resolveAuthorization, rejectAuthorization) => {
63
+ resolveResult = resolveAuthorization;
64
+ rejectResult = rejectAuthorization;
65
+ });
66
+ const server = createServer((request, response) => {
67
+ try {
68
+ const url = new URL(request.url || "", REDIRECT_URI);
69
+ if (url.pathname !== CALLBACK_PATH) {
70
+ sendHtml(response, 404, oauthErrorHtml("Callback route not found."));
71
+ return;
72
+ }
73
+ const error = url.searchParams.get("error");
74
+ if (error) {
75
+ sendHtml(response, 400, oauthErrorHtml("ChatGPT was not connected.", `Error: ${error}`));
76
+ rejectResult(new Error(`ChatGPT authorization failed: ${error}`));
77
+ return;
78
+ }
79
+ let authorizationResult;
80
+ try {
81
+ authorizationResult = authorizationResultFromCallback(url, expectedState);
82
+ }
83
+ catch (error) {
84
+ const message = error instanceof Error ? error.message : "Invalid callback";
85
+ sendHtml(response, 400, oauthErrorHtml(message));
86
+ return;
87
+ }
88
+ sendHtml(response, 200, oauthSuccessHtml("ChatGPT authentication completed. You can close this window."));
89
+ resolveResult(authorizationResult);
90
+ }
91
+ catch {
92
+ sendHtml(response, 500, oauthErrorHtml("Internal error while processing the callback."));
93
+ }
94
+ });
95
+ server.once("error", reject);
96
+ server.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
97
+ server.removeListener("error", reject);
98
+ server.on("error", rejectResult);
99
+ resolve({ server, result });
100
+ });
101
+ });
102
+ }
103
+ async function requestToken(body, signal) {
104
+ const response = await fetch(TOKEN_URL, {
105
+ method: "POST",
106
+ headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
107
+ body,
108
+ signal,
109
+ });
110
+ if (!response.ok) {
111
+ const responseBody = await response.text().catch(() => "");
112
+ throw new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody || response.statusText}`);
113
+ }
114
+ const data = await response.json();
115
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
116
+ throw new Error("OpenAI OAuth token response must be an object");
117
+ }
118
+ return data;
119
+ }
120
+ function requireTokenString(value, field) {
121
+ if (typeof value !== "string" || value.trim().length === 0) {
122
+ throw new Error(`OpenAI OAuth token response has invalid ${field}`);
123
+ }
124
+ return value;
125
+ }
126
+ function credentialFromTokenResponse(token, clientId) {
127
+ const access = requireTokenString(token.access_token, "access_token");
128
+ const refresh = requireTokenString(token.refresh_token, "refresh_token");
129
+ const scope = requireTokenString(token.scope, "scope");
130
+ if (typeof token.expires_in !== "number" || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {
131
+ throw new Error("OpenAI OAuth token response has invalid expires_in");
132
+ }
133
+ const scopes = scope.trim().split(/\s+/).filter(Boolean);
134
+ if (!scopes.includes(DIRECT_TOKEN_SCOPE)) {
135
+ throw new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);
136
+ }
137
+ return {
138
+ type: "oauth",
139
+ access,
140
+ refresh,
141
+ expires: Date.now() + token.expires_in * 1000 - EXPIRY_MARGIN_MS,
142
+ clientId,
143
+ scopes,
144
+ };
145
+ }
146
+ async function exchangeAuthorizationCode(code, verifier, clientId, signal) {
147
+ const token = await requestToken(new URLSearchParams({
148
+ grant_type: "authorization_code",
149
+ client_id: clientId,
150
+ code,
151
+ code_verifier: verifier,
152
+ redirect_uri: REDIRECT_URI,
153
+ resource: RESOURCE,
154
+ }), signal);
155
+ // The ID token is required by the response contract, but is not used for profile data.
156
+ if (typeof token.id_token !== "string" || token.id_token.trim().length === 0) {
157
+ throw new Error("OpenAI OAuth token response did not contain an ID token");
158
+ }
159
+ return credentialFromTokenResponse(token, clientId);
160
+ }
161
+ async function refreshAccessToken(credential, signal) {
162
+ const clientId = credential.clientId;
163
+ if (typeof clientId !== "string" || clientId.trim().length === 0) {
164
+ throw new Error("Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT");
165
+ }
166
+ const token = await requestToken(new URLSearchParams({
167
+ grant_type: "refresh_token",
168
+ client_id: clientId,
169
+ refresh_token: credential.refresh,
170
+ resource: RESOURCE,
171
+ }), signal);
172
+ return credentialFromTokenResponse(token, clientId);
173
+ }
174
+ function agentHostId(deviceId) {
175
+ if (!deviceId || !UUID_PATTERN.test(deviceId)) {
176
+ throw new Error("Sign in with ChatGPT requires a device ID (UUID) for this installation");
177
+ }
178
+ return `urn:uuid:${deviceId.toLowerCase()}`;
179
+ }
180
+ async function loginOpenAIChatGPT(interaction, options) {
181
+ const hostId = agentHostId(options?.getDeviceId?.());
182
+ const { verifier, challenge } = await generatePKCE();
183
+ const state = randomValue();
184
+ const nonce = randomValue();
185
+ let callback;
186
+ try {
187
+ callback = await startCallbackServer(state);
188
+ }
189
+ catch (error) {
190
+ interaction.notify({
191
+ type: "info",
192
+ message: `Could not listen on ${REDIRECT_URI}; paste the final redirect URL to continue. ${error instanceof Error ? error.message : String(error)}`,
193
+ });
194
+ }
195
+ const authorizationUrl = new URL(AUTHORIZE_URL);
196
+ authorizationUrl.search = new URLSearchParams({
197
+ client_id: DYNAMIC_CLIENT_ID,
198
+ agent_name_hint: AGENT_NAME_HINT,
199
+ ext_agent_host_id: hostId,
200
+ response_type: "code",
201
+ redirect_uri: REDIRECT_URI,
202
+ resource: RESOURCE,
203
+ scope: SCOPE,
204
+ state,
205
+ code_challenge: challenge,
206
+ code_challenge_method: "S256",
207
+ nonce,
208
+ }).toString();
209
+ interaction.notify({
210
+ type: "auth_url",
211
+ url: authorizationUrl.toString(),
212
+ instructions: "Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here.",
213
+ });
214
+ const manualAbort = new AbortController();
215
+ const manualCode = interaction
216
+ .prompt({
217
+ type: "manual_code",
218
+ message: "Complete login in your browser, or paste the final redirect URL here:",
219
+ placeholder: REDIRECT_URI,
220
+ signal: AbortSignal.any([manualAbort.signal, interaction.signal]),
221
+ })
222
+ .then((input) => authorizationResultFromManualInput(input, state));
223
+ try {
224
+ const result = await (callback ? Promise.race([callback.result, manualCode]) : manualCode);
225
+ interaction.notify({ type: "progress", message: "Exchanging authorization code for tokens..." });
226
+ return await exchangeAuthorizationCode(result.code, verifier, result.clientId, interaction.signal);
227
+ }
228
+ catch (error) {
229
+ if (interaction.signal.aborted)
230
+ throw new Error("Login cancelled");
231
+ throw error;
232
+ }
233
+ finally {
234
+ manualAbort.abort();
235
+ callback?.server.close();
236
+ // Spare browser connections must not deliver a later login to this old server.
237
+ callback?.server.closeAllConnections();
238
+ }
239
+ }
240
+ export const openaiChatGPTOAuth = {
241
+ name: "OpenAI (ChatGPT subscription)",
242
+ isSubscription: true,
243
+ loginLabel: "Sign in with ChatGPT",
244
+ login: loginOpenAIChatGPT,
245
+ refresh: refreshAccessToken,
246
+ async toAuth(credential) {
247
+ return { apiKey: credential.access };
248
+ },
249
+ };
250
+ //# sourceMappingURL=openai-chatgpt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-chatgpt.js","sourceRoot":"","sources":["../../../src/auth/oauth/openai-chatgpt.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,iBAAiB,GAAG,sBAAsB,CAAC;AACjD,MAAM,eAAe,GAAG,QAAQ,CAAC;AACjC,MAAM,YAAY,GAAG,iEAAiE,CAAC;AACvF,MAAM,aAAa,GAAG,gDAAgD,CAAC;AACvE,MAAM,SAAS,GAAG,kDAA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EAA+E;QAC/E,QAAQ,EAAE,MAAM,CAAC,mBAAmB,EAAE,CAAC;IACxC,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAc;IAC5C,IAAI,EAAE,+BAA+B;IACrC,cAAc,EAAE,IAAI;IACpB,UAAU,EAAE,sBAAsB;IAClC,KAAK,EAAE,kBAAkB;IACzB,OAAO,EAAE,kBAAkB;IAC3B,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/** Direct OpenAI Responses API token sharing through Sign in with ChatGPT. */\nimport { randomBytes } from \"node:crypto\";\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"../../utils/oauth-page.ts\";\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { LoginOptions, OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst DYNAMIC_CLIENT_ID = \"dynamic_agent_client\";\nconst AGENT_NAME_HINT = \"Atomic\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst AUTHORIZE_URL = \"https://auth.openai.com/api/accounts/authorize\";\nconst TOKEN_URL = \"https://auth.openai.com/api/accounts/oauth/token\";\nconst RESOURCE = \"https://api.openai.com/v1\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 1455;\nconst CALLBACK_PATH = \"/auth/callback\";\nconst REDIRECT_URI = `http://127.0.0.1:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst DIRECT_TOKEN_SCOPE = \"chatgpt.tokens.use.direct\";\nconst SCOPE = `openid profile email offline_access resource.invoke ${DIRECT_TOKEN_SCOPE}`;\nconst EXPIRY_MARGIN_MS = 3 * 60 * 1000;\n\ntype AuthorizationResult = { code: string; clientId: string };\ntype CallbackServer = { server: Server; result: Promise<AuthorizationResult> };\ntype TokenResponse = {\n\taccess_token?: unknown;\n\trefresh_token?: unknown;\n\texpires_in?: unknown;\n\tid_token?: unknown;\n\tscope?: unknown;\n};\n\nfunction randomValue(): string {\n\treturn randomBytes(32).toString(\"base64url\");\n}\n\nfunction authorizationResultFromCallback(url: URL, expectedState: string): AuthorizationResult {\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"Missing authorization code\");\n\tconst state = url.searchParams.get(\"state\");\n\tif (!state) throw new Error(\"Missing OAuth state\");\n\tif (state !== expectedState) throw new Error(\"OAuth state mismatch\");\n\tconst clientId = url.searchParams.get(\"client_id\")?.trim();\n\tif (!clientId) throw new Error(\"OpenAI OAuth registration callback did not contain an issued client ID\");\n\treturn { code, clientId };\n}\n\nfunction authorizationResultFromManualInput(input: string, expectedState: string): AuthorizationResult {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Paste the full callback URL from the browser\");\n\t}\n\tconst expected = new URL(REDIRECT_URI);\n\tif (url.origin !== expected.origin || url.pathname !== expected.pathname) {\n\t\tthrow new Error(`The pasted callback URL must start with ${REDIRECT_URI}`);\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(`ChatGPT authorization failed: ${error}`);\n\treturn authorizationResultFromCallback(url, expectedState);\n}\n\nfunction sendHtml(response: ServerResponse, status: number, body: string): void {\n\tresponse.writeHead(status, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\tresponse.end(body);\n}\n\nfunction startCallbackServer(expectedState: string): Promise<CallbackServer> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet resolveResult!: (result: AuthorizationResult) => void;\n\t\tlet rejectResult!: (error: Error) => void;\n\t\tconst result = new Promise<AuthorizationResult>((resolveAuthorization, rejectAuthorization) => {\n\t\t\tresolveResult = resolveAuthorization;\n\t\t\trejectResult = rejectAuthorization;\n\t\t});\n\t\tconst server = createServer((request, response) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(request.url || \"\", REDIRECT_URI);\n\t\t\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\t\t\tsendHtml(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst error = url.searchParams.get(\"error\");\n\t\t\t\tif (error) {\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(\"ChatGPT was not connected.\", `Error: ${error}`));\n\t\t\t\t\trejectResult(new Error(`ChatGPT authorization failed: ${error}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet authorizationResult: AuthorizationResult;\n\t\t\t\ttry {\n\t\t\t\t\tauthorizationResult = authorizationResultFromCallback(url, expectedState);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst message = error instanceof Error ? error.message : \"Invalid callback\";\n\t\t\t\t\tsendHtml(response, 400, oauthErrorHtml(message));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsendHtml(response, 200, oauthSuccessHtml(\"ChatGPT authentication completed. You can close this window.\"));\n\t\t\t\tresolveResult(authorizationResult);\n\t\t\t} catch {\n\t\t\t\tsendHtml(response, 500, oauthErrorHtml(\"Internal error while processing the callback.\"));\n\t\t\t}\n\t\t});\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\tserver.removeListener(\"error\", reject);\n\t\t\tserver.on(\"error\", rejectResult);\n\t\t\tresolve({ server, result });\n\t\t});\n\t});\n}\n\nasync function requestToken(body: URLSearchParams, signal: AbortSignal): Promise<TokenResponse> {\n\tconst response = await fetch(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\tbody,\n\t\tsignal,\n\t});\n\tif (!response.ok) {\n\t\tconst responseBody = await response.text().catch(() => \"\");\n\t\tthrow new Error(`OpenAI OAuth token request failed (${response.status}): ${responseBody || response.statusText}`);\n\t}\n\tconst data: unknown = await response.json();\n\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\tthrow new Error(\"OpenAI OAuth token response must be an object\");\n\t}\n\treturn data as TokenResponse;\n}\n\nfunction requireTokenString(value: unknown, field: \"access_token\" | \"refresh_token\" | \"scope\"): string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new Error(`OpenAI OAuth token response has invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction credentialFromTokenResponse(token: TokenResponse, clientId: string): OAuthCredential {\n\tconst access = requireTokenString(token.access_token, \"access_token\");\n\tconst refresh = requireTokenString(token.refresh_token, \"refresh_token\");\n\tconst scope = requireTokenString(token.scope, \"scope\");\n\tif (typeof token.expires_in !== \"number\" || !Number.isFinite(token.expires_in) || token.expires_in <= 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response has invalid expires_in\");\n\t}\n\tconst scopes = scope.trim().split(/\\s+/).filter(Boolean);\n\tif (!scopes.includes(DIRECT_TOKEN_SCOPE)) {\n\t\tthrow new Error(`OpenAI OAuth grant did not include ${DIRECT_TOKEN_SCOPE}`);\n\t}\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + token.expires_in * 1000 - EXPIRY_MARGIN_MS,\n\t\tclientId,\n\t\tscopes,\n\t};\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tclientId: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: clientId,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\t// The ID token is required by the response contract, but is not used for profile data.\n\tif (typeof token.id_token !== \"string\" || token.id_token.trim().length === 0) {\n\t\tthrow new Error(\"OpenAI OAuth token response did not contain an ID token\");\n\t}\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nasync function refreshAccessToken(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst clientId = credential.clientId;\n\tif (typeof clientId !== \"string\" || clientId.trim().length === 0) {\n\t\tthrow new Error(\"Stored OpenAI OAuth credential does not contain an issued client ID; reconnect ChatGPT\");\n\t}\n\tconst token = await requestToken(\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: clientId,\n\t\t\trefresh_token: credential.refresh,\n\t\t\tresource: RESOURCE,\n\t\t}),\n\t\tsignal,\n\t);\n\treturn credentialFromTokenResponse(token, clientId);\n}\n\nfunction agentHostId(deviceId: string | undefined): string {\n\tif (!deviceId || !UUID_PATTERN.test(deviceId)) {\n\t\tthrow new Error(\"Sign in with ChatGPT requires a device ID (UUID) for this installation\");\n\t}\n\treturn `urn:uuid:${deviceId.toLowerCase()}`;\n}\n\nasync function loginOpenAIChatGPT(\n\tinteraction: ProviderAuthInteraction,\n\toptions?: LoginOptions,\n): Promise<OAuthCredential> {\n\tconst hostId = agentHostId(options?.getDeviceId?.());\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = randomValue();\n\tconst nonce = randomValue();\n\tlet callback: CallbackServer | undefined;\n\ttry {\n\t\tcallback = await startCallbackServer(state);\n\t} catch (error) {\n\t\tinteraction.notify({\n\t\t\ttype: \"info\",\n\t\t\tmessage: `Could not listen on ${REDIRECT_URI}; paste the final redirect URL to continue. ${error instanceof Error ? error.message : String(error)}`,\n\t\t});\n\t}\n\tconst authorizationUrl = new URL(AUTHORIZE_URL);\n\tauthorizationUrl.search = new URLSearchParams({\n\t\tclient_id: DYNAMIC_CLIENT_ID,\n\t\tagent_name_hint: AGENT_NAME_HINT,\n\t\text_agent_host_id: hostId,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: REDIRECT_URI,\n\t\tresource: RESOURCE,\n\t\tscope: SCOPE,\n\t\tstate,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tnonce,\n\t}).toString();\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizationUrl.toString(),\n\t\tinstructions:\n\t\t\t\"Complete sign-in in your browser. If the callback does not complete, paste the final redirect URL here.\",\n\t});\n\tconst manualAbort = new AbortController();\n\tconst manualCode = interaction\n\t\t.prompt({\n\t\t\ttype: \"manual_code\",\n\t\t\tmessage: \"Complete login in your browser, or paste the final redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t\tsignal: AbortSignal.any([manualAbort.signal, interaction.signal]),\n\t\t})\n\t\t.then((input) => authorizationResultFromManualInput(input, state));\n\ttry {\n\t\tconst result = await (callback ? Promise.race([callback.result, manualCode]) : manualCode);\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(result.code, verifier, result.clientId, interaction.signal);\n\t} catch (error) {\n\t\tif (interaction.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tthrow error;\n\t} finally {\n\t\tmanualAbort.abort();\n\t\tcallback?.server.close();\n\t\t// Spare browser connections must not deliver a later login to this old server.\n\t\tcallback?.server.closeAllConnections();\n\t}\n}\n\nexport const openaiChatGPTOAuth: OAuthAuth = {\n\tname: \"OpenAI (ChatGPT subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with ChatGPT\",\n\tlogin: loginOpenAIChatGPT,\n\trefresh: refreshAccessToken,\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * OpenAI Codex (ChatGPT OAuth) flow
3
3
  *
4
- * NOTE: This module uses Node.js crypto and http for the OAuth callback.
4
+ * NOTE: This module uses Node.js crypto and http via callback-server.ts.
5
5
  * It is only intended for CLI use, not browser environments.
6
6
  */
7
7
  import type { OAuthAuth } from "../types.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAeH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA8evF,eAAO,MAAM,gBAAgB,EAAE,SA6B9B,CAAC"}
1
+ {"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAWH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAqYvF,eAAO,MAAM,gBAAgB,EAAE,SA6B9B,CAAC"}
@@ -1,23 +1,19 @@
1
1
  /**
2
2
  * OpenAI Codex (ChatGPT OAuth) flow
3
3
  *
4
- * NOTE: This module uses Node.js crypto and http for the OAuth callback.
4
+ * NOTE: This module uses Node.js crypto and http via callback-server.ts.
5
5
  * It is only intended for CLI use, not browser environments.
6
6
  */
7
7
  // NEVER convert to top-level imports - breaks browser/Vite builds
8
8
  let _randomBytes = null;
9
- let _http = null;
10
9
  if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
11
10
  import("node:crypto").then((m) => {
12
11
  _randomBytes = m.randomBytes;
13
12
  });
14
- import("node:http").then((m) => {
15
- _http = m;
16
- });
17
13
  }
18
14
  import { getProviderEnvValue } from "../../utils/provider-env.js";
15
+ import { startOAuthCallbackServer, waitForCallbackOrManualInput } from "./callback-server.js";
19
16
  import { pollOAuthDeviceCodeFlow } from "./device-code.js";
20
- import { oauthErrorHtml, oauthSuccessHtml } from "./oauth-page.js";
21
17
  import { generatePKCE } from "./pkce.js";
22
18
  const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
23
19
  const AUTH_BASE_URL = "https://auth.openai.com";
@@ -242,81 +238,6 @@ async function createAuthorizationFlow(originator = "pi") {
242
238
  url.searchParams.set("originator", originator);
243
239
  return { verifier, state, url: url.toString() };
244
240
  }
245
- function startLocalOAuthServer(state) {
246
- if (!_http) {
247
- throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
248
- }
249
- let settleWait;
250
- const waitForCodePromise = new Promise((resolve) => {
251
- let settled = false;
252
- settleWait = (value) => {
253
- if (settled)
254
- return;
255
- settled = true;
256
- resolve(value);
257
- };
258
- });
259
- const server = _http.createServer((req, res) => {
260
- try {
261
- const url = new URL(req.url || "", "http://localhost");
262
- if (url.pathname !== "/auth/callback") {
263
- res.statusCode = 404;
264
- res.setHeader("Content-Type", "text/html; charset=utf-8");
265
- res.end(oauthErrorHtml("Callback route not found."));
266
- return;
267
- }
268
- if (url.searchParams.get("state") !== state) {
269
- res.statusCode = 400;
270
- res.setHeader("Content-Type", "text/html; charset=utf-8");
271
- res.end(oauthErrorHtml("State mismatch."));
272
- return;
273
- }
274
- const code = url.searchParams.get("code");
275
- if (!code) {
276
- res.statusCode = 400;
277
- res.setHeader("Content-Type", "text/html; charset=utf-8");
278
- res.end(oauthErrorHtml("Missing authorization code."));
279
- return;
280
- }
281
- res.statusCode = 200;
282
- res.setHeader("Content-Type", "text/html; charset=utf-8");
283
- res.end(oauthSuccessHtml("OpenAI authentication completed. You can close this window."));
284
- settleWait?.({ code });
285
- }
286
- catch {
287
- res.statusCode = 500;
288
- res.setHeader("Content-Type", "text/html; charset=utf-8");
289
- res.end(oauthErrorHtml("Internal error while processing OAuth callback."));
290
- }
291
- });
292
- return new Promise((resolve) => {
293
- server
294
- .listen(1455, getCallbackHost(), () => {
295
- resolve({
296
- close: () => server.close(),
297
- cancelWait: () => {
298
- settleWait?.(null);
299
- },
300
- waitForCode: () => waitForCodePromise,
301
- });
302
- })
303
- .on("error", (_err) => {
304
- settleWait?.(null);
305
- resolve({
306
- close: () => {
307
- try {
308
- server.close();
309
- }
310
- catch {
311
- // ignore
312
- }
313
- },
314
- cancelWait: () => { },
315
- waitForCode: async () => null,
316
- });
317
- });
318
- });
319
- }
320
241
  function getAccountId(accessToken) {
321
242
  const payload = decodeJwt(accessToken);
322
243
  const auth = payload?.[JWT_CLAIM_PATH];
@@ -353,67 +274,42 @@ async function loginOpenAICodexDeviceCode(interaction) {
353
274
  }
354
275
  async function loginOpenAICodex(interaction) {
355
276
  const { verifier, state, url } = await createAuthorizationFlow();
356
- const server = await startLocalOAuthServer(state);
357
- const manualAbort = new AbortController();
358
- const onAbort = () => server.cancelWait();
359
- interaction.signal.addEventListener("abort", onAbort, { once: true });
360
- if (interaction.signal.aborted)
361
- onAbort();
362
- let code;
363
- let manualCode;
364
- let manualError;
277
+ // Port 1455 is shared with Codex CLI. Fall back to a pasted URL when occupied.
278
+ const callback = await startOAuthCallbackServer({
279
+ providerName: "OpenAI",
280
+ host: getCallbackHost(),
281
+ port: 1455,
282
+ path: "/auth/callback",
283
+ state,
284
+ complete: async (code) => code,
285
+ signal: interaction.signal,
286
+ }).catch(() => undefined);
365
287
  interaction.notify({
366
288
  type: "auth_url",
367
289
  url,
368
290
  instructions: "A browser window should open. Complete login to finish.",
369
291
  });
370
292
  try {
371
- const manualPromise = interaction
372
- .prompt({
373
- type: "manual_code",
293
+ const result = await waitForCallbackOrManualInput(interaction, callback, {
374
294
  message: "Complete login in your browser, or paste the authorization code / redirect URL here:",
375
295
  placeholder: REDIRECT_URI,
376
- signal: manualAbort.signal,
377
- })
378
- .then((input) => {
379
- manualCode = input;
380
- server.cancelWait();
381
- })
382
- .catch((error) => {
383
- manualError = error instanceof Error ? error : new Error(String(error));
384
- server.cancelWait();
385
296
  });
386
- const result = await server.waitForCode();
387
- if (manualError)
388
- throw manualError;
389
- if (result?.code) {
390
- code = result.code;
297
+ let code;
298
+ if (result.type === "callback") {
299
+ code = result.value;
391
300
  }
392
- else if (manualCode) {
393
- const parsed = parseAuthorizationInput(manualCode);
301
+ else {
302
+ const parsed = parseAuthorizationInput(result.input);
394
303
  if (parsed.state && parsed.state !== state)
395
304
  throw new Error("State mismatch");
396
305
  code = parsed.code;
397
306
  }
398
- if (!code) {
399
- await manualPromise;
400
- if (manualError)
401
- throw manualError;
402
- if (manualCode) {
403
- const parsed = parseAuthorizationInput(manualCode);
404
- if (parsed.state && parsed.state !== state)
405
- throw new Error("State mismatch");
406
- code = parsed.code;
407
- }
408
- }
409
307
  if (!code)
410
308
  throw new Error("Missing authorization code");
411
- return exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);
309
+ return await exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);
412
310
  }
413
311
  finally {
414
- interaction.signal.removeEventListener("abort", onAbort);
415
- manualAbort.abort();
416
- server.close();
312
+ callback?.close();
417
313
  }
418
314
  }
419
315
  /**