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.
@@ -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
- adminRouter.use(express.static(publicDirectory, { index: false }));
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 and Client Quota ───────────────────────────────────────────────
82
+ // ─── Models ────────────────────────────────────────────────────────────────
104
83
  app.get('/v1/models', requireClientAuth, handleListModels);
105
- app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
106
84
 
107
- adminRouter.use(requireAdminAuth);
85
+ app.use(requireAdminAuth);
108
86
 
109
- adminRouter.get('/accounts/models', handleAccountModels);
110
- adminRouter.get('/accounts/usage', handleAccountUsage);
87
+ app.get('/accounts/models', handleAccountModels);
88
+ app.get('/accounts/usage', handleAccountUsage);
111
89
 
112
90
  // ─── Settings ──────────────────────────────────────────────────────────────
113
- adminRouter.get('/settings/account-strategy', handleGetAccountStrategy);
114
- adminRouter.post('/settings/account-strategy', handleSetAccountStrategy);
115
- adminRouter.get('/settings/model-map', handleGetModelMap);
116
- adminRouter.post('/settings/model-map', handleSetModelMap);
117
- adminRouter.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
118
- adminRouter.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
119
- adminRouter.get('/settings/client-api-keys', handleListClientApiKeys);
120
- adminRouter.post('/settings/client-api-keys', handleCreateClientApiKey);
121
- adminRouter.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
122
- adminRouter.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
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
- adminRouter.get('/accounts', handleListAccounts);
126
- adminRouter.get('/accounts/status', handleAccountStatus);
127
- adminRouter.get('/accounts/quota', handleGetQuota);
128
- adminRouter.get('/accounts/quota/all', handleGetAllQuotas);
129
- adminRouter.get('/accounts/rate-limit-reset-credits', handleGetRateLimitResetCredits);
130
- adminRouter.post('/accounts/rate-limit-reset-credits/consume', handleConsumeRateLimitResetCredit);
131
-
132
- adminRouter.post('/accounts/add', handleAddAccount);
133
- adminRouter.post('/accounts/add/manual', handleAddAccountManual);
134
- adminRouter.post('/accounts/switch', handleSwitchAccount);
135
- adminRouter.post('/accounts/import', handleImportAccount);
136
- adminRouter.post('/accounts/refresh', handleRefreshActiveAccount);
137
- adminRouter.post('/accounts/refresh/all', handleRefreshAllAccounts);
138
- adminRouter.post('/accounts/oauth/cleanup', handleOAuthCleanup);
139
- adminRouter.post('/accounts/:email/refresh', handleRefreshAccount);
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
- adminRouter.get('/claude/config', handleGetClaudeConfig);
145
- adminRouter.post('/claude/config/direct', handleSetDirectMode);
146
- adminRouter.post('/claude/config/set', handleSetClaudeApiEndpoint);
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
- adminRouter.get('/api/logs', handleGetLogs);
150
- adminRouter.get('/api/logs/stream', handleStreamLogs);
125
+ app.get('/api/logs', handleGetLogs);
126
+ app.get('/api/logs/stream', handleStreamLogs);
151
127
  }
152
128
 
153
129
  export default { registerApiRoutes };
@@ -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 { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
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
- if (shouldLogRawProxyPayloads()) {
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: configureCommands,
76
- powershell: configureCommands,
77
- clear: {
78
- bash: clearCommands,
79
- powershell: clearCommands
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 });
@@ -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 a newest-first page of in-memory log history.
12
+ * Returns the in-memory log history as JSON.
21
13
  */
22
14
  export function handleGetLogs(req, res) {
23
- const page = parsePositiveInteger(req.query.page, 1);
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 (shouldLogRawProxyPayloads()) {
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, req.clientApiKey?.id);
100
+ await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
104
101
  } else {
105
- await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
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, clientKeyId) {
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, clientKeyId) {
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 = '', weeklyLimitUsd = DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } = req.body || {};
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, weeklyLimitUsd } = req.body || {};
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
 
@@ -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
  };
@@ -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>