forked from numman-ali/opencode-openai-codex-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
298 lines (276 loc) · 8.93 KB
/
index.ts
File metadata and controls
298 lines (276 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/**
* OpenAI ChatGPT (Codex) OAuth Authentication Plugin for opencode
*
* COMPLIANCE NOTICE:
* This plugin uses OpenAI's official OAuth authentication flow (the same method
* used by OpenAI's official Codex CLI at https://github.com/openai/codex).
*
* INTENDED USE: Personal development and coding assistance with your own
* ChatGPT Plus/Pro subscription.
*
* NOT INTENDED FOR: Commercial resale, multi-user services, high-volume
* automated extraction, or any use that violates OpenAI's Terms of Service.
*
* Users are responsible for ensuring their usage complies with:
* - OpenAI Terms of Use: https://openai.com/policies/terms-of-use/
* - OpenAI Usage Policies: https://openai.com/policies/usage-policies/
*
* For production applications, use the OpenAI Platform API: https://platform.openai.com/
*
* @license MIT with Usage Disclaimer (see LICENSE file)
* @author numman-ali
* @repository https://github.com/numman-ali/opencode-openai-codex-auth
*/
import type { Plugin, PluginInput } from "@opencode-ai/plugin";
import type { Auth } from "@opencode-ai/sdk";
import {
createAuthorizationFlow,
decodeJWT,
exchangeAuthorizationCode,
parseAuthorizationInput,
REDIRECT_URI,
} from "./lib/auth/auth.js";
import { openBrowserUrl } from "./lib/auth/browser.js";
import { startLocalOAuthServer } from "./lib/auth/server.js";
import { getCodexMode, loadPluginConfig } from "./lib/config.js";
import {
AUTH_LABELS,
CODEX_BASE_URL,
DUMMY_API_KEY,
ERROR_MESSAGES,
JWT_CLAIM_PATH,
LOG_STAGES,
OPENAI_HEADER_VALUES,
OPENAI_HEADERS,
PLUGIN_NAME,
PROVIDER_ID,
} from "./lib/constants.js";
import { logRequest, logDebug } from "./lib/logger.js";
import {
createCodexHeaders,
extractRequestUrl,
handleErrorResponse,
handleSuccessResponse,
refreshAndUpdateToken,
rewriteUrlForCodex,
shouldRefreshToken,
transformRequestForCodex,
} from "./lib/request/fetch-helpers.js";
import type { UserConfig } from "./lib/types.js";
/**
* OpenAI Codex OAuth authentication plugin for opencode
*
* This plugin enables opencode to use OpenAI's Codex backend via ChatGPT Plus/Pro
* OAuth authentication, allowing users to leverage their ChatGPT subscription
* instead of OpenAI Platform API credits.
*
* @example
* ```json
* {
* "plugin": ["opencode-openai-codex-auth"],
* "model": "openai/gpt-5-codex"
* }
* ```
*/
export const OpenAIAuthPlugin: Plugin = async ({ client }: PluginInput) => {
const buildManualOAuthFlow = (pkce: { verifier: string }, url: string) => ({
url,
method: "code" as const,
instructions: AUTH_LABELS.INSTRUCTIONS_MANUAL,
callback: async (input: string) => {
const parsed = parseAuthorizationInput(input);
if (!parsed.code) {
return { type: "failed" as const };
}
const tokens = await exchangeAuthorizationCode(
parsed.code,
pkce.verifier,
REDIRECT_URI,
);
return tokens?.type === "success" ? tokens : { type: "failed" as const };
},
});
return {
auth: {
provider: PROVIDER_ID,
/**
* Loader function that configures OAuth authentication and request handling
*
* This function:
* 1. Validates OAuth authentication
* 2. Extracts ChatGPT account ID from access token
* 3. Loads user configuration from opencode.json
* 4. Fetches Codex system instructions from GitHub (cached)
* 5. Returns SDK configuration with custom fetch implementation
*
* @param getAuth - Function to retrieve current auth state
* @param provider - Provider configuration from opencode.json
* @returns SDK configuration object or empty object for non-OAuth auth
*/
async loader(getAuth: () => Promise<Auth>, provider: unknown) {
const auth = await getAuth();
// Only handle OAuth auth type, skip API key auth
if (auth.type !== "oauth") {
return {};
}
// Extract ChatGPT account ID from JWT access token
const decoded = decodeJWT(auth.access);
const accountId = decoded?.[JWT_CLAIM_PATH]?.chatgpt_account_id;
if (!accountId) {
logDebug(
`[${PLUGIN_NAME}] ${ERROR_MESSAGES.NO_ACCOUNT_ID} (skipping plugin)`,
);
return {};
}
// Extract user configuration (global + per-model options)
const providerConfig = provider as
| { options?: Record<string, unknown>; models?: UserConfig["models"] }
| undefined;
const userConfig: UserConfig = {
global: providerConfig?.options || {},
models: providerConfig?.models || {},
};
// Load plugin configuration and determine CODEX_MODE
// Priority: CODEX_MODE env var > config file > default (true)
const pluginConfig = loadPluginConfig();
const codexMode = getCodexMode(pluginConfig);
// Return SDK configuration
return {
apiKey: DUMMY_API_KEY,
baseURL: CODEX_BASE_URL,
/**
* Custom fetch implementation for Codex API
*
* Handles:
* - Token refresh when expired
* - URL rewriting for Codex backend
* - Request body transformation
* - OAuth header injection
* - SSE to JSON conversion for non-tool requests
* - Error handling and logging
*
* @param input - Request URL or Request object
* @param init - Request options
* @returns Response from Codex API
*/
async fetch(
input: Request | string | URL,
init?: RequestInit,
): Promise<Response> {
// Step 1: Check and refresh token if needed
let currentAuth = await getAuth();
if (shouldRefreshToken(currentAuth)) {
currentAuth = await refreshAndUpdateToken(currentAuth, client);
}
// Step 2: Extract and rewrite URL for Codex backend
const originalUrl = extractRequestUrl(input);
const url = rewriteUrlForCodex(originalUrl);
// Step 3: Transform request body with model-specific Codex instructions
// Instructions are fetched per model family (codex-max, codex, gpt-5.1)
// Capture original stream value before transformation
// generateText() sends no stream field, streamText() sends stream=true
const originalBody = init?.body ? JSON.parse(init.body as string) : {};
const isStreaming = originalBody.stream === true;
const transformation = await transformRequestForCodex(
init,
url,
userConfig,
codexMode,
);
const requestInit = transformation?.updatedInit ?? init;
// Step 4: Create headers with OAuth and ChatGPT account info
const accessToken =
currentAuth.type === "oauth" ? currentAuth.access : "";
const headers = createCodexHeaders(
requestInit,
accountId,
accessToken,
{
model: transformation?.body.model,
promptCacheKey: (transformation?.body as any)?.prompt_cache_key,
},
);
// Step 5: Make request to Codex API
const response = await fetch(url, {
...requestInit,
headers,
});
// Step 6: Log response
logRequest(LOG_STAGES.RESPONSE, {
status: response.status,
ok: response.ok,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
});
// Step 7: Handle error or success response
if (!response.ok) {
return await handleErrorResponse(response);
}
return await handleSuccessResponse(response, isStreaming);
},
};
},
methods: [
{
label: AUTH_LABELS.OAUTH,
type: "oauth" as const,
/**
* OAuth authorization flow
*
* Steps:
* 1. Generate PKCE challenge and state for security
* 2. Start local OAuth callback server on port 1455
* 3. Open browser to OpenAI authorization page
* 4. Wait for user to complete login
* 5. Exchange authorization code for tokens
*
* @returns Authorization flow configuration
*/
authorize: async () => {
const { pkce, state, url } = await createAuthorizationFlow();
const serverInfo = await startLocalOAuthServer({ state });
// Attempt to open browser automatically
openBrowserUrl(url);
if (!serverInfo.ready) {
serverInfo.close();
return buildManualOAuthFlow(pkce, url);
}
return {
url,
method: "auto" as const,
instructions: AUTH_LABELS.INSTRUCTIONS,
callback: async () => {
const result = await serverInfo.waitForCode(state);
serverInfo.close();
if (!result) {
return { type: "failed" as const };
}
const tokens = await exchangeAuthorizationCode(
result.code,
pkce.verifier,
REDIRECT_URI,
);
return tokens?.type === "success"
? tokens
: { type: "failed" as const };
},
};
},
},
{
label: AUTH_LABELS.OAUTH_MANUAL,
type: "oauth" as const,
authorize: async () => {
const { pkce, url } = await createAuthorizationFlow();
return buildManualOAuthFlow(pkce, url);
},
},
{
label: AUTH_LABELS.API_KEY,
type: "api" as const,
},
],
},
};
};
export default OpenAIAuthPlugin;