claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.30
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 +0 -272
- package/bin/cli.js +37 -2
- package/package.json +1 -1
- package/public/css/style.css +132 -0
- package/public/index.html +60 -60
- package/public/js/app.js +194 -116
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +61 -2
- package/public/views/accounts.html +29 -10
- package/public/views/client-api-keys-modals.html +15 -1
- package/public/views/client-api-keys.html +68 -31
- package/public/views/logs.html +10 -3
- package/src/account-manager.js +34 -3
- package/src/account-rotation/rate-limits.js +4 -0
- package/src/account-rotation/strategies/base-strategy.js +4 -0
- package/src/account-rotation/strategies/sticky-strategy.js +7 -0
- package/src/admin-path.js +33 -0
- package/src/client-key-usage.js +193 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +11 -11
- package/src/format-converter.js +83 -48
- package/src/index.js +13 -4
- package/src/middleware/auth.js +54 -16
- package/src/middleware/credentials.js +17 -7
- package/src/middleware/sse.js +69 -29
- package/src/model-api.js +60 -0
- package/src/model-pricing.js +127 -0
- package/src/response-streamer.js +23 -7
- package/src/routes/accounts-route.js +106 -2
- package/src/routes/api-routes.js +59 -42
- package/src/routes/chat-route.js +25 -4
- package/src/routes/claude-config-route.js +19 -10
- package/src/routes/client-quota-route.js +31 -0
- package/src/routes/logs-route.js +21 -2
- package/src/routes/messages-route.js +100 -51
- package/src/routes/settings-route.js +66 -5
- package/src/server-settings.js +25 -2
- package/src/utils/logger.js +30 -0
- package/src/utils/proxy-logging.js +5 -0
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,18 +7,14 @@ 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';
|
|
11
10
|
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
|
-
}
|
|
21
|
-
|
|
22
18
|
function createAnthropicUsage(upstreamUsage = {}) {
|
|
23
19
|
const usage = {
|
|
24
20
|
input_tokens: upstreamUsage.input_tokens || 0,
|
|
@@ -30,6 +26,10 @@ function createAnthropicUsage(upstreamUsage = {}) {
|
|
|
30
26
|
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
31
27
|
enumerable: false
|
|
32
28
|
});
|
|
29
|
+
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
30
|
+
value: upstreamUsage.input_tokens_details?.cache_write_tokens || 0,
|
|
31
|
+
enumerable: false
|
|
32
|
+
});
|
|
33
33
|
return usage;
|
|
34
34
|
}
|
|
35
35
|
|
|
@@ -134,9 +134,7 @@ async function createResponsesAPIStreamResponse(anthropicRequest, accessToken, a
|
|
|
134
134
|
if (response.ok) return response;
|
|
135
135
|
|
|
136
136
|
const errorText = await response.text();
|
|
137
|
-
|
|
138
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
139
|
-
}
|
|
137
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
140
138
|
|
|
141
139
|
if (response.status === 401) {
|
|
142
140
|
if (accountRotator && currentEmail) {
|
|
@@ -202,9 +200,7 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
202
200
|
|
|
203
201
|
if (!response.ok) {
|
|
204
202
|
const errorText = await response.text();
|
|
205
|
-
|
|
206
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
207
|
-
}
|
|
203
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
208
204
|
|
|
209
205
|
if (response.status === 401) {
|
|
210
206
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
|
@@ -220,6 +216,10 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
220
216
|
throw error;
|
|
221
217
|
}
|
|
222
218
|
|
|
219
|
+
if (response.status === 400) {
|
|
220
|
+
throw createHTTPError(`INVALID_REQUEST: ${errorText}`, 400, 'invalid_request_error', response.status);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
223
|
throw createUpstreamHTTPError(response, errorText);
|
|
224
224
|
}
|
|
225
225
|
|
package/src/format-converter.js
CHANGED
|
@@ -8,6 +8,7 @@ import { cleanCacheControl, processAssistantContent, hasUnsignedThinkingBlocks }
|
|
|
8
8
|
import { getCachedSignature, cacheSignature, cacheThinkingSignature, SIGNATURE_CONSTANTS } from './signature-cache.js';
|
|
9
9
|
|
|
10
10
|
const { MIN_SIGNATURE_LENGTH } = SIGNATURE_CONSTANTS;
|
|
11
|
+
const SUPPORTED_REASONING_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* Convert Anthropic tool ID to OpenAI fc_ format
|
|
@@ -146,11 +147,11 @@ export function convertAnthropicToResponsesAPI(anthropicRequest) {
|
|
|
146
147
|
const instructions = extractSystemPrompt(system);
|
|
147
148
|
|
|
148
149
|
const request = {
|
|
149
|
-
model: model
|
|
150
|
+
model: model,
|
|
150
151
|
input: convertMessagesToInput(cleanedMessages),
|
|
151
152
|
tools: tools ? convertAnthropicToolsToOpenAI(tools) : [],
|
|
152
|
-
tool_choice:
|
|
153
|
-
parallel_tool_calls: true,
|
|
153
|
+
tool_choice: 'auto',
|
|
154
|
+
parallel_tool_calls: tool_choice?.disable_parallel_tool_use !== true,
|
|
154
155
|
store: false,
|
|
155
156
|
stream: true,
|
|
156
157
|
include: []
|
|
@@ -162,6 +163,11 @@ export function convertAnthropicToResponsesAPI(anthropicRequest) {
|
|
|
162
163
|
request.instructions = '';
|
|
163
164
|
}
|
|
164
165
|
|
|
166
|
+
const effort = anthropicRequest.output_config?.effort;
|
|
167
|
+
if (SUPPORTED_REASONING_EFFORTS.has(effort)) {
|
|
168
|
+
request.reasoning = { effort };
|
|
169
|
+
}
|
|
170
|
+
|
|
165
171
|
return request;
|
|
166
172
|
}
|
|
167
173
|
|
|
@@ -177,23 +183,7 @@ function convertMessagesToInput(messages) {
|
|
|
177
183
|
|
|
178
184
|
for (const msg of messages) {
|
|
179
185
|
if (msg.role === 'user') {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (textParts.length > 0) {
|
|
183
|
-
// API accepts: string OR array of {type: 'input_text', text: '...'}
|
|
184
|
-
const content = textParts.length === 1
|
|
185
|
-
? textParts[0] // Use string for single text
|
|
186
|
-
: textParts.map(text => ({ type: 'input_text', text }));
|
|
187
|
-
input.push({
|
|
188
|
-
type: 'message',
|
|
189
|
-
role: 'user',
|
|
190
|
-
content
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
for (const result of toolResults) {
|
|
195
|
-
input.push(result);
|
|
196
|
-
}
|
|
186
|
+
input.push(...convertUserContent(msg.content));
|
|
197
187
|
} else if (msg.role === 'assistant') {
|
|
198
188
|
// Process assistant content: restore signatures, reorder, sanitize
|
|
199
189
|
let msgContent = msg.content;
|
|
@@ -225,34 +215,62 @@ function convertMessagesToInput(messages) {
|
|
|
225
215
|
}
|
|
226
216
|
|
|
227
217
|
/**
|
|
228
|
-
* Convert user content
|
|
218
|
+
* Convert Anthropic user content while preserving block order.
|
|
229
219
|
*/
|
|
230
220
|
function convertUserContent(content) {
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
221
|
+
const inputItems = [];
|
|
222
|
+
let messageParts = [];
|
|
223
|
+
|
|
224
|
+
const flushMessageParts = () => {
|
|
225
|
+
if (messageParts.length === 0) return;
|
|
226
|
+
|
|
227
|
+
const messageContent =
|
|
228
|
+
messageParts.length === 1 && messageParts[0].type === 'input_text'
|
|
229
|
+
? messageParts[0].text
|
|
230
|
+
: messageParts;
|
|
231
|
+
|
|
232
|
+
inputItems.push({
|
|
233
|
+
type: 'message',
|
|
234
|
+
role: 'user',
|
|
235
|
+
content: messageContent
|
|
236
|
+
});
|
|
237
|
+
messageParts = [];
|
|
238
|
+
};
|
|
239
|
+
|
|
234
240
|
if (typeof content === 'string') {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
textParts.push(block.text);
|
|
240
|
-
} else if (block.type === 'tool_result') {
|
|
241
|
-
const outputContent = convertToolResultContentToResponsesOutput(block);
|
|
241
|
+
messageParts.push({ type: 'input_text', text: content });
|
|
242
|
+
flushMessageParts();
|
|
243
|
+
return inputItems;
|
|
244
|
+
}
|
|
242
245
|
|
|
243
|
-
|
|
244
|
-
|
|
246
|
+
if (!Array.isArray(content)) {
|
|
247
|
+
return inputItems;
|
|
248
|
+
}
|
|
245
249
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
250
|
+
for (const block of content) {
|
|
251
|
+
if (!block || typeof block !== 'object') continue;
|
|
252
|
+
|
|
253
|
+
if (block.type === 'text') {
|
|
254
|
+
messageParts.push({ type: 'input_text', text: block.text || '' });
|
|
255
|
+
} else if (block.type === 'image') {
|
|
256
|
+
const image = convertAnthropicImageToResponsesInputImage(block);
|
|
257
|
+
if (image) messageParts.push(image);
|
|
258
|
+
} else if (block.type === 'tool_result') {
|
|
259
|
+
flushMessageParts();
|
|
260
|
+
|
|
261
|
+
const outputContent = convertToolResultContentToResponsesOutput(block);
|
|
262
|
+
const callId = toOpenAIToolId(block.tool_use_id);
|
|
263
|
+
|
|
264
|
+
inputItems.push({
|
|
265
|
+
type: 'function_call_output',
|
|
266
|
+
call_id: callId,
|
|
267
|
+
output: block.is_error ? prefixToolErrorOutput(outputContent) : outputContent
|
|
268
|
+
});
|
|
252
269
|
}
|
|
253
270
|
}
|
|
254
|
-
|
|
255
|
-
|
|
271
|
+
|
|
272
|
+
flushMessageParts();
|
|
273
|
+
return inputItems;
|
|
256
274
|
}
|
|
257
275
|
|
|
258
276
|
/**
|
|
@@ -310,19 +328,36 @@ function convertAssistantContentToOpenAI(content) {
|
|
|
310
328
|
}
|
|
311
329
|
|
|
312
330
|
/**
|
|
313
|
-
* Convert Anthropic tools to OpenAI
|
|
331
|
+
* Convert Anthropic tools to OpenAI Responses API tool format.
|
|
314
332
|
*/
|
|
315
333
|
function convertAnthropicToolsToOpenAI(tools) {
|
|
316
334
|
if (!Array.isArray(tools)) {
|
|
317
335
|
return [];
|
|
318
336
|
}
|
|
319
337
|
|
|
320
|
-
return tools.map(tool =>
|
|
321
|
-
type
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
338
|
+
return tools.map(tool => {
|
|
339
|
+
if (tool.type === 'web_search_20250305' && tool.name === 'web_search') {
|
|
340
|
+
const webSearchTool = {
|
|
341
|
+
type: 'web_search',
|
|
342
|
+
external_web_access: true
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
if (Array.isArray(tool.allowed_domains)) {
|
|
346
|
+
webSearchTool.filters = {
|
|
347
|
+
allowed_domains: tool.allowed_domains
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return webSearchTool;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
type: 'function',
|
|
356
|
+
name: tool.name,
|
|
357
|
+
description: tool.description || '',
|
|
358
|
+
parameters: sanitizeSchema(tool.input_schema || { type: 'object' })
|
|
359
|
+
};
|
|
360
|
+
});
|
|
326
361
|
}
|
|
327
362
|
|
|
328
363
|
function sanitizeAnthropicToolInput(name, input) {
|
package/src/index.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
7
|
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
8
|
+
import { getAdminPath } from './admin-path.js';
|
|
8
9
|
import { startServer } from './server.js';
|
|
9
10
|
import { logger } from './utils/logger.js';
|
|
10
11
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -21,6 +22,14 @@ try {
|
|
|
21
22
|
}
|
|
22
23
|
const HOST = getServerHost();
|
|
23
24
|
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}`;
|
|
24
33
|
const BANNER_WIDTH = 62;
|
|
25
34
|
|
|
26
35
|
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
@@ -45,10 +54,10 @@ console.log(`
|
|
|
45
54
|
╠══════════════════════════════════════════════════════════════╣
|
|
46
55
|
${bannerLine('Host:', HOST)}
|
|
47
56
|
${bannerLine('Server:', BASE_URL)}
|
|
48
|
-
${bannerLine('WebUI:',
|
|
57
|
+
${bannerLine('WebUI:', ADMIN_URL)}
|
|
49
58
|
${bannerLine('Health:', `${BASE_URL}/health`)}
|
|
50
|
-
${bannerLine('Accounts:', `${
|
|
51
|
-
${bannerLine('Logs:', `${
|
|
59
|
+
${bannerLine('Accounts:', `${ADMIN_URL}/accounts`)}
|
|
60
|
+
${bannerLine('Logs:', `${ADMIN_URL}/api/logs/stream`)}
|
|
52
61
|
╠══════════════════════════════════════════════════════════════╣
|
|
53
62
|
║ Features: ║
|
|
54
63
|
║ ✓ Native tool calling support ║
|
|
@@ -66,7 +75,7 @@ const status = getStatus();
|
|
|
66
75
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
67
76
|
|
|
68
77
|
if (status.total === 0) {
|
|
69
|
-
logger.warn(`No accounts configured. Open ${
|
|
78
|
+
logger.warn(`No accounts configured. Open ${ADMIN_URL} to add one.`);
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
// Expose config path in logs for convenience
|
package/src/middleware/auth.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
-
import { getServerSettings } from '../server-settings.js';
|
|
3
|
+
import { getServerSettings, DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
4
|
+
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
5
|
+
import { createErrorResponse } from './sse.js';
|
|
4
6
|
|
|
5
7
|
function timingSafeEqualString(a, b) {
|
|
6
8
|
const left = Buffer.from(String(a));
|
|
@@ -25,7 +27,7 @@ function getRequestApiKey(req) {
|
|
|
25
27
|
return String(headerKey).trim();
|
|
26
28
|
}
|
|
27
29
|
|
|
28
|
-
const queryKey = req.query?.api_key
|
|
30
|
+
const queryKey = req.query?.api_key;
|
|
29
31
|
if (queryKey) {
|
|
30
32
|
return String(queryKey).trim();
|
|
31
33
|
}
|
|
@@ -35,19 +37,16 @@ function getRequestApiKey(req) {
|
|
|
35
37
|
|
|
36
38
|
function sendUnauthorized(req, res) {
|
|
37
39
|
if (req.path?.startsWith('/v1/')) {
|
|
38
|
-
return res.status(401).json(
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
});
|
|
40
|
+
return res.status(401).json(
|
|
41
|
+
createErrorResponse('authentication_error', 'Invalid API key')
|
|
42
|
+
);
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
function
|
|
48
|
-
return
|
|
49
|
-
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
50
|
-
));
|
|
48
|
+
function matchesKey(requestKey, expectedKey) {
|
|
49
|
+
return expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey);
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
function requireKeys(getExpectedKeys) {
|
|
@@ -58,7 +57,7 @@ function requireKeys(getExpectedKeys) {
|
|
|
58
57
|
|
|
59
58
|
const expectedKeys = getExpectedKeys();
|
|
60
59
|
const requestKey = getRequestApiKey(req);
|
|
61
|
-
if (!
|
|
60
|
+
if (!expectedKeys.some((expectedKey) => matchesKey(requestKey, expectedKey))) {
|
|
62
61
|
return sendUnauthorized(req, res);
|
|
63
62
|
}
|
|
64
63
|
|
|
@@ -66,14 +65,53 @@ function requireKeys(getExpectedKeys) {
|
|
|
66
65
|
};
|
|
67
66
|
}
|
|
68
67
|
|
|
68
|
+
function sendQuotaExceeded(res, period, resetsAt) {
|
|
69
|
+
return res.status(429).json(
|
|
70
|
+
createErrorResponse('rate_limit_error', `${period} client key quota exhausted. Resets at ${resetsAt}`)
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function findClientKey(requestKey) {
|
|
75
|
+
return getServerSettings().clientApiKeys.find(({ key }) => matchesKey(requestKey, key));
|
|
76
|
+
}
|
|
77
|
+
|
|
69
78
|
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);
|
|
74
79
|
|
|
75
80
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
76
|
-
|
|
81
|
+
|
|
82
|
+
export function requireClientAuth(req, res, next) {
|
|
83
|
+
const requestKey = getRequestApiKey(req);
|
|
84
|
+
const clientKey = findClientKey(requestKey);
|
|
85
|
+
if (isPublicDeployment() && !clientKey) {
|
|
86
|
+
return sendUnauthorized(req, res);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (!clientKey) {
|
|
90
|
+
return next();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const quota = getClientKeyQuota(
|
|
94
|
+
clientKey.id,
|
|
95
|
+
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD,
|
|
96
|
+
{
|
|
97
|
+
enabled: clientKey.fiveHourLimitEnabled,
|
|
98
|
+
usd: clientKey.fiveHourLimitUsd
|
|
99
|
+
}
|
|
100
|
+
);
|
|
101
|
+
const isModelRequest = req.method === 'POST' && (
|
|
102
|
+
req.path === '/v1/messages' || req.path === '/v1/chat/completions'
|
|
103
|
+
);
|
|
104
|
+
if (isModelRequest && quota.fiveHourLimitEnabled && quota.fiveHourRemainingMicrousd <= 0) {
|
|
105
|
+
return sendQuotaExceeded(res, 'Five-hour', quota.nextFiveHourPeriodStart);
|
|
106
|
+
}
|
|
107
|
+
if (isModelRequest && quota.remainingMicrousd <= 0) {
|
|
108
|
+
return sendQuotaExceeded(res, 'Weekly', quota.nextPeriodStart);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
req.clientApiKey = { id: clientKey.id, name: clientKey.name };
|
|
112
|
+
req.clientApiKeyQuota = quota;
|
|
113
|
+
return next();
|
|
114
|
+
}
|
|
77
115
|
|
|
78
116
|
export { isPublicDeployment };
|
|
79
117
|
|
|
@@ -8,9 +8,11 @@ import {
|
|
|
8
8
|
getActiveAccount,
|
|
9
9
|
refreshAccountToken,
|
|
10
10
|
isTokenExpiredOrExpiringSoon,
|
|
11
|
+
isAccountExpired,
|
|
11
12
|
loadAccounts
|
|
12
13
|
} from '../account-manager.js';
|
|
13
14
|
import { logger } from '../utils/logger.js';
|
|
15
|
+
import { createErrorResponse } from './sse.js';
|
|
14
16
|
|
|
15
17
|
/**
|
|
16
18
|
* Resolves the active account credentials, refreshing the token if needed.
|
|
@@ -26,6 +28,11 @@ export async function getCredentialsOrError() {
|
|
|
26
28
|
return null;
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
if (isAccountExpired(account)) {
|
|
32
|
+
logger.info(`Account ${account.email} has expired`);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
29
36
|
if (!account.accessToken || !account.accountId) {
|
|
30
37
|
logger.info(`Account ${account.email} missing token or accountId`);
|
|
31
38
|
return null;
|
|
@@ -41,8 +48,8 @@ export async function getCredentialsOrError() {
|
|
|
41
48
|
}
|
|
42
49
|
|
|
43
50
|
const refreshedAccount = getActiveAccount();
|
|
44
|
-
if (!refreshedAccount) {
|
|
45
|
-
logger.error('Failed to get refreshed account');
|
|
51
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) {
|
|
52
|
+
logger.error('Failed to get refreshed active account');
|
|
46
53
|
return null;
|
|
47
54
|
}
|
|
48
55
|
|
|
@@ -74,6 +81,10 @@ export async function getCredentialsForAccount(email) {
|
|
|
74
81
|
return null;
|
|
75
82
|
}
|
|
76
83
|
|
|
84
|
+
if (isAccountExpired(account)) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
77
88
|
if (!account.accessToken || !account.accountId) {
|
|
78
89
|
return null;
|
|
79
90
|
}
|
|
@@ -85,7 +96,7 @@ export async function getCredentialsForAccount(email) {
|
|
|
85
96
|
}
|
|
86
97
|
const refreshedData = loadAccounts();
|
|
87
98
|
const refreshedAccount = refreshedData.accounts.find(a => a.email === email);
|
|
88
|
-
if (!refreshedAccount) return null;
|
|
99
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) return null;
|
|
89
100
|
|
|
90
101
|
return {
|
|
91
102
|
accessToken: refreshedAccount.accessToken,
|
|
@@ -107,10 +118,9 @@ export async function getCredentialsForAccount(email) {
|
|
|
107
118
|
* @param {string} [message]
|
|
108
119
|
*/
|
|
109
120
|
export function sendAuthError(res, message = 'No active account with valid credentials. Add an account via /accounts/add') {
|
|
110
|
-
return res.status(401).json(
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
});
|
|
121
|
+
return res.status(401).json(
|
|
122
|
+
createErrorResponse('authentication_error', message)
|
|
123
|
+
);
|
|
114
124
|
}
|
|
115
125
|
|
|
116
126
|
export default { getCredentialsOrError, getCredentialsForAccount, sendAuthError };
|