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.
- package/README.md +39 -6
- package/bin/cli.js +43 -0
- package/docs/API.md +22 -0
- package/package.json +3 -2
- package/public/index.html +126 -11
- package/public/js/app.js +148 -14
- package/src/deployment.js +49 -0
- package/src/direct-api.js +15 -5
- package/src/index.js +26 -8
- package/src/middleware/auth.js +80 -0
- package/src/oauth.js +65 -26
- package/src/response-streamer.js +6 -1
- package/src/routes/accounts-route.js +30 -14
- package/src/routes/api-routes.js +31 -7
- package/src/routes/chat-route.js +1 -1
- package/src/routes/claude-config-route.js +47 -10
- package/src/routes/messages-route.js +1 -1
- package/src/routes/settings-route.js +99 -1
- package/src/server-settings.js +2 -1
- package/src/server.js +10 -6
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deployment policy helpers shared by server, routes and auth middleware.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const VALID_DEPLOYMENT_MODES = new Set(['local', 'public']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Returns the validated deployment mode, defaulting to local when unset.
|
|
9
|
+
* @returns {'local'|'public'}
|
|
10
|
+
*/
|
|
11
|
+
export function getDeploymentMode() {
|
|
12
|
+
const mode = process.env.PROXY_DEPLOYMENT_MODE || 'local';
|
|
13
|
+
if (!VALID_DEPLOYMENT_MODES.has(mode)) {
|
|
14
|
+
throw new Error(`Invalid PROXY_DEPLOYMENT_MODE "${mode}". Expected "local" or "public".`);
|
|
15
|
+
}
|
|
16
|
+
return mode;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Indicates whether the proxy is running in public deployment mode.
|
|
21
|
+
* @returns {boolean}
|
|
22
|
+
*/
|
|
23
|
+
export function isPublicDeployment() {
|
|
24
|
+
return getDeploymentMode() === 'public';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Returns the host address the main HTTP server should bind to.
|
|
29
|
+
* @returns {string}
|
|
30
|
+
*/
|
|
31
|
+
export function getServerHost() {
|
|
32
|
+
if (process.env.HOST) {
|
|
33
|
+
return process.env.HOST;
|
|
34
|
+
}
|
|
35
|
+
return isPublicDeployment() ? '0.0.0.0' : '127.0.0.1';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Returns a display URL for logs and local helper responses.
|
|
40
|
+
* @param {number|string} port
|
|
41
|
+
* @returns {string}
|
|
42
|
+
*/
|
|
43
|
+
export function getLocalBaseUrl(port) {
|
|
44
|
+
const host = getServerHost();
|
|
45
|
+
const displayHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
|
|
46
|
+
return `http://${displayHost}:${port}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export default { getDeploymentMode, isPublicDeployment, getServerHost, getLocalBaseUrl };
|
package/src/direct-api.js
CHANGED
|
@@ -19,6 +19,20 @@ function shouldLogRawProxyPayloads() {
|
|
|
19
19
|
return getServerSettings().logRawProxyPayloads === true;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
function createAnthropicUsage(upstreamUsage = {}) {
|
|
23
|
+
const usage = {
|
|
24
|
+
input_tokens: upstreamUsage.input_tokens || 0,
|
|
25
|
+
output_tokens: upstreamUsage.output_tokens || 0,
|
|
26
|
+
// Responses API cache metrics are already included in input_tokens.
|
|
27
|
+
cache_read_input_tokens: 0
|
|
28
|
+
};
|
|
29
|
+
Object.defineProperty(usage, 'upstreamCacheReadInputTokens', {
|
|
30
|
+
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
31
|
+
enumerable: false
|
|
32
|
+
});
|
|
33
|
+
return usage;
|
|
34
|
+
}
|
|
35
|
+
|
|
22
36
|
function buildOpencodeHeaders(accessToken, accountId, context = {}) {
|
|
23
37
|
const headers = {
|
|
24
38
|
'Authorization': `Bearer ${accessToken}`,
|
|
@@ -226,11 +240,7 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
226
240
|
model: anthropicRequest.model,
|
|
227
241
|
stop_reason: stopReason,
|
|
228
242
|
stop_sequence: null,
|
|
229
|
-
usage:
|
|
230
|
-
input_tokens: apiResponse.usage?.input_tokens || 0,
|
|
231
|
-
output_tokens: apiResponse.usage?.output_tokens || 0,
|
|
232
|
-
cache_read_input_tokens: apiResponse.usage?.cache_read_input_tokens || apiResponse.usage?.input_tokens_details?.cached_tokens || 0
|
|
233
|
-
}
|
|
243
|
+
usage: createAnthropicUsage(apiResponse.usage)
|
|
234
244
|
};
|
|
235
245
|
}
|
|
236
246
|
|
package/src/index.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
|
+
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
7
8
|
import { startServer } from './server.js';
|
|
8
9
|
import { logger } from './utils/logger.js';
|
|
9
10
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -11,7 +12,21 @@ import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
|
11
12
|
const require = createRequire(import.meta.url);
|
|
12
13
|
const packageJson = require('../package.json');
|
|
13
14
|
const PORT = Number(process.env.PORT || 8081);
|
|
15
|
+
let DEPLOYMENT_MODE;
|
|
16
|
+
try {
|
|
17
|
+
DEPLOYMENT_MODE = getDeploymentMode();
|
|
18
|
+
} catch (error) {
|
|
19
|
+
console.error(error.message);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
22
|
+
const HOST = getServerHost();
|
|
23
|
+
const BASE_URL = getLocalBaseUrl(PORT);
|
|
14
24
|
const BANNER_WIDTH = 62;
|
|
25
|
+
|
|
26
|
+
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
27
|
+
console.error('Public deployment mode requires a UI/admin access key.');
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
15
30
|
const centerBannerText = (text) => {
|
|
16
31
|
const padding = Math.max(0, BANNER_WIDTH - text.length);
|
|
17
32
|
const left = Math.floor(padding / 2);
|
|
@@ -19,18 +34,21 @@ const centerBannerText = (text) => {
|
|
|
19
34
|
return `${' '.repeat(left)}${text}${' '.repeat(right)}`;
|
|
20
35
|
};
|
|
21
36
|
|
|
22
|
-
|
|
37
|
+
const bannerLine = (label, value) => `║ ${label.padEnd(9)}${String(value).padEnd(49)}║`;
|
|
38
|
+
|
|
39
|
+
startServer({ port: PORT, host: HOST });
|
|
23
40
|
|
|
24
41
|
console.log(`
|
|
25
42
|
╔══════════════════════════════════════════════════════════════╗
|
|
26
43
|
║${centerBannerText(`Claude Codex Proxy v${packageJson.version}`)}║
|
|
27
|
-
|
|
44
|
+
║${centerBannerText(DEPLOYMENT_MODE === 'public' ? 'Public Deployment Mode' : 'Local Deployment Mode')}║
|
|
28
45
|
╠══════════════════════════════════════════════════════════════╣
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
46
|
+
${bannerLine('Host:', HOST)}
|
|
47
|
+
${bannerLine('Server:', BASE_URL)}
|
|
48
|
+
${bannerLine('WebUI:', BASE_URL)}
|
|
49
|
+
${bannerLine('Health:', `${BASE_URL}/health`)}
|
|
50
|
+
${bannerLine('Accounts:', `${BASE_URL}/accounts`)}
|
|
51
|
+
${bannerLine('Logs:', `${BASE_URL}/api/logs/stream`)}
|
|
34
52
|
╠══════════════════════════════════════════════════════════════╣
|
|
35
53
|
║ Features: ║
|
|
36
54
|
║ ✓ Native tool calling support ║
|
|
@@ -48,7 +66,7 @@ const status = getStatus();
|
|
|
48
66
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
49
67
|
|
|
50
68
|
if (status.total === 0) {
|
|
51
|
-
logger.warn(`No accounts configured. Open
|
|
69
|
+
logger.warn(`No accounts configured. Open ${BASE_URL} to add one.`);
|
|
52
70
|
}
|
|
53
71
|
|
|
54
72
|
// Expose config path in logs for convenience
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
+
import { getServerSettings } from '../server-settings.js';
|
|
4
|
+
|
|
5
|
+
function timingSafeEqualString(a, b) {
|
|
6
|
+
const left = Buffer.from(String(a));
|
|
7
|
+
const right = Buffer.from(String(b));
|
|
8
|
+
|
|
9
|
+
if (left.length !== right.length) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
return crypto.timingSafeEqual(left, right);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function getRequestApiKey(req) {
|
|
17
|
+
const authorization = req.get?.('authorization') || req.headers?.authorization || '';
|
|
18
|
+
const bearerMatch = authorization.match(/^Bearer\s+(.+)$/i);
|
|
19
|
+
if (bearerMatch) {
|
|
20
|
+
return bearerMatch[1].trim();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const headerKey = req.get?.('x-api-key') || req.headers?.['x-api-key'];
|
|
24
|
+
if (headerKey) {
|
|
25
|
+
return String(headerKey).trim();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const queryKey = req.query?.api_key || req.query?.access_token;
|
|
29
|
+
if (queryKey) {
|
|
30
|
+
return String(queryKey).trim();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return '';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function sendUnauthorized(req, res) {
|
|
37
|
+
if (req.path?.startsWith('/v1/')) {
|
|
38
|
+
return res.status(401).json({
|
|
39
|
+
type: 'error',
|
|
40
|
+
error: { type: 'authentication_error', message: 'Invalid API key' }
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function matchesAnyKey(requestKey, expectedKeys) {
|
|
48
|
+
return expectedKeys.some((expectedKey) => (
|
|
49
|
+
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
50
|
+
));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function requireKeys(getExpectedKeys) {
|
|
54
|
+
return (req, res, next) => {
|
|
55
|
+
if (!isPublicDeployment()) {
|
|
56
|
+
return next();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const expectedKeys = getExpectedKeys();
|
|
60
|
+
const requestKey = getRequestApiKey(req);
|
|
61
|
+
if (!matchesAnyKey(requestKey, expectedKeys)) {
|
|
62
|
+
return sendUnauthorized(req, res);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return next();
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const getAdminKeys = () => [process.env.PROXY_ADMIN_KEY].filter(Boolean);
|
|
70
|
+
const getClientKeys = () => [
|
|
71
|
+
...getServerSettings().clientApiKeys.map(({ key }) => key),
|
|
72
|
+
process.env.PROXY_CLIENT_KEY
|
|
73
|
+
].filter(Boolean);
|
|
74
|
+
|
|
75
|
+
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
76
|
+
export const requireClientAuth = requireKeys(getClientKeys);
|
|
77
|
+
|
|
78
|
+
export { isPublicDeployment };
|
|
79
|
+
|
|
80
|
+
export default { isPublicDeployment, requireAdminAuth, requireClientAuth };
|
package/src/oauth.js
CHANGED
|
@@ -8,6 +8,8 @@ import http from 'http';
|
|
|
8
8
|
import { exec } from 'child_process';
|
|
9
9
|
import { promisify } from 'util';
|
|
10
10
|
|
|
11
|
+
import { getServerHost } from './deployment.js';
|
|
12
|
+
|
|
11
13
|
const execAsync = promisify(exec);
|
|
12
14
|
|
|
13
15
|
// OpenAI OAuth Configuration (from Codex app)
|
|
@@ -18,7 +20,7 @@ const OAUTH_CONFIG = {
|
|
|
18
20
|
logoutUrl: 'https://auth.openai.com/logout',
|
|
19
21
|
userInfoUrl: 'https://api.openai.com/v1/me',
|
|
20
22
|
scopes: ['openid', 'profile', 'email', 'offline_access'],
|
|
21
|
-
callbackPort: 1455,
|
|
23
|
+
callbackPort: Number(process.env.OAUTH_CALLBACK_PORT || 1455),
|
|
22
24
|
callbackFallbackPorts: [1456, 1457, 1458, 1459, 1460],
|
|
23
25
|
callbackPath: '/auth/callback'
|
|
24
26
|
};
|
|
@@ -91,11 +93,11 @@ function extractAccountInfo(accessToken) {
|
|
|
91
93
|
* @param {number} port - Callback server port
|
|
92
94
|
* @returns {string} Authorization URL
|
|
93
95
|
*/
|
|
94
|
-
function getAuthorizationUrl(verifier, state, port) {
|
|
96
|
+
function getAuthorizationUrl(verifier, state, port, callbackHost = getOAuthCallbackHost()) {
|
|
95
97
|
const { challenge } = generatePKCEFromVerifier(verifier);
|
|
96
|
-
const redirectUri =
|
|
97
|
-
|
|
98
|
-
pkceStore.set(state, { verifier, port, createdAt: Date.now() });
|
|
98
|
+
const redirectUri = getOAuthRedirectUri(port, callbackHost);
|
|
99
|
+
|
|
100
|
+
pkceStore.set(state, { verifier, port, callbackHost, createdAt: Date.now() });
|
|
99
101
|
|
|
100
102
|
// Clean up old entries
|
|
101
103
|
for (const [key, value] of pkceStore.entries()) {
|
|
@@ -213,6 +215,29 @@ function generatePKCEFromVerifier(verifier) {
|
|
|
213
215
|
return { challenge };
|
|
214
216
|
}
|
|
215
217
|
|
|
218
|
+
/**
|
|
219
|
+
* Returns the externally reachable OAuth callback host.
|
|
220
|
+
* @returns {string}
|
|
221
|
+
*/
|
|
222
|
+
function getOAuthCallbackHost() {
|
|
223
|
+
if (process.env.OAUTH_CALLBACK_HOST) {
|
|
224
|
+
return process.env.OAUTH_CALLBACK_HOST;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const serverHost = getServerHost();
|
|
228
|
+
return serverHost === '0.0.0.0' || serverHost === '::' ? 'localhost' : serverHost;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Builds the OAuth redirect URI used for both authorization and token exchange.
|
|
233
|
+
* @param {number} port
|
|
234
|
+
* @param {string} callbackHost
|
|
235
|
+
* @returns {string}
|
|
236
|
+
*/
|
|
237
|
+
function getOAuthRedirectUri(port, callbackHost = getOAuthCallbackHost()) {
|
|
238
|
+
return `http://${callbackHost}:${port}${OAUTH_CONFIG.callbackPath}`;
|
|
239
|
+
}
|
|
240
|
+
|
|
216
241
|
/**
|
|
217
242
|
* Get stored PKCE data for a state
|
|
218
243
|
* @param {string} state - OAuth state
|
|
@@ -249,21 +274,27 @@ function tryBindPort(server, port, host = '0.0.0.0') {
|
|
|
249
274
|
* Start local callback server with port fallback and abort support
|
|
250
275
|
* @param {string} expectedState - Expected state for validation
|
|
251
276
|
* @param {number} timeoutMs - Timeout in milliseconds
|
|
252
|
-
* @returns {{promise: Promise<string>, abort: Function, getPort: Function}}
|
|
277
|
+
* @returns {{promise: Promise<string>, ready: Promise<number>, abort: Function, getPort: Function}}
|
|
253
278
|
*/
|
|
254
|
-
function startCallbackServer(expectedState, timeoutMs = 120000) {
|
|
279
|
+
function startCallbackServer(expectedState, timeoutMs = 120000, callbackHost = getOAuthCallbackHost(), preferredPort = OAUTH_CONFIG.callbackPort) {
|
|
255
280
|
let server = null;
|
|
256
281
|
let timeoutId = null;
|
|
257
282
|
let isAborted = false;
|
|
258
|
-
let actualPort =
|
|
259
|
-
const host = process.env.
|
|
283
|
+
let actualPort = preferredPort;
|
|
284
|
+
const host = process.env.OAUTH_BIND_HOST || getServerHost();
|
|
285
|
+
let resolveReady;
|
|
286
|
+
let rejectReady;
|
|
287
|
+
const ready = new Promise((resolve, reject) => {
|
|
288
|
+
resolveReady = resolve;
|
|
289
|
+
rejectReady = reject;
|
|
290
|
+
});
|
|
260
291
|
|
|
261
292
|
const promise = new Promise(async (resolve, reject) => {
|
|
262
|
-
const portsToTry = [OAUTH_CONFIG.callbackPort, ...(OAUTH_CONFIG.callbackFallbackPorts || [])];
|
|
293
|
+
const portsToTry = [preferredPort, ...[OAUTH_CONFIG.callbackPort, ...(OAUTH_CONFIG.callbackFallbackPorts || [])].filter(port => port !== preferredPort)];
|
|
263
294
|
const errors = [];
|
|
264
295
|
|
|
265
296
|
server = http.createServer((req, res) => {
|
|
266
|
-
const url = new URL(req.url,
|
|
297
|
+
const url = new URL(req.url, getOAuthRedirectUri(actualPort, callbackHost));
|
|
267
298
|
console.log(`[OAuth] Received request: ${req.method} ${req.url}`);
|
|
268
299
|
|
|
269
300
|
if (url.pathname !== OAUTH_CONFIG.callbackPath && url.pathname !== '/success') {
|
|
@@ -327,8 +358,8 @@ function startCallbackServer(expectedState, timeoutMs = 120000) {
|
|
|
327
358
|
actualPort = port;
|
|
328
359
|
boundSuccessfully = true;
|
|
329
360
|
|
|
330
|
-
if (port !==
|
|
331
|
-
console.log(`[OAuth] Primary port ${
|
|
361
|
+
if (port !== preferredPort) {
|
|
362
|
+
console.log(`[OAuth] Primary port ${preferredPort} unavailable, using fallback port ${port}`);
|
|
332
363
|
} else {
|
|
333
364
|
console.log(`[OAuth] Callback server listening on ${host}:${port}`);
|
|
334
365
|
}
|
|
@@ -366,10 +397,13 @@ Option 3: Check reserved port ranges
|
|
|
366
397
|
errorMsg += `\n\nTry setting a custom port via environment variable.`;
|
|
367
398
|
}
|
|
368
399
|
|
|
400
|
+
rejectReady(new Error(errorMsg));
|
|
369
401
|
reject(new Error(errorMsg));
|
|
370
402
|
return;
|
|
371
403
|
}
|
|
372
404
|
|
|
405
|
+
resolveReady(actualPort);
|
|
406
|
+
|
|
373
407
|
timeoutId = setTimeout(() => {
|
|
374
408
|
if (!isAborted) {
|
|
375
409
|
server.close();
|
|
@@ -392,7 +426,7 @@ Option 3: Check reserved port ranges
|
|
|
392
426
|
|
|
393
427
|
const getPort = () => actualPort;
|
|
394
428
|
|
|
395
|
-
return { promise, abort, getPort };
|
|
429
|
+
return { promise, ready, abort, getPort };
|
|
396
430
|
}
|
|
397
431
|
|
|
398
432
|
/**
|
|
@@ -402,9 +436,9 @@ Option 3: Check reserved port ranges
|
|
|
402
436
|
* @param {number} port - Callback port used
|
|
403
437
|
* @returns {Promise<{accessToken: string, refreshToken: string, idToken: string, expiresIn: number}>}
|
|
404
438
|
*/
|
|
405
|
-
async function exchangeCodeForTokens(code, verifier, port) {
|
|
406
|
-
const redirectUri =
|
|
407
|
-
|
|
439
|
+
async function exchangeCodeForTokens(code, verifier, port = OAUTH_CONFIG.callbackPort, callbackHost = getOAuthCallbackHost()) {
|
|
440
|
+
const redirectUri = getOAuthRedirectUri(port, callbackHost);
|
|
441
|
+
|
|
408
442
|
const response = await fetch(OAUTH_CONFIG.tokenUrl, {
|
|
409
443
|
method: 'POST',
|
|
410
444
|
headers: {
|
|
@@ -498,17 +532,18 @@ async function openBrowser(url) {
|
|
|
498
532
|
*/
|
|
499
533
|
async function performOAuthFlow(customPort) {
|
|
500
534
|
const port = customPort || OAUTH_CONFIG.callbackPort;
|
|
535
|
+
const callbackHost = getOAuthCallbackHost();
|
|
501
536
|
const { verifier } = generatePKCE();
|
|
502
537
|
const state = generateState();
|
|
503
|
-
|
|
538
|
+
|
|
504
539
|
// Get authorization URL
|
|
505
|
-
const authUrl = getAuthorizationUrl(verifier, state, port);
|
|
506
|
-
|
|
540
|
+
const authUrl = getAuthorizationUrl(verifier, state, port, callbackHost);
|
|
541
|
+
|
|
507
542
|
// Start callback server
|
|
508
|
-
const { promise: callbackPromise } = startCallbackServer(state);
|
|
509
|
-
|
|
543
|
+
const { promise: callbackPromise } = startCallbackServer(state, 120000, callbackHost);
|
|
544
|
+
|
|
510
545
|
console.log(`\n[OAuth] Starting authentication flow...`);
|
|
511
|
-
console.log(`[OAuth] Callback URL:
|
|
546
|
+
console.log(`[OAuth] Callback URL: ${getOAuthRedirectUri(port, callbackHost)}`);
|
|
512
547
|
|
|
513
548
|
// Open browser
|
|
514
549
|
await openBrowser(authUrl);
|
|
@@ -522,7 +557,7 @@ async function performOAuthFlow(customPort) {
|
|
|
522
557
|
|
|
523
558
|
// Exchange code for tokens
|
|
524
559
|
console.log(`[OAuth] Exchanging code for tokens...`);
|
|
525
|
-
const tokens = await exchangeCodeForTokens(code, verifier, port);
|
|
560
|
+
const tokens = await exchangeCodeForTokens(code, verifier, port, callbackHost);
|
|
526
561
|
console.log(`[OAuth] Token exchange successful`);
|
|
527
562
|
|
|
528
563
|
// Extract account info from access token
|
|
@@ -551,7 +586,7 @@ async function handleOAuthCallback(code, state) {
|
|
|
551
586
|
throw new Error('Invalid or expired OAuth state');
|
|
552
587
|
}
|
|
553
588
|
|
|
554
|
-
const tokens = await exchangeCodeForTokens(code, pkceData.verifier, pkceData.port);
|
|
589
|
+
const tokens = await exchangeCodeForTokens(code, pkceData.verifier, pkceData.port, pkceData.callbackHost);
|
|
555
590
|
const accountInfo = extractAccountInfo(tokens.accessToken);
|
|
556
591
|
|
|
557
592
|
// Clean up
|
|
@@ -614,6 +649,8 @@ export {
|
|
|
614
649
|
extractAccountInfo,
|
|
615
650
|
getAuthorizationUrl,
|
|
616
651
|
getLogoutThenAuthUrl,
|
|
652
|
+
getOAuthCallbackHost,
|
|
653
|
+
getOAuthRedirectUri,
|
|
617
654
|
startCallbackServer,
|
|
618
655
|
exchangeCodeForTokens,
|
|
619
656
|
refreshAccessToken,
|
|
@@ -628,5 +665,7 @@ export default {
|
|
|
628
665
|
handleOAuthCallback,
|
|
629
666
|
refreshAccessToken,
|
|
630
667
|
extractAccountInfo,
|
|
631
|
-
extractCodeFromInput
|
|
668
|
+
extractCodeFromInput,
|
|
669
|
+
getOAuthCallbackHost,
|
|
670
|
+
getOAuthRedirectUri
|
|
632
671
|
};
|
package/src/response-streamer.js
CHANGED
|
@@ -110,8 +110,13 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
110
110
|
usage = {
|
|
111
111
|
input_tokens: inputTokens,
|
|
112
112
|
output_tokens: outputTokens,
|
|
113
|
-
|
|
113
|
+
// Responses API cache metrics are already included in input_tokens.
|
|
114
|
+
cache_read_input_tokens: 0
|
|
114
115
|
};
|
|
116
|
+
Object.defineProperty(usage, 'upstreamCacheReadInputTokens', {
|
|
117
|
+
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
118
|
+
enumerable: false
|
|
119
|
+
});
|
|
115
120
|
}
|
|
116
121
|
|
|
117
122
|
// Handle output item added
|
|
@@ -37,8 +37,10 @@ import {
|
|
|
37
37
|
getAuthorizationUrl,
|
|
38
38
|
generatePKCE,
|
|
39
39
|
generateState,
|
|
40
|
+
getOAuthCallbackHost,
|
|
40
41
|
startCallbackServer,
|
|
41
42
|
exchangeCodeForTokens,
|
|
43
|
+
handleOAuthCallback,
|
|
42
44
|
OAUTH_CONFIG,
|
|
43
45
|
extractCodeFromInput,
|
|
44
46
|
extractAccountInfo
|
|
@@ -73,22 +75,32 @@ export function handleOAuthCleanup(req, res) {
|
|
|
73
75
|
|
|
74
76
|
export async function handleAddAccount(req, res) {
|
|
75
77
|
const { port } = req.body || {};
|
|
76
|
-
const
|
|
78
|
+
const requestedPort = port || OAUTH_CONFIG.callbackPort;
|
|
79
|
+
const callbackHost = process.env.OAUTH_CALLBACK_HOST || req.hostname || getOAuthCallbackHost();
|
|
77
80
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
// Close any existing server on this port
|
|
83
|
-
if (activeCallbackServers.has(callbackPort)) {
|
|
84
|
-
const existing = activeCallbackServers.get(callbackPort);
|
|
81
|
+
// Close any existing server on the requested primary port.
|
|
82
|
+
if (activeCallbackServers.has(requestedPort)) {
|
|
83
|
+
const existing = activeCallbackServers.get(requestedPort);
|
|
85
84
|
if (existing.abort) existing.abort();
|
|
86
|
-
activeCallbackServers.delete(
|
|
85
|
+
activeCallbackServers.delete(requestedPort);
|
|
87
86
|
}
|
|
88
87
|
|
|
88
|
+
const { verifier } = generatePKCE();
|
|
89
|
+
const state = generateState();
|
|
89
90
|
let serverResult;
|
|
90
91
|
try {
|
|
91
|
-
serverResult = startCallbackServer(state, 120000);
|
|
92
|
+
serverResult = startCallbackServer(state, 120000, callbackHost, requestedPort);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
return res.status(500).json({
|
|
95
|
+
error: 'Failed to start OAuth callback server',
|
|
96
|
+
message: err.message,
|
|
97
|
+
status: 'error'
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
let callbackPort;
|
|
102
|
+
try {
|
|
103
|
+
callbackPort = await serverResult.ready;
|
|
92
104
|
} catch (err) {
|
|
93
105
|
return res.status(500).json({
|
|
94
106
|
error: 'Failed to start OAuth callback server',
|
|
@@ -97,6 +109,7 @@ export async function handleAddAccount(req, res) {
|
|
|
97
109
|
});
|
|
98
110
|
}
|
|
99
111
|
|
|
112
|
+
const oauthUrl = getAuthorizationUrl(verifier, state, callbackPort, callbackHost);
|
|
100
113
|
activeCallbackServers.set(callbackPort, serverResult);
|
|
101
114
|
|
|
102
115
|
serverResult.promise
|
|
@@ -104,7 +117,7 @@ export async function handleAddAccount(req, res) {
|
|
|
104
117
|
activeCallbackServers.delete(callbackPort);
|
|
105
118
|
if (!code) return null;
|
|
106
119
|
|
|
107
|
-
return exchangeCodeForTokens(code, verifier, callbackPort)
|
|
120
|
+
return exchangeCodeForTokens(code, verifier, callbackPort, callbackHost)
|
|
108
121
|
.then(async tokens => {
|
|
109
122
|
const accountInfo = createAccountInfoFromTokens(tokens);
|
|
110
123
|
await _upsertAccount(accountInfo);
|
|
@@ -121,6 +134,7 @@ export async function handleAddAccount(req, res) {
|
|
|
121
134
|
oauth_url: oauthUrl,
|
|
122
135
|
verifier,
|
|
123
136
|
state,
|
|
137
|
+
callback_host: callbackHost,
|
|
124
138
|
callback_port: callbackPort
|
|
125
139
|
});
|
|
126
140
|
}
|
|
@@ -133,9 +147,11 @@ export async function handleAddAccountManual(req, res) {
|
|
|
133
147
|
}
|
|
134
148
|
|
|
135
149
|
try {
|
|
136
|
-
const { code: extractedCode } = extractCodeFromInput(code);
|
|
137
|
-
const tokens =
|
|
138
|
-
|
|
150
|
+
const { code: extractedCode, state } = extractCodeFromInput(code);
|
|
151
|
+
const tokens = state
|
|
152
|
+
? await handleOAuthCallback(extractedCode, state)
|
|
153
|
+
: await exchangeCodeForTokens(extractedCode, verifier, OAUTH_CONFIG.callbackPort);
|
|
154
|
+
const accountInfo = tokens.email ? tokens : createAccountInfoFromTokens(tokens);
|
|
139
155
|
|
|
140
156
|
await _upsertAccount(accountInfo);
|
|
141
157
|
logger.info(`Added account via manual OAuth: ${accountInfo.email}`);
|
package/src/routes/api-routes.js
CHANGED
|
@@ -10,6 +10,7 @@ import { join, dirname } from 'path';
|
|
|
10
10
|
import { fileURLToPath } from 'url';
|
|
11
11
|
|
|
12
12
|
import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
|
|
13
|
+
import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
|
|
13
14
|
|
|
14
15
|
// Route handlers
|
|
15
16
|
import { handleMessages } from './messages-route.js';
|
|
@@ -21,7 +22,11 @@ import {
|
|
|
21
22
|
handleGetModelMap,
|
|
22
23
|
handleSetModelMap,
|
|
23
24
|
handleGetRawProxyLogs,
|
|
24
|
-
handleSetRawProxyLogs
|
|
25
|
+
handleSetRawProxyLogs,
|
|
26
|
+
handleListClientApiKeys,
|
|
27
|
+
handleCreateClientApiKey,
|
|
28
|
+
handleUpdateClientApiKey,
|
|
29
|
+
handleDeleteClientApiKey
|
|
25
30
|
} from './settings-route.js';
|
|
26
31
|
import { handleGetLogs, handleStreamLogs } from './logs-route.js';
|
|
27
32
|
import { handleGetClaudeConfig, handleSetProxyMode, handleSetDirectMode, handleSetClaudeApiEndpoint } from './claude-config-route.js';
|
|
@@ -51,18 +56,34 @@ export function registerApiRoutes(app, { port }) {
|
|
|
51
56
|
|
|
52
57
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
53
58
|
app.get('/health', (req, res) => {
|
|
54
|
-
|
|
59
|
+
const health = {
|
|
60
|
+
status: 'ok',
|
|
61
|
+
version: packageJson.version,
|
|
62
|
+
publicMode: isPublicDeployment()
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
if (!isPublicDeployment()) {
|
|
66
|
+
Object.assign(health, getStatus(), { configPath: ACCOUNTS_FILE });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
res.json(health);
|
|
55
70
|
});
|
|
56
71
|
|
|
72
|
+
// ─── Public Claude CLI Configuration Helper ───────────────────────────────
|
|
73
|
+
app.post('/claude/config/proxy', (req, res) => handleSetProxyMode(req, res, { port }));
|
|
74
|
+
|
|
57
75
|
// ─── Anthropic Messages API ────────────────────────────────────────────────
|
|
58
|
-
app.post('/v1/messages', handleMessages);
|
|
59
|
-
app.post('/v1/messages/count_tokens', handleCountTokens);
|
|
76
|
+
app.post('/v1/messages', requireClientAuth, handleMessages);
|
|
77
|
+
app.post('/v1/messages/count_tokens', requireClientAuth, handleCountTokens);
|
|
60
78
|
|
|
61
79
|
// ─── OpenAI Chat Completions API ───────────────────────────────────────────
|
|
62
|
-
app.post('/v1/chat/completions', handleChatCompletion);
|
|
80
|
+
app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
|
|
63
81
|
|
|
64
82
|
// ─── Models ────────────────────────────────────────────────────────────────
|
|
65
|
-
app.get('/v1/models', handleListModels);
|
|
83
|
+
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
84
|
+
|
|
85
|
+
app.use(requireAdminAuth);
|
|
86
|
+
|
|
66
87
|
app.get('/accounts/models', handleAccountModels);
|
|
67
88
|
app.get('/accounts/usage', handleAccountUsage);
|
|
68
89
|
|
|
@@ -73,6 +94,10 @@ export function registerApiRoutes(app, { port }) {
|
|
|
73
94
|
app.post('/settings/model-map', handleSetModelMap);
|
|
74
95
|
app.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
75
96
|
app.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
97
|
+
app.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
98
|
+
app.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
99
|
+
app.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
100
|
+
app.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
76
101
|
|
|
77
102
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
78
103
|
app.get('/accounts', handleListAccounts);
|
|
@@ -93,7 +118,6 @@ export function registerApiRoutes(app, { port }) {
|
|
|
93
118
|
|
|
94
119
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
95
120
|
app.get('/claude/config', handleGetClaudeConfig);
|
|
96
|
-
app.post('/claude/config/proxy', (req, res) => handleSetProxyMode(req, res, { port }));
|
|
97
121
|
app.post('/claude/config/direct', handleSetDirectMode);
|
|
98
122
|
app.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
99
123
|
|
package/src/routes/chat-route.js
CHANGED
|
@@ -227,7 +227,7 @@ function _buildOpenAIResponse(response, responseModel) {
|
|
|
227
227
|
function getTokenDetails(usage = {}) {
|
|
228
228
|
const inputTokens = usage?.input_tokens || 0;
|
|
229
229
|
const outputTokens = usage?.output_tokens || 0;
|
|
230
|
-
const cacheReadInputTokens = usage?.cache_read_input_tokens
|
|
230
|
+
const cacheReadInputTokens = usage?.upstreamCacheReadInputTokens ?? usage?.cache_read_input_tokens ?? 0;
|
|
231
231
|
return {
|
|
232
232
|
tokens: inputTokens + outputTokens,
|
|
233
233
|
inputTokens,
|