claude-codex-proxy 1.0.5-beta.12 → 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 -108
- package/src/account-rotation/rate-limits.js +26 -0
- 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/model-api.js +0 -60
- package/src/response-streamer.js +5 -5
- package/src/routes/accounts-route.js +1 -78
- package/src/routes/api-routes.js +35 -59
- 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 +6 -30
- 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 -196
- package/public/views/accounts.html +0 -183
- 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/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,
|
|
@@ -46,8 +43,6 @@ import {
|
|
|
46
43
|
handleRemoveAccount,
|
|
47
44
|
handleImportAccount,
|
|
48
45
|
handleGetQuota,
|
|
49
|
-
handleGetRateLimitResetCredits,
|
|
50
|
-
handleConsumeRateLimitResetCredit,
|
|
51
46
|
handleGetAllQuotas
|
|
52
47
|
} from './accounts-route.js';
|
|
53
48
|
|
|
@@ -56,24 +51,8 @@ const require = createRequire(import.meta.url);
|
|
|
56
51
|
const packageJson = require('../../package.json');
|
|
57
52
|
|
|
58
53
|
export function registerApiRoutes(app, { port }) {
|
|
59
|
-
const adminPath = getAdminPath();
|
|
60
|
-
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
61
|
-
const adminRouter = express.Router();
|
|
62
|
-
const sendAdminHtml = (fileName) => {
|
|
63
|
-
const html = readFileSync(join(publicDirectory, fileName), 'utf8')
|
|
64
|
-
.replace(/(href|src)="\//g, `$1="${adminPath}/`)
|
|
65
|
-
.replace('</head>', `<script>window.__PROXY_ADMIN_PATH__=${JSON.stringify(adminPath)};</script></head>`);
|
|
66
|
-
return (req, res) => res.type('html').send(html);
|
|
67
|
-
};
|
|
68
|
-
|
|
69
54
|
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
adminRouter.get(['/', '/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], sendAdminHtml('index.html'));
|
|
73
|
-
|
|
74
|
-
adminRouter.get('/login', sendAdminHtml('login.html'));
|
|
75
|
-
|
|
76
|
-
app.use(adminPath, adminRouter);
|
|
55
|
+
app.use(express.static(join(__dirname, '..', '..', 'public')));
|
|
77
56
|
|
|
78
57
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
79
58
|
app.get('/health', (req, res) => {
|
|
@@ -100,54 +79,51 @@ export function registerApiRoutes(app, { port }) {
|
|
|
100
79
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
101
80
|
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
102
81
|
|
|
103
|
-
// ─── Models
|
|
82
|
+
// ─── Models ────────────────────────────────────────────────────────────────
|
|
104
83
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
105
|
-
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
106
84
|
|
|
107
|
-
|
|
85
|
+
app.use(requireAdminAuth);
|
|
108
86
|
|
|
109
|
-
|
|
110
|
-
|
|
87
|
+
app.get('/accounts/models', handleAccountModels);
|
|
88
|
+
app.get('/accounts/usage', handleAccountUsage);
|
|
111
89
|
|
|
112
90
|
// ─── Settings ──────────────────────────────────────────────────────────────
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
91
|
+
app.get('/settings/account-strategy', handleGetAccountStrategy);
|
|
92
|
+
app.post('/settings/account-strategy', handleSetAccountStrategy);
|
|
93
|
+
app.get('/settings/model-map', handleGetModelMap);
|
|
94
|
+
app.post('/settings/model-map', handleSetModelMap);
|
|
95
|
+
app.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
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);
|
|
123
101
|
|
|
124
102
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
adminRouter.delete('/accounts/:email', handleRemoveAccount);
|
|
103
|
+
app.get('/accounts', handleListAccounts);
|
|
104
|
+
app.get('/accounts/status', handleAccountStatus);
|
|
105
|
+
app.get('/accounts/quota', handleGetQuota);
|
|
106
|
+
app.get('/accounts/quota/all', handleGetAllQuotas);
|
|
107
|
+
|
|
108
|
+
app.post('/accounts/add', handleAddAccount);
|
|
109
|
+
app.post('/accounts/add/manual', handleAddAccountManual);
|
|
110
|
+
app.post('/accounts/switch', handleSwitchAccount);
|
|
111
|
+
app.post('/accounts/import', handleImportAccount);
|
|
112
|
+
app.post('/accounts/refresh', handleRefreshActiveAccount);
|
|
113
|
+
app.post('/accounts/refresh/all', handleRefreshAllAccounts);
|
|
114
|
+
app.post('/accounts/oauth/cleanup', handleOAuthCleanup);
|
|
115
|
+
app.post('/accounts/:email/refresh', handleRefreshAccount);
|
|
116
|
+
|
|
117
|
+
app.delete('/accounts/:email', handleRemoveAccount);
|
|
142
118
|
|
|
143
119
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
120
|
+
app.get('/claude/config', handleGetClaudeConfig);
|
|
121
|
+
app.post('/claude/config/direct', handleSetDirectMode);
|
|
122
|
+
app.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
147
123
|
|
|
148
124
|
// ─── Logs ──────────────────────────────────────────────────────────────────
|
|
149
|
-
|
|
150
|
-
|
|
125
|
+
app.get('/api/logs', handleGetLogs);
|
|
126
|
+
app.get('/api/logs/stream', handleStreamLogs);
|
|
151
127
|
}
|
|
152
128
|
|
|
153
129
|
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,15 @@ 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
|
+
`claude config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
64
|
+
`claude config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`
|
|
65
|
+
],
|
|
66
|
+
powershell: [
|
|
67
|
+
`claude config set env.ANTHROPIC_BASE_URL ${proxyUrl}`,
|
|
68
|
+
`claude config set env.ANTHROPIC_API_KEY ${apiKeyPlaceholder}`
|
|
69
|
+
]
|
|
81
70
|
};
|
|
82
71
|
|
|
83
72
|
res.json({
|
|
@@ -86,10 +75,14 @@ export async function handleSetProxyMode(req, res, { port }) {
|
|
|
86
75
|
message: 'Claude CLI config was not modified. Run the returned commands on the client machine that uses Claude Code.',
|
|
87
76
|
env: {
|
|
88
77
|
ANTHROPIC_BASE_URL: proxyUrl,
|
|
89
|
-
ANTHROPIC_API_KEY: apiKeyPlaceholder
|
|
90
|
-
CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
|
|
78
|
+
ANTHROPIC_API_KEY: apiKeyPlaceholder
|
|
91
79
|
},
|
|
92
|
-
commands
|
|
80
|
+
commands,
|
|
81
|
+
models: {
|
|
82
|
+
opus: 'claude-opus',
|
|
83
|
+
sonnet: 'claude-sonnet',
|
|
84
|
+
haiku: 'claude-haiku'
|
|
85
|
+
}
|
|
93
86
|
});
|
|
94
87
|
} catch (error) {
|
|
95
88
|
res.status(500).json({ success: false, error: error.message });
|
package/src/routes/logs-route.js
CHANGED
|
@@ -7,31 +7,12 @@
|
|
|
7
7
|
|
|
8
8
|
import { logger } from '../utils/logger.js';
|
|
9
9
|
|
|
10
|
-
const LOGS_PER_PAGE = 30;
|
|
11
|
-
const MAX_PAGE_SIZE = 100;
|
|
12
|
-
|
|
13
|
-
function parsePositiveInteger(value, fallback, maximum = Number.MAX_SAFE_INTEGER) {
|
|
14
|
-
const parsed = Number.parseInt(value, 10);
|
|
15
|
-
return Number.isInteger(parsed) && parsed > 0 ? Math.min(parsed, maximum) : fallback;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
10
|
/**
|
|
19
11
|
* GET /api/logs
|
|
20
|
-
* Returns
|
|
12
|
+
* Returns the in-memory log history as JSON.
|
|
21
13
|
*/
|
|
22
14
|
export function handleGetLogs(req, res) {
|
|
23
|
-
|
|
24
|
-
const pageSize = parsePositiveInteger(req.query.pageSize, LOGS_PER_PAGE, MAX_PAGE_SIZE);
|
|
25
|
-
const { logs, total } = logger.getHistoryPage(page, pageSize);
|
|
26
|
-
|
|
27
|
-
res.json({
|
|
28
|
-
status: 'ok',
|
|
29
|
-
logs,
|
|
30
|
-
page,
|
|
31
|
-
pageSize,
|
|
32
|
-
total,
|
|
33
|
-
totalPages: Math.ceil(total / pageSize)
|
|
34
|
-
});
|
|
15
|
+
res.json({ status: 'ok', logs: logger.getHistory() });
|
|
35
16
|
}
|
|
36
17
|
|
|
37
18
|
/**
|
|
@@ -6,9 +6,6 @@ import { logger } from '../utils/logger.js';
|
|
|
6
6
|
import { AccountRotator } from '../account-rotation/index.js';
|
|
7
7
|
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
|
|
8
8
|
import { getServerSettings } from '../server-settings.js';
|
|
9
|
-
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
10
|
-
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
11
|
-
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
12
9
|
|
|
13
10
|
const MAX_RETRIES = 5;
|
|
14
11
|
const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
@@ -53,10 +50,10 @@ export async function handleMessages(req, res) {
|
|
|
53
50
|
const startTime = Date.now();
|
|
54
51
|
const body = req.body;
|
|
55
52
|
const settings = getServerSettings();
|
|
56
|
-
if (
|
|
53
|
+
if (settings.logRawProxyPayloads === true) {
|
|
57
54
|
logger.info('[Claude Request]', body);
|
|
58
55
|
}
|
|
59
|
-
const requestedModel = body.model;
|
|
56
|
+
const requestedModel = body.model || 'gpt-5.2';
|
|
60
57
|
const isStreaming = body.stream !== false;
|
|
61
58
|
|
|
62
59
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
@@ -100,9 +97,9 @@ export async function handleMessages(req, res) {
|
|
|
100
97
|
|
|
101
98
|
try {
|
|
102
99
|
if (isStreaming) {
|
|
103
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
100
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
104
101
|
} else {
|
|
105
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext
|
|
102
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
106
103
|
}
|
|
107
104
|
rotator.notifySuccess(account, upstreamModel);
|
|
108
105
|
return;
|
|
@@ -137,41 +134,20 @@ export async function handleMessages(req, res) {
|
|
|
137
134
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
138
135
|
}
|
|
139
136
|
|
|
140
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
137
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
141
138
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
142
139
|
initSSEResponse(res);
|
|
143
140
|
const usage = await pipeSSEStream(res, stream);
|
|
144
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
145
141
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
146
142
|
}
|
|
147
143
|
|
|
148
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext
|
|
144
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
149
145
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
150
|
-
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
151
146
|
const duration = Date.now() - startTime;
|
|
152
147
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
153
148
|
res.json({ ...response, model: responseModel });
|
|
154
149
|
}
|
|
155
150
|
|
|
156
|
-
function recordRequestUsage(clientKeyId, model, usage) {
|
|
157
|
-
if (!clientKeyId) return;
|
|
158
|
-
|
|
159
|
-
const costMicrousd = calculateUsageCostMicrousd(model, {
|
|
160
|
-
...usage,
|
|
161
|
-
cache_read_input_tokens: usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens,
|
|
162
|
-
input_tokens_details: {
|
|
163
|
-
...(usage?.input_tokens_details || {}),
|
|
164
|
-
cache_write_tokens: usage?.upstreamCacheWriteInputTokens ?? usage?.input_tokens_details?.cache_write_tokens
|
|
165
|
-
}
|
|
166
|
-
});
|
|
167
|
-
if (costMicrousd === null) {
|
|
168
|
-
logger.warn(`[ClientKeyQuota] No pricing configured for ${model}; usage was not charged`);
|
|
169
|
-
return;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
recordClientKeyUsage(clientKeyId, costMicrousd);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
151
|
function syncActiveAccount(email) {
|
|
176
152
|
const active = getActiveAccount();
|
|
177
153
|
if (active?.email === email) return;
|
|
@@ -10,30 +10,13 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import crypto from 'crypto';
|
|
13
|
-
import {
|
|
14
|
-
getServerSettings,
|
|
15
|
-
setServerSettings,
|
|
16
|
-
DEFAULT_MODEL_MAP,
|
|
17
|
-
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
18
|
-
} from '../server-settings.js';
|
|
19
|
-
import { deleteClientKeyUsage, getClientKeyQuota } from '../client-key-usage.js';
|
|
13
|
+
import { getServerSettings, setServerSettings, DEFAULT_MODEL_MAP } from '../server-settings.js';
|
|
20
14
|
|
|
21
15
|
const VALID_STRATEGIES = ['sticky', 'round-robin'];
|
|
22
16
|
|
|
23
17
|
function getSafeClientApiKey(clientApiKey) {
|
|
24
18
|
const { key, ...safeClientApiKey } = clientApiKey;
|
|
25
|
-
return
|
|
26
|
-
...safeClientApiKey,
|
|
27
|
-
quota: getClientKeyQuota(clientApiKey.id, clientApiKey.weeklyLimitUsd)
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function validateWeeklyLimitUsd(weeklyLimitUsd) {
|
|
32
|
-
if (typeof weeklyLimitUsd !== 'number' || !Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) {
|
|
33
|
-
return 'weeklyLimitUsd must be a non-negative number';
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return null;
|
|
19
|
+
return safeClientApiKey;
|
|
37
20
|
}
|
|
38
21
|
|
|
39
22
|
function createClientApiKeyValue() {
|
|
@@ -185,23 +168,17 @@ export function handleListClientApiKeys(req, res) {
|
|
|
185
168
|
* Creates a Claude Code client API key.
|
|
186
169
|
*/
|
|
187
170
|
export function handleCreateClientApiKey(req, res) {
|
|
188
|
-
const { name = '', remark = ''
|
|
171
|
+
const { name = '', remark = '' } = req.body || {};
|
|
189
172
|
|
|
190
173
|
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
191
174
|
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
192
175
|
}
|
|
193
176
|
|
|
194
|
-
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
195
|
-
if (weeklyLimitError) {
|
|
196
|
-
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
197
|
-
}
|
|
198
|
-
|
|
199
177
|
const clientApiKey = {
|
|
200
178
|
id: crypto.randomUUID(),
|
|
201
179
|
key: createClientApiKeyValue(),
|
|
202
180
|
name: name.trim(),
|
|
203
181
|
remark: remark.trim(),
|
|
204
|
-
weeklyLimitUsd,
|
|
205
182
|
createdAt: new Date().toISOString()
|
|
206
183
|
};
|
|
207
184
|
const settings = getServerSettings();
|
|
@@ -216,7 +193,7 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
216
193
|
*/
|
|
217
194
|
export function handleUpdateClientApiKey(req, res) {
|
|
218
195
|
const { id } = req.params;
|
|
219
|
-
const { name, remark
|
|
196
|
+
const { name, remark } = req.body || {};
|
|
220
197
|
|
|
221
198
|
if (name !== undefined && typeof name !== 'string') {
|
|
222
199
|
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
@@ -224,12 +201,6 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
224
201
|
if (remark !== undefined && typeof remark !== 'string') {
|
|
225
202
|
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
226
203
|
}
|
|
227
|
-
if (weeklyLimitUsd !== undefined) {
|
|
228
|
-
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
229
|
-
if (weeklyLimitError) {
|
|
230
|
-
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
204
|
|
|
234
205
|
const settings = getServerSettings();
|
|
235
206
|
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
@@ -241,8 +212,7 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
241
212
|
const clientApiKey = {
|
|
242
213
|
...current,
|
|
243
214
|
...(name === undefined ? {} : { name: name.trim() }),
|
|
244
|
-
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
245
|
-
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
|
|
215
|
+
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
246
216
|
};
|
|
247
217
|
const clientApiKeys = [...settings.clientApiKeys];
|
|
248
218
|
clientApiKeys[index] = clientApiKey;
|
|
@@ -265,7 +235,6 @@ export function handleDeleteClientApiKey(req, res) {
|
|
|
265
235
|
}
|
|
266
236
|
|
|
267
237
|
setServerSettings({ clientApiKeys });
|
|
268
|
-
deleteClientKeyUsage(id);
|
|
269
238
|
res.json({ success: true });
|
|
270
239
|
}
|
|
271
240
|
|
package/src/server-settings.js
CHANGED
|
@@ -10,8 +10,6 @@ export const DEFAULT_MODEL_MAP = {
|
|
|
10
10
|
haiku: 'gpt-5.4-mini'
|
|
11
11
|
};
|
|
12
12
|
|
|
13
|
-
export const DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD = 50;
|
|
14
|
-
|
|
15
13
|
export const DEFAULT_SETTINGS = {
|
|
16
14
|
accountStrategy: 'sticky',
|
|
17
15
|
defaultCodexModel: 'gpt-5.5',
|
|
@@ -26,16 +24,6 @@ function ensureConfigDir() {
|
|
|
26
24
|
}
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
function normalizeClientApiKey(clientApiKey) {
|
|
30
|
-
const weeklyLimitUsd = Number(clientApiKey?.weeklyLimitUsd);
|
|
31
|
-
return {
|
|
32
|
-
...clientApiKey,
|
|
33
|
-
weeklyLimitUsd: Number.isFinite(weeklyLimitUsd) && weeklyLimitUsd >= 0
|
|
34
|
-
? weeklyLimitUsd
|
|
35
|
-
: DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
27
|
function mergeSettings(data = {}) {
|
|
40
28
|
return {
|
|
41
29
|
...DEFAULT_SETTINGS,
|
|
@@ -43,10 +31,7 @@ function mergeSettings(data = {}) {
|
|
|
43
31
|
modelMap: {
|
|
44
32
|
...DEFAULT_MODEL_MAP,
|
|
45
33
|
...(data.modelMap || {})
|
|
46
|
-
}
|
|
47
|
-
clientApiKeys: Array.isArray(data.clientApiKeys)
|
|
48
|
-
? data.clientApiKeys.map(normalizeClientApiKey)
|
|
49
|
-
: []
|
|
34
|
+
}
|
|
50
35
|
};
|
|
51
36
|
}
|
|
52
37
|
|
|
@@ -80,6 +65,5 @@ export default {
|
|
|
80
65
|
setServerSettings,
|
|
81
66
|
SETTINGS_FILE,
|
|
82
67
|
DEFAULT_SETTINGS,
|
|
83
|
-
DEFAULT_MODEL_MAP
|
|
84
|
-
DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
68
|
+
DEFAULT_MODEL_MAP
|
|
85
69
|
};
|
package/src/utils/logger.js
CHANGED
|
@@ -40,24 +40,6 @@ class Logger extends EventEmitter {
|
|
|
40
40
|
return [...this.history];
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
/**
|
|
44
|
-
* Returns a newest-first page of in-memory log entries.
|
|
45
|
-
*
|
|
46
|
-
* @param {number} page - One-based page number.
|
|
47
|
-
* @param {number} pageSize - Maximum number of entries per page.
|
|
48
|
-
* @returns {{ logs: object[], total: number }} Requested page and total entry count.
|
|
49
|
-
*/
|
|
50
|
-
getHistoryPage(page, pageSize) {
|
|
51
|
-
const total = this.history.length;
|
|
52
|
-
const end = Math.max(0, total - (page - 1) * pageSize);
|
|
53
|
-
const start = Math.max(0, end - pageSize);
|
|
54
|
-
|
|
55
|
-
return {
|
|
56
|
-
logs: this.history.slice(start, end).reverse(),
|
|
57
|
-
total
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
|
|
61
43
|
clear() {
|
|
62
44
|
this.history = [];
|
|
63
45
|
}
|
package/public/login.html
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
<!DOCTYPE html>
|
|
2
|
-
<html lang="en" data-theme="codex" class="dark">
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="UTF-8">
|
|
5
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
|
-
<title>Sign in · Claude Codex Proxy</title>
|
|
7
|
-
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
|
|
8
|
-
<link rel="stylesheet" href="/css/style.css">
|
|
9
|
-
</head>
|
|
10
|
-
<body class="bg-space-950 text-gray-300 font-sans antialiased min-h-screen" x-data="app" x-init="init()">
|
|
11
|
-
<main x-cloak x-show="authChecked" class="min-h-screen flex items-center justify-center px-4">
|
|
12
|
-
<div class="w-full max-w-md bg-space-900/70 border border-space-border rounded-2xl p-6 shadow-2xl backdrop-blur-md">
|
|
13
|
-
<div class="flex items-center gap-3 mb-6">
|
|
14
|
-
<div class="w-10 h-10 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
|
|
15
|
-
<div>
|
|
16
|
-
<h1 class="text-xl font-bold text-white">Access Required</h1>
|
|
17
|
-
<p class="text-sm text-gray-500">Enter the server access key to open the management UI.</p>
|
|
18
|
-
</div>
|
|
19
|
-
</div>
|
|
20
|
-
<form @submit.prevent="login" class="space-y-4">
|
|
21
|
-
<label class="form-control w-full">
|
|
22
|
-
<span class="label-text text-gray-400 mb-1">Access Key</span>
|
|
23
|
-
<input type="password" x-model="loginApiKey" class="input input-bordered w-full bg-space-950 border-space-border text-white" placeholder="Enter access key" autocomplete="current-password" autofocus>
|
|
24
|
-
</label>
|
|
25
|
-
<p x-show="loginError" x-text="loginError" class="text-sm text-red-400"></p>
|
|
26
|
-
<button type="submit" class="btn w-full bg-neon-purple hover:bg-purple-600 border-0 text-white">Unlock UI</button>
|
|
27
|
-
</form>
|
|
28
|
-
</div>
|
|
29
|
-
</main>
|
|
30
|
-
<script src="/js/app.js"></script>
|
|
31
|
-
</body>
|
|
32
|
-
</html>
|