claude-codex-proxy 1.0.4 → 1.0.5-beta.1

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.
@@ -9,11 +9,32 @@
9
9
 
10
10
  import {
11
11
  readClaudeConfig,
12
- setProxyMode,
13
12
  setDirectMode,
14
13
  setApiEndpoint,
15
14
  getClaudeConfigPath
16
15
  } from '../claude-config.js';
16
+ import { getLocalBaseUrl } from '../deployment.js';
17
+
18
+ /**
19
+ * Resolves the proxy URL shown to users without writing local config files.
20
+ * @param {object} req
21
+ * @param {number|string} port
22
+ * @returns {string}
23
+ */
24
+ function getProxyConfigBaseUrl(req, port) {
25
+ if (process.env.PROXY_PUBLIC_BASE_URL) {
26
+ return process.env.PROXY_PUBLIC_BASE_URL.replace(/\/$/, '');
27
+ }
28
+
29
+ const host = req.get?.('host');
30
+ if (host) {
31
+ const forwardedProto = req.get?.('x-forwarded-proto')?.split(',')[0]?.trim();
32
+ const protocol = forwardedProto || req.protocol || 'http';
33
+ return `${protocol}://${host}`;
34
+ }
35
+
36
+ return getLocalBaseUrl(port);
37
+ }
17
38
 
18
39
  /**
19
40
  * GET /claude/config
@@ -31,21 +52,37 @@ export async function handleGetClaudeConfig(req, res) {
31
52
 
32
53
  /**
33
54
  * POST /claude/config/proxy
34
- * Configures Claude CLI to use this proxy server.
55
+ * Returns commands for configuring the caller's Claude CLI without mutating server files.
35
56
  */
36
57
  export async function handleSetProxyMode(req, res, { port }) {
37
58
  try {
38
- const proxyUrl = `http://localhost:${port}`;
39
- const models = {
40
- opus: 'claude-opus',
41
- sonnet: 'claude-sonnet',
42
- haiku: 'claude-haiku'
59
+ const proxyUrl = getProxyConfigBaseUrl(req, port);
60
+ const apiKeyPlaceholder = '<client-api-key>';
61
+ const commands = {
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
+ ]
43
70
  };
44
- const config = await setProxyMode(proxyUrl, models);
71
+
45
72
  res.json({
46
73
  success: true,
47
- message: `Claude CLI configured to use proxy at ${proxyUrl}`,
48
- config
74
+ mode: 'dry_run',
75
+ message: 'Claude CLI config was not modified. Run the returned commands on the client machine that uses Claude Code.',
76
+ env: {
77
+ ANTHROPIC_BASE_URL: proxyUrl,
78
+ ANTHROPIC_API_KEY: apiKeyPlaceholder
79
+ },
80
+ commands,
81
+ models: {
82
+ opus: 'claude-opus',
83
+ sonnet: 'claude-sonnet',
84
+ haiku: 'claude-haiku'
85
+ }
49
86
  });
50
87
  } catch (error) {
51
88
  res.status(500).json({ success: false, error: error.message });
@@ -161,7 +161,7 @@ function syncActiveAccount(email) {
161
161
  function getTokenDetails(usage = {}) {
162
162
  const inputTokens = usage?.input_tokens || 0;
163
163
  const outputTokens = usage?.output_tokens || 0;
164
- const cacheReadInputTokens = usage?.cache_read_input_tokens || 0;
164
+ const cacheReadInputTokens = usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens ?? 0;
165
165
  return {
166
166
  tokens: inputTokens + outputTokens,
167
167
  inputTokens,
@@ -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
  };
@@ -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() {
package/src/server.js CHANGED
@@ -7,11 +7,14 @@ import express from 'express';
7
7
  import cors from 'cors';
8
8
 
9
9
  import { ensureAccountsPersist, startAutoRefresh } from './account-manager.js';
10
+ import { getServerHost } from './deployment.js';
10
11
  import { registerApiRoutes } from './routes/api-routes.js';
11
12
 
12
- export function createServer({ port, testMode = false }) {
13
- if (!testMode) {
13
+ export function createServer({ port, testMode = false, startBackgroundJobs = true, persistAccounts = true }) {
14
+ if (!testMode && persistAccounts) {
14
15
  ensureAccountsPersist();
16
+ }
17
+ if (!testMode && startBackgroundJobs) {
15
18
  startAutoRefresh();
16
19
  }
17
20
 
@@ -23,7 +26,8 @@ export function createServer({ port, testMode = false }) {
23
26
  const start = Date.now();
24
27
  res.on('finish', () => {
25
28
  const duration = Date.now() - start;
26
- const msg = `[${req.method}] ${req.originalUrl} ${res.statusCode} (${duration}ms)`;
29
+ const safeUrl = req.originalUrl.replace(/([?&](?:api_key|access_token)=)[^&]*/gi, '$1[redacted]');
30
+ const msg = `[${req.method}] ${safeUrl} ${res.statusCode} (${duration}ms)`;
27
31
  if (res.statusCode >= 400) {
28
32
  console.log(`\x1b[31m${msg}\x1b[0m`); // Red for error
29
33
  } else if (req.originalUrl !== '/health') { // Skip health check logs to reduce noise
@@ -41,7 +45,7 @@ export function createServer({ port, testMode = false }) {
41
45
  'http://127.0.0.1'
42
46
  ],
43
47
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
44
- allowedHeaders: ['Content-Type', 'Authorization'],
48
+ allowedHeaders: ['Content-Type', 'Authorization', 'x-api-key'],
45
49
  credentials: false
46
50
  }));
47
51
  app.use(express.json({ limit: process.env.JSON_BODY_LIMIT || '50mb' }));
@@ -51,9 +55,9 @@ export function createServer({ port, testMode = false }) {
51
55
  return app;
52
56
  }
53
57
 
54
- export function startServer({ port }) {
58
+ export function startServer({ port, host = getServerHost() }) {
55
59
  const app = createServer({ port });
56
- return app.listen(port);
60
+ return app.listen(port, host);
57
61
  }
58
62
 
59
63
  export default { createServer, startServer };