claude-codex-proxy 1.0.3 → 1.0.5-beta.0
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 +39 -6
- package/bin/cli.js +43 -0
- package/docs/API.md +22 -0
- package/package.json +3 -2
- package/public/index.html +130 -14
- package/public/js/app.js +162 -20
- package/src/account-manager.js +83 -29
- package/src/account-rotation/rate-limits.js +49 -0
- package/src/account-rotation/strategies/sticky-strategy.js +9 -22
- package/src/direct-api.js +30 -7
- package/src/index.js +7 -1
- package/src/middleware/auth.js +81 -0
- package/src/response-streamer.js +6 -1
- package/src/routes/api-routes.js +31 -7
- package/src/routes/chat-route.js +1 -1
- package/src/routes/claude-config-route.js +18 -1
- package/src/routes/messages-route.js +5 -12
- package/src/routes/models-route.js +1 -1
- package/src/routes/settings-route.js +99 -1
- package/src/server-settings.js +2 -3
- package/src/server.js +10 -5
package/src/index.js
CHANGED
|
@@ -11,7 +11,13 @@ import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
|
11
11
|
const require = createRequire(import.meta.url);
|
|
12
12
|
const packageJson = require('../package.json');
|
|
13
13
|
const PORT = Number(process.env.PORT || 8081);
|
|
14
|
+
const DEPLOYMENT_MODE = process.env.PROXY_DEPLOYMENT_MODE || 'local';
|
|
14
15
|
const BANNER_WIDTH = 62;
|
|
16
|
+
|
|
17
|
+
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
18
|
+
console.error('Public deployment mode requires a UI/admin access key.');
|
|
19
|
+
process.exit(1);
|
|
20
|
+
}
|
|
15
21
|
const centerBannerText = (text) => {
|
|
16
22
|
const padding = Math.max(0, BANNER_WIDTH - text.length);
|
|
17
23
|
const left = Math.floor(padding / 2);
|
|
@@ -24,7 +30,7 @@ startServer({ port: PORT });
|
|
|
24
30
|
console.log(`
|
|
25
31
|
╔══════════════════════════════════════════════════════════════╗
|
|
26
32
|
║${centerBannerText(`Claude Codex Proxy v${packageJson.version}`)}║
|
|
27
|
-
|
|
33
|
+
║${centerBannerText(DEPLOYMENT_MODE === 'public' ? 'Public Deployment Mode' : 'Local Deployment Mode')}║
|
|
28
34
|
╠══════════════════════════════════════════════════════════════╣
|
|
29
35
|
║ Server: http://localhost:${PORT} ║
|
|
30
36
|
║ WebUI: http://localhost:${PORT} ║
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getServerSettings } from '../server-settings.js';
|
|
3
|
+
|
|
4
|
+
export function isPublicDeployment() {
|
|
5
|
+
return process.env.PROXY_DEPLOYMENT_MODE === 'public';
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function timingSafeEqualString(a, b) {
|
|
9
|
+
const left = Buffer.from(String(a));
|
|
10
|
+
const right = Buffer.from(String(b));
|
|
11
|
+
|
|
12
|
+
if (left.length !== right.length) {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return crypto.timingSafeEqual(left, right);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function getRequestApiKey(req) {
|
|
20
|
+
const authorization = req.get?.('authorization') || req.headers?.authorization || '';
|
|
21
|
+
const bearerMatch = authorization.match(/^Bearer\s+(.+)$/i);
|
|
22
|
+
if (bearerMatch) {
|
|
23
|
+
return bearerMatch[1].trim();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const headerKey = req.get?.('x-api-key') || req.headers?.['x-api-key'];
|
|
27
|
+
if (headerKey) {
|
|
28
|
+
return String(headerKey).trim();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const queryKey = req.query?.api_key || req.query?.access_token;
|
|
32
|
+
if (queryKey) {
|
|
33
|
+
return String(queryKey).trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return '';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function sendUnauthorized(req, res) {
|
|
40
|
+
if (req.path?.startsWith('/v1/')) {
|
|
41
|
+
return res.status(401).json({
|
|
42
|
+
type: 'error',
|
|
43
|
+
error: { type: 'authentication_error', message: 'Invalid API key' }
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function matchesAnyKey(requestKey, expectedKeys) {
|
|
51
|
+
return expectedKeys.some((expectedKey) => (
|
|
52
|
+
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
53
|
+
));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function requireKeys(getExpectedKeys) {
|
|
57
|
+
return (req, res, next) => {
|
|
58
|
+
if (!isPublicDeployment()) {
|
|
59
|
+
return next();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const expectedKeys = getExpectedKeys();
|
|
63
|
+
const requestKey = getRequestApiKey(req);
|
|
64
|
+
if (!matchesAnyKey(requestKey, expectedKeys)) {
|
|
65
|
+
return sendUnauthorized(req, res);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return next();
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const getAdminKeys = () => [process.env.PROXY_ADMIN_KEY].filter(Boolean);
|
|
73
|
+
const getClientKeys = () => [
|
|
74
|
+
...getServerSettings().clientApiKeys.map(({ key }) => key),
|
|
75
|
+
process.env.PROXY_CLIENT_KEY
|
|
76
|
+
].filter(Boolean);
|
|
77
|
+
|
|
78
|
+
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
79
|
+
export const requireClientAuth = requireKeys(getClientKeys);
|
|
80
|
+
|
|
81
|
+
export default { isPublicDeployment, requireAdminAuth, requireClientAuth };
|
package/src/response-streamer.js
CHANGED
|
@@ -110,8 +110,13 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
110
110
|
usage = {
|
|
111
111
|
input_tokens: inputTokens,
|
|
112
112
|
output_tokens: outputTokens,
|
|
113
|
-
|
|
113
|
+
// Responses API cache metrics are already included in input_tokens.
|
|
114
|
+
cache_read_input_tokens: 0
|
|
114
115
|
};
|
|
116
|
+
Object.defineProperty(usage, 'upstreamCacheReadInputTokens', {
|
|
117
|
+
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
118
|
+
enumerable: false
|
|
119
|
+
});
|
|
115
120
|
}
|
|
116
121
|
|
|
117
122
|
// Handle output item added
|
package/src/routes/api-routes.js
CHANGED
|
@@ -10,6 +10,7 @@ import { join, dirname } from 'path';
|
|
|
10
10
|
import { fileURLToPath } from 'url';
|
|
11
11
|
|
|
12
12
|
import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
|
|
13
|
+
import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
|
|
13
14
|
|
|
14
15
|
// Route handlers
|
|
15
16
|
import { handleMessages } from './messages-route.js';
|
|
@@ -21,7 +22,11 @@ import {
|
|
|
21
22
|
handleGetModelMap,
|
|
22
23
|
handleSetModelMap,
|
|
23
24
|
handleGetRawProxyLogs,
|
|
24
|
-
handleSetRawProxyLogs
|
|
25
|
+
handleSetRawProxyLogs,
|
|
26
|
+
handleListClientApiKeys,
|
|
27
|
+
handleCreateClientApiKey,
|
|
28
|
+
handleUpdateClientApiKey,
|
|
29
|
+
handleDeleteClientApiKey
|
|
25
30
|
} from './settings-route.js';
|
|
26
31
|
import { handleGetLogs, handleStreamLogs } from './logs-route.js';
|
|
27
32
|
import { handleGetClaudeConfig, handleSetProxyMode, handleSetDirectMode, handleSetClaudeApiEndpoint } from './claude-config-route.js';
|
|
@@ -51,18 +56,34 @@ export function registerApiRoutes(app, { port }) {
|
|
|
51
56
|
|
|
52
57
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
53
58
|
app.get('/health', (req, res) => {
|
|
54
|
-
|
|
59
|
+
const health = {
|
|
60
|
+
status: 'ok',
|
|
61
|
+
version: packageJson.version,
|
|
62
|
+
publicMode: isPublicDeployment()
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
if (!isPublicDeployment()) {
|
|
66
|
+
Object.assign(health, getStatus(), { configPath: ACCOUNTS_FILE });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
res.json(health);
|
|
55
70
|
});
|
|
56
71
|
|
|
72
|
+
// ─── Public Claude CLI Configuration Helper ───────────────────────────────
|
|
73
|
+
app.post('/claude/config/proxy', (req, res) => handleSetProxyMode(req, res, { port }));
|
|
74
|
+
|
|
57
75
|
// ─── Anthropic Messages API ────────────────────────────────────────────────
|
|
58
|
-
app.post('/v1/messages', handleMessages);
|
|
59
|
-
app.post('/v1/messages/count_tokens', handleCountTokens);
|
|
76
|
+
app.post('/v1/messages', requireClientAuth, handleMessages);
|
|
77
|
+
app.post('/v1/messages/count_tokens', requireClientAuth, handleCountTokens);
|
|
60
78
|
|
|
61
79
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
62
|
-
app.post('/v1/chat/completions', handleChatCompletion);
|
|
80
|
+
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
63
81
|
|
|
64
82
|
// ─── Models ────────────────────────────────────────────────────────────────
|
|
65
|
-
app.get('/v1/models', handleListModels);
|
|
83
|
+
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
84
|
+
|
|
85
|
+
app.use(requireAdminAuth);
|
|
86
|
+
|
|
66
87
|
app.get('/accounts/models', handleAccountModels);
|
|
67
88
|
app.get('/accounts/usage', handleAccountUsage);
|
|
68
89
|
|
|
@@ -73,6 +94,10 @@ export function registerApiRoutes(app, { port }) {
|
|
|
73
94
|
app.post('/settings/model-map', handleSetModelMap);
|
|
74
95
|
app.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
75
96
|
app.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
97
|
+
app.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
98
|
+
app.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
99
|
+
app.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
100
|
+
app.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
76
101
|
|
|
77
102
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
78
103
|
app.get('/accounts', handleListAccounts);
|
|
@@ -93,7 +118,6 @@ export function registerApiRoutes(app, { port }) {
|
|
|
93
118
|
|
|
94
119
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
95
120
|
app.get('/claude/config', handleGetClaudeConfig);
|
|
96
|
-
app.post('/claude/config/proxy', (req, res) => handleSetProxyMode(req, res, { port }));
|
|
97
121
|
app.post('/claude/config/direct', handleSetDirectMode);
|
|
98
122
|
app.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
99
123
|
|
package/src/routes/chat-route.js
CHANGED
|
@@ -227,7 +227,7 @@ function _buildOpenAIResponse(response, responseModel) {
|
|
|
227
227
|
function getTokenDetails(usage = {}) {
|
|
228
228
|
const inputTokens = usage?.input_tokens || 0;
|
|
229
229
|
const outputTokens = usage?.output_tokens || 0;
|
|
230
|
-
const cacheReadInputTokens = usage?.cache_read_input_tokens
|
|
230
|
+
const cacheReadInputTokens = usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens ?? 0;
|
|
231
231
|
return {
|
|
232
232
|
tokens: inputTokens + outputTokens,
|
|
233
233
|
inputTokens,
|
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
setApiEndpoint,
|
|
15
15
|
getClaudeConfigPath
|
|
16
16
|
} from '../claude-config.js';
|
|
17
|
+
import { isPublicDeployment } from '../middleware/auth.js';
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* GET /claude/config
|
|
@@ -35,12 +36,28 @@ export async function handleGetClaudeConfig(req, res) {
|
|
|
35
36
|
*/
|
|
36
37
|
export async function handleSetProxyMode(req, res, { port }) {
|
|
37
38
|
try {
|
|
38
|
-
const proxyUrl =
|
|
39
|
+
const proxyUrl = isPublicDeployment()
|
|
40
|
+
? `${req.protocol}://${req.get('host')}`
|
|
41
|
+
: `http://localhost:${port}`;
|
|
39
42
|
const models = {
|
|
40
43
|
opus: 'claude-opus',
|
|
41
44
|
sonnet: 'claude-sonnet',
|
|
42
45
|
haiku: 'claude-haiku'
|
|
43
46
|
};
|
|
47
|
+
|
|
48
|
+
if (isPublicDeployment()) {
|
|
49
|
+
return res.json({
|
|
50
|
+
success: true,
|
|
51
|
+
mode: 'dry_run',
|
|
52
|
+
message: 'Public deployment mode: local Claude CLI config was not modified.',
|
|
53
|
+
env: {
|
|
54
|
+
ANTHROPIC_BASE_URL: proxyUrl,
|
|
55
|
+
ANTHROPIC_API_KEY: '<client-api-key>'
|
|
56
|
+
},
|
|
57
|
+
models
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
44
61
|
const config = await setProxyMode(proxyUrl, models);
|
|
45
62
|
res.json({
|
|
46
63
|
success: true,
|
|
@@ -67,16 +67,9 @@ export async function handleMessages(req, res) {
|
|
|
67
67
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
68
68
|
if (rotator.isAllRateLimited(upstreamModel)) {
|
|
69
69
|
const minWait = rotator.getMinWaitTimeMs(upstreamModel);
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
logger.info(`[Messages] All accounts rate-limited, waiting ${Math.round(minWait/1000)}s...`);
|
|
76
|
-
await sleep(minWait + 500);
|
|
77
|
-
rotator.clearExpiredLimits();
|
|
78
|
-
attempt--;
|
|
79
|
-
continue;
|
|
70
|
+
const waitSeconds = minWait > 0 ? Math.round(minWait / 1000) : 'unknown';
|
|
71
|
+
logger.info(`[Messages] All accounts rate-limited, not retrying. Next possible reset: ${waitSeconds}s`);
|
|
72
|
+
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
80
73
|
}
|
|
81
74
|
|
|
82
75
|
const { account, waitMs } = rotator.selectAccount(upstreamModel);
|
|
@@ -149,7 +142,7 @@ async function _streamDirectWithRotation(res, anthropicRequest, creds, responseM
|
|
|
149
142
|
}
|
|
150
143
|
|
|
151
144
|
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
152
|
-
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext);
|
|
145
|
+
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
153
146
|
const duration = Date.now() - startTime;
|
|
154
147
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
155
148
|
res.json({ ...response, model: responseModel });
|
|
@@ -168,7 +161,7 @@ function syncActiveAccount(email) {
|
|
|
168
161
|
function getTokenDetails(usage = {}) {
|
|
169
162
|
const inputTokens = usage?.input_tokens || 0;
|
|
170
163
|
const outputTokens = usage?.output_tokens || 0;
|
|
171
|
-
const cacheReadInputTokens = usage?.cache_read_input_tokens
|
|
164
|
+
const cacheReadInputTokens = usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens ?? 0;
|
|
172
165
|
return {
|
|
173
166
|
tokens: inputTokens + outputTokens,
|
|
174
167
|
inputTokens,
|
|
@@ -11,7 +11,7 @@ import { getActiveAccount, loadAccounts } from '../account-manager.js';
|
|
|
11
11
|
import { logger } from '../utils/logger.js';
|
|
12
12
|
import { getCredentialsOrError } from '../middleware/credentials.js';
|
|
13
13
|
|
|
14
|
-
const FALLBACK_MODELS = [
|
|
14
|
+
export const FALLBACK_MODELS = [
|
|
15
15
|
// OpenAI upstream models
|
|
16
16
|
{ id: 'gpt-5.3-codex', object: 'model', owned_by: 'openai' },
|
|
17
17
|
{ id: 'gpt-5.2-codex', object: 'model', owned_by: 'openai' },
|
|
@@ -9,10 +9,20 @@
|
|
|
9
9
|
* POST /settings/raw-proxy-logs
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import crypto from 'crypto';
|
|
12
13
|
import { getServerSettings, setServerSettings, DEFAULT_MODEL_MAP } from '../server-settings.js';
|
|
13
14
|
|
|
14
15
|
const VALID_STRATEGIES = ['sticky', 'round-robin'];
|
|
15
16
|
|
|
17
|
+
function getSafeClientApiKey(clientApiKey) {
|
|
18
|
+
const { key, ...safeClientApiKey } = clientApiKey;
|
|
19
|
+
return safeClientApiKey;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function createClientApiKeyValue() {
|
|
23
|
+
return `ccp_${crypto.randomBytes(24).toString('base64url')}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
16
26
|
/**
|
|
17
27
|
* GET /settings/account-strategy
|
|
18
28
|
* Returns the current account selection strategy.
|
|
@@ -144,11 +154,99 @@ export function handleSetRawProxyLogs(req, res) {
|
|
|
144
154
|
res.json({ success: true, logRawProxyPayloads: settings.logRawProxyPayloads === true });
|
|
145
155
|
}
|
|
146
156
|
|
|
157
|
+
/**
|
|
158
|
+
* GET /settings/client-api-keys
|
|
159
|
+
* Returns metadata only; client API key values are never returned after creation.
|
|
160
|
+
*/
|
|
161
|
+
export function handleListClientApiKeys(req, res) {
|
|
162
|
+
const { clientApiKeys } = getServerSettings();
|
|
163
|
+
res.json({ success: true, clientApiKeys: clientApiKeys.map(getSafeClientApiKey) });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* POST /settings/client-api-keys
|
|
168
|
+
* Creates a Claude Code client API key.
|
|
169
|
+
*/
|
|
170
|
+
export function handleCreateClientApiKey(req, res) {
|
|
171
|
+
const { name = '', remark = '' } = req.body || {};
|
|
172
|
+
|
|
173
|
+
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
174
|
+
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const clientApiKey = {
|
|
178
|
+
id: crypto.randomUUID(),
|
|
179
|
+
key: createClientApiKeyValue(),
|
|
180
|
+
name: name.trim(),
|
|
181
|
+
remark: remark.trim(),
|
|
182
|
+
createdAt: new Date().toISOString()
|
|
183
|
+
};
|
|
184
|
+
const settings = getServerSettings();
|
|
185
|
+
setServerSettings({ clientApiKeys: [...settings.clientApiKeys, clientApiKey] });
|
|
186
|
+
|
|
187
|
+
res.status(201).json({ success: true, clientApiKey });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* PUT /settings/client-api-keys/:id
|
|
192
|
+
* Updates a client API key's name or remark without exposing its value.
|
|
193
|
+
*/
|
|
194
|
+
export function handleUpdateClientApiKey(req, res) {
|
|
195
|
+
const { id } = req.params;
|
|
196
|
+
const { name, remark } = req.body || {};
|
|
197
|
+
|
|
198
|
+
if (name !== undefined && typeof name !== 'string') {
|
|
199
|
+
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
200
|
+
}
|
|
201
|
+
if (remark !== undefined && typeof remark !== 'string') {
|
|
202
|
+
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const settings = getServerSettings();
|
|
206
|
+
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
207
|
+
if (index < 0) {
|
|
208
|
+
return res.status(404).json({ success: false, error: 'Client API key not found' });
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const current = settings.clientApiKeys[index];
|
|
212
|
+
const clientApiKey = {
|
|
213
|
+
...current,
|
|
214
|
+
...(name === undefined ? {} : { name: name.trim() }),
|
|
215
|
+
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
216
|
+
};
|
|
217
|
+
const clientApiKeys = [...settings.clientApiKeys];
|
|
218
|
+
clientApiKeys[index] = clientApiKey;
|
|
219
|
+
setServerSettings({ clientApiKeys });
|
|
220
|
+
|
|
221
|
+
res.json({ success: true, clientApiKey: getSafeClientApiKey(clientApiKey) });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* DELETE /settings/client-api-keys/:id
|
|
226
|
+
* Removes a Claude Code client API key immediately.
|
|
227
|
+
*/
|
|
228
|
+
export function handleDeleteClientApiKey(req, res) {
|
|
229
|
+
const { id } = req.params;
|
|
230
|
+
const settings = getServerSettings();
|
|
231
|
+
const clientApiKeys = settings.clientApiKeys.filter((clientApiKey) => clientApiKey.id !== id);
|
|
232
|
+
|
|
233
|
+
if (clientApiKeys.length === settings.clientApiKeys.length) {
|
|
234
|
+
return res.status(404).json({ success: false, error: 'Client API key not found' });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
setServerSettings({ clientApiKeys });
|
|
238
|
+
res.json({ success: true });
|
|
239
|
+
}
|
|
240
|
+
|
|
147
241
|
export default {
|
|
148
242
|
handleGetAccountStrategy,
|
|
149
243
|
handleSetAccountStrategy,
|
|
150
244
|
handleGetModelMap,
|
|
151
245
|
handleSetModelMap,
|
|
152
246
|
handleGetRawProxyLogs,
|
|
153
|
-
handleSetRawProxyLogs
|
|
247
|
+
handleSetRawProxyLogs,
|
|
248
|
+
handleListClientApiKeys,
|
|
249
|
+
handleCreateClientApiKey,
|
|
250
|
+
handleUpdateClientApiKey,
|
|
251
|
+
handleDeleteClientApiKey
|
|
154
252
|
};
|
package/src/server-settings.js
CHANGED
|
@@ -14,7 +14,8 @@ export const DEFAULT_SETTINGS = {
|
|
|
14
14
|
accountStrategy: 'sticky',
|
|
15
15
|
defaultCodexModel: 'gpt-5.5',
|
|
16
16
|
logRawProxyPayloads: false,
|
|
17
|
-
modelMap: DEFAULT_MODEL_MAP
|
|
17
|
+
modelMap: DEFAULT_MODEL_MAP,
|
|
18
|
+
clientApiKeys: []
|
|
18
19
|
};
|
|
19
20
|
|
|
20
21
|
function ensureConfigDir() {
|
|
@@ -35,8 +36,6 @@ function mergeSettings(data = {}) {
|
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
export function getServerSettings() {
|
|
38
|
-
ensureConfigDir();
|
|
39
|
-
|
|
40
39
|
if (!existsSync(SETTINGS_FILE)) {
|
|
41
40
|
return mergeSettings();
|
|
42
41
|
}
|
package/src/server.js
CHANGED
|
@@ -9,9 +9,13 @@ import cors from 'cors';
|
|
|
9
9
|
import { ensureAccountsPersist, startAutoRefresh } from './account-manager.js';
|
|
10
10
|
import { registerApiRoutes } from './routes/api-routes.js';
|
|
11
11
|
|
|
12
|
-
export function createServer({ port }) {
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
export function createServer({ port, testMode = false, startBackgroundJobs = true, persistAccounts = true }) {
|
|
13
|
+
if (!testMode && persistAccounts) {
|
|
14
|
+
ensureAccountsPersist();
|
|
15
|
+
}
|
|
16
|
+
if (!testMode && startBackgroundJobs) {
|
|
17
|
+
startAutoRefresh();
|
|
18
|
+
}
|
|
15
19
|
|
|
16
20
|
const app = express();
|
|
17
21
|
app.disable('x-powered-by');
|
|
@@ -21,7 +25,8 @@ export function createServer({ port }) {
|
|
|
21
25
|
const start = Date.now();
|
|
22
26
|
res.on('finish', () => {
|
|
23
27
|
const duration = Date.now() - start;
|
|
24
|
-
const
|
|
28
|
+
const safeUrl = req.originalUrl.replace(/([?&](?:api_key|access_token)=)[^&]*/gi, '$1[redacted]');
|
|
29
|
+
const msg = `[${req.method}] ${safeUrl} ${res.statusCode} (${duration}ms)`;
|
|
25
30
|
if (res.statusCode >= 400) {
|
|
26
31
|
console.log(`\x1b[31m${msg}\x1b[0m`); // Red for error
|
|
27
32
|
} else if (req.originalUrl !== '/health') { // Skip health check logs to reduce noise
|
|
@@ -39,7 +44,7 @@ export function createServer({ port }) {
|
|
|
39
44
|
'http://127.0.0.1'
|
|
40
45
|
],
|
|
41
46
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
|
42
|
-
allowedHeaders: ['Content-Type', 'Authorization'],
|
|
47
|
+
allowedHeaders: ['Content-Type', 'Authorization', 'x-api-key'],
|
|
43
48
|
credentials: false
|
|
44
49
|
}));
|
|
45
50
|
app.use(express.json({ limit: process.env.JSON_BODY_LIMIT || '50mb' }));
|