@draht/ai 2026.3.2-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.
- package/README.md +1185 -0
- package/dist/api-registry.d.ts +20 -0
- package/dist/api-registry.d.ts.map +1 -0
- package/dist/api-registry.js +44 -0
- package/dist/api-registry.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +116 -0
- package/dist/cli.js.map +1 -0
- package/dist/env-api-keys.d.ts +9 -0
- package/dist/env-api-keys.d.ts.map +1 -0
- package/dist/env-api-keys.js +99 -0
- package/dist/env-api-keys.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +24 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.generated.d.ts +13133 -0
- package/dist/models.generated.d.ts.map +1 -0
- package/dist/models.generated.js +12939 -0
- package/dist/models.generated.js.map +1 -0
- package/dist/models.js +55 -0
- package/dist/models.js.map +1 -0
- package/dist/providers/amazon-bedrock.d.ts +15 -0
- package/dist/providers/amazon-bedrock.d.ts.map +1 -0
- package/dist/providers/amazon-bedrock.js +585 -0
- package/dist/providers/amazon-bedrock.js.map +1 -0
- package/dist/providers/anthropic.d.ts +33 -0
- package/dist/providers/anthropic.d.ts.map +1 -0
- package/dist/providers/anthropic.js +729 -0
- package/dist/providers/anthropic.js.map +1 -0
- package/dist/providers/azure-openai-responses.d.ts +15 -0
- package/dist/providers/azure-openai-responses.d.ts.map +1 -0
- package/dist/providers/azure-openai-responses.js +184 -0
- package/dist/providers/azure-openai-responses.js.map +1 -0
- package/dist/providers/github-copilot-headers.d.ts +8 -0
- package/dist/providers/github-copilot-headers.d.ts.map +1 -0
- package/dist/providers/github-copilot-headers.js +29 -0
- package/dist/providers/github-copilot-headers.js.map +1 -0
- package/dist/providers/google-gemini-cli.d.ts +74 -0
- package/dist/providers/google-gemini-cli.d.ts.map +1 -0
- package/dist/providers/google-gemini-cli.js +735 -0
- package/dist/providers/google-gemini-cli.js.map +1 -0
- package/dist/providers/google-shared.d.ts +65 -0
- package/dist/providers/google-shared.d.ts.map +1 -0
- package/dist/providers/google-shared.js +306 -0
- package/dist/providers/google-shared.js.map +1 -0
- package/dist/providers/google-vertex.d.ts +15 -0
- package/dist/providers/google-vertex.d.ts.map +1 -0
- package/dist/providers/google-vertex.js +371 -0
- package/dist/providers/google-vertex.js.map +1 -0
- package/dist/providers/google.d.ts +13 -0
- package/dist/providers/google.d.ts.map +1 -0
- package/dist/providers/google.js +352 -0
- package/dist/providers/google.js.map +1 -0
- package/dist/providers/openai-codex-responses.d.ts +9 -0
- package/dist/providers/openai-codex-responses.d.ts.map +1 -0
- package/dist/providers/openai-codex-responses.js +699 -0
- package/dist/providers/openai-codex-responses.js.map +1 -0
- package/dist/providers/openai-completions.d.ts +15 -0
- package/dist/providers/openai-completions.d.ts.map +1 -0
- package/dist/providers/openai-completions.js +712 -0
- package/dist/providers/openai-completions.js.map +1 -0
- package/dist/providers/openai-responses-shared.d.ts +17 -0
- package/dist/providers/openai-responses-shared.d.ts.map +1 -0
- package/dist/providers/openai-responses-shared.js +427 -0
- package/dist/providers/openai-responses-shared.js.map +1 -0
- package/dist/providers/openai-responses.d.ts +13 -0
- package/dist/providers/openai-responses.d.ts.map +1 -0
- package/dist/providers/openai-responses.js +198 -0
- package/dist/providers/openai-responses.js.map +1 -0
- package/dist/providers/register-builtins.d.ts +3 -0
- package/dist/providers/register-builtins.d.ts.map +1 -0
- package/dist/providers/register-builtins.js +63 -0
- package/dist/providers/register-builtins.js.map +1 -0
- package/dist/providers/simple-options.d.ts +8 -0
- package/dist/providers/simple-options.d.ts.map +1 -0
- package/dist/providers/simple-options.js +35 -0
- package/dist/providers/simple-options.js.map +1 -0
- package/dist/providers/transform-messages.d.ts +8 -0
- package/dist/providers/transform-messages.d.ts.map +1 -0
- package/dist/providers/transform-messages.js +155 -0
- package/dist/providers/transform-messages.js.map +1 -0
- package/dist/stream.d.ts +9 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/stream.js +28 -0
- package/dist/stream.js.map +1 -0
- package/dist/types.d.ts +279 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/event-stream.d.ts +21 -0
- package/dist/utils/event-stream.d.ts.map +1 -0
- package/dist/utils/event-stream.js +81 -0
- package/dist/utils/event-stream.js.map +1 -0
- package/dist/utils/http-proxy.d.ts +2 -0
- package/dist/utils/http-proxy.d.ts.map +1 -0
- package/dist/utils/http-proxy.js +15 -0
- package/dist/utils/http-proxy.js.map +1 -0
- package/dist/utils/json-parse.d.ts +9 -0
- package/dist/utils/json-parse.d.ts.map +1 -0
- package/dist/utils/json-parse.js +29 -0
- package/dist/utils/json-parse.js.map +1 -0
- package/dist/utils/oauth/anthropic.d.ts +17 -0
- package/dist/utils/oauth/anthropic.d.ts.map +1 -0
- package/dist/utils/oauth/anthropic.js +104 -0
- package/dist/utils/oauth/anthropic.js.map +1 -0
- package/dist/utils/oauth/github-copilot.d.ts +30 -0
- package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
- package/dist/utils/oauth/github-copilot.js +281 -0
- package/dist/utils/oauth/github-copilot.js.map +1 -0
- package/dist/utils/oauth/google-antigravity.d.ts +26 -0
- package/dist/utils/oauth/google-antigravity.d.ts.map +1 -0
- package/dist/utils/oauth/google-antigravity.js +373 -0
- package/dist/utils/oauth/google-antigravity.js.map +1 -0
- package/dist/utils/oauth/google-gemini-cli.d.ts +26 -0
- package/dist/utils/oauth/google-gemini-cli.d.ts.map +1 -0
- package/dist/utils/oauth/google-gemini-cli.js +478 -0
- package/dist/utils/oauth/google-gemini-cli.js.map +1 -0
- package/dist/utils/oauth/index.d.ts +62 -0
- package/dist/utils/oauth/index.d.ts.map +1 -0
- package/dist/utils/oauth/index.js +133 -0
- package/dist/utils/oauth/index.js.map +1 -0
- package/dist/utils/oauth/openai-codex.d.ts +34 -0
- package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
- package/dist/utils/oauth/openai-codex.js +380 -0
- package/dist/utils/oauth/openai-codex.js.map +1 -0
- package/dist/utils/oauth/pkce.d.ts +13 -0
- package/dist/utils/oauth/pkce.d.ts.map +1 -0
- package/dist/utils/oauth/pkce.js +31 -0
- package/dist/utils/oauth/pkce.js.map +1 -0
- package/dist/utils/oauth/types.d.ts +47 -0
- package/dist/utils/oauth/types.d.ts.map +1 -0
- package/dist/utils/oauth/types.js +2 -0
- package/dist/utils/oauth/types.js.map +1 -0
- package/dist/utils/overflow.d.ts +52 -0
- package/dist/utils/overflow.d.ts.map +1 -0
- package/dist/utils/overflow.js +115 -0
- package/dist/utils/overflow.js.map +1 -0
- package/dist/utils/sanitize-unicode.d.ts +22 -0
- package/dist/utils/sanitize-unicode.d.ts.map +1 -0
- package/dist/utils/sanitize-unicode.js +26 -0
- package/dist/utils/sanitize-unicode.js.map +1 -0
- package/dist/utils/typebox-helpers.d.ts +17 -0
- package/dist/utils/typebox-helpers.d.ts.map +1 -0
- package/dist/utils/typebox-helpers.js +21 -0
- package/dist/utils/typebox-helpers.js.map +1 -0
- package/dist/utils/validation.d.ts +18 -0
- package/dist/utils/validation.d.ts.map +1 -0
- package/dist/utils/validation.js +72 -0
- package/dist/utils/validation.js.map +1 -0
- package/package.json +67 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth credential management for AI providers.
|
|
3
|
+
*
|
|
4
|
+
* This module handles login, token refresh, and credential storage
|
|
5
|
+
* for OAuth-based providers:
|
|
6
|
+
* - Anthropic (Claude Pro/Max)
|
|
7
|
+
* - GitHub Copilot
|
|
8
|
+
* - Google Cloud Code Assist (Gemini CLI)
|
|
9
|
+
* - Antigravity (Gemini 3, Claude, GPT-OSS via Google Cloud)
|
|
10
|
+
*/
|
|
11
|
+
// Set up HTTP proxy for fetch() calls (respects HTTP_PROXY, HTTPS_PROXY env vars)
|
|
12
|
+
import "../http-proxy.js";
|
|
13
|
+
// Anthropic
|
|
14
|
+
export { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from "./anthropic.js";
|
|
15
|
+
// GitHub Copilot
|
|
16
|
+
export { getGitHubCopilotBaseUrl, githubCopilotOAuthProvider, loginGitHubCopilot, normalizeDomain, refreshGitHubCopilotToken, } from "./github-copilot.js";
|
|
17
|
+
// Google Antigravity
|
|
18
|
+
export { antigravityOAuthProvider, loginAntigravity, refreshAntigravityToken } from "./google-antigravity.js";
|
|
19
|
+
// Google Gemini CLI
|
|
20
|
+
export { geminiCliOAuthProvider, loginGeminiCli, refreshGoogleCloudToken } from "./google-gemini-cli.js";
|
|
21
|
+
// OpenAI Codex (ChatGPT OAuth)
|
|
22
|
+
export { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from "./openai-codex.js";
|
|
23
|
+
export * from "./types.js";
|
|
24
|
+
// ============================================================================
|
|
25
|
+
// Provider Registry
|
|
26
|
+
// ============================================================================
|
|
27
|
+
import { anthropicOAuthProvider } from "./anthropic.js";
|
|
28
|
+
import { githubCopilotOAuthProvider } from "./github-copilot.js";
|
|
29
|
+
import { antigravityOAuthProvider } from "./google-antigravity.js";
|
|
30
|
+
import { geminiCliOAuthProvider } from "./google-gemini-cli.js";
|
|
31
|
+
import { openaiCodexOAuthProvider } from "./openai-codex.js";
|
|
32
|
+
const BUILT_IN_OAUTH_PROVIDERS = [
|
|
33
|
+
anthropicOAuthProvider,
|
|
34
|
+
githubCopilotOAuthProvider,
|
|
35
|
+
geminiCliOAuthProvider,
|
|
36
|
+
antigravityOAuthProvider,
|
|
37
|
+
openaiCodexOAuthProvider,
|
|
38
|
+
];
|
|
39
|
+
const oauthProviderRegistry = new Map(BUILT_IN_OAUTH_PROVIDERS.map((provider) => [provider.id, provider]));
|
|
40
|
+
/**
|
|
41
|
+
* Get an OAuth provider by ID
|
|
42
|
+
*/
|
|
43
|
+
export function getOAuthProvider(id) {
|
|
44
|
+
return oauthProviderRegistry.get(id);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Register a custom OAuth provider
|
|
48
|
+
*/
|
|
49
|
+
export function registerOAuthProvider(provider) {
|
|
50
|
+
oauthProviderRegistry.set(provider.id, provider);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Unregister an OAuth provider.
|
|
54
|
+
*
|
|
55
|
+
* If the provider is built-in, restores the built-in implementation.
|
|
56
|
+
* Custom providers are removed completely.
|
|
57
|
+
*/
|
|
58
|
+
export function unregisterOAuthProvider(id) {
|
|
59
|
+
const builtInProvider = BUILT_IN_OAUTH_PROVIDERS.find((provider) => provider.id === id);
|
|
60
|
+
if (builtInProvider) {
|
|
61
|
+
oauthProviderRegistry.set(id, builtInProvider);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
oauthProviderRegistry.delete(id);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Reset OAuth providers to built-ins.
|
|
68
|
+
*/
|
|
69
|
+
export function resetOAuthProviders() {
|
|
70
|
+
oauthProviderRegistry.clear();
|
|
71
|
+
for (const provider of BUILT_IN_OAUTH_PROVIDERS) {
|
|
72
|
+
oauthProviderRegistry.set(provider.id, provider);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Get all registered OAuth providers
|
|
77
|
+
*/
|
|
78
|
+
export function getOAuthProviders() {
|
|
79
|
+
return Array.from(oauthProviderRegistry.values());
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* @deprecated Use getOAuthProviders() which returns OAuthProviderInterface[]
|
|
83
|
+
*/
|
|
84
|
+
export function getOAuthProviderInfoList() {
|
|
85
|
+
return getOAuthProviders().map((p) => ({
|
|
86
|
+
id: p.id,
|
|
87
|
+
name: p.name,
|
|
88
|
+
available: true,
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
// ============================================================================
|
|
92
|
+
// High-level API (uses provider registry)
|
|
93
|
+
// ============================================================================
|
|
94
|
+
/**
|
|
95
|
+
* Refresh token for any OAuth provider.
|
|
96
|
+
* @deprecated Use getOAuthProvider(id).refreshToken() instead
|
|
97
|
+
*/
|
|
98
|
+
export async function refreshOAuthToken(providerId, credentials) {
|
|
99
|
+
const provider = getOAuthProvider(providerId);
|
|
100
|
+
if (!provider) {
|
|
101
|
+
throw new Error(`Unknown OAuth provider: ${providerId}`);
|
|
102
|
+
}
|
|
103
|
+
return provider.refreshToken(credentials);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Get API key for a provider from OAuth credentials.
|
|
107
|
+
* Automatically refreshes expired tokens.
|
|
108
|
+
*
|
|
109
|
+
* @returns API key string and updated credentials, or null if no credentials
|
|
110
|
+
* @throws Error if refresh fails
|
|
111
|
+
*/
|
|
112
|
+
export async function getOAuthApiKey(providerId, credentials) {
|
|
113
|
+
const provider = getOAuthProvider(providerId);
|
|
114
|
+
if (!provider) {
|
|
115
|
+
throw new Error(`Unknown OAuth provider: ${providerId}`);
|
|
116
|
+
}
|
|
117
|
+
let creds = credentials[providerId];
|
|
118
|
+
if (!creds) {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
// Refresh if expired
|
|
122
|
+
if (Date.now() >= creds.expires) {
|
|
123
|
+
try {
|
|
124
|
+
creds = await provider.refreshToken(creds);
|
|
125
|
+
}
|
|
126
|
+
catch (_error) {
|
|
127
|
+
throw new Error(`Failed to refresh OAuth token for ${providerId}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const apiKey = provider.getApiKey(creds);
|
|
131
|
+
return { newCredentials: creds, apiKey };
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/oauth/index.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * OAuth credential management for AI providers.\n *\n * This module handles login, token refresh, and credential storage\n * for OAuth-based providers:\n * - Anthropic (Claude Pro/Max)\n * - GitHub Copilot\n * - Google Cloud Code Assist (Gemini CLI)\n * - Antigravity (Gemini 3, Claude, GPT-OSS via Google Cloud)\n */\n\n// Set up HTTP proxy for fetch() calls (respects HTTP_PROXY, HTTPS_PROXY env vars)\nimport \"../http-proxy.js\";\n\n// Anthropic\nexport { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from \"./anthropic.js\";\n// GitHub Copilot\nexport {\n\tgetGitHubCopilotBaseUrl,\n\tgithubCopilotOAuthProvider,\n\tloginGitHubCopilot,\n\tnormalizeDomain,\n\trefreshGitHubCopilotToken,\n} from \"./github-copilot.js\";\n// Google Antigravity\nexport { antigravityOAuthProvider, loginAntigravity, refreshAntigravityToken } from \"./google-antigravity.js\";\n// Google Gemini CLI\nexport { geminiCliOAuthProvider, loginGeminiCli, refreshGoogleCloudToken } from \"./google-gemini-cli.js\";\n// OpenAI Codex (ChatGPT OAuth)\nexport { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from \"./openai-codex.js\";\n\nexport * from \"./types.js\";\n\n// ============================================================================\n// Provider Registry\n// ============================================================================\n\nimport { anthropicOAuthProvider } from \"./anthropic.js\";\nimport { githubCopilotOAuthProvider } from \"./github-copilot.js\";\nimport { antigravityOAuthProvider } from \"./google-antigravity.js\";\nimport { geminiCliOAuthProvider } from \"./google-gemini-cli.js\";\nimport { openaiCodexOAuthProvider } from \"./openai-codex.js\";\nimport type { OAuthCredentials, OAuthProviderId, OAuthProviderInfo, OAuthProviderInterface } from \"./types.js\";\n\nconst BUILT_IN_OAUTH_PROVIDERS: OAuthProviderInterface[] = [\n\tanthropicOAuthProvider,\n\tgithubCopilotOAuthProvider,\n\tgeminiCliOAuthProvider,\n\tantigravityOAuthProvider,\n\topenaiCodexOAuthProvider,\n];\n\nconst oauthProviderRegistry = new Map<string, OAuthProviderInterface>(\n\tBUILT_IN_OAUTH_PROVIDERS.map((provider) => [provider.id, provider]),\n);\n\n/**\n * Get an OAuth provider by ID\n */\nexport function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined {\n\treturn oauthProviderRegistry.get(id);\n}\n\n/**\n * Register a custom OAuth provider\n */\nexport function registerOAuthProvider(provider: OAuthProviderInterface): void {\n\toauthProviderRegistry.set(provider.id, provider);\n}\n\n/**\n * Unregister an OAuth provider.\n *\n * If the provider is built-in, restores the built-in implementation.\n * Custom providers are removed completely.\n */\nexport function unregisterOAuthProvider(id: string): void {\n\tconst builtInProvider = BUILT_IN_OAUTH_PROVIDERS.find((provider) => provider.id === id);\n\tif (builtInProvider) {\n\t\toauthProviderRegistry.set(id, builtInProvider);\n\t\treturn;\n\t}\n\toauthProviderRegistry.delete(id);\n}\n\n/**\n * Reset OAuth providers to built-ins.\n */\nexport function resetOAuthProviders(): void {\n\toauthProviderRegistry.clear();\n\tfor (const provider of BUILT_IN_OAUTH_PROVIDERS) {\n\t\toauthProviderRegistry.set(provider.id, provider);\n\t}\n}\n\n/**\n * Get all registered OAuth providers\n */\nexport function getOAuthProviders(): OAuthProviderInterface[] {\n\treturn Array.from(oauthProviderRegistry.values());\n}\n\n/**\n * @deprecated Use getOAuthProviders() which returns OAuthProviderInterface[]\n */\nexport function getOAuthProviderInfoList(): OAuthProviderInfo[] {\n\treturn getOAuthProviders().map((p) => ({\n\t\tid: p.id,\n\t\tname: p.name,\n\t\tavailable: true,\n\t}));\n}\n\n// ============================================================================\n// High-level API (uses provider registry)\n// ============================================================================\n\n/**\n * Refresh token for any OAuth provider.\n * @deprecated Use getOAuthProvider(id).refreshToken() instead\n */\nexport async function refreshOAuthToken(\n\tproviderId: OAuthProviderId,\n\tcredentials: OAuthCredentials,\n): Promise<OAuthCredentials> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t}\n\treturn provider.refreshToken(credentials);\n}\n\n/**\n * Get API key for a provider from OAuth credentials.\n * Automatically refreshes expired tokens.\n *\n * @returns API key string and updated credentials, or null if no credentials\n * @throws Error if refresh fails\n */\nexport async function getOAuthApiKey(\n\tproviderId: OAuthProviderId,\n\tcredentials: Record<string, OAuthCredentials>,\n): Promise<{ newCredentials: OAuthCredentials; apiKey: string } | null> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t}\n\n\tlet creds = credentials[providerId];\n\tif (!creds) {\n\t\treturn null;\n\t}\n\n\t// Refresh if expired\n\tif (Date.now() >= creds.expires) {\n\t\ttry {\n\t\t\tcreds = await provider.refreshToken(creds);\n\t\t} catch (_error) {\n\t\t\tthrow new Error(`Failed to refresh OAuth token for ${providerId}`);\n\t\t}\n\t}\n\n\tconst apiKey = provider.getApiKey(creds);\n\treturn { newCredentials: creds, apiKey };\n}\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Codex (ChatGPT OAuth) flow
|
|
3
|
+
*
|
|
4
|
+
* NOTE: This module uses Node.js crypto and http for the OAuth callback.
|
|
5
|
+
* It is only intended for CLI use, not browser environments.
|
|
6
|
+
*/
|
|
7
|
+
import type { OAuthCredentials, OAuthPrompt, OAuthProviderInterface } from "./types.js";
|
|
8
|
+
/**
|
|
9
|
+
* Login with OpenAI Codex OAuth
|
|
10
|
+
*
|
|
11
|
+
* @param options.onAuth - Called with URL and instructions when auth starts
|
|
12
|
+
* @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)
|
|
13
|
+
* @param options.onProgress - Optional progress messages
|
|
14
|
+
* @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.
|
|
15
|
+
* Races with browser callback - whichever completes first wins.
|
|
16
|
+
* Useful for showing paste input immediately alongside browser flow.
|
|
17
|
+
* @param options.originator - OAuth originator parameter (defaults to "draht")
|
|
18
|
+
*/
|
|
19
|
+
export declare function loginOpenAICodex(options: {
|
|
20
|
+
onAuth: (info: {
|
|
21
|
+
url: string;
|
|
22
|
+
instructions?: string;
|
|
23
|
+
}) => void;
|
|
24
|
+
onPrompt: (prompt: OAuthPrompt) => Promise<string>;
|
|
25
|
+
onProgress?: (message: string) => void;
|
|
26
|
+
onManualCodeInput?: () => Promise<string>;
|
|
27
|
+
originator?: string;
|
|
28
|
+
}): Promise<OAuthCredentials>;
|
|
29
|
+
/**
|
|
30
|
+
* Refresh OpenAI Codex OAuth token
|
|
31
|
+
*/
|
|
32
|
+
export declare function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials>;
|
|
33
|
+
export declare const openaiCodexOAuthProvider: OAuthProviderInterface;
|
|
34
|
+
//# sourceMappingURL=openai-codex.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAeH,OAAO,KAAK,EAAE,gBAAgB,EAAuB,WAAW,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAiR7G;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE;IAC/C,MAAM,EAAE,CAAC,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/D,QAAQ,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACnD,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,iBAAiB,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAmG5B;AAED;;GAEG;AACH,wBAAsB,uBAAuB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAiB7F;AAED,eAAO,MAAM,wBAAwB,EAAE,sBAqBtC,CAAC","sourcesContent":["/**\n * OpenAI Codex (ChatGPT OAuth) flow\n *\n * NOTE: This module uses Node.js crypto and http for the OAuth callback.\n * It is only intended for CLI use, not browser environments.\n */\n\n// NEVER convert to top-level imports - breaks browser/Vite builds (web-ui)\nlet _randomBytes: typeof import(\"node:crypto\").randomBytes | null = null;\nlet _http: typeof import(\"node:http\") | null = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:crypto\").then((m) => {\n\t\t_randomBytes = m.randomBytes;\n\t});\n\timport(\"node:http\").then((m) => {\n\t\t_http = m;\n\t});\n}\n\nimport { generatePKCE } from \"./pkce.js\";\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthPrompt, OAuthProviderInterface } from \"./types.js\";\n\nconst CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\";\nconst AUTHORIZE_URL = \"https://auth.openai.com/oauth/authorize\";\nconst TOKEN_URL = \"https://auth.openai.com/oauth/token\";\nconst REDIRECT_URI = \"http://localhost:1455/auth/callback\";\nconst SCOPE = \"openid profile email offline_access\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\";\n\nconst SUCCESS_HTML = `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Authentication successful</title>\n</head>\n<body>\n <p>Authentication successful. Return to your terminal to continue.</p>\n</body>\n</html>`;\n\ntype TokenSuccess = { type: \"success\"; access: string; refresh: string; expires: number };\ntype TokenFailure = { type: \"failed\" };\ntype TokenResult = TokenSuccess | TokenFailure;\n\ntype JwtPayload = {\n\t[JWT_CLAIM_PATH]?: {\n\t\tchatgpt_account_id?: string;\n\t};\n\t[key: string]: unknown;\n};\n\nfunction createState(): string {\n\tif (!_randomBytes) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\treturn _randomBytes(16).toString(\"hex\");\n}\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\n\t}\n\n\treturn { code: value };\n}\n\nfunction decodeJwt(token: string): JwtPayload | null {\n\ttry {\n\t\tconst parts = token.split(\".\");\n\t\tif (parts.length !== 3) return null;\n\t\tconst payload = parts[1] ?? \"\";\n\t\tconst decoded = atob(payload);\n\t\treturn JSON.parse(decoded) as JwtPayload;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tverifier: string,\n\tredirectUri: string = REDIRECT_URI,\n): Promise<TokenResult> {\n\tconst response = await fetch(TOKEN_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\tbody: new URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tcode,\n\t\t\tcode_verifier: verifier,\n\t\t\tredirect_uri: redirectUri,\n\t\t}),\n\t});\n\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tconsole.error(\"[openai-codex] code->token failed:\", response.status, text);\n\t\treturn { type: \"failed\" };\n\t}\n\n\tconst json = (await response.json()) as {\n\t\taccess_token?: string;\n\t\trefresh_token?: string;\n\t\texpires_in?: number;\n\t};\n\n\tif (!json.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\tconsole.error(\"[openai-codex] token response missing fields:\", json);\n\t\treturn { type: \"failed\" };\n\t}\n\n\treturn {\n\t\ttype: \"success\",\n\t\taccess: json.access_token,\n\t\trefresh: json.refresh_token,\n\t\texpires: Date.now() + json.expires_in * 1000,\n\t};\n}\n\nasync function refreshAccessToken(refreshToken: string): Promise<TokenResult> {\n\ttry {\n\t\tconst response = await fetch(TOKEN_URL, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t}),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tconsole.error(\"[openai-codex] Token refresh failed:\", response.status, text);\n\t\t\treturn { type: \"failed\" };\n\t\t}\n\n\t\tconst json = (await response.json()) as {\n\t\t\taccess_token?: string;\n\t\t\trefresh_token?: string;\n\t\t\texpires_in?: number;\n\t\t};\n\n\t\tif (!json.access_token || !json.refresh_token || typeof json.expires_in !== \"number\") {\n\t\t\tconsole.error(\"[openai-codex] Token refresh response missing fields:\", json);\n\t\t\treturn { type: \"failed\" };\n\t\t}\n\n\t\treturn {\n\t\t\ttype: \"success\",\n\t\t\taccess: json.access_token,\n\t\t\trefresh: json.refresh_token,\n\t\t\texpires: Date.now() + json.expires_in * 1000,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"[openai-codex] Token refresh error:\", error);\n\t\treturn { type: \"failed\" };\n\t}\n}\n\nasync function createAuthorizationFlow(\n\toriginator: string = \"draht\",\n): Promise<{ verifier: string; state: string; url: string }> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = createState();\n\n\tconst url = new URL(AUTHORIZE_URL);\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", CLIENT_ID);\n\turl.searchParams.set(\"redirect_uri\", REDIRECT_URI);\n\turl.searchParams.set(\"scope\", SCOPE);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"state\", state);\n\turl.searchParams.set(\"id_token_add_organizations\", \"true\");\n\turl.searchParams.set(\"codex_cli_simplified_flow\", \"true\");\n\turl.searchParams.set(\"originator\", originator);\n\n\treturn { verifier, state, url: url.toString() };\n}\n\ntype OAuthServerInfo = {\n\tclose: () => void;\n\tcancelWait: () => void;\n\twaitForCode: () => Promise<{ code: string } | null>;\n};\n\nfunction startLocalOAuthServer(state: string): Promise<OAuthServerInfo> {\n\tif (!_http) {\n\t\tthrow new Error(\"OpenAI Codex OAuth is only available in Node.js environments\");\n\t}\n\tlet lastCode: string | null = null;\n\tlet cancelled = false;\n\tconst server = _http.createServer((req, res) => {\n\t\ttry {\n\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\tif (url.pathname !== \"/auth/callback\") {\n\t\t\t\tres.statusCode = 404;\n\t\t\t\tres.end(\"Not found\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (url.searchParams.get(\"state\") !== state) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.end(\"State mismatch\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = url.searchParams.get(\"code\");\n\t\t\tif (!code) {\n\t\t\t\tres.statusCode = 400;\n\t\t\t\tres.end(\"Missing authorization code\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres.statusCode = 200;\n\t\t\tres.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n\t\t\tres.end(SUCCESS_HTML);\n\t\t\tlastCode = code;\n\t\t} catch {\n\t\t\tres.statusCode = 500;\n\t\t\tres.end(\"Internal error\");\n\t\t}\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(1455, \"127.0.0.1\", () => {\n\t\t\t\tresolve({\n\t\t\t\t\tclose: () => server.close(),\n\t\t\t\t\tcancelWait: () => {\n\t\t\t\t\t\tcancelled = true;\n\t\t\t\t\t},\n\t\t\t\t\twaitForCode: async () => {\n\t\t\t\t\t\tconst sleep = () => new Promise((r) => setTimeout(r, 100));\n\t\t\t\t\t\tfor (let i = 0; i < 600; i += 1) {\n\t\t\t\t\t\t\tif (lastCode) return { code: lastCode };\n\t\t\t\t\t\t\tif (cancelled) return null;\n\t\t\t\t\t\t\tawait sleep();\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t})\n\t\t\t.on(\"error\", (err: NodeJS.ErrnoException) => {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"[openai-codex] Failed to bind http://127.0.0.1:1455 (\",\n\t\t\t\t\terr.code,\n\t\t\t\t\t\") Falling back to manual paste.\",\n\t\t\t\t);\n\t\t\t\tresolve({\n\t\t\t\t\tclose: () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tserver.close();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// ignore\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tcancelWait: () => {},\n\t\t\t\t\twaitForCode: async () => null,\n\t\t\t\t});\n\t\t\t});\n\t});\n}\n\nfunction getAccountId(accessToken: string): string | null {\n\tconst payload = decodeJwt(accessToken);\n\tconst auth = payload?.[JWT_CLAIM_PATH];\n\tconst accountId = auth?.chatgpt_account_id;\n\treturn typeof accountId === \"string\" && accountId.length > 0 ? accountId : null;\n}\n\n/**\n * Login with OpenAI Codex OAuth\n *\n * @param options.onAuth - Called with URL and instructions when auth starts\n * @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)\n * @param options.onProgress - Optional progress messages\n * @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.\n * Races with browser callback - whichever completes first wins.\n * Useful for showing paste input immediately alongside browser flow.\n * @param options.originator - OAuth originator parameter (defaults to \"draht\")\n */\nexport async function loginOpenAICodex(options: {\n\tonAuth: (info: { url: string; instructions?: string }) => void;\n\tonPrompt: (prompt: OAuthPrompt) => Promise<string>;\n\tonProgress?: (message: string) => void;\n\tonManualCodeInput?: () => Promise<string>;\n\toriginator?: string;\n}): Promise<OAuthCredentials> {\n\tconst { verifier, state, url } = await createAuthorizationFlow(options.originator);\n\tconst server = await startLocalOAuthServer(state);\n\n\toptions.onAuth({ url, instructions: \"A browser window should open. Complete login to finish.\" });\n\n\tlet code: string | undefined;\n\ttry {\n\t\tif (options.onManualCodeInput) {\n\t\t\t// Race between browser callback and manual input\n\t\t\tlet manualCode: string | undefined;\n\t\t\tlet manualError: Error | undefined;\n\t\t\tconst manualPromise = options\n\t\t\t\t.onManualCodeInput()\n\t\t\t\t.then((input) => {\n\t\t\t\t\tmanualCode = input;\n\t\t\t\t\tserver.cancelWait();\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tmanualError = err instanceof Error ? err : new Error(String(err));\n\t\t\t\t\tserver.cancelWait();\n\t\t\t\t});\n\n\t\t\tconst result = await server.waitForCode();\n\n\t\t\t// If manual input was cancelled, throw that error\n\t\t\tif (manualError) {\n\t\t\t\tthrow manualError;\n\t\t\t}\n\n\t\t\tif (result?.code) {\n\t\t\t\t// Browser callback won\n\t\t\t\tcode = result.code;\n\t\t\t} else if (manualCode) {\n\t\t\t\t// Manual input won (or callback timed out and user had entered code)\n\t\t\t\tconst parsed = parseAuthorizationInput(manualCode);\n\t\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t\t}\n\t\t\t\tcode = parsed.code;\n\t\t\t}\n\n\t\t\t// If still no code, wait for manual promise to complete and try that\n\t\t\tif (!code) {\n\t\t\t\tawait manualPromise;\n\t\t\t\tif (manualError) {\n\t\t\t\t\tthrow manualError;\n\t\t\t\t}\n\t\t\t\tif (manualCode) {\n\t\t\t\t\tconst parsed = parseAuthorizationInput(manualCode);\n\t\t\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t\t\t}\n\t\t\t\t\tcode = parsed.code;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// Original flow: wait for callback, then prompt if needed\n\t\t\tconst result = await server.waitForCode();\n\t\t\tif (result?.code) {\n\t\t\t\tcode = result.code;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to onPrompt if still no code\n\t\tif (!code) {\n\t\t\tconst input = await options.onPrompt({\n\t\t\t\tmessage: \"Paste the authorization code (or full redirect URL):\",\n\t\t\t});\n\t\t\tconst parsed = parseAuthorizationInput(input);\n\t\t\tif (parsed.state && parsed.state !== state) {\n\t\t\t\tthrow new Error(\"State mismatch\");\n\t\t\t}\n\t\t\tcode = parsed.code;\n\t\t}\n\n\t\tif (!code) {\n\t\t\tthrow new Error(\"Missing authorization code\");\n\t\t}\n\n\t\tconst tokenResult = await exchangeAuthorizationCode(code, verifier);\n\t\tif (tokenResult.type !== \"success\") {\n\t\t\tthrow new Error(\"Token exchange failed\");\n\t\t}\n\n\t\tconst accountId = getAccountId(tokenResult.access);\n\t\tif (!accountId) {\n\t\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t\t}\n\n\t\treturn {\n\t\t\taccess: tokenResult.access,\n\t\t\trefresh: tokenResult.refresh,\n\t\t\texpires: tokenResult.expires,\n\t\t\taccountId,\n\t\t};\n\t} finally {\n\t\tserver.close();\n\t}\n}\n\n/**\n * Refresh OpenAI Codex OAuth token\n */\nexport async function refreshOpenAICodexToken(refreshToken: string): Promise<OAuthCredentials> {\n\tconst result = await refreshAccessToken(refreshToken);\n\tif (result.type !== \"success\") {\n\t\tthrow new Error(\"Failed to refresh OpenAI Codex token\");\n\t}\n\n\tconst accountId = getAccountId(result.access);\n\tif (!accountId) {\n\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t}\n\n\treturn {\n\t\taccess: result.access,\n\t\trefresh: result.refresh,\n\t\texpires: result.expires,\n\t\taccountId,\n\t};\n}\n\nexport const openaiCodexOAuthProvider: OAuthProviderInterface = {\n\tid: \"openai-codex\",\n\tname: \"ChatGPT Plus/Pro (Codex Subscription)\",\n\tusesCallbackServer: true,\n\n\tasync login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n\t\treturn loginOpenAICodex({\n\t\t\tonAuth: callbacks.onAuth,\n\t\t\tonPrompt: callbacks.onPrompt,\n\t\t\tonProgress: callbacks.onProgress,\n\t\t\tonManualCodeInput: callbacks.onManualCodeInput,\n\t\t});\n\t},\n\n\tasync refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n\t\treturn refreshOpenAICodexToken(credentials.refresh);\n\t},\n\n\tgetApiKey(credentials: OAuthCredentials): string {\n\t\treturn credentials.access;\n\t},\n};\n"]}
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Codex (ChatGPT OAuth) flow
|
|
3
|
+
*
|
|
4
|
+
* NOTE: This module uses Node.js crypto and http for the OAuth callback.
|
|
5
|
+
* It is only intended for CLI use, not browser environments.
|
|
6
|
+
*/
|
|
7
|
+
// NEVER convert to top-level imports - breaks browser/Vite builds (web-ui)
|
|
8
|
+
let _randomBytes = null;
|
|
9
|
+
let _http = null;
|
|
10
|
+
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
|
|
11
|
+
import("node:crypto").then((m) => {
|
|
12
|
+
_randomBytes = m.randomBytes;
|
|
13
|
+
});
|
|
14
|
+
import("node:http").then((m) => {
|
|
15
|
+
_http = m;
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
import { generatePKCE } from "./pkce.js";
|
|
19
|
+
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
20
|
+
const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";
|
|
21
|
+
const TOKEN_URL = "https://auth.openai.com/oauth/token";
|
|
22
|
+
const REDIRECT_URI = "http://localhost:1455/auth/callback";
|
|
23
|
+
const SCOPE = "openid profile email offline_access";
|
|
24
|
+
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
|
|
25
|
+
const SUCCESS_HTML = `<!doctype html>
|
|
26
|
+
<html lang="en">
|
|
27
|
+
<head>
|
|
28
|
+
<meta charset="utf-8" />
|
|
29
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
30
|
+
<title>Authentication successful</title>
|
|
31
|
+
</head>
|
|
32
|
+
<body>
|
|
33
|
+
<p>Authentication successful. Return to your terminal to continue.</p>
|
|
34
|
+
</body>
|
|
35
|
+
</html>`;
|
|
36
|
+
function createState() {
|
|
37
|
+
if (!_randomBytes) {
|
|
38
|
+
throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
|
|
39
|
+
}
|
|
40
|
+
return _randomBytes(16).toString("hex");
|
|
41
|
+
}
|
|
42
|
+
function parseAuthorizationInput(input) {
|
|
43
|
+
const value = input.trim();
|
|
44
|
+
if (!value)
|
|
45
|
+
return {};
|
|
46
|
+
try {
|
|
47
|
+
const url = new URL(value);
|
|
48
|
+
return {
|
|
49
|
+
code: url.searchParams.get("code") ?? undefined,
|
|
50
|
+
state: url.searchParams.get("state") ?? undefined,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// not a URL
|
|
55
|
+
}
|
|
56
|
+
if (value.includes("#")) {
|
|
57
|
+
const [code, state] = value.split("#", 2);
|
|
58
|
+
return { code, state };
|
|
59
|
+
}
|
|
60
|
+
if (value.includes("code=")) {
|
|
61
|
+
const params = new URLSearchParams(value);
|
|
62
|
+
return {
|
|
63
|
+
code: params.get("code") ?? undefined,
|
|
64
|
+
state: params.get("state") ?? undefined,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
return { code: value };
|
|
68
|
+
}
|
|
69
|
+
function decodeJwt(token) {
|
|
70
|
+
try {
|
|
71
|
+
const parts = token.split(".");
|
|
72
|
+
if (parts.length !== 3)
|
|
73
|
+
return null;
|
|
74
|
+
const payload = parts[1] ?? "";
|
|
75
|
+
const decoded = atob(payload);
|
|
76
|
+
return JSON.parse(decoded);
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function exchangeAuthorizationCode(code, verifier, redirectUri = REDIRECT_URI) {
|
|
83
|
+
const response = await fetch(TOKEN_URL, {
|
|
84
|
+
method: "POST",
|
|
85
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
86
|
+
body: new URLSearchParams({
|
|
87
|
+
grant_type: "authorization_code",
|
|
88
|
+
client_id: CLIENT_ID,
|
|
89
|
+
code,
|
|
90
|
+
code_verifier: verifier,
|
|
91
|
+
redirect_uri: redirectUri,
|
|
92
|
+
}),
|
|
93
|
+
});
|
|
94
|
+
if (!response.ok) {
|
|
95
|
+
const text = await response.text().catch(() => "");
|
|
96
|
+
console.error("[openai-codex] code->token failed:", response.status, text);
|
|
97
|
+
return { type: "failed" };
|
|
98
|
+
}
|
|
99
|
+
const json = (await response.json());
|
|
100
|
+
if (!json.access_token || !json.refresh_token || typeof json.expires_in !== "number") {
|
|
101
|
+
console.error("[openai-codex] token response missing fields:", json);
|
|
102
|
+
return { type: "failed" };
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
type: "success",
|
|
106
|
+
access: json.access_token,
|
|
107
|
+
refresh: json.refresh_token,
|
|
108
|
+
expires: Date.now() + json.expires_in * 1000,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
async function refreshAccessToken(refreshToken) {
|
|
112
|
+
try {
|
|
113
|
+
const response = await fetch(TOKEN_URL, {
|
|
114
|
+
method: "POST",
|
|
115
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
116
|
+
body: new URLSearchParams({
|
|
117
|
+
grant_type: "refresh_token",
|
|
118
|
+
refresh_token: refreshToken,
|
|
119
|
+
client_id: CLIENT_ID,
|
|
120
|
+
}),
|
|
121
|
+
});
|
|
122
|
+
if (!response.ok) {
|
|
123
|
+
const text = await response.text().catch(() => "");
|
|
124
|
+
console.error("[openai-codex] Token refresh failed:", response.status, text);
|
|
125
|
+
return { type: "failed" };
|
|
126
|
+
}
|
|
127
|
+
const json = (await response.json());
|
|
128
|
+
if (!json.access_token || !json.refresh_token || typeof json.expires_in !== "number") {
|
|
129
|
+
console.error("[openai-codex] Token refresh response missing fields:", json);
|
|
130
|
+
return { type: "failed" };
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
type: "success",
|
|
134
|
+
access: json.access_token,
|
|
135
|
+
refresh: json.refresh_token,
|
|
136
|
+
expires: Date.now() + json.expires_in * 1000,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
console.error("[openai-codex] Token refresh error:", error);
|
|
141
|
+
return { type: "failed" };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async function createAuthorizationFlow(originator = "draht") {
|
|
145
|
+
const { verifier, challenge } = await generatePKCE();
|
|
146
|
+
const state = createState();
|
|
147
|
+
const url = new URL(AUTHORIZE_URL);
|
|
148
|
+
url.searchParams.set("response_type", "code");
|
|
149
|
+
url.searchParams.set("client_id", CLIENT_ID);
|
|
150
|
+
url.searchParams.set("redirect_uri", REDIRECT_URI);
|
|
151
|
+
url.searchParams.set("scope", SCOPE);
|
|
152
|
+
url.searchParams.set("code_challenge", challenge);
|
|
153
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
154
|
+
url.searchParams.set("state", state);
|
|
155
|
+
url.searchParams.set("id_token_add_organizations", "true");
|
|
156
|
+
url.searchParams.set("codex_cli_simplified_flow", "true");
|
|
157
|
+
url.searchParams.set("originator", originator);
|
|
158
|
+
return { verifier, state, url: url.toString() };
|
|
159
|
+
}
|
|
160
|
+
function startLocalOAuthServer(state) {
|
|
161
|
+
if (!_http) {
|
|
162
|
+
throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
|
|
163
|
+
}
|
|
164
|
+
let lastCode = null;
|
|
165
|
+
let cancelled = false;
|
|
166
|
+
const server = _http.createServer((req, res) => {
|
|
167
|
+
try {
|
|
168
|
+
const url = new URL(req.url || "", "http://localhost");
|
|
169
|
+
if (url.pathname !== "/auth/callback") {
|
|
170
|
+
res.statusCode = 404;
|
|
171
|
+
res.end("Not found");
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (url.searchParams.get("state") !== state) {
|
|
175
|
+
res.statusCode = 400;
|
|
176
|
+
res.end("State mismatch");
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const code = url.searchParams.get("code");
|
|
180
|
+
if (!code) {
|
|
181
|
+
res.statusCode = 400;
|
|
182
|
+
res.end("Missing authorization code");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
res.statusCode = 200;
|
|
186
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
187
|
+
res.end(SUCCESS_HTML);
|
|
188
|
+
lastCode = code;
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
res.statusCode = 500;
|
|
192
|
+
res.end("Internal error");
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
return new Promise((resolve) => {
|
|
196
|
+
server
|
|
197
|
+
.listen(1455, "127.0.0.1", () => {
|
|
198
|
+
resolve({
|
|
199
|
+
close: () => server.close(),
|
|
200
|
+
cancelWait: () => {
|
|
201
|
+
cancelled = true;
|
|
202
|
+
},
|
|
203
|
+
waitForCode: async () => {
|
|
204
|
+
const sleep = () => new Promise((r) => setTimeout(r, 100));
|
|
205
|
+
for (let i = 0; i < 600; i += 1) {
|
|
206
|
+
if (lastCode)
|
|
207
|
+
return { code: lastCode };
|
|
208
|
+
if (cancelled)
|
|
209
|
+
return null;
|
|
210
|
+
await sleep();
|
|
211
|
+
}
|
|
212
|
+
return null;
|
|
213
|
+
},
|
|
214
|
+
});
|
|
215
|
+
})
|
|
216
|
+
.on("error", (err) => {
|
|
217
|
+
console.error("[openai-codex] Failed to bind http://127.0.0.1:1455 (", err.code, ") Falling back to manual paste.");
|
|
218
|
+
resolve({
|
|
219
|
+
close: () => {
|
|
220
|
+
try {
|
|
221
|
+
server.close();
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
// ignore
|
|
225
|
+
}
|
|
226
|
+
},
|
|
227
|
+
cancelWait: () => { },
|
|
228
|
+
waitForCode: async () => null,
|
|
229
|
+
});
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
function getAccountId(accessToken) {
|
|
234
|
+
const payload = decodeJwt(accessToken);
|
|
235
|
+
const auth = payload?.[JWT_CLAIM_PATH];
|
|
236
|
+
const accountId = auth?.chatgpt_account_id;
|
|
237
|
+
return typeof accountId === "string" && accountId.length > 0 ? accountId : null;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Login with OpenAI Codex OAuth
|
|
241
|
+
*
|
|
242
|
+
* @param options.onAuth - Called with URL and instructions when auth starts
|
|
243
|
+
* @param options.onPrompt - Called to prompt user for manual code paste (fallback if no onManualCodeInput)
|
|
244
|
+
* @param options.onProgress - Optional progress messages
|
|
245
|
+
* @param options.onManualCodeInput - Optional promise that resolves with user-pasted code.
|
|
246
|
+
* Races with browser callback - whichever completes first wins.
|
|
247
|
+
* Useful for showing paste input immediately alongside browser flow.
|
|
248
|
+
* @param options.originator - OAuth originator parameter (defaults to "draht")
|
|
249
|
+
*/
|
|
250
|
+
export async function loginOpenAICodex(options) {
|
|
251
|
+
const { verifier, state, url } = await createAuthorizationFlow(options.originator);
|
|
252
|
+
const server = await startLocalOAuthServer(state);
|
|
253
|
+
options.onAuth({ url, instructions: "A browser window should open. Complete login to finish." });
|
|
254
|
+
let code;
|
|
255
|
+
try {
|
|
256
|
+
if (options.onManualCodeInput) {
|
|
257
|
+
// Race between browser callback and manual input
|
|
258
|
+
let manualCode;
|
|
259
|
+
let manualError;
|
|
260
|
+
const manualPromise = options
|
|
261
|
+
.onManualCodeInput()
|
|
262
|
+
.then((input) => {
|
|
263
|
+
manualCode = input;
|
|
264
|
+
server.cancelWait();
|
|
265
|
+
})
|
|
266
|
+
.catch((err) => {
|
|
267
|
+
manualError = err instanceof Error ? err : new Error(String(err));
|
|
268
|
+
server.cancelWait();
|
|
269
|
+
});
|
|
270
|
+
const result = await server.waitForCode();
|
|
271
|
+
// If manual input was cancelled, throw that error
|
|
272
|
+
if (manualError) {
|
|
273
|
+
throw manualError;
|
|
274
|
+
}
|
|
275
|
+
if (result?.code) {
|
|
276
|
+
// Browser callback won
|
|
277
|
+
code = result.code;
|
|
278
|
+
}
|
|
279
|
+
else if (manualCode) {
|
|
280
|
+
// Manual input won (or callback timed out and user had entered code)
|
|
281
|
+
const parsed = parseAuthorizationInput(manualCode);
|
|
282
|
+
if (parsed.state && parsed.state !== state) {
|
|
283
|
+
throw new Error("State mismatch");
|
|
284
|
+
}
|
|
285
|
+
code = parsed.code;
|
|
286
|
+
}
|
|
287
|
+
// If still no code, wait for manual promise to complete and try that
|
|
288
|
+
if (!code) {
|
|
289
|
+
await manualPromise;
|
|
290
|
+
if (manualError) {
|
|
291
|
+
throw manualError;
|
|
292
|
+
}
|
|
293
|
+
if (manualCode) {
|
|
294
|
+
const parsed = parseAuthorizationInput(manualCode);
|
|
295
|
+
if (parsed.state && parsed.state !== state) {
|
|
296
|
+
throw new Error("State mismatch");
|
|
297
|
+
}
|
|
298
|
+
code = parsed.code;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
// Original flow: wait for callback, then prompt if needed
|
|
304
|
+
const result = await server.waitForCode();
|
|
305
|
+
if (result?.code) {
|
|
306
|
+
code = result.code;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// Fallback to onPrompt if still no code
|
|
310
|
+
if (!code) {
|
|
311
|
+
const input = await options.onPrompt({
|
|
312
|
+
message: "Paste the authorization code (or full redirect URL):",
|
|
313
|
+
});
|
|
314
|
+
const parsed = parseAuthorizationInput(input);
|
|
315
|
+
if (parsed.state && parsed.state !== state) {
|
|
316
|
+
throw new Error("State mismatch");
|
|
317
|
+
}
|
|
318
|
+
code = parsed.code;
|
|
319
|
+
}
|
|
320
|
+
if (!code) {
|
|
321
|
+
throw new Error("Missing authorization code");
|
|
322
|
+
}
|
|
323
|
+
const tokenResult = await exchangeAuthorizationCode(code, verifier);
|
|
324
|
+
if (tokenResult.type !== "success") {
|
|
325
|
+
throw new Error("Token exchange failed");
|
|
326
|
+
}
|
|
327
|
+
const accountId = getAccountId(tokenResult.access);
|
|
328
|
+
if (!accountId) {
|
|
329
|
+
throw new Error("Failed to extract accountId from token");
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
access: tokenResult.access,
|
|
333
|
+
refresh: tokenResult.refresh,
|
|
334
|
+
expires: tokenResult.expires,
|
|
335
|
+
accountId,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
finally {
|
|
339
|
+
server.close();
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Refresh OpenAI Codex OAuth token
|
|
344
|
+
*/
|
|
345
|
+
export async function refreshOpenAICodexToken(refreshToken) {
|
|
346
|
+
const result = await refreshAccessToken(refreshToken);
|
|
347
|
+
if (result.type !== "success") {
|
|
348
|
+
throw new Error("Failed to refresh OpenAI Codex token");
|
|
349
|
+
}
|
|
350
|
+
const accountId = getAccountId(result.access);
|
|
351
|
+
if (!accountId) {
|
|
352
|
+
throw new Error("Failed to extract accountId from token");
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
access: result.access,
|
|
356
|
+
refresh: result.refresh,
|
|
357
|
+
expires: result.expires,
|
|
358
|
+
accountId,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
export const openaiCodexOAuthProvider = {
|
|
362
|
+
id: "openai-codex",
|
|
363
|
+
name: "ChatGPT Plus/Pro (Codex Subscription)",
|
|
364
|
+
usesCallbackServer: true,
|
|
365
|
+
async login(callbacks) {
|
|
366
|
+
return loginOpenAICodex({
|
|
367
|
+
onAuth: callbacks.onAuth,
|
|
368
|
+
onPrompt: callbacks.onPrompt,
|
|
369
|
+
onProgress: callbacks.onProgress,
|
|
370
|
+
onManualCodeInput: callbacks.onManualCodeInput,
|
|
371
|
+
});
|
|
372
|
+
},
|
|
373
|
+
async refreshToken(credentials) {
|
|
374
|
+
return refreshOpenAICodexToken(credentials.refresh);
|
|
375
|
+
},
|
|
376
|
+
getApiKey(credentials) {
|
|
377
|
+
return credentials.access;
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
//# sourceMappingURL=openai-codex.js.map
|