claude-codex-proxy 1.0.5-beta.13 → 1.0.5-beta.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/README.md +272 -0
- package/bin/cli.js +2 -37
- package/package.json +1 -1
- package/public/css/style.css +0 -127
- package/public/index.html +60 -60
- package/public/js/app.js +116 -133
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +0 -56
- package/public/views/accounts.html +10 -29
- package/public/views/client-api-keys-modals.html +1 -6
- package/public/views/client-api-keys.html +31 -54
- package/public/views/logs.html +3 -10
- package/src/account-manager.js +3 -34
- package/src/account-rotation/rate-limits.js +0 -4
- package/src/account-rotation/strategies/base-strategy.js +0 -4
- package/src/account-rotation/strategies/sticky-strategy.js +0 -7
- 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 +42 -59
- package/src/routes/chat-route.js +4 -25
- package/src/routes/claude-config-route.js +10 -19
- 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/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/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
|
|
@@ -5,8 +5,6 @@
|
|
|
5
5
|
* GET /accounts/status
|
|
6
6
|
* GET /accounts/quota
|
|
7
7
|
* GET /accounts/quota/all
|
|
8
|
-
* GET /accounts/rate-limit-reset-credits
|
|
9
|
-
* POST /accounts/rate-limit-reset-credits/consume
|
|
10
8
|
* POST /accounts/add
|
|
11
9
|
* POST /accounts/add/manual
|
|
12
10
|
* POST /accounts/switch
|
|
@@ -14,7 +12,6 @@
|
|
|
14
12
|
* POST /accounts/refresh
|
|
15
13
|
* POST /accounts/refresh/all
|
|
16
14
|
* POST /accounts/:email/refresh
|
|
17
|
-
* PUT /accounts/:email/expiration
|
|
18
15
|
* POST /accounts/oauth/cleanup
|
|
19
16
|
* DELETE /accounts/:email
|
|
20
17
|
*/
|
|
@@ -33,8 +30,7 @@ import {
|
|
|
33
30
|
saveAccounts,
|
|
34
31
|
updateAccountAuth,
|
|
35
32
|
updateAccountQuota,
|
|
36
|
-
getAccountQuota
|
|
37
|
-
updateAccountExpiration
|
|
33
|
+
getAccountQuota
|
|
38
34
|
} from '../account-manager.js';
|
|
39
35
|
|
|
40
36
|
import {
|
|
@@ -49,13 +45,9 @@ import {
|
|
|
49
45
|
} from '../oauth.js';
|
|
50
46
|
|
|
51
47
|
import {
|
|
52
|
-
getAccountQuota as fetchAccountQuota
|
|
53
|
-
fetchRateLimitResetCredits,
|
|
54
|
-
consumeRateLimitResetCredit
|
|
48
|
+
getAccountQuota as fetchAccountQuota
|
|
55
49
|
} from '../model-api.js';
|
|
56
50
|
|
|
57
|
-
import { randomUUID } from 'crypto';
|
|
58
|
-
|
|
59
51
|
import { logger } from '../utils/logger.js';
|
|
60
52
|
|
|
61
53
|
// Tracks active OAuth callback servers keyed by port
|
|
@@ -180,30 +172,6 @@ export async function handleRefreshAllAccounts(req, res) {
|
|
|
180
172
|
res.json(result);
|
|
181
173
|
}
|
|
182
174
|
|
|
183
|
-
export function handleUpdateAccountExpiration(req, res) {
|
|
184
|
-
const email = decodeURIComponent(req.params.email);
|
|
185
|
-
const { accountExpiresAt } = req.body || {};
|
|
186
|
-
|
|
187
|
-
if (accountExpiresAt !== null && accountExpiresAt !== undefined) {
|
|
188
|
-
if (typeof accountExpiresAt !== 'string' || !accountExpiresAt.trim()) {
|
|
189
|
-
return res.status(400).json({ success: false, message: 'accountExpiresAt must be an ISO 8601 date or null' });
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
const normalizedAccountExpiresAt = accountExpiresAt.trim();
|
|
193
|
-
const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
194
|
-
const expiresAt = new Date(normalizedAccountExpiresAt);
|
|
195
|
-
if (!isoDatePattern.test(normalizedAccountExpiresAt) || Number.isNaN(expiresAt.getTime())) {
|
|
196
|
-
return res.status(400).json({ success: false, message: 'accountExpiresAt must be a valid ISO 8601 date' });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
const result = updateAccountExpiration(email, expiresAt.toISOString());
|
|
200
|
-
return res.status(result.success ? 200 : 404).json(result);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const result = updateAccountExpiration(email, null);
|
|
204
|
-
return res.status(result.success ? 200 : 404).json(result);
|
|
205
|
-
}
|
|
206
|
-
|
|
207
175
|
export async function handleRefreshActiveAccount(req, res) {
|
|
208
176
|
const result = await refreshActiveAccount();
|
|
209
177
|
res.json(result);
|
|
@@ -264,75 +232,6 @@ export async function handleGetQuota(req, res) {
|
|
|
264
232
|
}
|
|
265
233
|
}
|
|
266
234
|
|
|
267
|
-
/**
|
|
268
|
-
* Lists an account's rate-limit reset credits.
|
|
269
|
-
*/
|
|
270
|
-
export async function handleGetRateLimitResetCredits(req, res) {
|
|
271
|
-
const { email } = req.query;
|
|
272
|
-
const account = email
|
|
273
|
-
? loadAccounts().accounts.find(a => a.email === email)
|
|
274
|
-
: getActiveAccount();
|
|
275
|
-
|
|
276
|
-
if (!account) {
|
|
277
|
-
return res.status(404).json({
|
|
278
|
-
success: false,
|
|
279
|
-
error: email ? `Account not found: ${email}` : 'No active account'
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
try {
|
|
284
|
-
const credits = await fetchRateLimitResetCredits(account.accessToken, account.accountId);
|
|
285
|
-
res.json({ success: true, email: account.email, credits });
|
|
286
|
-
} catch (error) {
|
|
287
|
-
logger.error(`Failed to fetch rate-limit reset credits for ${account.email}: ${error.message}`);
|
|
288
|
-
res.status(502).json({ success: false, error: error.message });
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Redeems one available rate-limit reset credit for an account.
|
|
294
|
-
*/
|
|
295
|
-
export async function handleConsumeRateLimitResetCredit(req, res) {
|
|
296
|
-
const { email, creditId, redeemRequestId } = req.body || {};
|
|
297
|
-
const account = email
|
|
298
|
-
? loadAccounts().accounts.find(a => a.email === email)
|
|
299
|
-
: getActiveAccount();
|
|
300
|
-
|
|
301
|
-
if (!account) {
|
|
302
|
-
return res.status(404).json({
|
|
303
|
-
success: false,
|
|
304
|
-
error: email ? `Account not found: ${email}` : 'No active account'
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
if (redeemRequestId !== undefined && (
|
|
309
|
-
typeof redeemRequestId !== 'string' ||
|
|
310
|
-
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(redeemRequestId.trim())
|
|
311
|
-
)) {
|
|
312
|
-
return res.status(400).json({ success: false, error: 'redeemRequestId must be a UUID string' });
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
if (creditId !== undefined && (typeof creditId !== 'string' || !creditId.trim())) {
|
|
316
|
-
return res.status(400).json({ success: false, error: 'creditId must be a non-empty string when provided' });
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
const idempotencyKey = redeemRequestId?.trim() || randomUUID();
|
|
320
|
-
|
|
321
|
-
try {
|
|
322
|
-
const result = await consumeRateLimitResetCredit(
|
|
323
|
-
account.accessToken,
|
|
324
|
-
account.accountId,
|
|
325
|
-
idempotencyKey,
|
|
326
|
-
creditId?.trim() || null
|
|
327
|
-
);
|
|
328
|
-
logger.info(`Redeemed rate-limit reset credit for: ${account.email}`);
|
|
329
|
-
res.json({ success: true, email: account.email, redeemRequestId: idempotencyKey, result });
|
|
330
|
-
} catch (error) {
|
|
331
|
-
logger.error(`Failed to redeem rate-limit reset credit for ${account.email}: ${error.message}`);
|
|
332
|
-
res.status(502).json({ success: false, error: error.message, redeemRequestId: idempotencyKey });
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
|
|
336
235
|
export async function handleGetAllQuotas(req, res) {
|
|
337
236
|
const { accounts: accountList } = listAccounts();
|
|
338
237
|
const results = [];
|
|
@@ -405,12 +304,9 @@ export default {
|
|
|
405
304
|
handleSwitchAccount,
|
|
406
305
|
handleRefreshAccount,
|
|
407
306
|
handleRefreshAllAccounts,
|
|
408
|
-
handleUpdateAccountExpiration,
|
|
409
307
|
handleRefreshActiveAccount,
|
|
410
308
|
handleRemoveAccount,
|
|
411
309
|
handleImportAccount,
|
|
412
310
|
handleGetQuota,
|
|
413
|
-
handleGetRateLimitResetCredits,
|
|
414
|
-
handleConsumeRateLimitResetCredit,
|
|
415
311
|
handleGetAllQuotas
|
|
416
312
|
};
|
package/src/routes/api-routes.js
CHANGED
|
@@ -7,18 +7,15 @@
|
|
|
7
7
|
import express from 'express';
|
|
8
8
|
import { createRequire } from 'module';
|
|
9
9
|
import { join, dirname } from 'path';
|
|
10
|
-
import { readFileSync } from 'fs';
|
|
11
10
|
import { fileURLToPath } from 'url';
|
|
12
11
|
|
|
13
12
|
import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
|
|
14
13
|
import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
|
|
15
|
-
import { getAdminPath } from '../admin-path.js';
|
|
16
14
|
|
|
17
15
|
// Route handlers
|
|
18
16
|
import { handleMessages } from './messages-route.js';
|
|
19
17
|
import { handleChatCompletion, handleCountTokens } from './chat-route.js';
|
|
20
18
|
import { handleListModels, handleAccountModels, handleAccountUsage } from './models-route.js';
|
|
21
|
-
import { handleGetClientQuota } from './client-quota-route.js';
|
|
22
19
|
import {
|
|
23
20
|
handleGetAccountStrategy,
|
|
24
21
|
handleSetAccountStrategy,
|
|
@@ -42,13 +39,10 @@ import {
|
|
|
42
39
|
handleSwitchAccount,
|
|
43
40
|
handleRefreshAccount,
|
|
44
41
|
handleRefreshAllAccounts,
|
|
45
|
-
handleUpdateAccountExpiration,
|
|
46
42
|
handleRefreshActiveAccount,
|
|
47
43
|
handleRemoveAccount,
|
|
48
44
|
handleImportAccount,
|
|
49
45
|
handleGetQuota,
|
|
50
|
-
handleGetRateLimitResetCredits,
|
|
51
|
-
handleConsumeRateLimitResetCredit,
|
|
52
46
|
handleGetAllQuotas
|
|
53
47
|
} from './accounts-route.js';
|
|
54
48
|
|
|
@@ -57,24 +51,17 @@ const require = createRequire(import.meta.url);
|
|
|
57
51
|
const packageJson = require('../../package.json');
|
|
58
52
|
|
|
59
53
|
export function registerApiRoutes(app, { port }) {
|
|
60
|
-
const adminPath = getAdminPath();
|
|
61
|
-
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
62
|
-
const adminRouter = express.Router();
|
|
63
|
-
const sendAdminHtml = (fileName) => {
|
|
64
|
-
const html = readFileSync(join(publicDirectory, fileName), 'utf8')
|
|
65
|
-
.replace(/(href|src)="\//g, `$1="${adminPath}/`)
|
|
66
|
-
.replace('</head>', `<script>window.__PROXY_ADMIN_PATH__=${JSON.stringify(adminPath)};</script></head>`);
|
|
67
|
-
return (req, res) => res.type('html').send(html);
|
|
68
|
-
};
|
|
69
|
-
|
|
70
54
|
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
adminRouter.get(['/', '/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], sendAdminHtml('index.html'));
|
|
55
|
+
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
56
|
+
app.use(express.static(publicDirectory));
|
|
74
57
|
|
|
75
|
-
|
|
58
|
+
app.get(['/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], (req, res) => {
|
|
59
|
+
res.sendFile(join(publicDirectory, 'index.html'));
|
|
60
|
+
});
|
|
76
61
|
|
|
77
|
-
app.
|
|
62
|
+
app.get('/login', (req, res) => {
|
|
63
|
+
res.sendFile(join(publicDirectory, 'login.html'));
|
|
64
|
+
});
|
|
78
65
|
|
|
79
66
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
80
67
|
app.get('/health', (req, res) => {
|
|
@@ -101,55 +88,51 @@ export function registerApiRoutes(app, { port }) {
|
|
|
101
88
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
102
89
|
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
103
90
|
|
|
104
|
-
// ─── Models
|
|
91
|
+
// ─── Models ────────────────────────────────────────────────────────────────
|
|
105
92
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
106
|
-
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
107
93
|
|
|
108
|
-
|
|
94
|
+
app.use(requireAdminAuth);
|
|
109
95
|
|
|
110
|
-
|
|
111
|
-
|
|
96
|
+
app.get('/accounts/models', handleAccountModels);
|
|
97
|
+
app.get('/accounts/usage', handleAccountUsage);
|
|
112
98
|
|
|
113
99
|
// ─── Settings ──────────────────────────────────────────────────────────────
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
100
|
+
app.get('/settings/account-strategy', handleGetAccountStrategy);
|
|
101
|
+
app.post('/settings/account-strategy', handleSetAccountStrategy);
|
|
102
|
+
app.get('/settings/model-map', handleGetModelMap);
|
|
103
|
+
app.post('/settings/model-map', handleSetModelMap);
|
|
104
|
+
app.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
105
|
+
app.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
106
|
+
app.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
107
|
+
app.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
108
|
+
app.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
109
|
+
app.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
124
110
|
|
|
125
111
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
adminRouter.put('/accounts/:email/expiration', handleUpdateAccountExpiration);
|
|
142
|
-
|
|
143
|
-
adminRouter.delete('/accounts/:email', handleRemoveAccount);
|
|
112
|
+
app.get('/accounts', handleListAccounts);
|
|
113
|
+
app.get('/accounts/status', handleAccountStatus);
|
|
114
|
+
app.get('/accounts/quota', handleGetQuota);
|
|
115
|
+
app.get('/accounts/quota/all', handleGetAllQuotas);
|
|
116
|
+
|
|
117
|
+
app.post('/accounts/add', handleAddAccount);
|
|
118
|
+
app.post('/accounts/add/manual', handleAddAccountManual);
|
|
119
|
+
app.post('/accounts/switch', handleSwitchAccount);
|
|
120
|
+
app.post('/accounts/import', handleImportAccount);
|
|
121
|
+
app.post('/accounts/refresh', handleRefreshActiveAccount);
|
|
122
|
+
app.post('/accounts/refresh/all', handleRefreshAllAccounts);
|
|
123
|
+
app.post('/accounts/oauth/cleanup', handleOAuthCleanup);
|
|
124
|
+
app.post('/accounts/:email/refresh', handleRefreshAccount);
|
|
125
|
+
|
|
126
|
+
app.delete('/accounts/:email', handleRemoveAccount);
|
|
144
127
|
|
|
145
128
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
129
|
+
app.get('/claude/config', handleGetClaudeConfig);
|
|
130
|
+
app.post('/claude/config/direct', handleSetDirectMode);
|
|
131
|
+
app.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
149
132
|
|
|
150
133
|
// ─── Logs ──────────────────────────────────────────────────────────────────
|
|
151
|
-
|
|
152
|
-
|
|
134
|
+
app.get('/api/logs', handleGetLogs);
|
|
135
|
+
app.get('/api/logs/stream', handleStreamLogs);
|
|
153
136
|
}
|
|
154
137
|
|
|
155
138
|
export default { registerApiRoutes };
|
package/src/routes/chat-route.js
CHANGED
|
@@ -9,9 +9,7 @@ import { resolveModelRouting } from '../model-mapper.js';
|
|
|
9
9
|
import { getCredentialsOrError, sendAuthError } from '../middleware/credentials.js';
|
|
10
10
|
import { handleStreamError } from '../middleware/sse.js';
|
|
11
11
|
import { logger } from '../utils/logger.js';
|
|
12
|
-
import {
|
|
13
|
-
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
14
|
-
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
12
|
+
import { getServerSettings } from '../server-settings.js';
|
|
15
13
|
|
|
16
14
|
/**
|
|
17
15
|
* POST /v1/chat/completions
|
|
@@ -30,10 +28,11 @@ function getRequestContext(req) {
|
|
|
30
28
|
export async function handleChatCompletion(req, res) {
|
|
31
29
|
const startTime = Date.now();
|
|
32
30
|
const body = req.body;
|
|
33
|
-
|
|
31
|
+
const settings = getServerSettings();
|
|
32
|
+
if (settings.logRawProxyPayloads === true) {
|
|
34
33
|
logger.info('[Client Request]', body);
|
|
35
34
|
}
|
|
36
|
-
const requestedModel = body.model;
|
|
35
|
+
const requestedModel = body.model || 'gpt-5.2';
|
|
37
36
|
|
|
38
37
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
39
38
|
|
|
@@ -54,7 +53,6 @@ export async function handleChatCompletion(req, res) {
|
|
|
54
53
|
|
|
55
54
|
try {
|
|
56
55
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, getRequestContext(req));
|
|
57
|
-
recordRequestUsage(req.clientApiKey?.id, upstreamModel, response.usage);
|
|
58
56
|
|
|
59
57
|
const duration = Date.now() - startTime;
|
|
60
58
|
logger.response(200, { model: upstreamModel, ...getTokenDetails(response.usage), duration });
|
|
@@ -111,25 +109,6 @@ export function handleCountTokens(req, res) {
|
|
|
111
109
|
|
|
112
110
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
113
111
|
|
|
114
|
-
function recordRequestUsage(clientKeyId, model, usage) {
|
|
115
|
-
if (!clientKeyId) return;
|
|
116
|
-
|
|
117
|
-
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
118
|
-
...usage,
|
|
119
|
-
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
120
|
-
input_tokens_details: {
|
|
121
|
-
...(usage?.input_tokens_details || {}),
|
|
122
|
-
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
123
|
-
}
|
|
124
|
-
});
|
|
125
|
-
if (costMicrousd === null) {
|
|
126
|
-
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
127
|
-
return;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
112
|
/**
|
|
134
113
|
* Converts an OpenAI Chat Completions request body into an Anthropic-style request.
|
|
135
114
|
* @param {object} body
|
|
@@ -58,26 +58,17 @@ export async function handleSetProxyMode(req, res, { port }) {
|
|
|
58
58
|
try {
|
|
59
59
|
const proxyUrl = getProxyConfigBaseUrl(req, port);
|
|
60
60
|
const apiKeyPlaceholder = '<client-api-key>';
|
|
61
|
-
const clearEnvironmentVariables = [
|
|
62
|
-
'ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
|
63
|
-
'ANTHROPIC_DEFAULT_OPUS_MODEL',
|
|
64
|
-
'ANTHROPIC_DEFAULT_SONNET_MODEL',
|
|
65
|
-
'ANTHROPIC_MODEL'
|
|
66
|
-
];
|
|
67
|
-
const configureCommands = [
|
|
68
|
-
`cc config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
69
|
-
`cc config set env.ANTHROPIC_AUTH_TOKEN ${apiKeyPlaceholder}`,
|
|
70
|
-
`cc config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`,
|
|
71
|
-
'cc config set env.CLAUDE_CODE_AUTO_COMPACT_WINDOW 258000'
|
|
72
|
-
];
|
|
73
|
-
const clearCommands = clearEnvironmentVariables.map(variable => `cc config unset env.${variable}`);
|
|
74
61
|
const commands = {
|
|
75
|
-
bash:
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
62
|
+
bash: [
|
|
63
|
+
`cc config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
64
|
+
`cc config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`,
|
|
65
|
+
'cc config set env.CLAUDE_CODE_AUTO_COMPACT_WINDOW 258000'
|
|
66
|
+
],
|
|
67
|
+
powershell: [
|
|
68
|
+
`cc config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
69
|
+
`cc config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`,
|
|
70
|
+
'cc config set env.CLAUDE_CODE_AUTO_COMPACT_WINDOW 258000'
|
|
71
|
+
]
|
|
81
72
|
};
|
|
82
73
|
|
|
83
74
|
res.json({
|