claude-codex-proxy 1.0.5-beta.0 → 1.0.5-beta.10
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 +16 -0
- package/bin/cli.js +30 -2
- package/package.json +1 -1
- package/public/css/style.css +210 -9
- package/public/index.html +32 -926
- package/public/js/app.js +98 -744
- package/public/login.html +32 -0
- package/public/views/accounts-modals.html +159 -0
- package/public/views/accounts.html +183 -0
- package/public/views/client-api-keys-modals.html +55 -0
- package/public/views/client-api-keys.html +69 -0
- package/public/views/dashboard.html +90 -0
- package/public/views/empty.html +0 -0
- package/public/views/logs.html +99 -0
- package/public/views/settings.html +123 -0
- package/src/account-rotation/rate-limits.js +0 -26
- package/src/claude-config.js +0 -18
- package/src/client-key-usage.js +125 -0
- package/src/deployment.js +49 -0
- package/src/direct-api.js +12 -13
- package/src/index.js +20 -8
- package/src/middleware/auth.js +49 -15
- package/src/model-pricing.js +96 -0
- package/src/response-streamer.js +5 -5
- package/src/routes/api-routes.js +13 -2
- package/src/routes/chat-route.js +25 -4
- package/src/routes/claude-config-route.js +53 -26
- package/src/routes/client-quota-route.js +25 -0
- package/src/routes/logs-route.js +21 -2
- package/src/routes/messages-route.js +30 -6
- package/src/routes/settings-route.js +36 -5
- package/src/server-settings.js +18 -2
- package/src/server.js +3 -2
- package/src/utils/logger.js +18 -0
- package/src/utils/proxy-logging.js +5 -0
package/src/middleware/auth.js
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
return process.env.PROXY_DEPLOYMENT_MODE === 'public';
|
|
6
|
-
}
|
|
2
|
+
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
+
import { getServerSettings, DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
4
|
+
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
7
5
|
|
|
8
6
|
function timingSafeEqualString(a, b) {
|
|
9
7
|
const left = Buffer.from(String(a));
|
|
@@ -47,10 +45,8 @@ function sendUnauthorized(req, res) {
|
|
|
47
45
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
48
46
|
}
|
|
49
47
|
|
|
50
|
-
function
|
|
51
|
-
return
|
|
52
|
-
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
53
|
-
));
|
|
48
|
+
function matchesKey(requestKey, expectedKey) {
|
|
49
|
+
return expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey);
|
|
54
50
|
}
|
|
55
51
|
|
|
56
52
|
function requireKeys(getExpectedKeys) {
|
|
@@ -61,7 +57,7 @@ function requireKeys(getExpectedKeys) {
|
|
|
61
57
|
|
|
62
58
|
const expectedKeys = getExpectedKeys();
|
|
63
59
|
const requestKey = getRequestApiKey(req);
|
|
64
|
-
if (!
|
|
60
|
+
if (!expectedKeys.some((expectedKey) => matchesKey(requestKey, expectedKey))) {
|
|
65
61
|
return sendUnauthorized(req, res);
|
|
66
62
|
}
|
|
67
63
|
|
|
@@ -69,13 +65,51 @@ function requireKeys(getExpectedKeys) {
|
|
|
69
65
|
};
|
|
70
66
|
}
|
|
71
67
|
|
|
68
|
+
function sendQuotaExceeded(res, quota) {
|
|
69
|
+
return res.status(429).json({
|
|
70
|
+
type: 'error',
|
|
71
|
+
error: {
|
|
72
|
+
type: 'rate_limit_error',
|
|
73
|
+
message: `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function findClientKey(requestKey) {
|
|
79
|
+
return getServerSettings().clientApiKeys.find(({ key }) => matchesKey(requestKey, key));
|
|
80
|
+
}
|
|
81
|
+
|
|
72
82
|
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
83
|
|
|
78
84
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
79
|
-
|
|
85
|
+
|
|
86
|
+
export function requireClientAuth(req, res, next) {
|
|
87
|
+
const requestKey = getRequestApiKey(req);
|
|
88
|
+
const clientKey = findClientKey(requestKey);
|
|
89
|
+
if (isPublicDeployment() && !clientKey) {
|
|
90
|
+
return sendUnauthorized(req, res);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (!clientKey) {
|
|
94
|
+
return next();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const quota = getClientKeyQuota(
|
|
98
|
+
clientKey.id,
|
|
99
|
+
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
100
|
+
);
|
|
101
|
+
const isModelRequest = req.method === 'POST' && (
|
|
102
|
+
req.path === '/v1/messages' || req.path === '/v1/chat/completions'
|
|
103
|
+
);
|
|
104
|
+
if (isModelRequest && quota.remainingMicrousd <= 0) {
|
|
105
|
+
return sendQuotaExceeded(res, quota);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
req.clientApiKey = { id: clientKey.id, name: clientKey.name };
|
|
109
|
+
req.clientApiKeyQuota = quota;
|
|
110
|
+
return next();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export { isPublicDeployment };
|
|
80
114
|
|
|
81
115
|
export default { isPublicDeployment, requireAdminAuth, requireClientAuth };
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Upstream Codex model pricing in USD per one million tokens.
|
|
3
|
+
* Long-context pricing applies when input tokens exceed 272,000.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const PRICE_UNIT_TOKENS = 1_000_000;
|
|
7
|
+
export const LONG_CONTEXT_THRESHOLD_TOKENS = 272_000;
|
|
8
|
+
|
|
9
|
+
const STANDARD_PRICING = {
|
|
10
|
+
'gpt-5.6-sol': {
|
|
11
|
+
input: 5,
|
|
12
|
+
cachedInput: 0.5,
|
|
13
|
+
cacheWrite: 6.25,
|
|
14
|
+
output: 30
|
|
15
|
+
},
|
|
16
|
+
'gpt-5.6-terra': {
|
|
17
|
+
input: 2.5,
|
|
18
|
+
cachedInput: 0.25,
|
|
19
|
+
cacheWrite: 3.125,
|
|
20
|
+
output: 15
|
|
21
|
+
},
|
|
22
|
+
'gpt-5.4-mini': {
|
|
23
|
+
input: 0.75,
|
|
24
|
+
cachedInput: 0.075,
|
|
25
|
+
cacheWrite: 0,
|
|
26
|
+
output: 4.5
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const LONG_CONTEXT_PRICING = {
|
|
31
|
+
'gpt-5.6-sol': {
|
|
32
|
+
input: 10,
|
|
33
|
+
cachedInput: 1,
|
|
34
|
+
cacheWrite: 12.5,
|
|
35
|
+
output: 45
|
|
36
|
+
},
|
|
37
|
+
'gpt-5.6-terra': {
|
|
38
|
+
input: 5,
|
|
39
|
+
cachedInput: 0.5,
|
|
40
|
+
cacheWrite: 6.25,
|
|
41
|
+
output: 22.5
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Returns the applicable USD-per-million-token price record for an upstream
|
|
47
|
+
* model. Models without a configured price return null.
|
|
48
|
+
*/
|
|
49
|
+
export function getModelPricing(model, inputTokens = 0) {
|
|
50
|
+
const normalizedModel = String(model || '').toLowerCase();
|
|
51
|
+
const standard = STANDARD_PRICING[normalizedModel];
|
|
52
|
+
if (!standard) return null;
|
|
53
|
+
|
|
54
|
+
const usesLongContext = Number(inputTokens) > LONG_CONTEXT_THRESHOLD_TOKENS;
|
|
55
|
+
const longContext = usesLongContext ? LONG_CONTEXT_PRICING[normalizedModel] : null;
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
...standard,
|
|
59
|
+
...(longContext || {}),
|
|
60
|
+
model: normalizedModel,
|
|
61
|
+
priceUnitTokens: PRICE_UNIT_TOKENS,
|
|
62
|
+
longContext: Boolean(longContext)
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Calculates a request charge from Responses API usage and returns it in
|
|
68
|
+
* integer microdollars. Cached input and cache-write tokens are included in
|
|
69
|
+
* input_tokens, so both are removed from standard input before applying their
|
|
70
|
+
* respective prices.
|
|
71
|
+
*/
|
|
72
|
+
export function calculateUsageCostMicrousd(model, usage = {}) {
|
|
73
|
+
const inputTokens = Math.max(0, Number(usage.input_tokens) || 0);
|
|
74
|
+
const outputTokens = Math.max(0, Number(usage.output_tokens) || 0);
|
|
75
|
+
const cachedInputTokens = Math.min(
|
|
76
|
+
inputTokens,
|
|
77
|
+
Math.max(0, Number(usage.cache_read_input_tokens ?? usage.input_tokens_details?.cached_tokens) || 0)
|
|
78
|
+
);
|
|
79
|
+
const cacheWriteTokens = Math.max(0, Number(usage.input_tokens_details?.cache_write_tokens) || 0);
|
|
80
|
+
const pricing = getModelPricing(model, inputTokens);
|
|
81
|
+
if (!pricing) return null;
|
|
82
|
+
|
|
83
|
+
const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
|
|
84
|
+
const usd = (
|
|
85
|
+
(uncachedInputTokens * pricing.input)
|
|
86
|
+
+ (cachedInputTokens * pricing.cachedInput)
|
|
87
|
+
+ (cacheWriteTokens * pricing.cacheWrite)
|
|
88
|
+
+ (outputTokens * pricing.output)
|
|
89
|
+
) / PRICE_UNIT_TOKENS;
|
|
90
|
+
|
|
91
|
+
return Math.round(usd * 1_000_000);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export { STANDARD_PRICING, LONG_CONTEXT_PRICING };
|
|
95
|
+
|
|
96
|
+
export default { getModelPricing, calculateUsageCostMicrousd };
|
package/src/response-streamer.js
CHANGED
|
@@ -5,15 +5,11 @@
|
|
|
5
5
|
|
|
6
6
|
import { generateMessageId, sanitizeAnthropicToolInputJson, toAnthropicToolId } from './format-converter.js';
|
|
7
7
|
import { cacheSignature, cacheThinkingSignature, SIGNATURE_CONSTANTS } from './signature-cache.js';
|
|
8
|
-
import { getServerSettings } from './server-settings.js';
|
|
9
8
|
import { logger } from './utils/logger.js';
|
|
9
|
+
import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
|
|
10
10
|
|
|
11
11
|
const { MIN_SIGNATURE_LENGTH } = SIGNATURE_CONSTANTS;
|
|
12
12
|
|
|
13
|
-
function shouldLogRawProxyPayloads() {
|
|
14
|
-
return getServerSettings().logRawProxyPayloads === true;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
13
|
export function createResponsesAPIError(message, status = 502) {
|
|
18
14
|
const error = new Error(message);
|
|
19
15
|
error.status = status;
|
|
@@ -117,6 +113,10 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
117
113
|
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
118
114
|
enumerable: false
|
|
119
115
|
});
|
|
116
|
+
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
117
|
+
value: event.response.usage.input_tokens_details?.cache_write_tokens || 0,
|
|
118
|
+
enumerable: false
|
|
119
|
+
});
|
|
120
120
|
}
|
|
121
121
|
|
|
122
122
|
// Handle output item added
|
package/src/routes/api-routes.js
CHANGED
|
@@ -16,6 +16,7 @@ import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../midd
|
|
|
16
16
|
import { handleMessages } from './messages-route.js';
|
|
17
17
|
import { handleChatCompletion, handleCountTokens } from './chat-route.js';
|
|
18
18
|
import { handleListModels, handleAccountModels, handleAccountUsage } from './models-route.js';
|
|
19
|
+
import { handleGetClientQuota } from './client-quota-route.js';
|
|
19
20
|
import {
|
|
20
21
|
handleGetAccountStrategy,
|
|
21
22
|
handleSetAccountStrategy,
|
|
@@ -52,7 +53,16 @@ const packageJson = require('../../package.json');
|
|
|
52
53
|
|
|
53
54
|
export function registerApiRoutes(app, { port }) {
|
|
54
55
|
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
55
|
-
|
|
56
|
+
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
57
|
+
app.use(express.static(publicDirectory));
|
|
58
|
+
|
|
59
|
+
app.get(['/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], (req, res) => {
|
|
60
|
+
res.sendFile(join(publicDirectory, 'index.html'));
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
app.get('/login', (req, res) => {
|
|
64
|
+
res.sendFile(join(publicDirectory, 'login.html'));
|
|
65
|
+
});
|
|
56
66
|
|
|
57
67
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
58
68
|
app.get('/health', (req, res) => {
|
|
@@ -79,8 +89,9 @@ export function registerApiRoutes(app, { port }) {
|
|
|
79
89
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
80
90
|
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
81
91
|
|
|
82
|
-
// ─── Models
|
|
92
|
+
// ─── Models and Client Quota ───────────────────────────────────────────────
|
|
83
93
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
94
|
+
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
84
95
|
|
|
85
96
|
app.use(requireAdminAuth);
|
|
86
97
|
|
package/src/routes/chat-route.js
CHANGED
|
@@ -9,7 +9,9 @@ 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 {
|
|
12
|
+
import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
|
|
13
|
+
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
14
|
+
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
13
15
|
|
|
14
16
|
/**
|
|
15
17
|
* POST /v1/chat/completions
|
|
@@ -28,11 +30,10 @@ function getRequestContext(req) {
|
|
|
28
30
|
export async function handleChatCompletion(req, res) {
|
|
29
31
|
const startTime = Date.now();
|
|
30
32
|
const body = req.body;
|
|
31
|
-
|
|
32
|
-
if (settings.logRawProxyPayloads === true) {
|
|
33
|
+
if (shouldLogRawProxyPayloads()) {
|
|
33
34
|
logger.info('[Client Request]', body);
|
|
34
35
|
}
|
|
35
|
-
const requestedModel = body.model
|
|
36
|
+
const requestedModel = body.model;
|
|
36
37
|
|
|
37
38
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
38
39
|
|
|
@@ -53,6 +54,7 @@ export async function handleChatCompletion(req, res) {
|
|
|
53
54
|
|
|
54
55
|
try {
|
|
55
56
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, getRequestContext(req));
|
|
57
|
+
recordRequestUsage(req.clientApiKey?.id, upstreamModel, response.usage);
|
|
56
58
|
|
|
57
59
|
const duration = Date.now() - startTime;
|
|
58
60
|
logger.response(200, { model: upstreamModel, ...getTokenDetails(response.usage), duration });
|
|
@@ -109,6 +111,25 @@ export function handleCountTokens(req, res) {
|
|
|
109
111
|
|
|
110
112
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
111
113
|
|
|
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
|
+
|
|
112
133
|
/**
|
|
113
134
|
* Converts an OpenAI Chat Completions request body into an Anthropic-style request.
|
|
114
135
|
* @param {object} body
|
|
@@ -9,12 +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';
|
|
17
|
-
import {
|
|
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
|
+
}
|
|
18
38
|
|
|
19
39
|
/**
|
|
20
40
|
* GET /claude/config
|
|
@@ -32,37 +52,44 @@ export async function handleGetClaudeConfig(req, res) {
|
|
|
32
52
|
|
|
33
53
|
/**
|
|
34
54
|
* POST /claude/config/proxy
|
|
35
|
-
*
|
|
55
|
+
* Returns commands for configuring the caller's Claude CLI without mutating server files.
|
|
36
56
|
*/
|
|
37
57
|
export async function handleSetProxyMode(req, res, { port }) {
|
|
38
58
|
try {
|
|
39
|
-
const proxyUrl =
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
59
|
+
const proxyUrl = getProxyConfigBaseUrl(req, port);
|
|
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
|
+
const commands = {
|
|
75
|
+
bash: configureCommands,
|
|
76
|
+
powershell: configureCommands,
|
|
77
|
+
clear: {
|
|
78
|
+
bash: clearCommands,
|
|
79
|
+
powershell: clearCommands
|
|
80
|
+
}
|
|
46
81
|
};
|
|
47
82
|
|
|
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
|
-
|
|
61
|
-
const config = await setProxyMode(proxyUrl, models);
|
|
62
83
|
res.json({
|
|
63
84
|
success: true,
|
|
64
|
-
|
|
65
|
-
config
|
|
85
|
+
mode: 'dry_run',
|
|
86
|
+
message: 'Claude CLI config was not modified. Run the returned commands on the client machine that uses Claude Code.',
|
|
87
|
+
env: {
|
|
88
|
+
ANTHROPIC_BASE_URL: proxyUrl,
|
|
89
|
+
ANTHROPIC_API_KEY: apiKeyPlaceholder,
|
|
90
|
+
CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
|
|
91
|
+
},
|
|
92
|
+
commands
|
|
66
93
|
});
|
|
67
94
|
} catch (error) {
|
|
68
95
|
res.status(500).json({ success: false, error: error.message });
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns the authenticated client key's weekly quota using Claude Code's
|
|
5
|
+
* utilization response shape, so the terminal can consume it directly.
|
|
6
|
+
*/
|
|
7
|
+
export function handleGetClientQuota(req, res) {
|
|
8
|
+
const quota = req.clientApiKeyQuota;
|
|
9
|
+
const weeklyLimitUsd = quota?.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD;
|
|
10
|
+
const utilization = quota && weeklyLimitUsd > 0
|
|
11
|
+
? Math.min(100, Math.max(0, (quota.consumedUsd / weeklyLimitUsd) * 100))
|
|
12
|
+
: null;
|
|
13
|
+
|
|
14
|
+
return res.json({
|
|
15
|
+
five_hour: null,
|
|
16
|
+
seven_day: quota ? {
|
|
17
|
+
utilization,
|
|
18
|
+
resets_at: quota.nextPeriodStart
|
|
19
|
+
} : null,
|
|
20
|
+
seven_day_oauth_apps: null,
|
|
21
|
+
seven_day_opus: null,
|
|
22
|
+
seven_day_sonnet: null,
|
|
23
|
+
extra_usage: null
|
|
24
|
+
});
|
|
25
|
+
}
|
package/src/routes/logs-route.js
CHANGED
|
@@ -7,12 +7,31 @@
|
|
|
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
|
+
|
|
10
18
|
/**
|
|
11
19
|
* GET /api/logs
|
|
12
|
-
* Returns
|
|
20
|
+
* Returns a newest-first page of in-memory log history.
|
|
13
21
|
*/
|
|
14
22
|
export function handleGetLogs(req, res) {
|
|
15
|
-
|
|
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
|
+
});
|
|
16
35
|
}
|
|
17
36
|
|
|
18
37
|
/**
|
|
@@ -6,6 +6,9 @@ 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';
|
|
9
12
|
|
|
10
13
|
const MAX_RETRIES = 5;
|
|
11
14
|
const MAX_WAIT_BEFORE_ERROR_MS = 120000;
|
|
@@ -50,10 +53,10 @@ export async function handleMessages(req, res) {
|
|
|
50
53
|
const startTime = Date.now();
|
|
51
54
|
const body = req.body;
|
|
52
55
|
const settings = getServerSettings();
|
|
53
|
-
if (
|
|
56
|
+
if (shouldLogRawProxyPayloads()) {
|
|
54
57
|
logger.info('[Claude Request]', body);
|
|
55
58
|
}
|
|
56
|
-
const requestedModel = body.model
|
|
59
|
+
const requestedModel = body.model;
|
|
57
60
|
const isStreaming = body.stream !== false;
|
|
58
61
|
|
|
59
62
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
@@ -97,9 +100,9 @@ export async function handleMessages(req, res) {
|
|
|
97
100
|
|
|
98
101
|
try {
|
|
99
102
|
if (isStreaming) {
|
|
100
|
-
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
103
|
+
await _streamDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
101
104
|
} else {
|
|
102
|
-
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext);
|
|
105
|
+
await _sendDirectWithRotation(res, anthropicRequest, creds, requestedModel, startTime, rotator, requestContext, req.clientApiKey?.id);
|
|
103
106
|
}
|
|
104
107
|
rotator.notifySuccess(account, upstreamModel);
|
|
105
108
|
return;
|
|
@@ -134,20 +137,41 @@ export async function handleMessages(req, res) {
|
|
|
134
137
|
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
135
138
|
}
|
|
136
139
|
|
|
137
|
-
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
140
|
+
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
138
141
|
const stream = await createMessageStream(anthropicRequest, creds.accessToken, creds.accountId, rotator, creds.email, requestContext, responseModel);
|
|
139
142
|
initSSEResponse(res);
|
|
140
143
|
const usage = await pipeSSEStream(res, stream);
|
|
144
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
141
145
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
142
146
|
}
|
|
143
147
|
|
|
144
|
-
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext) {
|
|
148
|
+
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
145
149
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
150
|
+
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
146
151
|
const duration = Date.now() - startTime;
|
|
147
152
|
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
148
153
|
res.json({ ...response, model: responseModel });
|
|
149
154
|
}
|
|
150
155
|
|
|
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
|
+
|
|
151
175
|
function syncActiveAccount(email) {
|
|
152
176
|
const active = getActiveAccount();
|
|
153
177
|
if (active?.email === email) return;
|
|
@@ -10,13 +10,30 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import crypto from 'crypto';
|
|
13
|
-
import {
|
|
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';
|
|
14
20
|
|
|
15
21
|
const VALID_STRATEGIES = ['sticky', 'round-robin'];
|
|
16
22
|
|
|
17
23
|
function getSafeClientApiKey(clientApiKey) {
|
|
18
24
|
const { key, ...safeClientApiKey } = clientApiKey;
|
|
19
|
-
return
|
|
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;
|
|
20
37
|
}
|
|
21
38
|
|
|
22
39
|
function createClientApiKeyValue() {
|
|
@@ -168,17 +185,23 @@ export function handleListClientApiKeys(req, res) {
|
|
|
168
185
|
* Creates a Claude Code client API key.
|
|
169
186
|
*/
|
|
170
187
|
export function handleCreateClientApiKey(req, res) {
|
|
171
|
-
const { name = '', remark = '' } = req.body || {};
|
|
188
|
+
const { name = '', remark = '', weeklyLimitUsd = DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } = req.body || {};
|
|
172
189
|
|
|
173
190
|
if (typeof name !== 'string' || typeof remark !== 'string') {
|
|
174
191
|
return res.status(400).json({ success: false, error: 'name and remark must be strings' });
|
|
175
192
|
}
|
|
176
193
|
|
|
194
|
+
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
195
|
+
if (weeklyLimitError) {
|
|
196
|
+
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
197
|
+
}
|
|
198
|
+
|
|
177
199
|
const clientApiKey = {
|
|
178
200
|
id: crypto.randomUUID(),
|
|
179
201
|
key: createClientApiKeyValue(),
|
|
180
202
|
name: name.trim(),
|
|
181
203
|
remark: remark.trim(),
|
|
204
|
+
weeklyLimitUsd,
|
|
182
205
|
createdAt: new Date().toISOString()
|
|
183
206
|
};
|
|
184
207
|
const settings = getServerSettings();
|
|
@@ -193,7 +216,7 @@ export function handleCreateClientApiKey(req, res) {
|
|
|
193
216
|
*/
|
|
194
217
|
export function handleUpdateClientApiKey(req, res) {
|
|
195
218
|
const { id } = req.params;
|
|
196
|
-
const { name, remark } = req.body || {};
|
|
219
|
+
const { name, remark, weeklyLimitUsd } = req.body || {};
|
|
197
220
|
|
|
198
221
|
if (name !== undefined && typeof name !== 'string') {
|
|
199
222
|
return res.status(400).json({ success: false, error: 'name must be a string' });
|
|
@@ -201,6 +224,12 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
201
224
|
if (remark !== undefined && typeof remark !== 'string') {
|
|
202
225
|
return res.status(400).json({ success: false, error: 'remark must be a string' });
|
|
203
226
|
}
|
|
227
|
+
if (weeklyLimitUsd !== undefined) {
|
|
228
|
+
const weeklyLimitError = validateWeeklyLimitUsd(weeklyLimitUsd);
|
|
229
|
+
if (weeklyLimitError) {
|
|
230
|
+
return res.status(400).json({ success: false, error: weeklyLimitError });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
204
233
|
|
|
205
234
|
const settings = getServerSettings();
|
|
206
235
|
const index = settings.clientApiKeys.findIndex((clientApiKey) => clientApiKey.id === id);
|
|
@@ -212,7 +241,8 @@ export function handleUpdateClientApiKey(req, res) {
|
|
|
212
241
|
const clientApiKey = {
|
|
213
242
|
...current,
|
|
214
243
|
...(name === undefined ? {} : { name: name.trim() }),
|
|
215
|
-
...(remark === undefined ? {} : { remark: remark.trim() })
|
|
244
|
+
...(remark === undefined ? {} : { remark: remark.trim() }),
|
|
245
|
+
...(weeklyLimitUsd === undefined ? {} : { weeklyLimitUsd })
|
|
216
246
|
};
|
|
217
247
|
const clientApiKeys = [...settings.clientApiKeys];
|
|
218
248
|
clientApiKeys[index] = clientApiKey;
|
|
@@ -235,6 +265,7 @@ export function handleDeleteClientApiKey(req, res) {
|
|
|
235
265
|
}
|
|
236
266
|
|
|
237
267
|
setServerSettings({ clientApiKeys });
|
|
268
|
+
deleteClientKeyUsage(id);
|
|
238
269
|
res.json({ success: true });
|
|
239
270
|
}
|
|
240
271
|
|