claude-codex-proxy 1.0.5-beta.13 → 1.0.5-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +272 -0
- package/bin/cli.js +2 -37
- package/package.json +1 -1
- package/public/css/style.css +9 -210
- package/public/index.html +926 -32
- package/public/js/app.js +744 -115
- package/src/account-manager.js +3 -34
- package/src/account-rotation/rate-limits.js +26 -4
- package/src/account-rotation/strategies/base-strategy.js +0 -4
- package/src/account-rotation/strategies/sticky-strategy.js +0 -7
- package/src/claude-config.js +18 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +13 -12
- package/src/index.js +4 -13
- package/src/middleware/auth.js +11 -46
- package/src/middleware/credentials.js +3 -13
- package/src/model-api.js +0 -60
- package/src/response-streamer.js +5 -5
- package/src/routes/accounts-route.js +2 -106
- package/src/routes/api-routes.js +35 -61
- package/src/routes/chat-route.js +4 -25
- package/src/routes/claude-config-route.js +15 -22
- package/src/routes/logs-route.js +2 -21
- package/src/routes/messages-route.js +13 -39
- package/src/routes/settings-route.js +5 -36
- package/src/server-settings.js +2 -18
- package/src/utils/logger.js +0 -18
- package/public/login.html +0 -32
- package/public/views/accounts-modals.html +0 -215
- package/public/views/accounts.html +0 -202
- package/public/views/client-api-keys-modals.html +0 -55
- package/public/views/client-api-keys.html +0 -69
- package/public/views/dashboard.html +0 -90
- package/public/views/empty.html +0 -0
- package/public/views/logs.html +0 -99
- package/public/views/settings.html +0 -123
- package/src/admin-path.js +0 -33
- package/src/client-key-usage.js +0 -125
- package/src/model-pricing.js +0 -96
- package/src/routes/client-quota-route.js +0 -25
- package/src/utils/proxy-logging.js +0 -5
package/src/account-manager.js
CHANGED
|
@@ -98,25 +98,6 @@ function getActiveAccount() {
|
|
|
98
98
|
return data.accounts.find(a => a.email === data.activeAccount) || null;
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
function isAccountExpired(account, now = Date.now()) {
|
|
102
|
-
if (!account?.accountExpiresAt) return false;
|
|
103
|
-
const expiresAt = Date.parse(account.accountExpiresAt);
|
|
104
|
-
return Number.isFinite(expiresAt) && expiresAt <= now;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function updateAccountExpiration(email, accountExpiresAt) {
|
|
108
|
-
const data = loadAccounts();
|
|
109
|
-
const account = data.accounts.find(a => a.email === email);
|
|
110
|
-
|
|
111
|
-
if (!account) {
|
|
112
|
-
return { success: false, message: `Account not found: ${email}` };
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
account.accountExpiresAt = accountExpiresAt;
|
|
116
|
-
saveAccounts(data);
|
|
117
|
-
return { success: true, message: `Account expiration updated: ${email}` };
|
|
118
|
-
}
|
|
119
|
-
|
|
120
101
|
function updateAccountAuth(account) {
|
|
121
102
|
if (!account) return;
|
|
122
103
|
|
|
@@ -150,15 +131,11 @@ function updateAccountAuth(account) {
|
|
|
150
131
|
function setActiveAccount(email) {
|
|
151
132
|
const data = loadAccounts();
|
|
152
133
|
const account = data.accounts.find(a => a.email === email);
|
|
153
|
-
|
|
134
|
+
|
|
154
135
|
if (!account) {
|
|
155
136
|
return { success: false, message: `Account not found: ${email}` };
|
|
156
137
|
}
|
|
157
|
-
|
|
158
|
-
if (isAccountExpired(account)) {
|
|
159
|
-
return { success: false, message: `Account has expired: ${email}` };
|
|
160
|
-
}
|
|
161
|
-
|
|
138
|
+
|
|
162
139
|
data.activeAccount = email;
|
|
163
140
|
saveAccounts(data);
|
|
164
141
|
|
|
@@ -213,8 +190,6 @@ function listAccounts() {
|
|
|
213
190
|
lastUsed: account.lastUsed,
|
|
214
191
|
isActive: account.email === data.activeAccount,
|
|
215
192
|
tokenExpired: info?.expiresAt ? info.expiresAt < Date.now() : false,
|
|
216
|
-
accountExpiresAt: account.accountExpiresAt || null,
|
|
217
|
-
accountExpired: isAccountExpired(account),
|
|
218
193
|
quota: account.quota || null
|
|
219
194
|
};
|
|
220
195
|
});
|
|
@@ -501,7 +476,7 @@ function importFromCodex() {
|
|
|
501
476
|
|
|
502
477
|
const existingIndex = data.accounts.findIndex(a => a.email === newAccount.email);
|
|
503
478
|
if (existingIndex >= 0) {
|
|
504
|
-
data.accounts[existingIndex] =
|
|
479
|
+
data.accounts[existingIndex] = newAccount;
|
|
505
480
|
} else {
|
|
506
481
|
data.accounts.push(newAccount);
|
|
507
482
|
}
|
|
@@ -532,8 +507,6 @@ function getStatus() {
|
|
|
532
507
|
isActive: a.email === data.activeAccount,
|
|
533
508
|
quota: a.quota || null,
|
|
534
509
|
tokenExpired: info?.expiresAt ? info.expiresAt < Date.now() : false,
|
|
535
|
-
accountExpiresAt: a.accountExpiresAt || null,
|
|
536
|
-
accountExpired: isAccountExpired(a),
|
|
537
510
|
lastUsed: a.lastUsed
|
|
538
511
|
};
|
|
539
512
|
});
|
|
@@ -575,8 +548,6 @@ export {
|
|
|
575
548
|
ensureAccountsPersist,
|
|
576
549
|
updateAccountQuota,
|
|
577
550
|
getAccountQuota,
|
|
578
|
-
updateAccountExpiration,
|
|
579
|
-
isAccountExpired,
|
|
580
551
|
startAutoRefresh,
|
|
581
552
|
stopAutoRefresh,
|
|
582
553
|
isTokenExpiredOrExpiringSoon,
|
|
@@ -603,8 +574,6 @@ export default {
|
|
|
603
574
|
ensureAccountsPersist,
|
|
604
575
|
updateAccountQuota,
|
|
605
576
|
getAccountQuota,
|
|
606
|
-
updateAccountExpiration,
|
|
607
|
-
isAccountExpired,
|
|
608
577
|
startAutoRefresh,
|
|
609
578
|
stopAutoRefresh,
|
|
610
579
|
isTokenExpiredOrExpiringSoon,
|
|
@@ -33,10 +33,6 @@ export function getAvailableAccounts(accounts, modelId) {
|
|
|
33
33
|
return accounts.filter(account => {
|
|
34
34
|
if (account.isInvalid) return false;
|
|
35
35
|
if (account.enabled === false) return false;
|
|
36
|
-
if (account.accountExpiresAt) {
|
|
37
|
-
const expiresAt = Date.parse(account.accountExpiresAt);
|
|
38
|
-
if (Number.isFinite(expiresAt) && expiresAt <= now) return false;
|
|
39
|
-
}
|
|
40
36
|
if (isAccountCoolingDown(account)) return false;
|
|
41
37
|
if (isQuotaLimitReached(account)) return false;
|
|
42
38
|
const rateLimit = account.modelRateLimits?.[modelId];
|
|
@@ -121,6 +117,18 @@ export function clearExpiredLimits(accounts) {
|
|
|
121
117
|
return clearedCount;
|
|
122
118
|
}
|
|
123
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Reset all rate limits for all accounts (optimistic retry)
|
|
122
|
+
* @param {Array} accounts - Array of account objects
|
|
123
|
+
*/
|
|
124
|
+
export function resetAllRateLimits(accounts) {
|
|
125
|
+
if (!accounts || accounts.length === 0) return;
|
|
126
|
+
for (const account of accounts) {
|
|
127
|
+
account.modelRateLimits = {};
|
|
128
|
+
}
|
|
129
|
+
logger.info('Reset all rate limits for all accounts (optimistic retry)');
|
|
130
|
+
}
|
|
131
|
+
|
|
124
132
|
/**
|
|
125
133
|
* Mark an account as rate-limited for a specific model
|
|
126
134
|
* @param {Array} accounts - Array of account objects
|
|
@@ -227,6 +235,20 @@ export function getMinWaitTimeMs(accounts, modelId) {
|
|
|
227
235
|
return minWait === Infinity ? 0 : minWait;
|
|
228
236
|
}
|
|
229
237
|
|
|
238
|
+
/**
|
|
239
|
+
* Get rate limit info for a specific account and model
|
|
240
|
+
* @param {Array} accounts - Array of account objects
|
|
241
|
+
* @param {string} email - Account email
|
|
242
|
+
* @param {string} modelId - Model identifier
|
|
243
|
+
* @returns {Object|null} Rate limit info object or null
|
|
244
|
+
*/
|
|
245
|
+
export function getRateLimitInfo(accounts, email, modelId) {
|
|
246
|
+
const account = accounts?.find(a => a.email === email);
|
|
247
|
+
if (!account) return null;
|
|
248
|
+
|
|
249
|
+
return account.modelRateLimits?.[modelId] || null;
|
|
250
|
+
}
|
|
251
|
+
|
|
230
252
|
/**
|
|
231
253
|
* Check if an account is currently cooling down
|
|
232
254
|
* @param {Object} account - Account object
|
|
@@ -23,10 +23,6 @@ export class BaseStrategy {
|
|
|
23
23
|
if (!account) return false;
|
|
24
24
|
if (account.isInvalid) return false;
|
|
25
25
|
if (account.enabled === false) return false;
|
|
26
|
-
if (account.accountExpiresAt) {
|
|
27
|
-
const expiresAt = Date.parse(account.accountExpiresAt);
|
|
28
|
-
if (Number.isFinite(expiresAt) && expiresAt <= Date.now()) return false;
|
|
29
|
-
}
|
|
30
26
|
if (isAccountCoolingDown(account)) return false;
|
|
31
27
|
if (isQuotaLimitReached(account)) return false;
|
|
32
28
|
|
|
@@ -56,13 +56,6 @@ export class StickyStrategy extends BaseStrategy {
|
|
|
56
56
|
return { shouldWait: false, waitMs: 0 };
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
if (account.accountExpiresAt) {
|
|
60
|
-
const expiresAt = Date.parse(account.accountExpiresAt);
|
|
61
|
-
if (Number.isFinite(expiresAt) && expiresAt <= Date.now()) {
|
|
62
|
-
return { shouldWait: false, waitMs: 0 };
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
59
|
// Check model-specific rate limit
|
|
67
60
|
if (modelId && account.modelRateLimits && account.modelRateLimits[modelId]) {
|
|
68
61
|
const limit = account.modelRateLimits[modelId];
|
package/src/claude-config.js
CHANGED
|
@@ -75,6 +75,23 @@ export async function updateClaudeConfig(updates) {
|
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
export async function setProxyMode(proxyUrl, models = {}) {
|
|
79
|
+
const updates = {
|
|
80
|
+
env: {
|
|
81
|
+
ANTHROPIC_BASE_URL: proxyUrl,
|
|
82
|
+
ANTHROPIC_API_KEY: 'sk-ant-proxy',
|
|
83
|
+
ANTHROPIC_AUTH_TOKEN: undefined, // Explicitly unset to avoid conflict
|
|
84
|
+
ANTHROPIC_DEFAULT_OPUS_MODEL: models.opus || 'claude-opus',
|
|
85
|
+
ANTHROPIC_DEFAULT_SONNET_MODEL: models.sonnet || 'claude-sonnet',
|
|
86
|
+
ANTHROPIC_DEFAULT_HAIKU_MODEL: models.haiku || 'claude-haiku',
|
|
87
|
+
CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
|
|
88
|
+
},
|
|
89
|
+
autoCompactEnabled: true
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
return await updateClaudeConfig(updates);
|
|
93
|
+
}
|
|
94
|
+
|
|
78
95
|
export async function setDirectMode(apiKey) {
|
|
79
96
|
const updates = {
|
|
80
97
|
env: {
|
|
@@ -131,6 +148,7 @@ export default {
|
|
|
131
148
|
readClaudeConfig,
|
|
132
149
|
readClaudeConfigSync,
|
|
133
150
|
updateClaudeConfig,
|
|
151
|
+
setProxyMode,
|
|
134
152
|
setDirectMode,
|
|
135
153
|
setApiEndpoint
|
|
136
154
|
};
|
package/src/deployment.js
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Deployment policy helpers shared by server, routes and auth middleware.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
const VALID_DEPLOYMENT_MODES = new Set(['local', 'public']);
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Returns the validated deployment mode, defaulting to local when unset.
|
|
9
|
-
* @returns {'local'|'public'}
|
|
10
|
-
*/
|
|
11
|
-
export function getDeploymentMode() {
|
|
12
|
-
const mode = process.env.PROXY_DEPLOYMENT_MODE || 'local';
|
|
13
|
-
if (!VALID_DEPLOYMENT_MODES.has(mode)) {
|
|
14
|
-
throw new Error(`Invalid PROXY_DEPLOYMENT_MODE "${mode}". Expected "local" or "public".`);
|
|
15
|
-
}
|
|
16
|
-
return mode;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Indicates whether the proxy is running in public deployment mode.
|
|
21
|
-
* @returns {boolean}
|
|
22
|
-
*/
|
|
23
|
-
export function isPublicDeployment() {
|
|
24
|
-
return getDeploymentMode() === 'public';
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Returns the host address the main HTTP server should bind to.
|
|
29
|
-
* @returns {string}
|
|
30
|
-
*/
|
|
31
|
-
export function getServerHost() {
|
|
32
|
-
if (process.env.HOST) {
|
|
33
|
-
return process.env.HOST;
|
|
34
|
-
}
|
|
35
|
-
return isPublicDeployment() ? '0.0.0.0' : '127.0.0.1';
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Returns a display URL for logs and local helper responses.
|
|
40
|
-
* @param {number|string} port
|
|
41
|
-
* @returns {string}
|
|
42
|
-
*/
|
|
43
|
-
export function getLocalBaseUrl(port) {
|
|
44
|
-
const host = getServerHost();
|
|
45
|
-
const displayHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
|
|
46
|
-
return `http://${displayHost}:${port}`;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export default { getDeploymentMode, isPublicDeployment, getServerHost, getLocalBaseUrl };
|
|
1
|
+
/**
|
|
2
|
+
* Deployment policy helpers shared by server, routes and auth middleware.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const VALID_DEPLOYMENT_MODES = new Set(['local', 'public']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Returns the validated deployment mode, defaulting to local when unset.
|
|
9
|
+
* @returns {'local'|'public'}
|
|
10
|
+
*/
|
|
11
|
+
export function getDeploymentMode() {
|
|
12
|
+
const mode = process.env.PROXY_DEPLOYMENT_MODE || 'local';
|
|
13
|
+
if (!VALID_DEPLOYMENT_MODES.has(mode)) {
|
|
14
|
+
throw new Error(`Invalid PROXY_DEPLOYMENT_MODE "${mode}". Expected "local" or "public".`);
|
|
15
|
+
}
|
|
16
|
+
return mode;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Indicates whether the proxy is running in public deployment mode.
|
|
21
|
+
* @returns {boolean}
|
|
22
|
+
*/
|
|
23
|
+
export function isPublicDeployment() {
|
|
24
|
+
return getDeploymentMode() === 'public';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Returns the host address the main HTTP server should bind to.
|
|
29
|
+
* @returns {string}
|
|
30
|
+
*/
|
|
31
|
+
export function getServerHost() {
|
|
32
|
+
if (process.env.HOST) {
|
|
33
|
+
return process.env.HOST;
|
|
34
|
+
}
|
|
35
|
+
return isPublicDeployment() ? '0.0.0.0' : '127.0.0.1';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns a display URL for logs and local helper responses.
|
|
40
|
+
* @param {number|string} port
|
|
41
|
+
* @returns {string}
|
|
42
|
+
*/
|
|
43
|
+
export function getLocalBaseUrl(port) {
|
|
44
|
+
const host = getServerHost();
|
|
45
|
+
const displayHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
|
|
46
|
+
return `http://${displayHost}:${port}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export default { getDeploymentMode, isPublicDeployment, getServerHost, getLocalBaseUrl };
|
package/src/direct-api.js
CHANGED
|
@@ -7,14 +7,17 @@ import os from 'os';
|
|
|
7
7
|
import { createRequire } from 'module';
|
|
8
8
|
import { convertAnthropicToResponsesAPI, convertOutputToAnthropic, generateMessageId } from './format-converter.js';
|
|
9
9
|
import { streamResponsesAPI, parseResponsesAPIResponse, createResponsesAPIError } from './response-streamer.js';
|
|
10
|
+
import { getServerSettings } from './server-settings.js';
|
|
10
11
|
import { logger } from './utils/logger.js';
|
|
11
|
-
import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
|
|
12
12
|
|
|
13
13
|
const require = createRequire(import.meta.url);
|
|
14
14
|
const packageJson = require('../package.json');
|
|
15
15
|
const API_URL = 'https://chatgpt.com/backend-api/codex/responses';
|
|
16
16
|
const APP_VERSION = packageJson.version;
|
|
17
|
-
|
|
17
|
+
|
|
18
|
+
function shouldLogRawProxyPayloads() {
|
|
19
|
+
return getServerSettings().logRawProxyPayloads === true;
|
|
20
|
+
}
|
|
18
21
|
|
|
19
22
|
function createAnthropicUsage(upstreamUsage = {}) {
|
|
20
23
|
const usage = {
|
|
@@ -27,10 +30,6 @@ function createAnthropicUsage(upstreamUsage = {}) {
|
|
|
27
30
|
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
28
31
|
enumerable: false
|
|
29
32
|
});
|
|
30
|
-
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
31
|
-
value: upstreamUsage.input_tokens_details?.cache_write_tokens || 0,
|
|
32
|
-
enumerable: false
|
|
33
|
-
});
|
|
34
33
|
return usage;
|
|
35
34
|
}
|
|
36
35
|
|
|
@@ -129,14 +128,15 @@ async function createResponsesAPIStreamResponse(anthropicRequest, accessToken, a
|
|
|
129
128
|
const response = await fetch(API_URL, {
|
|
130
129
|
method: 'POST',
|
|
131
130
|
headers: buildOpencodeHeaders(accessToken, accountId, context),
|
|
132
|
-
body: JSON.stringify(request)
|
|
133
|
-
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
131
|
+
body: JSON.stringify(request)
|
|
134
132
|
});
|
|
135
133
|
|
|
136
134
|
if (response.ok) return response;
|
|
137
135
|
|
|
138
136
|
const errorText = await response.text();
|
|
139
|
-
|
|
137
|
+
if (shouldLogRawProxyPayloads()) {
|
|
138
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
139
|
+
}
|
|
140
140
|
|
|
141
141
|
if (response.status === 401) {
|
|
142
142
|
if (accountRotator && currentEmail) {
|
|
@@ -197,13 +197,14 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
197
197
|
const response = await fetch(API_URL, {
|
|
198
198
|
method: 'POST',
|
|
199
199
|
headers: buildOpencodeHeaders(accessToken, accountId, context),
|
|
200
|
-
body: JSON.stringify(request)
|
|
201
|
-
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
200
|
+
body: JSON.stringify(request)
|
|
202
201
|
});
|
|
203
202
|
|
|
204
203
|
if (!response.ok) {
|
|
205
204
|
const errorText = await response.text();
|
|
206
|
-
|
|
205
|
+
if (shouldLogRawProxyPayloads()) {
|
|
206
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
207
|
+
}
|
|
207
208
|
|
|
208
209
|
if (response.status === 401) {
|
|
209
210
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
package/src/index.js
CHANGED
|
@@ -5,7 +5,6 @@
|
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
7
|
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
8
|
-
import { getAdminPath } from './admin-path.js';
|
|
9
8
|
import { startServer } from './server.js';
|
|
10
9
|
import { logger } from './utils/logger.js';
|
|
11
10
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -22,14 +21,6 @@ try {
|
|
|
22
21
|
}
|
|
23
22
|
const HOST = getServerHost();
|
|
24
23
|
const BASE_URL = getLocalBaseUrl(PORT);
|
|
25
|
-
let ADMIN_PATH;
|
|
26
|
-
try {
|
|
27
|
-
ADMIN_PATH = getAdminPath();
|
|
28
|
-
} catch (error) {
|
|
29
|
-
console.error(error.message);
|
|
30
|
-
process.exit(1);
|
|
31
|
-
}
|
|
32
|
-
const ADMIN_URL = `${BASE_URL}${ADMIN_PATH}`;
|
|
33
24
|
const BANNER_WIDTH = 62;
|
|
34
25
|
|
|
35
26
|
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
@@ -54,10 +45,10 @@ console.log(`
|
|
|
54
45
|
╠══════════════════════════════════════════════════════════════╣
|
|
55
46
|
${bannerLine('Host:', HOST)}
|
|
56
47
|
${bannerLine('Server:', BASE_URL)}
|
|
57
|
-
${bannerLine('WebUI:',
|
|
48
|
+
${bannerLine('WebUI:', BASE_URL)}
|
|
58
49
|
${bannerLine('Health:', `${BASE_URL}/health`)}
|
|
59
|
-
${bannerLine('Accounts:', `${
|
|
60
|
-
${bannerLine('Logs:', `${
|
|
50
|
+
${bannerLine('Accounts:', `${BASE_URL}/accounts`)}
|
|
51
|
+
${bannerLine('Logs:', `${BASE_URL}/api/logs/stream`)}
|
|
61
52
|
╠══════════════════════════════════════════════════════════════╣
|
|
62
53
|
║ Features: ║
|
|
63
54
|
║ ✓ Native tool calling support ║
|
|
@@ -75,7 +66,7 @@ const status = getStatus();
|
|
|
75
66
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
76
67
|
|
|
77
68
|
if (status.total === 0) {
|
|
78
|
-
logger.warn(`No accounts configured. Open ${
|
|
69
|
+
logger.warn(`No accounts configured. Open ${BASE_URL} to add one.`);
|
|
79
70
|
}
|
|
80
71
|
|
|
81
72
|
// Expose config path in logs for convenience
|
package/src/middleware/auth.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
-
import { getServerSettings
|
|
4
|
-
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
3
|
+
import { getServerSettings } from '../server-settings.js';
|
|
5
4
|
|
|
6
5
|
function timingSafeEqualString(a, b) {
|
|
7
6
|
const left = Buffer.from(String(a));
|
|
@@ -45,8 +44,10 @@ function sendUnauthorized(req, res) {
|
|
|
45
44
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
46
45
|
}
|
|
47
46
|
|
|
48
|
-
function
|
|
49
|
-
return expectedKey
|
|
47
|
+
function matchesAnyKey(requestKey, expectedKeys) {
|
|
48
|
+
return expectedKeys.some((expectedKey) => (
|
|
49
|
+
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
50
|
+
));
|
|
50
51
|
}
|
|
51
52
|
|
|
52
53
|
function requireKeys(getExpectedKeys) {
|
|
@@ -57,7 +58,7 @@ function requireKeys(getExpectedKeys) {
|
|
|
57
58
|
|
|
58
59
|
const expectedKeys = getExpectedKeys();
|
|
59
60
|
const requestKey = getRequestApiKey(req);
|
|
60
|
-
if (!
|
|
61
|
+
if (!matchesAnyKey(requestKey, expectedKeys)) {
|
|
61
62
|
return sendUnauthorized(req, res);
|
|
62
63
|
}
|
|
63
64
|
|
|
@@ -65,50 +66,14 @@ function requireKeys(getExpectedKeys) {
|
|
|
65
66
|
};
|
|
66
67
|
}
|
|
67
68
|
|
|
68
|
-
function sendQuotaExceeded(res, quota) {
|
|
69
|
-
return res.status(429).json({
|
|
70
|
-
type: 'error',
|
|
71
|
-
error: {
|
|
72
|
-
type: 'rate_limit_error',
|
|
73
|
-
message: `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function findClientKey(requestKey) {
|
|
79
|
-
return getServerSettings().clientApiKeys.find(({ key }) => matchesKey(requestKey, key));
|
|
80
|
-
}
|
|
81
|
-
|
|
82
69
|
const getAdminKeys = () => [process.env.PROXY_ADMIN_KEY].filter(Boolean);
|
|
70
|
+
const getClientKeys = () => [
|
|
71
|
+
...getServerSettings().clientApiKeys.map(({ key }) => key),
|
|
72
|
+
process.env.PROXY_CLIENT_KEY
|
|
73
|
+
].filter(Boolean);
|
|
83
74
|
|
|
84
75
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
85
|
-
|
|
86
|
-
export function requireClientAuth(req, res, next) {
|
|
87
|
-
const requestKey = getRequestApiKey(req);
|
|
88
|
-
const clientKey = findClientKey(requestKey);
|
|
89
|
-
if (isPublicDeployment() && !clientKey) {
|
|
90
|
-
return sendUnauthorized(req, res);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
if (!clientKey) {
|
|
94
|
-
return next();
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const quota = getClientKeyQuota(
|
|
98
|
-
clientKey.id,
|
|
99
|
-
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
100
|
-
);
|
|
101
|
-
const isModelRequest = req.method === 'POST' && (
|
|
102
|
-
req.path === '/v1/messages' || req.path === '/v1/chat/completions'
|
|
103
|
-
);
|
|
104
|
-
if (isModelRequest && quota.remainingMicrousd <= 0) {
|
|
105
|
-
return sendQuotaExceeded(res, quota);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
req.clientApiKey = { id: clientKey.id, name: clientKey.name };
|
|
109
|
-
req.clientApiKeyQuota = quota;
|
|
110
|
-
return next();
|
|
111
|
-
}
|
|
76
|
+
export const requireClientAuth = requireKeys(getClientKeys);
|
|
112
77
|
|
|
113
78
|
export { isPublicDeployment };
|
|
114
79
|
|
|
@@ -8,7 +8,6 @@ import {
|
|
|
8
8
|
getActiveAccount,
|
|
9
9
|
refreshAccountToken,
|
|
10
10
|
isTokenExpiredOrExpiringSoon,
|
|
11
|
-
isAccountExpired,
|
|
12
11
|
loadAccounts
|
|
13
12
|
} from '../account-manager.js';
|
|
14
13
|
import { logger } from '../utils/logger.js';
|
|
@@ -27,11 +26,6 @@ export async function getCredentialsOrError() {
|
|
|
27
26
|
return null;
|
|
28
27
|
}
|
|
29
28
|
|
|
30
|
-
if (isAccountExpired(account)) {
|
|
31
|
-
logger.info(`Account ${account.email} has expired`);
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
29
|
if (!account.accessToken || !account.accountId) {
|
|
36
30
|
logger.info(`Account ${account.email} missing token or accountId`);
|
|
37
31
|
return null;
|
|
@@ -47,8 +41,8 @@ export async function getCredentialsOrError() {
|
|
|
47
41
|
}
|
|
48
42
|
|
|
49
43
|
const refreshedAccount = getActiveAccount();
|
|
50
|
-
if (!refreshedAccount
|
|
51
|
-
logger.error('Failed to get refreshed
|
|
44
|
+
if (!refreshedAccount) {
|
|
45
|
+
logger.error('Failed to get refreshed account');
|
|
52
46
|
return null;
|
|
53
47
|
}
|
|
54
48
|
|
|
@@ -80,10 +74,6 @@ export async function getCredentialsForAccount(email) {
|
|
|
80
74
|
return null;
|
|
81
75
|
}
|
|
82
76
|
|
|
83
|
-
if (isAccountExpired(account)) {
|
|
84
|
-
return null;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
77
|
if (!account.accessToken || !account.accountId) {
|
|
88
78
|
return null;
|
|
89
79
|
}
|
|
@@ -95,7 +85,7 @@ export async function getCredentialsForAccount(email) {
|
|
|
95
85
|
}
|
|
96
86
|
const refreshedData = loadAccounts();
|
|
97
87
|
const refreshedAccount = refreshedData.accounts.find(a => a.email === email);
|
|
98
|
-
if (!refreshedAccount
|
|
88
|
+
if (!refreshedAccount) return null;
|
|
99
89
|
|
|
100
90
|
return {
|
|
101
91
|
accessToken: refreshedAccount.accessToken,
|
package/src/model-api.js
CHANGED
|
@@ -100,64 +100,6 @@ export async function fetchUsage(accessToken, accountId) {
|
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
-
/**
|
|
104
|
-
* Lists the account's available rate-limit reset credits.
|
|
105
|
-
* @param {string} accessToken
|
|
106
|
-
* @param {string} accountId
|
|
107
|
-
* @returns {Promise<object>}
|
|
108
|
-
*/
|
|
109
|
-
export async function fetchRateLimitResetCredits(accessToken, accountId) {
|
|
110
|
-
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits`, {
|
|
111
|
-
method: 'GET',
|
|
112
|
-
headers: {
|
|
113
|
-
'Authorization': `Bearer ${accessToken}`,
|
|
114
|
-
'ChatGPT-Account-ID': accountId,
|
|
115
|
-
'Accept': 'application/json',
|
|
116
|
-
'User-Agent': 'codex-cli'
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
if (!response.ok) {
|
|
121
|
-
const errorText = await response.text();
|
|
122
|
-
throw new Error(`Failed to fetch rate-limit reset credits: ${response.status} - ${errorText}`);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
return await response.json();
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Redeems a rate-limit reset credit for an account.
|
|
130
|
-
* @param {string} accessToken
|
|
131
|
-
* @param {string} accountId
|
|
132
|
-
* @param {string} redeemRequestId Stable idempotency key for retries of this redemption.
|
|
133
|
-
* @param {string|null} creditId Specific credit to redeem, or null for server selection.
|
|
134
|
-
* @returns {Promise<object>}
|
|
135
|
-
*/
|
|
136
|
-
export async function consumeRateLimitResetCredit(accessToken, accountId, redeemRequestId, creditId = null) {
|
|
137
|
-
const body = { redeem_request_id: redeemRequestId };
|
|
138
|
-
if (creditId) body.credit_id = creditId;
|
|
139
|
-
|
|
140
|
-
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits/consume`, {
|
|
141
|
-
method: 'POST',
|
|
142
|
-
headers: {
|
|
143
|
-
'Authorization': `Bearer ${accessToken}`,
|
|
144
|
-
'ChatGPT-Account-ID': accountId,
|
|
145
|
-
'Content-Type': 'application/json',
|
|
146
|
-
'Accept': 'application/json',
|
|
147
|
-
'User-Agent': 'codex-cli'
|
|
148
|
-
},
|
|
149
|
-
body: JSON.stringify(body)
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
if (!response.ok) {
|
|
153
|
-
const errorText = await response.text();
|
|
154
|
-
throw new Error(`Failed to redeem rate-limit reset credit: ${response.status} - ${errorText}`);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const text = await response.text();
|
|
158
|
-
return text ? JSON.parse(text) : {};
|
|
159
|
-
}
|
|
160
|
-
|
|
161
103
|
export async function fetchAccountCheck(accessToken, accountId) {
|
|
162
104
|
const url = `${CHATGPT_API_BASE}/wham/accounts/check`;
|
|
163
105
|
|
|
@@ -240,8 +182,6 @@ export function clearModelCache() {
|
|
|
240
182
|
export default {
|
|
241
183
|
fetchModels,
|
|
242
184
|
fetchUsage,
|
|
243
|
-
fetchRateLimitResetCredits,
|
|
244
|
-
consumeRateLimitResetCredit,
|
|
245
185
|
fetchAccountCheck,
|
|
246
186
|
getAccountQuota,
|
|
247
187
|
getModelsAndQuota,
|
package/src/response-streamer.js
CHANGED
|
@@ -5,11 +5,15 @@
|
|
|
5
5
|
|
|
6
6
|
import { generateMessageId, sanitizeAnthropicToolInputJson, toAnthropicToolId } from './format-converter.js';
|
|
7
7
|
import { cacheSignature, cacheThinkingSignature, SIGNATURE_CONSTANTS } from './signature-cache.js';
|
|
8
|
+
import { getServerSettings } from './server-settings.js';
|
|
8
9
|
import { logger } from './utils/logger.js';
|
|
9
|
-
import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
|
|
10
10
|
|
|
11
11
|
const { MIN_SIGNATURE_LENGTH } = SIGNATURE_CONSTANTS;
|
|
12
12
|
|
|
13
|
+
function shouldLogRawProxyPayloads() {
|
|
14
|
+
return getServerSettings().logRawProxyPayloads === true;
|
|
15
|
+
}
|
|
16
|
+
|
|
13
17
|
export function createResponsesAPIError(message, status = 502) {
|
|
14
18
|
const error = new Error(message);
|
|
15
19
|
error.status = status;
|
|
@@ -113,10 +117,6 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
113
117
|
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
114
118
|
enumerable: false
|
|
115
119
|
});
|
|
116
|
-
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
117
|
-
value: event.response.usage.input_tokens_details?.cache_write_tokens || 0,
|
|
118
|
-
enumerable: false
|
|
119
|
-
});
|
|
120
120
|
}
|
|
121
121
|
|
|
122
122
|
// Handle output item added
|