@wengine-ai/ccr-provider-codex 1.0.1 → 1.0.3

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/dist/plugin.js DELETED
@@ -1,2346 +0,0 @@
1
- // src/auth-service.ts
2
- import { createServer } from "node:http";
3
- import { randomBytes as randomBytes2 } from "node:crypto";
4
- import { promises as fs, constants } from "node:fs";
5
- import { dirname, join } from "node:path";
6
-
7
- // src/protocol.ts
8
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
9
- var CODEX_PROVIDER_NAME = "codex-subscription";
10
- var CODEX_TRANSFORMER_NAME = "codex";
11
- var CODEX_TRANSFORMER_CHAIN = ["openai-responses", CODEX_TRANSFORMER_NAME];
12
- var CODEX_API_KEY = "ccr-managed-codex";
13
- var CODEX_DEFAULT_ISSUER = "https://auth.openai.com";
14
- var CODEX_DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
15
- var CODEX_LOGIN_SCOPES = "openid profile email offline_access api.connectors.read api.connectors.invoke";
16
- var CODEX_REFRESH_SCOPE = "openid profile email";
17
- var CODEX_AUTHORIZE_PATH = "/oauth/authorize";
18
- var CODEX_TOKEN_PATH = "/oauth/token";
19
- var CODEX_BACKEND_BASE = "https://chatgpt.com/backend-api/codex";
20
- var CODEX_WHAM_USAGE_PATH = "/backend-api/wham/usage";
21
- var CODEX_DEFAULT_CLIENT_VERSION = "0.160.1";
22
- var CODEX_UPSTREAM_URL = `${CODEX_BACKEND_BASE}/responses`;
23
- var CODEX_CLIENT_VERSION = CODEX_DEFAULT_CLIENT_VERSION;
24
- var CODEX_ORIGINATOR = "codex_cli_rs";
25
- var CODEX_CALLBACK_PORTS = [1455, 1457];
26
- var CODEX_LOOPBACK_HOSTS = ["127.0.0.1", "localhost", "::1"];
27
- var CODEX_CALLBACK_PATH = "/auth/callback";
28
- var CODEX_LOGIN_TTL_MS = 10 * 60 * 1e3;
29
- var CODEX_REFRESH_LEAD_MS = 5 * 60 * 1e3;
30
- var CODEX_FETCH_TIMEOUT_MS = 3e4;
31
- function codexClientId() {
32
- return process.env.CODEX_OAUTH_CLIENT_ID?.trim() || CODEX_DEFAULT_CLIENT_ID;
33
- }
34
- function codexIssuer() {
35
- return (process.env.CODEX_OAUTH_ISSUER?.trim() || CODEX_DEFAULT_ISSUER).replace(/\/+$/, "");
36
- }
37
- function codexClientVersion() {
38
- return process.env.CODEX_CLIENT_VERSION?.trim() || CODEX_DEFAULT_CLIENT_VERSION;
39
- }
40
- function codexUserAgent(version = codexClientVersion(), platform = process.platform, arch = process.arch) {
41
- const osName = platform === "darwin" ? "Mac OS X" : platform === "win32" ? "Windows NT" : "Linux";
42
- return `codex_cli_rs/${version} (${osName}; ${arch})`;
43
- }
44
- function codexManagementHeaders(accessToken, accountId) {
45
- return {
46
- Authorization: `Bearer ${accessToken}`,
47
- ...accountId ? { "chatgpt-account-id": accountId } : {},
48
- "OpenAI-Beta": "responses=experimental",
49
- originator: "codex_cli_rs",
50
- version: codexClientVersion(),
51
- "User-Agent": codexUserAgent(),
52
- Accept: "application/json"
53
- };
54
- }
55
- function randomToken(n) {
56
- return randomBytes(n).toString("base64url");
57
- }
58
- function boundedFetchInit(init = {}) {
59
- return {
60
- redirect: "error",
61
- ...init,
62
- signal: init.signal ?? AbortSignal.timeout(CODEX_FETCH_TIMEOUT_MS)
63
- };
64
- }
65
- function codexError(info) {
66
- return Object.assign(new Error(info.message), {
67
- code: info.code,
68
- statusCode: info.httpStatus,
69
- ...info.cooldownMs ? { cooldownMs: info.cooldownMs } : {},
70
- codex: true,
71
- nonRetryable: !info.retryable
72
- });
73
- }
74
- function codexAdminError(code, statusCode = 422) {
75
- return Object.assign(new Error(code), { code, statusCode, codex: true });
76
- }
77
- var CODEX_SAFE_MESSAGES = {
78
- codex_reauth_required: "The saved Codex sign-in was rejected; authorize again.",
79
- codex_usage_limit: "This Codex account has reached its usage limit; wait for the window to reset.",
80
- codex_rate_limited: "Codex is rate limiting this account temporarily.",
81
- codex_overloaded: "Codex upstream is temporarily unavailable.",
82
- codex_request_rejected: "Codex rejected the request.",
83
- codex_upstream_error: "Codex upstream request failed."
84
- };
85
- function bodyText(body) {
86
- if (typeof body === "string") return body;
87
- try {
88
- return JSON.stringify(body);
89
- } catch {
90
- return "";
91
- }
92
- }
93
- function parseBody(body) {
94
- if (typeof body === "string") {
95
- try {
96
- return JSON.parse(body);
97
- } catch {
98
- return null;
99
- }
100
- }
101
- return body;
102
- }
103
- function epochMs(value) {
104
- const n = typeof value === "string" ? Number(value) : value;
105
- if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) return void 0;
106
- return n < 1e11 ? n * 1e3 : n;
107
- }
108
- function classifyCodexError(status, body, _systemText) {
109
- const json = parseBody(body) ?? (typeof body === "string" ? {} : body);
110
- const err = json?.error;
111
- const errType = typeof err?.type === "string" ? err.type : "";
112
- const message = typeof err?.message === "string" ? err.message : bodyText(body);
113
- const resetMs = epochMs(err?.resets_at ?? json?.resets_at);
114
- const resetInSeconds = Number(err?.resets_in_seconds ?? json?.resets_in_seconds);
115
- const resetInMs = Number.isFinite(resetInSeconds) && resetInSeconds > 0 ? resetInSeconds * 1e3 : void 0;
116
- const quotaCooldown = () => {
117
- const now2 = Date.now();
118
- if (resetMs && resetMs > now2) return Math.max(resetMs - now2, 6e4);
119
- if (resetInMs) return Math.max(resetInMs, 6e4);
120
- return void 0;
121
- };
122
- const now = Date.now();
123
- if (/usage_limit_reached|RESOURCE_EXHAUSTED|limit reached/i.test(errType) || status === 429 && /usage_limit_reached|limit reached/i.test(message)) {
124
- return {
125
- code: "codex_usage_limit",
126
- message: CODEX_SAFE_MESSAGES.codex_usage_limit,
127
- httpStatus: 429,
128
- ...quotaCooldown() ? { cooldownMs: quotaCooldown() } : {}
129
- };
130
- }
131
- if (status === 401 || /invalid_grant|token.*(expired|revoked|invalid)|refresh_token/i.test(`${errType} ${message}`)) {
132
- return {
133
- code: "codex_reauth_required",
134
- message: CODEX_SAFE_MESSAGES.codex_reauth_required,
135
- httpStatus: 401
136
- };
137
- }
138
- if (status === 429) {
139
- return {
140
- code: "codex_rate_limited",
141
- message: CODEX_SAFE_MESSAGES.codex_rate_limited,
142
- httpStatus: 429,
143
- retryable: true,
144
- ...quotaCooldown() ? { cooldownMs: quotaCooldown() } : {}
145
- };
146
- }
147
- if (status >= 500) {
148
- return {
149
- code: "codex_overloaded",
150
- message: CODEX_SAFE_MESSAGES.codex_overloaded,
151
- httpStatus: status,
152
- retryable: true
153
- };
154
- }
155
- if (status >= 400) {
156
- return {
157
- code: "codex_request_rejected",
158
- message: CODEX_SAFE_MESSAGES.codex_request_rejected,
159
- httpStatus: status
160
- };
161
- }
162
- return null;
163
- }
164
- function createCodexPkce(rand = randomToken) {
165
- const verifier = rand(48);
166
- const challenge = createHash("sha256").update(verifier).digest("base64url");
167
- return { verifier, challenge };
168
- }
169
- function buildCodexAuthorizeUrl(params) {
170
- const q = new URLSearchParams({
171
- response_type: "code",
172
- client_id: params.clientId ?? codexClientId(),
173
- redirect_uri: params.redirectUri,
174
- scope: CODEX_LOGIN_SCOPES,
175
- state: params.state,
176
- code_challenge: params.codeChallenge,
177
- code_challenge_method: "S256",
178
- // Official login server extras, in its exact order.
179
- id_token_add_organizations: "true",
180
- codex_cli_simplified_flow: "true",
181
- originator: "codex_cli_rs"
182
- });
183
- return `${params.issuer ?? codexIssuer()}${CODEX_AUTHORIZE_PATH}?${q.toString()}`;
184
- }
185
- async function exchangeCodexCode(params) {
186
- const res = await params.fetchImpl(`${params.issuer ?? codexIssuer()}${CODEX_TOKEN_PATH}`, boundedFetchInit({
187
- method: "POST",
188
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
189
- body: new URLSearchParams({
190
- grant_type: "authorization_code",
191
- code: params.code,
192
- redirect_uri: params.redirectUri,
193
- client_id: params.clientId ?? codexClientId(),
194
- code_verifier: params.codeVerifier
195
- }).toString()
196
- }));
197
- return readTokenResponse(res, "code exchange");
198
- }
199
- async function refreshCodexTokens(params) {
200
- const res = await params.fetchImpl(`${params.issuer ?? codexIssuer()}${CODEX_TOKEN_PATH}`, boundedFetchInit({
201
- method: "POST",
202
- headers: { "Content-Type": "application/json" },
203
- body: JSON.stringify({
204
- client_id: params.clientId ?? codexClientId(),
205
- grant_type: "refresh_token",
206
- refresh_token: params.refreshToken,
207
- scope: CODEX_REFRESH_SCOPE
208
- })
209
- }));
210
- return readTokenResponse(res, "refresh");
211
- }
212
- async function readTokenResponse(res, stage) {
213
- const text = await res.text().catch(() => "");
214
- let json = null;
215
- try {
216
- json = text ? JSON.parse(text) : {};
217
- } catch {
218
- json = {};
219
- }
220
- const ok = res.ok && json && typeof json === "object";
221
- const t = ok && json.id_token && json.access_token && json.refresh_token ? {
222
- idToken: String(json.id_token),
223
- accessToken: String(json.access_token),
224
- refreshToken: String(json.refresh_token)
225
- } : null;
226
- if (!t) {
227
- const errType = typeof json?.error === "string" ? json.error : json?.error?.type ?? "";
228
- const reauth = !res.ok && (res.status === 400 || res.status === 401 || /invalid_grant|refresh_token_(reused|invalidated|expired)|token_revoked|invalidated/i.test(String(errType)));
229
- throw codexError({
230
- code: reauth ? "codex_reauth_required" : "codex_upstream_error",
231
- message: reauth ? CODEX_SAFE_MESSAGES.codex_reauth_required : `Codex OAuth ${stage} failed.`,
232
- httpStatus: reauth ? 401 : 502
233
- });
234
- }
235
- return t;
236
- }
237
- function decodeJwtPayload(token) {
238
- const parts = token.split(".");
239
- if (parts.length < 2) return null;
240
- try {
241
- const json = Buffer.from(parts[1].replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8");
242
- const parsed = JSON.parse(json);
243
- return parsed && typeof parsed === "object" ? parsed : null;
244
- } catch {
245
- return null;
246
- }
247
- }
248
- function readCodexIdClaims(idToken, accessToken) {
249
- const id = decodeJwtPayload(idToken);
250
- const authClaim = id?.["https://api.openai.com/auth"];
251
- const accountId = typeof authClaim?.chatgpt_account_id === "string" ? authClaim.chatgpt_account_id : "";
252
- const plan = typeof authClaim?.chatgpt_plan_type === "string" ? authClaim.chatgpt_plan_type : "";
253
- const email = typeof id?.email === "string" ? id.email : "";
254
- const access = accessToken ? decodeJwtPayload(accessToken) : null;
255
- const accessExp = typeof access?.exp === "number" ? access.exp * 1e3 : void 0;
256
- return { accountId, plan, email, accessExp };
257
- }
258
- function accessTokenExpiryMs(accessToken) {
259
- const claims = decodeJwtPayload(accessToken);
260
- return typeof claims?.exp === "number" ? claims.exp * 1e3 : void 0;
261
- }
262
- function safeEqualState(a, b) {
263
- const ab = Buffer.from(a);
264
- const bb = Buffer.from(b);
265
- if (ab.length !== bb.length) return false;
266
- return timingSafeEqual(ab, bb);
267
- }
268
- function parseCodexModels(raw) {
269
- const source = Array.isArray(raw) ? raw : Array.isArray(raw?.models) ? raw.models : raw?.models && typeof raw.models === "object" ? Object.entries(raw.models).map(([slug, v]) => ({ slug, ...v })) : [];
270
- const out = [];
271
- for (const m of source) {
272
- if (!m || typeof m !== "object") continue;
273
- const slug = typeof m.slug === "string" ? m.slug : typeof m.id === "string" ? m.id : "";
274
- if (!slug || slug.length > 256 || /[\x00-\x1f\x7f]/.test(slug)) continue;
275
- const visibility = typeof m.visibility === "string" ? m.visibility : "";
276
- const priority = Number.isFinite(m.priority) ? Number(m.priority) : Number.MAX_SAFE_INTEGER;
277
- const template = typeof m.base_instructions === "string" && m.base_instructions.trim() ? m.base_instructions : typeof m.model_messages?.instructions_template === "string" && m.model_messages.instructions_template.trim() ? m.model_messages.instructions_template : void 0;
278
- out.push({
279
- slug,
280
- displayName: typeof m.display_name === "string" ? m.display_name : typeof m.displayName === "string" ? m.displayName : slug,
281
- visibility,
282
- priority,
283
- ...template ? { instructions: template } : {}
284
- });
285
- }
286
- return out;
287
- }
288
- function selectCodexModels(models) {
289
- return models.filter((m) => m.visibility !== "hide").sort((a, b) => a.priority - b.priority || a.slug.localeCompare(b.slug));
290
- }
291
- async function fetchCodexModels(params) {
292
- const version = params.version ?? codexClientVersion();
293
- const url = `${params.base ?? CODEX_BACKEND_BASE}/models?client_version=${encodeURIComponent(version)}`;
294
- const res = await params.fetchImpl(url, boundedFetchInit({
295
- method: "GET",
296
- headers: codexManagementHeaders(params.accessToken, params.accountId)
297
- }));
298
- const text = await res.text().catch(() => "");
299
- let json = null;
300
- try {
301
- json = text ? JSON.parse(text) : {};
302
- } catch {
303
- json = {};
304
- }
305
- if (!res.ok) {
306
- const classified = classifyCodexError(res.status, json || text);
307
- throw codexError({
308
- code: classified?.code === "codex_reauth_required" ? "codex_reauth_required" : "codex_upstream_error",
309
- message: classified?.message ?? "Codex model list could not be loaded.",
310
- httpStatus: classified?.httpStatus ?? 502
311
- });
312
- }
313
- return selectCodexModels(parseCodexModels(json));
314
- }
315
- function readUsageWindow(raw) {
316
- if (!raw || typeof raw !== "object") return void 0;
317
- const usedPercent = typeof raw.used_percent === "number" ? raw.used_percent : typeof raw.usedPercent === "number" ? raw.usedPercent : void 0;
318
- const windowSeconds = typeof raw.limit_window_seconds === "number" ? raw.limit_window_seconds : typeof raw.windowSeconds === "number" ? raw.windowSeconds : void 0;
319
- const resetAt = epochMs(raw.reset_at ?? raw.resetAt);
320
- if (usedPercent === void 0 || !windowSeconds || !resetAt) return void 0;
321
- return { usedPercent, windowSeconds, resetAt };
322
- }
323
- function parseCodexUsage(raw) {
324
- if (!raw || typeof raw !== "object") return null;
325
- const r = raw;
326
- const plan = typeof r.plan_type === "string" ? r.plan_type : typeof r.planType === "string" ? r.planType : "";
327
- const rateLimit = r.rate_limit ?? r.rateLimit ?? {};
328
- const primary = readUsageWindow(rateLimit.primary_window ?? rateLimit.primaryWindow);
329
- const secondary = readUsageWindow(rateLimit.secondary_window ?? rateLimit.secondaryWindow);
330
- if (!plan && !primary && !secondary) return null;
331
- return {
332
- plan,
333
- ...primary ? { primary } : {},
334
- ...secondary ? { secondary } : {}
335
- };
336
- }
337
- async function fetchCodexUsage(params) {
338
- const origin = params.origin ?? "https://chatgpt.com";
339
- const res = await params.fetchImpl(`${origin}${CODEX_WHAM_USAGE_PATH}`, boundedFetchInit({
340
- method: "GET",
341
- headers: codexManagementHeaders(params.accessToken, params.accountId)
342
- }));
343
- if (!res.ok) return null;
344
- const text = await res.text().catch(() => "");
345
- try {
346
- return parseCodexUsage(text ? JSON.parse(text) : {});
347
- } catch {
348
- return null;
349
- }
350
- }
351
- function rateLimitsSaturated(limits, now) {
352
- for (const w of [limits.primary, limits.secondary]) {
353
- if (!w) continue;
354
- if (w.usedPercent >= 100 && typeof w.resetAt === "number" && w.resetAt > now) return true;
355
- }
356
- return false;
357
- }
358
- function isCodexManagedConfigProvider(p) {
359
- if (p?.codex_managed === true || p?.codexManaged === true) return true;
360
- const name = typeof p?.name === "string" ? p.name : "";
361
- const key = typeof p?.api_key === "string" ? p.api_key : typeof p?.apiKey === "string" ? p.apiKey : "";
362
- return name === CODEX_PROVIDER_NAME && key === CODEX_API_KEY;
363
- }
364
- function lockCodexProvider(p) {
365
- return {
366
- ...p,
367
- name: CODEX_PROVIDER_NAME,
368
- codex_managed: true,
369
- codexManaged: true,
370
- api_base_url: CODEX_BACKEND_BASE,
371
- api_key: CODEX_API_KEY,
372
- transformer: { use: [...CODEX_TRANSFORMER_CHAIN] }
373
- };
374
- }
375
- function protectCodexConfig(next, prev) {
376
- for (const key of ["Providers", "providers"]) {
377
- if (!Array.isArray(next?.[key])) continue;
378
- const olds = (prev?.Providers || prev?.providers || []).filter((p) => isCodexManagedConfigProvider(p));
379
- next[key] = next[key].map((p) => {
380
- if (isCodexManagedConfigProvider(p)) {
381
- return lockCodexProvider({ ...p });
382
- }
383
- return p;
384
- });
385
- for (const old of olds) {
386
- if (!next[key].some((p) => p?.name === old.name)) {
387
- next[key].push(lockCodexProvider({ ...old }));
388
- }
389
- }
390
- }
391
- }
392
- function isCodexRuntime(p) {
393
- if (p?.codexManaged === true && p?.name === CODEX_PROVIDER_NAME) return true;
394
- const base = typeof p?.baseUrl === "string" ? p.baseUrl : typeof p?.api_base_url === "string" ? p.api_base_url : "";
395
- if (/(?:^|\/\/)chatgpt\.com\/backend-api\/codex(?:\/|$)/.test(base) && Array.isArray(p?.transformer?.use) && p.transformer.use.some((t) => (typeof t === "string" ? t : t?.name) === CODEX_TRANSFORMER_NAME)) {
396
- return true;
397
- }
398
- return p?.name === CODEX_PROVIDER_NAME && (p?.apiKey === CODEX_API_KEY || p?.api_key === CODEX_API_KEY);
399
- }
400
-
401
- // src/auth-service.ts
402
- var CODEX_CREDENTIAL_FILE = "codex-credentials.json";
403
- var MAX_CREDENTIAL_BYTES = 256 * 1024;
404
- var PROVIDER_KEYS = ["Providers", "providers"];
405
- var USAGE_CACHE_MS = 6e4;
406
- var LAST_ERROR_CODES = /* @__PURE__ */ new Set([
407
- "codex_reauth_required",
408
- "codex_usage_limit",
409
- "codex_rate_limited",
410
- "codex_overloaded",
411
- "codex_request_rejected",
412
- "codex_upstream_error"
413
- ]);
414
- function boundedString(value, max, min = 1) {
415
- return typeof value === "string" && value.length >= min && value.length <= max && !/[\x00-\x1f\x7f]/.test(value);
416
- }
417
- function normalizeRateLimits(raw) {
418
- if (!raw || typeof raw !== "object") return null;
419
- const r = raw;
420
- if (typeof r.observedAt !== "number" || !Number.isFinite(r.observedAt) || r.source !== "headers" && r.source !== "sse") {
421
- return null;
422
- }
423
- const window = (w) => {
424
- if (!w || typeof w !== "object" || typeof w.usedPercent !== "number") return void 0;
425
- const out = { usedPercent: w.usedPercent };
426
- if (typeof w.windowSeconds === "number") out.windowSeconds = w.windowSeconds;
427
- if (typeof w.resetAt === "number") out.resetAt = w.resetAt;
428
- return out;
429
- };
430
- return {
431
- ...window(r.primary) ? { primary: window(r.primary) } : {},
432
- ...window(r.secondary) ? { secondary: window(r.secondary) } : {},
433
- observedAt: r.observedAt,
434
- source: r.source
435
- };
436
- }
437
- function normalizeCodexCredentialData(raw) {
438
- const invalid = () => codexAdminError("codex_credential_invalid", 500);
439
- if (!raw || typeof raw !== "object" || raw.version !== 1 || raw.kind !== "codex-subscription") {
440
- throw invalid();
441
- }
442
- const a = raw.account;
443
- if (!a || typeof a !== "object") throw invalid();
444
- for (const key of ["accessToken", "refreshToken", "idToken"]) {
445
- if (!boundedString(a[key], 16384)) throw invalid();
446
- }
447
- for (const key of ["accountId", "email", "plan"]) {
448
- if (typeof a[key] !== "string" || a[key].length > 320) throw invalid();
449
- }
450
- if (typeof a.connectedAt !== "string" || Number.isNaN(Date.parse(a.connectedAt))) {
451
- throw invalid();
452
- }
453
- if (a.accessExp !== null && !(typeof a.accessExp === "number" && Number.isFinite(a.accessExp))) {
454
- throw invalid();
455
- }
456
- let lastError = null;
457
- if (a.lastError !== null && a.lastError !== void 0) {
458
- if (!a.lastError || typeof a.lastError !== "object" || !LAST_ERROR_CODES.has(a.lastError.code)) {
459
- throw invalid();
460
- }
461
- lastError = { code: a.lastError.code };
462
- }
463
- const cooldown = (v) => v === null || v === void 0 ? null : typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : (() => {
464
- throw invalid();
465
- })();
466
- const models = [];
467
- if (Array.isArray(raw.models)) {
468
- if (raw.models.length > 256) throw invalid();
469
- for (const m of raw.models) {
470
- if (!m || typeof m !== "object" || !boundedString(m.slug, 256)) continue;
471
- const item = {
472
- slug: m.slug,
473
- displayName: boundedString(m.displayName, 256) ? m.displayName : m.slug
474
- };
475
- if (typeof m.instructions === "string" && m.instructions.length > 0 && m.instructions.length <= 65536) {
476
- item.instructions = m.instructions;
477
- }
478
- models.push(item);
479
- }
480
- }
481
- const rateLimits = normalizeRateLimits(raw.rateLimits);
482
- return {
483
- version: 1,
484
- kind: "codex-subscription",
485
- account: {
486
- accessToken: a.accessToken,
487
- refreshToken: a.refreshToken,
488
- idToken: a.idToken,
489
- accountId: a.accountId,
490
- email: a.email,
491
- plan: a.plan,
492
- connectedAt: a.connectedAt,
493
- accessExp: a.accessExp ?? null,
494
- lastError,
495
- cooldownUntil: cooldown(a.cooldownUntil),
496
- rateLimitCooldownUntil: cooldown(a.rateLimitCooldownUntil)
497
- },
498
- models,
499
- rateLimits
500
- };
501
- }
502
- var CodexCredentialStore = class {
503
- constructor(path) {
504
- this.path = path;
505
- }
506
- async load() {
507
- let file;
508
- try {
509
- file = await fs.open(this.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
510
- const stat = await file.stat();
511
- if (!stat.isFile() || stat.size > MAX_CREDENTIAL_BYTES || process.platform !== "win32" && stat.mode & 63) {
512
- throw new Error("codex_credential_unreadable");
513
- }
514
- const text = await file.readFile("utf8");
515
- return normalizeCodexCredentialData(JSON.parse(text));
516
- } catch (error) {
517
- if (error?.code === "ENOENT") return null;
518
- throw codexAdminError("codex_credential_unreadable", 500);
519
- } finally {
520
- await file?.close();
521
- }
522
- }
523
- /** Atomic 0600 write: exclusive temp, fsync, rename, chmod. */
524
- async save(data) {
525
- const safe = normalizeCodexCredentialData(data);
526
- await fs.mkdir(dirname(this.path), { recursive: true, mode: 448 }).catch(() => {
527
- });
528
- const temp = `${this.path}.${randomBytes2(12).toString("hex")}.tmp`;
529
- try {
530
- const file = await fs.open(temp, "wx", 384);
531
- try {
532
- await file.writeFile(JSON.stringify(safe), "utf8");
533
- await file.sync();
534
- } finally {
535
- await file.close();
536
- }
537
- await fs.rename(temp, this.path);
538
- if (process.platform !== "win32") await fs.chmod(this.path, 384);
539
- } catch {
540
- throw codexAdminError("codex_config_write_failed", 500);
541
- } finally {
542
- await fs.unlink(temp).catch(() => {
543
- });
544
- }
545
- }
546
- async delete() {
547
- try {
548
- await fs.unlink(this.path);
549
- return true;
550
- } catch (error) {
551
- if (error?.code === "ENOENT") return false;
552
- throw codexAdminError("codex_config_write_failed", 500);
553
- }
554
- }
555
- };
556
- var CodexAuthService = class {
557
- constructor(options) {
558
- this.options = options;
559
- this.store = options.store ?? new CodexCredentialStore(join(options.configDir, CODEX_CREDENTIAL_FILE));
560
- }
561
- store;
562
- mutationTail = Promise.resolve();
563
- epoch = 0;
564
- pending = null;
565
- loginStarting = 0;
566
- /** Terminal poll results, kept briefly for late polls. */
567
- lastResult = /* @__PURE__ */ new Map();
568
- data = null;
569
- loaded = false;
570
- instructions = /* @__PURE__ */ new Map();
571
- refreshFlight = null;
572
- forceRefreshRequested = false;
573
- usageCache = null;
574
- get now() {
575
- return (this.options.now ?? Date.now)();
576
- }
577
- get log() {
578
- const l = this.options.logger;
579
- return {
580
- info: (m) => {
581
- try {
582
- l?.info?.(m);
583
- } catch {
584
- }
585
- },
586
- warn: (m) => {
587
- try {
588
- l?.warn?.(m);
589
- } catch {
590
- }
591
- },
592
- error: (m) => {
593
- try {
594
- l?.error?.(m);
595
- } catch {
596
- }
597
- }
598
- };
599
- }
600
- get fetchImpl() {
601
- const injected = this.options.fetchImpl;
602
- return injected ?? ((url, init) => fetch(url, init));
603
- }
604
- /** Fixed OpenAI origins bypass configured CCR/proxy routing. */
605
- directFetch(url, init = {}) {
606
- return this.fetchImpl(url, { ...init, dispatcher: this.options.host.getDirectDispatcher() });
607
- }
608
- enqueueMutation(action) {
609
- const result = this.mutationTail.then(action);
610
- this.mutationTail = result.catch(() => {
611
- });
612
- return result;
613
- }
614
- // ---------------------------------------------------------------- loading --
615
- async ensureLoaded(force = false) {
616
- if (this.loaded && !force) return this.data;
617
- const data = await this.store.load().catch(() => null);
618
- this.applyLoaded(data);
619
- this.loaded = true;
620
- return this.data;
621
- }
622
- applyLoaded(data) {
623
- this.data = data;
624
- this.instructions.clear();
625
- for (const m of data?.models ?? []) {
626
- if (m.instructions) this.instructions.set(m.slug, m.instructions);
627
- }
628
- }
629
- async saveData(data) {
630
- await this.store.save(data);
631
- this.data = data;
632
- this.instructions.clear();
633
- for (const m of data.models) if (m.instructions) this.instructions.set(m.slug, m.instructions);
634
- }
635
- // ------------------------------------------------------------------ status -
636
- async getStatus() {
637
- const data = await this.ensureLoaded();
638
- const models = await this.configManagedModels();
639
- const account = data?.account;
640
- const now = this.now;
641
- if (!account) {
642
- return { status: "not_connected", providerName: CODEX_PROVIDER_NAME, models, modelCount: models.length };
643
- }
644
- const coolingUntil = this.latestCooldown(data);
645
- let status = "connected";
646
- if (account.lastError) status = "error";
647
- else if (typeof account.accessExp === "number" && account.accessExp <= now) status = "expired";
648
- return {
649
- status,
650
- providerName: CODEX_PROVIDER_NAME,
651
- ...account.accountId ? { accountId: account.accountId } : {},
652
- ...account.email ? { email: account.email } : {},
653
- ...account.plan ? { plan: account.plan } : {},
654
- models,
655
- modelCount: models.length,
656
- ...coolingUntil ? { coolingUntil } : {},
657
- lastError: account.lastError ? CODEX_SAFE_MESSAGES[account.lastError.code] ?? null : null
658
- };
659
- }
660
- latestCooldown(data) {
661
- const now = this.now;
662
- const a = data?.account;
663
- const candidates = [a?.cooldownUntil, a?.rateLimitCooldownUntil].filter((v) => typeof v === "number" && v > now);
664
- return candidates.length ? Math.max(...candidates) : void 0;
665
- }
666
- // ------------------------------------------------------------- raw config --
667
- async readRawConfig() {
668
- try {
669
- if (this.options.host.readRawConfig) return await this.options.host.readRawConfig();
670
- return await this.options.host.readConfig();
671
- } catch {
672
- return {};
673
- }
674
- }
675
- findManaged(config) {
676
- for (const key of PROVIDER_KEYS) {
677
- const list = config?.[key];
678
- if (Array.isArray(list)) {
679
- const found = list.find((p) => isCodexManagedConfigProvider(p));
680
- if (found) return found;
681
- }
682
- }
683
- return void 0;
684
- }
685
- async configManagedModels() {
686
- try {
687
- const config = await this.readRawConfig();
688
- const provider = this.findManaged(config);
689
- return Array.isArray(provider?.models) ? provider.models.filter((m) => typeof m === "string") : [];
690
- } catch {
691
- return [];
692
- }
693
- }
694
- /**
695
- * Raw read → upsert only the managed entry (Router untouched) → write →
696
- * reload. `protectCodexConfig` is defence in depth; unrelated providers are
697
- * never rewritten.
698
- */
699
- async upsertManagedProvider(models) {
700
- const config = await this.options.host.readRawConfig?.().catch(() => null) ?? await this.options.host.readConfig().catch(() => ({}));
701
- const previousConfig = structuredClone(config ?? {});
702
- const routerBefore = JSON.stringify((config ?? {}).Router ?? null);
703
- let list = [];
704
- let usedKey = "Providers";
705
- for (const key of PROVIDER_KEYS) {
706
- if (Array.isArray(config?.[key])) {
707
- usedKey = key;
708
- list = config[key];
709
- break;
710
- }
711
- }
712
- if (!Array.isArray(config?.[usedKey])) {
713
- if (!config || typeof config !== "object") throw codexAdminError("codex_config_write_failed", 500);
714
- config[usedKey] = list = [];
715
- }
716
- const index = list.findIndex((p) => isCodexManagedConfigProvider(p));
717
- if (index >= 0) {
718
- const existing = list[index];
719
- const enabled = existing.enabled !== false;
720
- list[index] = lockCodexProvider({ ...existing, models, enabled });
721
- } else {
722
- list.push(lockCodexProvider({ name: CODEX_PROVIDER_NAME, models, enabled: true }));
723
- }
724
- config[usedKey] = list;
725
- protectCodexConfig(config, config);
726
- try {
727
- await this.options.host.writeConfig(config);
728
- } catch {
729
- try {
730
- await this.options.host.writeConfig(previousConfig);
731
- await this.options.host.reloadRuntime?.(previousConfig);
732
- } catch {
733
- this.log.error("[codex] failed to restore previous configuration");
734
- }
735
- throw codexAdminError("codex_config_write_failed", 500);
736
- }
737
- if (JSON.stringify(config.Router ?? null) !== routerBefore) {
738
- throw codexAdminError("codex_config_write_failed", 500);
739
- }
740
- await this.options.host.reloadRuntime?.(config);
741
- }
742
- // ---------------------------------------------------------- browser login --
743
- async startLogin() {
744
- this.prunePending();
745
- if (this.pending || this.loginStarting > 0) {
746
- throw codexAdminError("codex_login_busy", 429);
747
- }
748
- this.loginStarting++;
749
- try {
750
- const start = await this.createPendingLogin();
751
- this.forgetResult(start.loginId);
752
- return start;
753
- } finally {
754
- this.loginStarting--;
755
- }
756
- }
757
- async createPendingLogin() {
758
- const { verifier, challenge } = createCodexPkce();
759
- const state = randomToken(24);
760
- const loginId = randomBytes2(16).toString("hex");
761
- const ttl = CODEX_LOGIN_TTL_MS;
762
- let server = null;
763
- let port = null;
764
- for (const candidate of CODEX_CALLBACK_PORTS) {
765
- const attempt = createServer();
766
- try {
767
- await new Promise((resolve, reject) => {
768
- attempt.once("error", reject);
769
- attempt.listen(candidate, "127.0.0.1", resolve);
770
- });
771
- server = attempt;
772
- port = candidate;
773
- break;
774
- } catch (error) {
775
- await new Promise((r) => attempt.close(r));
776
- if (error?.code !== "EADDRINUSE") {
777
- this.log.warn(`[codex] callback bind on port ${candidate} failed: ${error?.code ?? "error"}`);
778
- }
779
- }
780
- }
781
- const redirectPort = port ?? CODEX_CALLBACK_PORTS[0];
782
- const redirectUri = `http://127.0.0.1:${redirectPort}${CODEX_CALLBACK_PATH}`;
783
- const mode = server ? "callback" : "paste";
784
- const url = buildCodexAuthorizeUrl({ redirectUri, state, codeChallenge: challenge });
785
- const expiresAt = this.now + ttl;
786
- let resolveCode;
787
- let rejectCode;
788
- const waitForCode = new Promise((resolve, reject) => {
789
- resolveCode = resolve;
790
- rejectCode = reject;
791
- });
792
- waitForCode.catch(() => {
793
- });
794
- const job = {
795
- loginId,
796
- state,
797
- verifier,
798
- redirectUri,
799
- port,
800
- mode,
801
- expiresAt,
802
- server,
803
- timer: null,
804
- epoch: this.epoch,
805
- claimed: false,
806
- code: null,
807
- waitForCode,
808
- resolveCode,
809
- rejectCode,
810
- lastPoll: 0
811
- };
812
- job.timer = setTimeout(() => {
813
- this.terminalize(job, { status: "expired" });
814
- job.rejectCode(codexAdminError("codex_login_expired", 410));
815
- }, ttl);
816
- if (typeof job.timer.unref === "function") job.timer.unref();
817
- if (server) {
818
- server.on("request", (req, res) => {
819
- try {
820
- this.handleCallback(req, res, job);
821
- } catch {
822
- try {
823
- res.statusCode = 500;
824
- res.end();
825
- } catch {
826
- }
827
- }
828
- });
829
- }
830
- this.pending = job;
831
- return { loginId, url, expiresAt, mode, redirectUri };
832
- }
833
- /** Loopback request handler: GET, exact path, Host guard, one-use state. */
834
- handleCallback(req, res, job) {
835
- const page = (ok, heading, body, status = ok ? 200 : 400) => {
836
- res.statusCode = status;
837
- res.setHeader("Content-Type", "text/html; charset=utf-8");
838
- res.setHeader("Cache-Control", "no-store");
839
- res.end(`<!doctype html><meta charset="utf-8"><title>${heading}</title><body style="font-family:system-ui;padding:2rem"><h2>${heading}</h2><p>${body}</p></body>`);
840
- };
841
- if (req.method !== "GET") {
842
- res.statusCode = 405;
843
- res.end();
844
- return;
845
- }
846
- let target;
847
- try {
848
- target = new URL(req.url ?? "/", "http://127.0.0.1");
849
- } catch {
850
- res.statusCode = 400;
851
- res.end();
852
- return;
853
- }
854
- if (target.pathname === "/favicon.ico") {
855
- res.statusCode = 204;
856
- res.end();
857
- return;
858
- }
859
- if (target.pathname !== CODEX_CALLBACK_PATH) {
860
- res.statusCode = 404;
861
- res.end();
862
- return;
863
- }
864
- const host = String(req.headers?.host ?? "");
865
- const allowedHosts = /* @__PURE__ */ new Set([`127.0.0.1:${job.port}`, `localhost:${job.port}`, `[::1]:${job.port}`]);
866
- if (!allowedHosts.has(host)) {
867
- page(false, "Sign-in rejected", "This request did not come from the local sign-in page.");
868
- return;
869
- }
870
- const accept = (code) => {
871
- page(true, "Sign-in received", "You can close this page and return to CCR.");
872
- this.claimCallback(job, code);
873
- };
874
- this.consumeCallbackParams(job, target, {
875
- onCode: accept,
876
- onProviderError: () => {
877
- page(false, "Sign-in declined", "ChatGPT declined the authorization. Start it again from CCR.");
878
- this.terminalize(job, { status: "error", error: "codex_login_exchange_failed" });
879
- job.rejectCode(codexAdminError("codex_login_exchange_failed", 409));
880
- },
881
- onReject: () => {
882
- page(false, "This link isn't from CCR's sign-in", "Start it again from CCR.");
883
- }
884
- });
885
- }
886
- /**
887
- * Validate and one-time-consume callback query parameters. Shared by the
888
- * socket listener and paste mode (`submitCallback`); never logs the URL.
889
- */
890
- consumeCallbackParams(job, target, hooks) {
891
- if (this.pending !== job || job.claimed || this.now >= job.expiresAt) {
892
- hooks.onReject();
893
- return;
894
- }
895
- const state = target.searchParams.get("state");
896
- if (typeof state !== "string" || !safeEqualState(state, job.state)) {
897
- hooks.onReject();
898
- return;
899
- }
900
- if (target.searchParams.get("error")) {
901
- hooks.onProviderError();
902
- return;
903
- }
904
- const code = target.searchParams.get("code");
905
- if (!code || code.length > 2048 || /[\x00-\x1f\x7f]/.test(code)) {
906
- hooks.onReject();
907
- return;
908
- }
909
- job.claimed = true;
910
- hooks.onCode(code);
911
- }
912
- /** Stop listening (one callback only); keep job until exchange finishes. */
913
- claimCallback(job, code) {
914
- if (job.timer) {
915
- clearTimeout(job.timer);
916
- job.timer = null;
917
- }
918
- job.code = code;
919
- job.server?.close(() => {
920
- });
921
- job.resolveCode(code);
922
- }
923
- terminalize(job, result) {
924
- job.result = result;
925
- this.lastResult.set(job.loginId, result);
926
- if (job.timer) {
927
- clearTimeout(job.timer);
928
- job.timer = null;
929
- }
930
- job.server?.close(() => {
931
- });
932
- if (this.pending === job) this.pending = null;
933
- }
934
- /** Clear a stale terminal-result memo (called when a new login starts). */
935
- forgetResult(loginId) {
936
- this.lastResult.delete(loginId);
937
- }
938
- async cancelLogin(loginId) {
939
- const job = this.pending;
940
- if (job && (loginId === "*" || job.loginId === loginId)) {
941
- this.terminalize(job, { status: "cancelled" });
942
- job.rejectCode(codexAdminError("codex_login_cancelled", 409));
943
- }
944
- }
945
- /** Paste-mode completion: the user hands us the final browser URL. */
946
- async submitCallback(loginId, callbackUrl) {
947
- const job = this.pending;
948
- if (!job || job.loginId !== loginId) {
949
- return { status: "error", error: "codex_login_state_rejected" };
950
- }
951
- let target;
952
- try {
953
- target = new URL(callbackUrl);
954
- } catch {
955
- return { status: "error", error: "codex_login_state_rejected" };
956
- }
957
- if (target.protocol !== "http:" && target.protocol !== "https:") {
958
- return { status: "error", error: "codex_login_state_rejected" };
959
- }
960
- if (target.pathname !== CODEX_CALLBACK_PATH) {
961
- return { status: "error", error: "codex_login_state_rejected" };
962
- }
963
- const host = target.hostname.replace(/^\[|\]$/g, "").toLowerCase();
964
- if (!CODEX_LOOPBACK_HOSTS.includes(host)) {
965
- return { status: "error", error: "codex_login_state_rejected" };
966
- }
967
- const expectedPort = new URL(job.redirectUri).port;
968
- if (target.port !== expectedPort) {
969
- return { status: "error", error: "codex_login_state_rejected" };
970
- }
971
- let outcome;
972
- this.consumeCallbackParams(job, target, {
973
- onCode: (code) => {
974
- this.claimCallback(job, code);
975
- outcome = { status: "pending" };
976
- },
977
- onProviderError: () => {
978
- this.terminalize(job, { status: "error", error: "codex_login_exchange_failed" });
979
- job.rejectCode(codexAdminError("codex_login_exchange_failed", 409));
980
- outcome = job.result;
981
- },
982
- onReject: () => {
983
- outcome = { status: "error", error: "codex_login_state_rejected" };
984
- }
985
- });
986
- if (!outcome) return { status: "error", error: "codex_login_state_rejected" };
987
- if (outcome.status === "pending") return this.pollLogin(loginId);
988
- return outcome;
989
- }
990
- async pollLogin(loginId) {
991
- if (typeof loginId !== "string" || !/^[a-f0-9]{32}$/.test(loginId)) {
992
- return { status: "error", error: "codex_login_state_rejected" };
993
- }
994
- const job = this.pending;
995
- if (!job || job.loginId !== loginId) {
996
- const finished = this.lastResult.get(loginId);
997
- if (finished) return finished;
998
- return { status: "error", error: "codex_login_state_rejected" };
999
- }
1000
- if (job.result) return job.result;
1001
- if (this.now >= job.expiresAt) {
1002
- this.terminalize(job, { status: "expired" });
1003
- job.rejectCode(codexAdminError("codex_login_expired", 410));
1004
- return job.result;
1005
- }
1006
- if (job.inFlight) return job.inFlight;
1007
- if (!job.claimed) return { status: "pending" };
1008
- if (this.now - job.lastPoll < 250) return { status: "pending" };
1009
- job.lastPoll = this.now;
1010
- job.inFlight = this.runLogin(job).finally(() => {
1011
- job.inFlight = void 0;
1012
- });
1013
- return job.inFlight;
1014
- }
1015
- prunePending() {
1016
- const job = this.pending;
1017
- if (job && !job.result && this.now >= job.expiresAt) {
1018
- this.terminalize(job, { status: "expired" });
1019
- job.rejectCode(codexAdminError("codex_login_expired", 410));
1020
- }
1021
- }
1022
- /** Code → tokens → claims → models (best effort) → persist → config. */
1023
- async runLogin(job) {
1024
- const fail = (error) => {
1025
- this.terminalize(job, { status: "error", error });
1026
- return job.result;
1027
- };
1028
- let code;
1029
- try {
1030
- code = await job.waitForCode;
1031
- } catch {
1032
- return job.result ?? { status: "expired" };
1033
- }
1034
- const epoch = job.epoch;
1035
- let tokens;
1036
- try {
1037
- tokens = await exchangeCodexCode({
1038
- code,
1039
- codeVerifier: job.verifier,
1040
- redirectUri: job.redirectUri,
1041
- fetchImpl: (url, init) => this.directFetch(url, init)
1042
- });
1043
- } catch (error) {
1044
- this.log.warn(`[codex] token exchange failed: ${error?.code === "codex_reauth_required" ? "rejected" : "upstream"}`);
1045
- return fail("codex_login_exchange_failed");
1046
- }
1047
- if (this.epoch !== epoch || job.result && job.result.status !== "connected") {
1048
- return fail("codex_login_cancelled");
1049
- }
1050
- const claims = readCodexIdClaims(tokens.idToken, tokens.accessToken);
1051
- const accessExp = accessTokenExpiryMs(tokens.accessToken) ?? null;
1052
- let models = [];
1053
- try {
1054
- models = await fetchCodexModels({
1055
- accessToken: tokens.accessToken,
1056
- accountId: claims.accountId || void 0,
1057
- fetchImpl: (url, init) => this.directFetch(url, init)
1058
- });
1059
- } catch (error) {
1060
- this.log.warn(`[codex] model discovery after login failed: ${error?.code ?? "upstream"}`);
1061
- }
1062
- const previous = await this.store.load().catch(() => null);
1063
- const data = {
1064
- version: 1,
1065
- kind: "codex-subscription",
1066
- account: {
1067
- accessToken: tokens.accessToken,
1068
- refreshToken: tokens.refreshToken,
1069
- idToken: tokens.idToken,
1070
- accountId: claims.accountId,
1071
- email: claims.email,
1072
- plan: claims.plan,
1073
- connectedAt: new Date(this.now).toISOString(),
1074
- accessExp,
1075
- lastError: null,
1076
- cooldownUntil: null,
1077
- rateLimitCooldownUntil: null
1078
- },
1079
- models: models.map((m) => ({
1080
- slug: m.slug,
1081
- displayName: m.displayName,
1082
- ...m.instructions ? { instructions: m.instructions } : {}
1083
- })),
1084
- rateLimits: null
1085
- };
1086
- const slugs = models.map((m) => m.slug);
1087
- try {
1088
- await this.enqueueMutation(async () => {
1089
- if (this.epoch !== epoch) throw codexAdminError("codex_login_cancelled", 409);
1090
- await this.saveData(data);
1091
- if (this.epoch !== epoch) throw codexAdminError("codex_login_cancelled", 409);
1092
- try {
1093
- await this.upsertManagedProvider(slugs);
1094
- } catch (error) {
1095
- if (previous) await this.store.save(previous).catch(() => {
1096
- });
1097
- else await this.store.delete().catch(() => {
1098
- });
1099
- this.loaded = false;
1100
- throw error;
1101
- }
1102
- });
1103
- } catch (error) {
1104
- if (error?.code === "codex_login_cancelled") return fail("codex_login_cancelled");
1105
- this.log.error("[codex] login persist failed; credential rolled back");
1106
- return fail("codex_login_persist_failed");
1107
- }
1108
- this.refreshFlight = null;
1109
- this.forceRefreshRequested = false;
1110
- this.usageCache = null;
1111
- const result = { status: "connected", models: slugs, modelCount: slugs.length };
1112
- job.result = result;
1113
- this.lastResult.set(job.loginId, result);
1114
- if (this.pending === job) this.pending = null;
1115
- if (job.timer) {
1116
- clearTimeout(job.timer);
1117
- job.timer = null;
1118
- }
1119
- job.server?.close(() => {
1120
- });
1121
- return result;
1122
- }
1123
- // ------------------------------------------------------- data-plane tokens -
1124
- /** Live access token; refreshes with a 5-minute lead, single-flight. */
1125
- async getAccessToken() {
1126
- const data = await this.ensureLoaded();
1127
- const account = data?.account;
1128
- if (!account) throw codexAdminError("codex_not_connected", 409);
1129
- const fresh = typeof account.accessExp === "number" && account.accessExp - this.now > CODEX_REFRESH_LEAD_MS;
1130
- if (fresh && !this.forceRefreshRequested) return account.accessToken;
1131
- const key = `${account.refreshToken}|${account.connectedAt}`;
1132
- if (this.refreshFlight?.key === key) return this.refreshFlight.promise;
1133
- const epoch = this.epoch;
1134
- const promise = this.performRefresh(account.refreshToken, epoch).then((token) => {
1135
- if (this.epoch !== epoch) throw codexAdminError("codex_not_connected", 409);
1136
- return token;
1137
- }).catch((error) => {
1138
- if (this.refreshFlight?.key === key) this.refreshFlight = null;
1139
- throw error;
1140
- });
1141
- this.refreshFlight = { key, promise };
1142
- try {
1143
- return await promise;
1144
- } finally {
1145
- if (this.refreshFlight?.key === key && this.refreshFlight.promise === promise) {
1146
- this.refreshFlight = null;
1147
- }
1148
- }
1149
- }
1150
- /**
1151
- * Refresh grant → persist rotated tokens BEFORE the new access token can be
1152
- * used. Id-token account/plan claims are refreshed as well.
1153
- */
1154
- performRefresh(oldRefreshToken, epoch) {
1155
- return (async () => {
1156
- let tokens;
1157
- try {
1158
- tokens = await refreshCodexTokens({
1159
- refreshToken: oldRefreshToken,
1160
- fetchImpl: (url, init) => this.directFetch(url, init)
1161
- });
1162
- } catch (error) {
1163
- throw error;
1164
- }
1165
- const claims = readCodexIdClaims(tokens.idToken, tokens.accessToken);
1166
- const accessExp = accessTokenExpiryMs(tokens.accessToken) ?? null;
1167
- await this.enqueueMutation(async () => {
1168
- const current = await this.store.load().catch(() => null);
1169
- if (!current || this.epoch !== epoch || current.account.refreshToken !== oldRefreshToken) {
1170
- throw codexAdminError("codex_not_connected", 409);
1171
- }
1172
- const next = {
1173
- ...current,
1174
- account: {
1175
- ...current.account,
1176
- accessToken: tokens.accessToken,
1177
- refreshToken: tokens.refreshToken,
1178
- idToken: tokens.idToken,
1179
- accessExp,
1180
- ...claims.accountId ? { accountId: claims.accountId } : {},
1181
- ...claims.plan ? { plan: claims.plan } : {},
1182
- ...claims.email ? { email: claims.email } : {}
1183
- }
1184
- };
1185
- await this.saveData(next);
1186
- });
1187
- this.forceRefreshRequested = false;
1188
- return tokens.accessToken;
1189
- })();
1190
- }
1191
- /** The 401 seam's one forced re-send: bypass the exp lead once. */
1192
- async forceTokenRefresh() {
1193
- this.forceRefreshRequested = true;
1194
- await this.getAccessToken();
1195
- }
1196
- async getAccountId() {
1197
- const data = await this.ensureLoaded();
1198
- if (!data?.account) throw codexAdminError("codex_not_connected", 409);
1199
- if (!data.account.accountId) throw codexAdminError("codex_not_connected", 409);
1200
- return data.account.accountId;
1201
- }
1202
- // ------------------------------------------------------------------ models -
1203
- async syncModels() {
1204
- const data = await this.ensureLoaded();
1205
- if (!data?.account) throw codexAdminError("codex_not_connected", 409);
1206
- const accessToken = await this.getAccessToken();
1207
- const fresh = await this.ensureLoaded(true);
1208
- const accountId = fresh?.account.accountId || void 0;
1209
- let models;
1210
- try {
1211
- models = await fetchCodexModels({
1212
- accessToken,
1213
- accountId,
1214
- fetchImpl: (url, init) => this.directFetch(url, init)
1215
- });
1216
- } catch (error) {
1217
- if (error?.code === "codex_reauth_required") throw codexAdminError("codex_reauth_required", 401);
1218
- throw codexAdminError("codex_models_fetch_failed", 502);
1219
- }
1220
- const visible = selectCodexModels(models);
1221
- const slugs = visible.map((m) => m.slug);
1222
- if (!slugs.length) throw codexAdminError("codex_models_fetch_failed", 502);
1223
- await this.enqueueMutation(async () => {
1224
- const current = await this.store.load().catch(() => null);
1225
- if (!current) throw codexAdminError("codex_not_connected", 409);
1226
- await this.saveData({
1227
- ...current,
1228
- account: { ...current.account, lastError: null },
1229
- models: visible.map((m) => ({
1230
- slug: m.slug,
1231
- displayName: m.displayName,
1232
- ...m.instructions ? { instructions: m.instructions } : {}
1233
- }))
1234
- });
1235
- await this.upsertManagedProvider(slugs);
1236
- });
1237
- return { success: true, models: slugs, modelCount: slugs.length };
1238
- }
1239
- /** Stable synchronous getter over the in-memory per-model instruction cache. */
1240
- getModelInstructions(model) {
1241
- return this.instructions.get(model);
1242
- }
1243
- // ------------------------------------------------------------------- usage -
1244
- async getUsage() {
1245
- const data = await this.ensureLoaded();
1246
- if (!data?.account) return null;
1247
- if (this.usageCache && this.now - this.usageCache.at < USAGE_CACHE_MS) {
1248
- return this.usageCache.value;
1249
- }
1250
- const accessToken = await this.getAccessToken().catch(() => null);
1251
- if (!accessToken) return null;
1252
- const fresh = await this.ensureLoaded(true);
1253
- const usage = await fetchCodexUsage({
1254
- accessToken,
1255
- accountId: fresh?.account.accountId || void 0,
1256
- fetchImpl: (url, init) => this.directFetch(url, init)
1257
- }).catch(() => null);
1258
- this.usageCache = { at: this.now, value: usage };
1259
- return usage;
1260
- }
1261
- // -------------------------------------------------------------- cooling/... -
1262
- async isAccountCooling() {
1263
- const data = await this.ensureLoaded();
1264
- return this.latestCooldown(data) !== void 0;
1265
- }
1266
- /** Data-plane error channel (usage_limit_reached, 401, …). Never throws. */
1267
- noteUpstreamError(info) {
1268
- return this.enqueueMutation(async () => {
1269
- const current = await this.store.load().catch(() => null);
1270
- if (!current) return;
1271
- if (!info || typeof info.code !== "string" || !LAST_ERROR_CODES.has(info.code)) return;
1272
- const cooldownUntil = typeof info.cooldownMs === "number" && info.cooldownMs > 0 ? this.now + info.cooldownMs : null;
1273
- await this.saveData({
1274
- ...current,
1275
- account: {
1276
- ...current.account,
1277
- lastError: { code: info.code },
1278
- ...cooldownUntil ? { cooldownUntil } : {}
1279
- }
1280
- });
1281
- }).catch(() => {
1282
- });
1283
- }
1284
- /**
1285
- * Rate-limit observation channel (headers/SSE, parsed by the data plane).
1286
- * Storage + cooling determination only; separate from noteUpstreamError.
1287
- * Never throws.
1288
- */
1289
- noteRateLimits(limits) {
1290
- return (async () => {
1291
- const clean = normalizeRateLimits(limits);
1292
- if (!clean) return;
1293
- await this.enqueueMutation(async () => {
1294
- const current = await this.store.load().catch(() => null);
1295
- if (!current) return;
1296
- const now = this.now;
1297
- const reset = Math.max(clean.primary?.resetAt ?? 0, clean.secondary?.resetAt ?? 0);
1298
- const saturated = rateLimitsSaturated(clean, now);
1299
- await this.saveData({
1300
- ...current,
1301
- rateLimits: clean,
1302
- account: {
1303
- ...current.account,
1304
- // A saturated window parks the account until its reset; a fresh
1305
- // benign observation clears a stale cooldown.
1306
- rateLimitCooldownUntil: saturated && reset > now ? reset : null
1307
- }
1308
- });
1309
- });
1310
- })().catch(() => {
1311
- });
1312
- }
1313
- async getRateLimits() {
1314
- const data = await this.ensureLoaded();
1315
- return data?.rateLimits ?? null;
1316
- }
1317
- // -------------------------------------------------------------- disconnect -
1318
- async disconnect() {
1319
- const job = this.pending;
1320
- this.epoch++;
1321
- if (job) {
1322
- this.terminalize(job, { status: "cancelled" });
1323
- job.rejectCode(codexAdminError("codex_login_cancelled", 409));
1324
- }
1325
- return this.enqueueMutation(async () => {
1326
- const config = await this.readRawConfig();
1327
- const provider = this.findManaged(config);
1328
- if (provider) {
1329
- const previousConfig = structuredClone(config);
1330
- let removed = false;
1331
- for (const key of PROVIDER_KEYS) {
1332
- if (!Array.isArray(config?.[key])) continue;
1333
- const index = config[key].findIndex((p) => p === provider || isCodexManagedConfigProvider(p));
1334
- if (index >= 0) {
1335
- config[key].splice(index, 1);
1336
- removed = true;
1337
- }
1338
- }
1339
- if (removed) {
1340
- protectCodexConfig(config, config);
1341
- try {
1342
- await this.options.host.writeConfig(config);
1343
- await this.options.host.reloadRuntime?.(config);
1344
- } catch {
1345
- try {
1346
- await this.options.host.writeConfig(previousConfig);
1347
- await this.options.host.reloadRuntime?.(previousConfig);
1348
- } catch {
1349
- }
1350
- throw codexAdminError("codex_config_write_failed", 500);
1351
- }
1352
- }
1353
- }
1354
- await this.store.delete().catch(() => {
1355
- });
1356
- this.applyLoaded(null);
1357
- this.loaded = true;
1358
- this.refreshFlight = null;
1359
- this.forceRefreshRequested = false;
1360
- this.usageCache = null;
1361
- return { success: true };
1362
- });
1363
- }
1364
- async dispose() {
1365
- const job = this.pending;
1366
- if (job) {
1367
- this.terminalize(job, { status: "cancelled" });
1368
- job.rejectCode(codexAdminError("codex_login_cancelled", 409));
1369
- }
1370
- }
1371
- };
1372
-
1373
- // src/finalize-body.ts
1374
- import { createHash as createHash2 } from "node:crypto";
1375
- var CODEX_PARALLEL_TOOL_CALLS_DEFAULT = true;
1376
- var CODEX_TEXT_VERBOSITY_DEFAULT = "medium";
1377
- var CODEX_REASONING_SUMMARY_DEFAULT = "auto";
1378
- var CODEX_ENCRYPTED_REASONING_INCLUDE = "reasoning.encrypted_content";
1379
- var CODEX_MAX_CALL_ID = 64;
1380
- var CODEX_MAX_ORPHAN_OUTPUT = 16e3;
1381
- var DROP_FIELDS = [
1382
- "max_output_tokens",
1383
- "max_completion_tokens",
1384
- "temperature",
1385
- "top_p",
1386
- "previous_response_id",
1387
- "user",
1388
- "safety_identifier",
1389
- "prompt_cache_options"
1390
- ];
1391
- var ALLOWED_SERVICE_TIERS = /* @__PURE__ */ new Set(["priority", "ultrafast"]);
1392
- function clone(value) {
1393
- try {
1394
- return structuredClone(value);
1395
- } catch {
1396
- return JSON.parse(JSON.stringify(value));
1397
- }
1398
- }
1399
- function isPlainObject(value) {
1400
- return !!value && typeof value === "object" && !Array.isArray(value);
1401
- }
1402
- function boundCallId(callId) {
1403
- if (typeof callId !== "string" || callId.length <= CODEX_MAX_CALL_ID) return callId;
1404
- return sha256Hex(callId);
1405
- }
1406
- function sha256Hex(text) {
1407
- return createHash2("sha256").update(text).digest("hex");
1408
- }
1409
- function conversationKey(instructions, input, sessionId) {
1410
- const parts = [];
1411
- if (instructions) parts.push(instructions);
1412
- for (const item of input) {
1413
- parts.push(JSON.stringify(item));
1414
- if (item?.role === "user") break;
1415
- }
1416
- const digest = sha256Hex(sessionId + "\0" + parts.join("\0"));
1417
- return [
1418
- digest.slice(0, 8),
1419
- digest.slice(8, 12),
1420
- digest.slice(12, 16),
1421
- digest.slice(16, 20),
1422
- digest.slice(20, 32)
1423
- ].join("-");
1424
- }
1425
- function normalizeInputShape(input) {
1426
- if (typeof input === "string") {
1427
- return [{ type: "message", role: "user", content: [{ type: "input_text", text: input }] }];
1428
- }
1429
- return Array.isArray(input) ? input : [];
1430
- }
1431
- function normalizeItem(item, boundCallIds) {
1432
- if (!isPlainObject(item)) return null;
1433
- if (item.type === "item_reference") return null;
1434
- const next = { ...item };
1435
- delete next.id;
1436
- if (next.role === "system") next.role = "developer";
1437
- if (next.call_id !== void 0) {
1438
- const bounded = boundCallId(next.call_id);
1439
- if (bounded !== next.call_id) {
1440
- boundCallIds.set(item.call_id, bounded);
1441
- next.call_id = bounded;
1442
- }
1443
- }
1444
- return next;
1445
- }
1446
- function textOfOutput(output) {
1447
- if (typeof output === "string") return output;
1448
- if (Array.isArray(output)) {
1449
- return output.map((part) => typeof part === "string" ? part : typeof part?.text === "string" ? part.text : "").filter(Boolean).join("\n");
1450
- }
1451
- if (isPlainObject(output) && typeof output.text === "string") return output.text;
1452
- try {
1453
- return JSON.stringify(output ?? "");
1454
- } catch {
1455
- return String(output);
1456
- }
1457
- }
1458
- function orphanOutputAsMessage(item) {
1459
- let text = textOfOutput(item.output);
1460
- if (text.length > CODEX_MAX_ORPHAN_OUTPUT) text = text.slice(0, CODEX_MAX_ORPHAN_OUTPUT);
1461
- return {
1462
- type: "message",
1463
- role: "assistant",
1464
- content: [{ type: "output_text", text: `[tool output for ${String(item.call_id ?? "unknown")}]
1465
- ${text}` }]
1466
- };
1467
- }
1468
- function finalizeInput(input) {
1469
- const raw = normalizeInputShape(clone(input));
1470
- const boundCallIds = /* @__PURE__ */ new Map();
1471
- const normalized = raw.map((item) => normalizeItem(item, boundCallIds)).filter((item) => item !== null);
1472
- const calls = /* @__PURE__ */ new Set();
1473
- for (const item of normalized) {
1474
- if (item.type === "function_call") calls.add(item.call_id);
1475
- }
1476
- const out = [];
1477
- for (const item of normalized) {
1478
- if (item.type === "function_call_output" && !calls.has(item.call_id)) {
1479
- out.push(orphanOutputAsMessage(item));
1480
- continue;
1481
- }
1482
- out.push(item);
1483
- }
1484
- return { input: out, callIds: boundCallIds };
1485
- }
1486
- function finalizeReasoning(body) {
1487
- const reasoning = isPlainObject(body.reasoning) ? body.reasoning : void 0;
1488
- const effort = typeof reasoning?.effort === "string" ? reasoning.effort.trim().toLowerCase() : "";
1489
- if (effort === "none") {
1490
- if (Array.isArray(body.include)) {
1491
- const kept = body.include.filter((v) => v !== CODEX_ENCRYPTED_REASONING_INCLUDE);
1492
- if (kept.length) body.include = kept;
1493
- else delete body.include;
1494
- }
1495
- if (reasoning) body.reasoning = reasoning;
1496
- return;
1497
- }
1498
- if (reasoning && effort === "ultra") reasoning.effort = "max";
1499
- if (reasoning && reasoning.summary === void 0) reasoning.summary = CODEX_REASONING_SUMMARY_DEFAULT;
1500
- const include = Array.isArray(body.include) ? body.include.filter((v) => typeof v === "string") : [];
1501
- if (!include.includes(CODEX_ENCRYPTED_REASONING_INCLUDE)) include.push(CODEX_ENCRYPTED_REASONING_INCLUDE);
1502
- body.include = include;
1503
- }
1504
- function firstLine(text) {
1505
- return (text.split(/\r?\n/, 1)[0] ?? "").trim();
1506
- }
1507
- function finalizeInstructions(body, input, modelInstructions) {
1508
- const own = typeof body.instructions === "string" ? body.instructions : "";
1509
- if (typeof modelInstructions !== "string" || modelInstructions.trim() === "") {
1510
- return input;
1511
- }
1512
- let nextInput = input;
1513
- if (own.trim() !== "" && firstLine(own) !== firstLine(modelInstructions)) {
1514
- nextInput = [{
1515
- type: "message",
1516
- role: "developer",
1517
- content: [{ type: "input_text", text: own }]
1518
- }, ...input];
1519
- }
1520
- body.instructions = modelInstructions;
1521
- return nextInput;
1522
- }
1523
- function codexFinalizeBody(body, options = {}) {
1524
- const source = isPlainObject(body) ? clone(body) : {};
1525
- const out = { ...source };
1526
- for (const key of DROP_FIELDS) delete out[key];
1527
- if (typeof out.service_tier === "string" && !ALLOWED_SERVICE_TIERS.has(out.service_tier)) delete out.service_tier;
1528
- out.store = false;
1529
- out.stream = true;
1530
- out.tool_choice = "auto";
1531
- if (out.parallel_tool_calls === void 0) out.parallel_tool_calls = CODEX_PARALLEL_TOOL_CALLS_DEFAULT;
1532
- if (!isPlainObject(out.text)) out.text = { verbosity: CODEX_TEXT_VERBOSITY_DEFAULT };
1533
- finalizeReasoning(out);
1534
- let { input } = finalizeInput(out.input);
1535
- input = finalizeInstructions(out, input, options.modelInstructions);
1536
- out.input = input;
1537
- if (typeof out.prompt_cache_key !== "string" || out.prompt_cache_key.trim() === "") {
1538
- const seed = typeof options.sessionId === "string" && options.sessionId ? options.sessionId : JSON.stringify([out.instructions ?? "", input[0] ?? null]);
1539
- out.prompt_cache_key = conversationKey(
1540
- typeof out.instructions === "string" ? out.instructions : "",
1541
- input,
1542
- seed
1543
- );
1544
- }
1545
- return out;
1546
- }
1547
- function codexSessionKey(body) {
1548
- const key = body?.prompt_cache_key;
1549
- return typeof key === "string" && key ? key : void 0;
1550
- }
1551
-
1552
- // src/transformer.ts
1553
- var CODEX_RATE_LIMIT_SCAN_BYTES = 64 * 1024;
1554
- function finiteNumber(value) {
1555
- const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
1556
- return Number.isFinite(n) ? n : void 0;
1557
- }
1558
- function windowFromHeaders(get, which, now) {
1559
- const used = finiteNumber(get(`x-codex-${which}-used-percent`));
1560
- const minutes = finiteNumber(get(`x-codex-${which}-window-minutes`));
1561
- const resetAtSeconds = finiteNumber(get(`x-codex-${which}-reset-at`));
1562
- const resetAfterSeconds = finiteNumber(get(`x-codex-${which}-reset-after-seconds`));
1563
- if (used === void 0 && minutes === void 0 && resetAtSeconds === void 0 && resetAfterSeconds === void 0) {
1564
- return void 0;
1565
- }
1566
- const window = { usedPercent: used ?? 0 };
1567
- if (minutes !== void 0) window.windowSeconds = minutes * 60;
1568
- if (resetAtSeconds !== void 0) window.resetAt = resetAtSeconds * 1e3;
1569
- else if (resetAfterSeconds !== void 0) window.resetAt = now + resetAfterSeconds * 1e3;
1570
- return window;
1571
- }
1572
- function readCodexRateLimitHeaders(headers, now = Date.now()) {
1573
- const get = (name) => {
1574
- if (headers instanceof Headers) return headers.get(name);
1575
- const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
1576
- return key ? headers[key] : null;
1577
- };
1578
- const primary = windowFromHeaders(get, "primary", now);
1579
- const secondary = windowFromHeaders(get, "secondary", now);
1580
- return primary || secondary ? { ...primary ? { primary } : {}, ...secondary ? { secondary } : {}, observedAt: now, source: "headers" } : void 0;
1581
- }
1582
- function parseCodexRateLimitsEvent(payload, now = Date.now()) {
1583
- if (!payload || typeof payload !== "object") return void 0;
1584
- const event = payload.type === "codex.rate_limits" ? payload : payload.rate_limits ? payload : void 0;
1585
- if (!event) return void 0;
1586
- const limits = event.rate_limits ?? event;
1587
- if (!limits || typeof limits !== "object") return void 0;
1588
- const metered = limits.metered_limit_name;
1589
- if (typeof metered === "string" && metered !== "codex") return void 0;
1590
- const readWindow = (raw) => {
1591
- if (!raw || typeof raw !== "object") return void 0;
1592
- const used = finiteNumber(raw.used_percent);
1593
- if (used === void 0) return void 0;
1594
- const window = { usedPercent: used };
1595
- const seconds = finiteNumber(raw.window_seconds) ?? (finiteNumber(raw.window_minutes) !== void 0 ? finiteNumber(raw.window_minutes) * 60 : void 0);
1596
- if (seconds !== void 0) window.windowSeconds = seconds;
1597
- const resetAt = finiteNumber(raw.reset_at);
1598
- if (resetAt !== void 0) window.resetAt = resetAt * 1e3;
1599
- return window;
1600
- };
1601
- const primary = readWindow(limits.primary);
1602
- const secondary = readWindow(limits.secondary);
1603
- return primary || secondary ? { ...primary ? { primary } : {}, ...secondary ? { secondary } : {}, observedAt: now, source: "sse" } : void 0;
1604
- }
1605
- function codexTerminalError(event) {
1606
- if (!event || typeof event !== "object") return void 0;
1607
- const type = typeof event.type === "string" ? event.type : "";
1608
- if (type === "error") {
1609
- const error = event.error ?? event;
1610
- return typeof error === "object" && error !== null ? error : { message: String(event.message ?? "stream error") };
1611
- }
1612
- if (type === "response.failed") {
1613
- const error = event.response?.error ?? event.error;
1614
- return typeof error === "object" && error !== null ? error : { message: "response.failed without an error body", code: "response_failed" };
1615
- }
1616
- return void 0;
1617
- }
1618
- function codexClassifiedStreamError(event, upstreamStatus = 200) {
1619
- const probe = codexStreamError(event, upstreamStatus);
1620
- const terminal = codexTerminalError(event);
1621
- const effectiveStatus = probe.statusCode >= 400 ? probe.statusCode : probe.isRateLimit ? 429 : 502;
1622
- const classified = classifyCodexError(effectiveStatus, terminal ? { ...event, error: terminal } : event) ?? { code: "codex_upstream_error", message: "Codex upstream stream failed.", httpStatus: 502, retryable: true };
1623
- const error = codexError({
1624
- code: classified.code,
1625
- message: classified.message,
1626
- httpStatus: classified.httpStatus,
1627
- ...classified.cooldownMs !== void 0 ? { cooldownMs: classified.cooldownMs } : {},
1628
- retryable: classified.retryable === true
1629
- });
1630
- return Object.assign(error, {
1631
- pluginClassified: true,
1632
- upstreamStatus,
1633
- isRateLimit: classified.httpStatus === 429
1634
- });
1635
- }
1636
- function codexStreamError(event, status = 200) {
1637
- const error = codexTerminalError(event) ?? {};
1638
- const code = typeof error.code === "string" ? error.code : typeof error.type === "string" ? error.type : "codex_stream_error";
1639
- const message = typeof error.message === "string" && error.message ? error.message : "Codex upstream stream failed";
1640
- return Object.assign(new Error(message), {
1641
- code,
1642
- statusCode: status,
1643
- upstreamStatus: status,
1644
- isRateLimit: code === "usage_limit_reached" || error.type === "usage_limit_reached",
1645
- rawBody: JSON.stringify({ error })
1646
- });
1647
- }
1648
- var CodexTransformer = class {
1649
- static TransformerName = "codex";
1650
- name = "codex";
1651
- logger;
1652
- service;
1653
- constructor(options) {
1654
- if (!options?.service) throw new Error("CodexTransformer requires { service }");
1655
- this.service = options.service;
1656
- }
1657
- /**
1658
- * Request phase: finalize the Responses body produced by the preceding
1659
- * `openai-responses` transformer. The runtime performs auth injection later
1660
- * (after the body is final), so no token is touched here.
1661
- */
1662
- async transformRequestIn(request, _provider, context) {
1663
- const model = typeof request?.model === "string" ? request.model : "";
1664
- let modelInstructions;
1665
- try {
1666
- modelInstructions = model ? this.service.getModelInstructions?.(model) : void 0;
1667
- } catch {
1668
- modelInstructions = void 0;
1669
- }
1670
- const sessionId = this.sessionIdFor(request, context);
1671
- const body = codexFinalizeBody(request, { modelInstructions, sessionId });
1672
- if (context) context.codexSessionKey = codexSessionKey(body);
1673
- return { body };
1674
- }
1675
- /**
1676
- * Stable conversation identity for the derived prompt_cache_key: the client
1677
- * session when the server provides one, otherwise a hash of the first user
1678
- * turn (which is what the finalizer falls back to when this is absent).
1679
- */
1680
- sessionIdFor(request, context) {
1681
- const fromReq = context?.req?.clientContext?.stableSessionId;
1682
- if (typeof fromReq === "string" && fromReq) return fromReq;
1683
- const header = context?.req?.headers?.["x-session-id"] ?? context?.req?.headers?.["x-session-affinity"];
1684
- if (typeof header === "string" && header) return header;
1685
- return void 0;
1686
- }
1687
- /**
1688
- * Response phase. Byte-preserving for the happy path: the downstream
1689
- * `openai-responses` transformer needs the original Responses SSE/JSON.
1690
- * - terminal in-stream events (`error`, `response.failed`) become thrown
1691
- * errors so fallback/classification engage instead of a truncated reply;
1692
- * - quota channels (headers + a bounded `codex.rate_limits` SSE scan) are
1693
- * observed out-of-band for the runtime's cooldown bookkeeping.
1694
- * Nothing is buffered beyond the bounded scan window; a cancelled client
1695
- * cancels the upstream reader and never accumulates the whole response.
1696
- */
1697
- async transformResponseOut(response, context) {
1698
- this.observeHeaderRateLimits(response);
1699
- const contentType = response.headers.get("content-type") ?? "";
1700
- if (!contentType.includes("text/event-stream") || !response.body) {
1701
- return response;
1702
- }
1703
- return this.inspectStream(response, context);
1704
- }
1705
- /**
1706
- * Report an observation to the service. Ruling B: `noteRateLimits` must never
1707
- * throw into the response path — the transformer swallows both a synchronous
1708
- * throw and an async rejection so a broken bookkeeper cannot break a reply.
1709
- */
1710
- reportRateLimits(limits) {
1711
- try {
1712
- const result = this.service.noteRateLimits(limits);
1713
- if (result && typeof result.then === "function") result.then(void 0, () => {
1714
- });
1715
- } catch {
1716
- }
1717
- }
1718
- observeHeaderRateLimits(response) {
1719
- const limits = readCodexRateLimitHeaders(response.headers);
1720
- if (limits) this.reportRateLimits(limits);
1721
- }
1722
- /**
1723
- * Inspect only the PREFIX of the stream (bounded by CODEX_RATE_LIMIT_SCAN_BYTES
1724
- * and ending at the first content-bearing event). Errors that arrive later —
1725
- * after content has been committed to the client — are not re-classified
1726
- * (rotating/falling back after bytes are on the wire would duplicate text).
1727
- * After the prefix, bytes pass through untouched, including [DONE] and
1728
- * comments; a client cancel propagates to the upstream reader.
1729
- */
1730
- inspectStream(response, context) {
1731
- const reader = response.body.getReader();
1732
- const decoder = new TextDecoder();
1733
- const chunks = [];
1734
- let pending = "";
1735
- let scanned = 0;
1736
- let committed = false;
1737
- let finished = false;
1738
- let rateLimitsSeen = false;
1739
- const handleEvent = async (data) => {
1740
- if (data === "[DONE]") return true;
1741
- let event;
1742
- try {
1743
- event = JSON.parse(data);
1744
- } catch {
1745
- return true;
1746
- }
1747
- if (!rateLimitsSeen && event?.type === "codex.rate_limits") {
1748
- const limits = parseCodexRateLimitsEvent(event);
1749
- if (limits) {
1750
- rateLimitsSeen = true;
1751
- this.reportRateLimits(limits);
1752
- }
1753
- return false;
1754
- }
1755
- const terminal = codexTerminalError(event);
1756
- if (terminal) {
1757
- const error = codexStreamError(event, response.status);
1758
- try {
1759
- const effectiveStatus = error.statusCode >= 400 ? error.statusCode : error.isRateLimit ? 429 : 502;
1760
- const classified = classifyCodexError(effectiveStatus, terminal ? { ...event, error: terminal } : event) ?? {
1761
- code: "codex_upstream_error",
1762
- message: "Codex upstream stream failed.",
1763
- httpStatus: 502,
1764
- retryable: true
1765
- };
1766
- await this.service.noteUpstreamError?.({
1767
- code: classified.code,
1768
- message: classified.message,
1769
- httpStatus: classified.httpStatus,
1770
- ...classified.cooldownMs !== void 0 ? { cooldownMs: classified.cooldownMs } : {},
1771
- ...classified.retryable !== void 0 ? { retryable: classified.retryable } : {}
1772
- });
1773
- } catch {
1774
- }
1775
- throw codexClassifiedStreamError(event, response.status);
1776
- }
1777
- return typeof event?.type === "string" && (event.type.startsWith("response.output_text") || event.type.startsWith("response.function_call_arguments") || event.type.startsWith("response.reasoning") || event.type === "response.output_item.done" || event.type === "response.completed" || event.type === "response.incomplete");
1778
- };
1779
- const stream = new ReadableStream({
1780
- async pull(controller) {
1781
- try {
1782
- while (true) {
1783
- if (chunks.length) {
1784
- controller.enqueue(chunks.shift());
1785
- return;
1786
- }
1787
- if (committed) {
1788
- const next2 = await reader.read();
1789
- if (next2.done) {
1790
- controller.close();
1791
- reader.releaseLock();
1792
- return;
1793
- }
1794
- controller.enqueue(next2.value);
1795
- return;
1796
- }
1797
- const next = await reader.read();
1798
- if (next.done) {
1799
- pending = "";
1800
- committed = true;
1801
- controller.close();
1802
- reader.releaseLock();
1803
- return;
1804
- }
1805
- if (next.value?.byteLength) {
1806
- chunks.push(next.value);
1807
- scanned += next.value.byteLength;
1808
- pending += decoder.decode(next.value, { stream: true });
1809
- const events = pending.split(/\r\n\r\n|\n\n|\r\r/);
1810
- pending = events.pop() ?? "";
1811
- for (const raw of events) {
1812
- const data = raw.split(/\r\n|\r|\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
1813
- if (!data) continue;
1814
- if (await handleEvent(data)) {
1815
- committed = true;
1816
- break;
1817
- }
1818
- }
1819
- if (scanned >= CODEX_RATE_LIMIT_SCAN_BYTES) committed = true;
1820
- if (committed) pending = "";
1821
- }
1822
- }
1823
- } catch (error) {
1824
- await reader.cancel(error).catch(() => {
1825
- });
1826
- controller.error(error);
1827
- }
1828
- },
1829
- cancel(reason) {
1830
- return reader.cancel(reason);
1831
- }
1832
- });
1833
- const headers = new Headers(response.headers);
1834
- headers.delete("content-length");
1835
- return new Response(stream, { status: response.status, statusText: response.statusText, headers });
1836
- }
1837
- };
1838
-
1839
- // src/managed-runtime.ts
1840
- var CODEX_STRIPPED_HEADERS = [
1841
- "authorization",
1842
- "x-api-key",
1843
- "api-key",
1844
- "proxy-authorization",
1845
- "host",
1846
- "cookie",
1847
- // Session/conversation identity: only the FINAL body may define it, and only
1848
- // under the exact hyphenated names the backend reads.
1849
- "session_id",
1850
- "conversation_id",
1851
- "session-id",
1852
- "thread-id",
1853
- "conversation-id",
1854
- // Account identity is CONDITIONALLY injected (only when an account id is
1855
- // known); strip a client value even on a call that does not re-inject it,
1856
- // or it would ride through to the upstream verbatim.
1857
- "chatgpt-account-id"
1858
- ];
1859
- var STRIPPED = new Set(CODEX_STRIPPED_HEADERS);
1860
- function codexUserAgent2(version = CODEX_CLIENT_VERSION) {
1861
- const os = process.platform === "darwin" ? "Mac OS" : process.platform === "win32" ? "Windows" : "Linux";
1862
- const arch = process.arch === "x64" ? "x86_64" : process.arch;
1863
- return `${CODEX_ORIGINATOR}/${version} (${os}; ${arch})`;
1864
- }
1865
- function codexAccountHeaders(input) {
1866
- const version = input.version ?? CODEX_CLIENT_VERSION;
1867
- const headers = {
1868
- Authorization: `Bearer ${input.accessToken}`,
1869
- "OpenAI-Beta": "responses=experimental",
1870
- originator: CODEX_ORIGINATOR,
1871
- version,
1872
- "User-Agent": codexUserAgent2(version),
1873
- Accept: "text/event-stream"
1874
- };
1875
- if (input.accountId) headers["chatgpt-account-id"] = input.accountId;
1876
- const sessionKey = input.requestBody?.prompt_cache_key;
1877
- if (typeof sessionKey === "string" && sessionKey) {
1878
- headers["session-id"] = sessionKey;
1879
- headers["thread-id"] = sessionKey;
1880
- }
1881
- return headers;
1882
- }
1883
- function createCodexManagedRuntime(options) {
1884
- const { service } = options;
1885
- if (!service) throw new Error("createCodexManagedRuntime requires { service }");
1886
- return {
1887
- name: "codex",
1888
- isManaged: (provider) => isCodexRuntime(provider),
1889
- // Circuit breaker BEFORE any network touch — including a token refresh.
1890
- ensureUsable: async () => {
1891
- if (await service.isAccountCooling()) {
1892
- throw codexError({
1893
- code: "codex_account_cooling",
1894
- message: "Codex \u8BA2\u9605\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u51B7\u5374\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002",
1895
- httpStatus: 429,
1896
- retryable: false
1897
- });
1898
- }
1899
- },
1900
- // Pin the upstream: a config-supplied base_url can never win, a redirect
1901
- // away from the fixed origin is an error, and the fixed origin ignores
1902
- // CCR/proxy environment routing.
1903
- lockUpstream: async (config) => {
1904
- config.url = CODEX_UPSTREAM_URL;
1905
- config.redirect = "error";
1906
- config.dispatcher = options.host.getDirectDispatcher();
1907
- },
1908
- // Called AFTER the body is final: session headers derive from it.
1909
- signRequest: async ({ headers, requestBody }) => {
1910
- const accessToken = await service.getAccessToken();
1911
- const accountId = await Promise.resolve().then(() => service.getAccountId()).catch(() => void 0);
1912
- const injected = codexAccountHeaders({ accessToken, accountId, requestBody });
1913
- const injectedNames = new Set(Object.keys(injected).map((k) => k.toLowerCase()));
1914
- const next = {};
1915
- for (const [key, value] of Object.entries(headers ?? {})) {
1916
- const lower = key.toLowerCase();
1917
- if (STRIPPED.has(lower)) continue;
1918
- if (injectedNames.has(lower)) continue;
1919
- next[key] = value;
1920
- }
1921
- return { ...next, ...injected };
1922
- },
1923
- classifyError: (status, body, systemText) => {
1924
- if (status === 0) return null;
1925
- let parsed = body;
1926
- if (typeof parsed === "string") {
1927
- try {
1928
- parsed = JSON.parse(parsed);
1929
- } catch {
1930
- }
1931
- }
1932
- const classified = classifyCodexError(status, parsed ?? body, systemText);
1933
- return classified && { ...classified, retryable: classified.retryable === true };
1934
- },
1935
- noteUpstreamError: async (info) => {
1936
- try {
1937
- await service.noteUpstreamError({
1938
- code: info.code,
1939
- message: info.message,
1940
- httpStatus: info.httpStatus,
1941
- ...info.cooldownMs !== void 0 ? { cooldownMs: info.cooldownMs } : {},
1942
- ...info.validationUrl ? { validationUrl: info.validationUrl } : {},
1943
- ...info.retryable !== void 0 ? { retryable: info.retryable } : {}
1944
- });
1945
- } catch (error) {
1946
- options.log?.warn(`codex noteUpstreamError failed (code=${info.code}): ${String(error?.message ?? "unknown")}`);
1947
- }
1948
- },
1949
- // One forced refresh + one re-dispatch on 401; the core enforces the
1950
- // exactly-once budget. The service persists a rotated refresh token before
1951
- // switching the in-memory identity.
1952
- authRefresh: {
1953
- forceRefresh: async () => {
1954
- await service.forceTokenRefresh();
1955
- }
1956
- },
1957
- // Token hygiene: never log Codex request/response bodies or headers.
1958
- suppressDebugLog: true
1959
- };
1960
- }
1961
-
1962
- // src/admin-routes.ts
1963
- var CODEX_LOGIN_ID_RE = /^[a-f0-9]{32}$/;
1964
- function registerCodexAdminRoutes(app, deps) {
1965
- function assertLocalCodexRequest(req) {
1966
- const deny = () => {
1967
- const err = new Error("codex_unauthorized");
1968
- err.statusCode = 403;
1969
- throw err;
1970
- };
1971
- const ip = req.ip || req.connection?.remoteAddress || "";
1972
- const isLoopback = ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1";
1973
- if (!isLoopback) deny();
1974
- const origin = req.headers?.origin;
1975
- let host = "";
1976
- try {
1977
- if (origin !== void 0 && origin !== "") {
1978
- if (typeof origin !== "string") deny();
1979
- const parsed = new URL(origin);
1980
- if (!["http:", "https:"].includes(parsed.protocol)) deny();
1981
- host = parsed.host;
1982
- }
1983
- } catch {
1984
- deny();
1985
- }
1986
- const address = app.server?.address?.();
1987
- const port = typeof address?.port === "number" && address.port > 0 ? address.port : 3456;
1988
- const allowed = /* @__PURE__ */ new Set([
1989
- `127.0.0.1:${port}`,
1990
- `localhost:${port}`,
1991
- `[::1]:${port}`
1992
- ]);
1993
- const authority = req.headers?.host;
1994
- if (typeof authority === "string" && !allowed.has(authority)) deny();
1995
- if (host && !allowed.has(host)) deny();
1996
- }
1997
- const CODEX_ERROR_STATUS = {
1998
- codex_unauthorized: 403,
1999
- codex_not_connected: 409,
2000
- codex_login_busy: 429,
2001
- codex_login_cancelled: 409,
2002
- codex_login_state_rejected: 422,
2003
- codex_login_expired: 410,
2004
- codex_login_exchange_failed: 422,
2005
- codex_login_persist_failed: 500,
2006
- codex_credential_invalid: 422,
2007
- codex_credential_unreadable: 500,
2008
- codex_config_write_failed: 500,
2009
- codex_models_fetch_failed: 422,
2010
- codex_reauth_required: 422
2011
- };
2012
- const isCodexErrorCode = (value) => typeof value === "string" && Object.prototype.hasOwnProperty.call(CODEX_ERROR_STATUS, value);
2013
- function codexRouteError(error, reply, route, fallbackCode) {
2014
- if (error?.statusCode === 403) {
2015
- reply.status(403);
2016
- return { ok: false, success: false, error: "codex_unauthorized" };
2017
- }
2018
- if (isCodexErrorCode(error?.code)) {
2019
- reply.status(CODEX_ERROR_STATUS[error.code]);
2020
- return { ok: false, success: false, error: error.code };
2021
- }
2022
- app.log?.warn?.(
2023
- { route: `codex/${route}`, code: isCodexErrorCode(error?.code) ? error.code : void 0 },
2024
- "Codex management route failed"
2025
- );
2026
- reply.status(500);
2027
- return { ok: false, success: false, error: fallbackCode };
2028
- }
2029
- function requireLoginId(body) {
2030
- const loginId = body?.loginId;
2031
- return typeof loginId === "string" && CODEX_LOGIN_ID_RE.test(loginId) ? loginId : null;
2032
- }
2033
- function invalidLoginId(reply) {
2034
- reply.status(422);
2035
- return { ok: false, success: false, error: "codex_login_state_rejected" };
2036
- }
2037
- app.get("/api/codex/status", async (req, reply) => {
2038
- try {
2039
- assertLocalCodexRequest(req);
2040
- const service = deps.getService();
2041
- if (!service) {
2042
- reply.status(503);
2043
- return { ok: false, success: false, error: "codex_request_failed" };
2044
- }
2045
- return await service.getStatus();
2046
- } catch (error) {
2047
- return codexRouteError(error, reply, "status", "codex_request_failed");
2048
- }
2049
- });
2050
- app.post("/api/codex/login/start", async (req, reply) => {
2051
- try {
2052
- assertLocalCodexRequest(req);
2053
- const service = deps.getService();
2054
- if (!service) {
2055
- reply.status(503);
2056
- return { ok: false, success: false, error: "codex_request_failed" };
2057
- }
2058
- return await service.startLogin();
2059
- } catch (error) {
2060
- return codexRouteError(error, reply, "login/start", "codex_request_failed");
2061
- }
2062
- });
2063
- app.post("/api/codex/login/poll", async (req, reply) => {
2064
- try {
2065
- assertLocalCodexRequest(req);
2066
- const service = deps.getService();
2067
- if (!service) {
2068
- reply.status(503);
2069
- return { ok: false, success: false, error: "codex_request_failed" };
2070
- }
2071
- const loginId = requireLoginId(req.body);
2072
- if (!loginId) return invalidLoginId(reply);
2073
- return await service.pollLogin(loginId);
2074
- } catch (error) {
2075
- return codexRouteError(error, reply, "login/poll", "codex_request_failed");
2076
- }
2077
- });
2078
- app.post("/api/codex/login/complete", async (req, reply) => {
2079
- try {
2080
- assertLocalCodexRequest(req);
2081
- const service = deps.getService();
2082
- if (!service) {
2083
- reply.status(503);
2084
- return { ok: false, success: false, error: "codex_request_failed" };
2085
- }
2086
- const loginId = requireLoginId(req.body);
2087
- const callbackUrl = req.body?.callbackUrl;
2088
- if (!loginId || typeof callbackUrl !== "string" || !callbackUrl) return invalidLoginId(reply);
2089
- return await service.submitCallback(loginId, callbackUrl);
2090
- } catch (error) {
2091
- return codexRouteError(error, reply, "login/complete", "codex_request_failed");
2092
- }
2093
- });
2094
- app.post("/api/codex/login/cancel", async (req, reply) => {
2095
- try {
2096
- assertLocalCodexRequest(req);
2097
- const service = deps.getService();
2098
- if (!service) {
2099
- reply.status(503);
2100
- return { ok: false, success: false, error: "codex_request_failed" };
2101
- }
2102
- const loginId = requireLoginId(req.body);
2103
- if (!loginId) return invalidLoginId(reply);
2104
- await service.cancelLogin(loginId);
2105
- return { ok: true };
2106
- } catch (error) {
2107
- return codexRouteError(error, reply, "login/cancel", "codex_request_failed");
2108
- }
2109
- });
2110
- app.post("/api/codex/sync", async (req, reply) => {
2111
- try {
2112
- assertLocalCodexRequest(req);
2113
- const service = deps.getService();
2114
- if (!service) {
2115
- reply.status(503);
2116
- return { ok: false, success: false, error: "codex_request_failed" };
2117
- }
2118
- return await service.syncModels();
2119
- } catch (error) {
2120
- return codexRouteError(error, reply, "sync", "codex_request_failed");
2121
- }
2122
- });
2123
- app.post("/api/codex/usage", async (req, reply) => {
2124
- try {
2125
- assertLocalCodexRequest(req);
2126
- const service = deps.getService();
2127
- if (!service) {
2128
- reply.status(503);
2129
- return { ok: false, success: false, error: "codex_request_failed" };
2130
- }
2131
- const usage = await service.getUsage();
2132
- reply.status(200);
2133
- return usage;
2134
- } catch (error) {
2135
- return codexRouteError(error, reply, "usage", "codex_request_failed");
2136
- }
2137
- });
2138
- app.post("/api/codex/disconnect", async (req, reply) => {
2139
- try {
2140
- assertLocalCodexRequest(req);
2141
- const service = deps.getService();
2142
- if (!service) {
2143
- reply.status(503);
2144
- return { ok: false, success: false, error: "codex_request_failed" };
2145
- }
2146
- return await service.disconnect();
2147
- } catch (error) {
2148
- return codexRouteError(error, reply, "disconnect", "codex_request_failed");
2149
- }
2150
- });
2151
- }
2152
-
2153
- // src/locales.ts
2154
- var codexLocales = {
2155
- en: {
2156
- codex: {
2157
- title: "Codex Subscription",
2158
- builtin: "Official plugin",
2159
- experimental: "Experimental",
2160
- managed_provider: "Managed provider: {{name}}",
2161
- description: "Uses your ChatGPT/Codex plan through browser authorization. CCR never reads ~/.codex or imports the official CLI login.",
2162
- status: {
2163
- loading: "Loading\u2026",
2164
- not_connected: "Not connected",
2165
- connected: "Connected",
2166
- cooldown: "Quota cooldown",
2167
- needs_relogin: "Sign-in expired",
2168
- error: "Error"
2169
- },
2170
- labels: {
2171
- email: "Email",
2172
- account: "Account",
2173
- plan: "Plan",
2174
- models: "Models"
2175
- },
2176
- models_count: "{{count}} models",
2177
- unknown: "Unknown",
2178
- cooldown_until: "Quota cooldown until {{time}}",
2179
- needs_relogin_help: "The sign-in has expired. Reconnect to refresh the authorization.",
2180
- browser_login: "Browser login",
2181
- reconnect: "Reconnect",
2182
- sync: "Sync models",
2183
- disconnect: "Disconnect",
2184
- refresh_usage: "Refresh quota",
2185
- working: "Working\u2026",
2186
- cancel: "Cancel",
2187
- login_pending: "Waiting for authorization in your browser\u2026",
2188
- open_login: "Open OpenAI authorization page",
2189
- paste_title: "Paste callback URL",
2190
- paste_help: "The local callback port is unavailable (another application may own it \u2014 CCR will not terminate it). After approving in the browser, copy the full address your browser was redirected to (it will fail to load; that is expected) and paste it here.",
2191
- paste_hint: "Browser did not return automatically? Paste the redirected callback address here.",
2192
- paste_placeholder: "http://127.0.0.1:1455/auth/callback?code=\u2026&state=\u2026",
2193
- paste_submit: "Complete login",
2194
- login_success: "Connected as {{email}}.",
2195
- login_success_unknown: "Connected.",
2196
- synced: "Synced {{count}} Codex models.",
2197
- disconnected: "Disconnected.",
2198
- disconnect_title: "Disconnect Codex?",
2199
- disconnect_warning: "The managed provider entry and stored authorization are removed. Your OpenAI plan itself is not touched, and Router/other providers are preserved. You can reconnect anytime.",
2200
- usage_title: "Plan quota",
2201
- usage_primary: "Primary window ({{window}})",
2202
- usage_secondary: "Secondary window ({{window}})",
2203
- usage_line: "{{percent}}% used \xB7 resets {{time}}",
2204
- usage_plan: "Plan: {{plan}}",
2205
- usage_unavailable: "Quota information is not available right now.",
2206
- usage_updated: "Updated {{time}}",
2207
- window: {
2208
- minutes: "{{count}} min",
2209
- hours: "{{count}} h",
2210
- days: "{{count}} d"
2211
- },
2212
- about: "About this integration",
2213
- about_body: "After connecting, model syncing pulls the model list your plan exposes; the managed provider serves OpenAI Codex models through CCR. Quota is shown per rate-limit window (a short primary window plus a longer secondary window) and is read at most once per visit, then cached briefly.",
2214
- disclaimer: "Experimental integration using the official Codex client identity. Fair-use outcomes under your OpenAI plan terms cannot be guaranteed \u2014 use at your own discretion.",
2215
- other_edit: "Another change is in progress \u2014 actions are paused until it finishes.",
2216
- errors: {
2217
- request_failed: "The request failed. Please try again.",
2218
- config_busy: "Another save or action is running \u2014 try again when it finishes.",
2219
- login_invalid_response: "The login response was invalid. Please retry.",
2220
- login_failed: "Login failed.",
2221
- login_expired: "The authorization window expired. Please start again.",
2222
- login_cancelled: "Login cancelled.",
2223
- sync_failed: "Model sync failed.",
2224
- disconnect_failed: "Disconnect failed.",
2225
- callback_invalid: "That does not look like a valid callback URL (expected code and state parameters).",
2226
- callback_rejected: "The callback was rejected. Please copy the full address and try again.",
2227
- reconciliation_failed: "Applied, but the local settings draft could not be refreshed \u2014 reload the page to see the change."
2228
- }
2229
- }
2230
- },
2231
- zh: {
2232
- codex: {
2233
- title: "Codex \u8BA2\u9605",
2234
- builtin: "\u5B98\u65B9\u63D2\u4EF6",
2235
- experimental: "\u5B9E\u9A8C\u6027",
2236
- managed_provider: "\u53D7\u7BA1\u4F9B\u5E94\u5546\uFF1A{{name}}",
2237
- description: "\u901A\u8FC7\u6D4F\u89C8\u5668\u6388\u6743\u4F7F\u7528\u4F60\u7684 ChatGPT/Codex \u8BA2\u9605\u3002CCR \u4E0D\u8BFB\u53D6 ~/.codex\uFF0C\u4E5F\u4E0D\u5BFC\u5165\u5B98\u65B9 CLI \u767B\u5F55\u3002",
2238
- status: {
2239
- loading: "\u52A0\u8F7D\u4E2D\u2026",
2240
- not_connected: "\u672A\u8FDE\u63A5",
2241
- connected: "\u5DF2\u8FDE\u63A5",
2242
- cooldown: "\u914D\u989D\u51B7\u5374\u4E2D",
2243
- needs_relogin: "\u767B\u5F55\u5DF2\u8FC7\u671F",
2244
- error: "\u9519\u8BEF"
2245
- },
2246
- labels: {
2247
- email: "\u90AE\u7BB1",
2248
- account: "\u8D26\u53F7",
2249
- plan: "\u5957\u9910",
2250
- models: "\u6A21\u578B"
2251
- },
2252
- models_count: "{{count}} \u4E2A\u6A21\u578B",
2253
- unknown: "\u672A\u77E5",
2254
- cooldown_until: "\u914D\u989D\u51B7\u5374\u81F3 {{time}}",
2255
- needs_relogin_help: "\u767B\u5F55\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u8FDE\u63A5\u4EE5\u5237\u65B0\u6388\u6743\u3002",
2256
- browser_login: "\u6D4F\u89C8\u5668\u767B\u5F55",
2257
- reconnect: "\u91CD\u65B0\u8FDE\u63A5",
2258
- sync: "\u540C\u6B65\u6A21\u578B",
2259
- disconnect: "\u65AD\u5F00\u8FDE\u63A5",
2260
- refresh_usage: "\u5237\u65B0\u914D\u989D",
2261
- working: "\u5904\u7406\u4E2D\u2026",
2262
- cancel: "\u53D6\u6D88",
2263
- login_pending: "\u6B63\u5728\u7B49\u5F85\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u6388\u6743\u2026",
2264
- open_login: "\u6253\u5F00 OpenAI \u6388\u6743\u9875\u9762",
2265
- paste_title: "\u7C98\u8D34\u56DE\u8C03\u5730\u5740",
2266
- paste_help: "\u672C\u5730\u56DE\u8C03\u7AEF\u53E3\u4E0D\u53EF\u7528\uFF08\u53EF\u80FD\u88AB\u5176\u4ED6\u5E94\u7528\u5360\u7528\u2014\u2014CCR \u4E0D\u4F1A\u66FF\u4F60\u7ED3\u675F\u522B\u4EBA\u7684\u8FDB\u7A0B\uFF09\u3002\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u6388\u6743\u540E\uFF0C\u628A\u6D4F\u89C8\u5668\u8DF3\u8F6C\u5230\u7684\u5B8C\u6574\u5730\u5740\uFF08\u9875\u9762\u4F1A\u52A0\u8F7D\u5931\u8D25\uFF0C\u8FD9\u662F\u9884\u671F\u884C\u4E3A\uFF09\u590D\u5236\u5E76\u7C98\u8D34\u5230\u8FD9\u91CC\u3002",
2267
- paste_hint: "\u6D4F\u89C8\u5668\u6CA1\u6709\u81EA\u52A8\u8FD4\u56DE\uFF1F\u628A\u8DF3\u8F6C\u540E\u7684\u56DE\u8C03\u5730\u5740\u7C98\u8D34\u5230\u8FD9\u91CC\u3002",
2268
- paste_placeholder: "http://127.0.0.1:1455/auth/callback?code=\u2026&state=\u2026",
2269
- paste_submit: "\u5B8C\u6210\u767B\u5F55",
2270
- login_success: "\u5DF2\u8FDE\u63A5\uFF1A{{email}}\u3002",
2271
- login_success_unknown: "\u5DF2\u8FDE\u63A5\u3002",
2272
- synced: "\u5DF2\u540C\u6B65 {{count}} \u4E2A Codex \u6A21\u578B\u3002",
2273
- disconnected: "\u5DF2\u65AD\u5F00\u8FDE\u63A5\u3002",
2274
- disconnect_title: "\u65AD\u5F00 Codex\uFF1F",
2275
- disconnect_warning: "\u5C06\u79FB\u9664\u53D7\u7BA1\u4F9B\u5E94\u5546\u6761\u76EE\u548C\u5DF2\u5B58\u7684\u6388\u6743\u3002\u4E0D\u4F1A\u5F71\u54CD\u4F60\u7684 OpenAI \u8BA2\u9605\u672C\u8EAB\uFF0CRouter \u4E0E\u5176\u4ED6\u4F9B\u5E94\u5546\u4FDD\u6301\u4E0D\u53D8\u3002\u4E4B\u540E\u53EF\u968F\u65F6\u91CD\u65B0\u8FDE\u63A5\u3002",
2276
- usage_title: "\u8BA2\u9605\u914D\u989D",
2277
- usage_primary: "\u4E3B\u7A97\u53E3\uFF08{{window}}\uFF09",
2278
- usage_secondary: "\u6B21\u7A97\u53E3\uFF08{{window}}\uFF09",
2279
- usage_line: "\u5DF2\u7528 {{percent}}% \xB7 {{time}} \u91CD\u7F6E",
2280
- usage_plan: "\u5957\u9910\uFF1A{{plan}}",
2281
- usage_unavailable: "\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\u914D\u989D\u4FE1\u606F\u3002",
2282
- usage_updated: "\u66F4\u65B0\u4E8E {{time}}",
2283
- window: {
2284
- minutes: "{{count}} \u5206\u949F",
2285
- hours: "{{count}} \u5C0F\u65F6",
2286
- days: "{{count}} \u5929"
2287
- },
2288
- about: "\u5173\u4E8E\u672C\u96C6\u6210",
2289
- about_body: "\u8FDE\u63A5\u540E\uFF0C\u300C\u540C\u6B65\u6A21\u578B\u300D\u4F1A\u62C9\u53D6\u4F60\u7684\u8BA2\u9605\u53EF\u7528\u7684\u6A21\u578B\u5217\u8868\uFF0C\u7531\u53D7\u7BA1\u4F9B\u5E94\u5546\u7ECF CCR \u63D0\u4F9B OpenAI Codex \u6A21\u578B\u3002\u914D\u989D\u6309\u9650\u6D41\u7A97\u53E3\u663E\u793A\uFF08\u4E00\u4E2A\u8F83\u77ED\u7684\u4E3B\u7A97\u53E3\u52A0\u4E00\u4E2A\u8F83\u957F\u7684\u6B21\u7A97\u53E3\uFF09\uFF0C\u6BCF\u6B21\u8BBF\u95EE\u6700\u591A\u81EA\u52A8\u8BFB\u53D6\u4E00\u6B21\uFF0C\u4E4B\u540E\u77ED\u6682\u7F13\u5B58\u3002",
2290
- disclaimer: "\u5B9E\u9A8C\u6027\u96C6\u6210\uFF0C\u4F7F\u7528\u5B98\u65B9 Codex \u5BA2\u6237\u7AEF\u8EAB\u4EFD\u3002\u65E0\u6CD5\u4FDD\u8BC1\u5728\u4F60\u7684 OpenAI \u5957\u9910\u6761\u6B3E\u4E0B\u4E0D\u88AB\u5224\u4E3A\u8FDD\u89C4\uFF0C\u8BF7\u81EA\u884C\u659F\u914C\u4F7F\u7528\u3002",
2291
- other_edit: "\u53E6\u4E00\u5904\u4FEE\u6539\u6B63\u5728\u8FDB\u884C\uFF0C\u5B8C\u6210\u540E\u624D\u80FD\u64CD\u4F5C\u3002",
2292
- errors: {
2293
- request_failed: "\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u91CD\u8BD5\u3002",
2294
- config_busy: "\u53E6\u4E00\u4E2A\u4FDD\u5B58\u6216\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002",
2295
- login_invalid_response: "\u767B\u5F55\u54CD\u5E94\u65E0\u6548\uFF0C\u8BF7\u91CD\u8BD5\u3002",
2296
- login_failed: "\u767B\u5F55\u5931\u8D25\u3002",
2297
- login_expired: "\u6388\u6743\u6709\u6548\u671F\u5DF2\u8FC7\uFF0C\u8BF7\u91CD\u65B0\u5F00\u59CB\u3002",
2298
- login_cancelled: "\u5DF2\u53D6\u6D88\u767B\u5F55\u3002",
2299
- sync_failed: "\u6A21\u578B\u540C\u6B65\u5931\u8D25\u3002",
2300
- disconnect_failed: "\u65AD\u5F00\u8FDE\u63A5\u5931\u8D25\u3002",
2301
- callback_invalid: "\u8FD9\u770B\u8D77\u6765\u4E0D\u662F\u6709\u6548\u7684\u56DE\u8C03\u5730\u5740\uFF08\u5E94\u5305\u542B code \u4E0E state \u53C2\u6570\uFF09\u3002",
2302
- callback_rejected: "\u56DE\u8C03\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u590D\u5236\u5B8C\u6574\u5730\u5740\u540E\u91CD\u8BD5\u3002",
2303
- reconciliation_failed: "\u5DF2\u751F\u6548\uFF0C\u4F46\u672C\u5730\u8BBE\u7F6E\u8349\u7A3F\u672A\u80FD\u5237\u65B0\u2014\u2014\u5237\u65B0\u9875\u9762\u5373\u53EF\u770B\u5230\u53D8\u66F4\u3002"
2304
- }
2305
- }
2306
- }
2307
- };
2308
-
2309
- // src/plugin.ts
2310
- var manifest = {
2311
- name: "codex",
2312
- version: "1.0.0",
2313
- coreApi: "1",
2314
- description: "Codex subscription managed provider: chatgpt.com backend-api/codex data plane, browser OAuth login (PKCE, loopback 1455/1457 + paste), model sync, usage and admin routes."
2315
- };
2316
- async function activate(ctx) {
2317
- const upstreamHost = {
2318
- ...ctx.host,
2319
- getDirectDispatcher: () => ctx.host.getSubscriptionDispatcher ? ctx.host.getSubscriptionDispatcher() : ctx.host.getDirectDispatcher()
2320
- };
2321
- const service = new CodexAuthService({
2322
- configDir: ctx.host.configDir,
2323
- host: upstreamHost,
2324
- logger: ctx.log
2325
- });
2326
- class ActivatedCodexTransformer extends CodexTransformer {
2327
- constructor() {
2328
- super({ service });
2329
- }
2330
- }
2331
- const runtime = createCodexManagedRuntime({ service, host: upstreamHost, log: ctx.log });
2332
- ctx.registerTransformer(ActivatedCodexTransformer);
2333
- ctx.registerManagedRuntime(runtime);
2334
- ctx.registerAdminRoutes((app) => registerCodexAdminRoutes(app, { getService: () => service }));
2335
- ctx.registerConfigProtector((next, prev) => protectCodexConfig(next, prev));
2336
- ctx.registerUiCard({ cardPath: "card.js" });
2337
- ctx.registerLocales(codexLocales);
2338
- ctx.log.info("codex plugin active");
2339
- }
2340
- var plugin = { manifest, activate };
2341
- var plugin_default = plugin;
2342
- export {
2343
- activate,
2344
- plugin_default as default,
2345
- manifest
2346
- };