claude-codex-proxy 1.0.5-beta.1 → 1.0.5-beta.11
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 +0 -272
- 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 +104 -744
- package/public/login.html +32 -0
- package/public/views/accounts-modals.html +196 -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 -49
- package/src/direct-api.js +12 -13
- package/src/middleware/auth.js +46 -11
- package/src/model-api.js +60 -0
- package/src/model-pricing.js +96 -0
- package/src/oauth.js +26 -65
- package/src/response-streamer.js +5 -5
- package/src/routes/accounts-route.js +92 -31
- package/src/routes/api-routes.js +17 -2
- package/src/routes/chat-route.js +25 -4
- package/src/routes/claude-config-route.js +22 -15
- 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/utils/logger.js +18 -0
- package/src/utils/proxy-logging.js +5 -0
package/src/direct-api.js
CHANGED
|
@@ -7,17 +7,14 @@ import os from 'os';
|
|
|
7
7
|
import { createRequire } from 'module';
|
|
8
8
|
import { convertAnthropicToResponsesAPI, convertOutputToAnthropic, generateMessageId } from './format-converter.js';
|
|
9
9
|
import { streamResponsesAPI, parseResponsesAPIResponse, createResponsesAPIError } from './response-streamer.js';
|
|
10
|
-
import { getServerSettings } from './server-settings.js';
|
|
11
10
|
import { logger } from './utils/logger.js';
|
|
11
|
+
import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
|
|
12
12
|
|
|
13
13
|
const require = createRequire(import.meta.url);
|
|
14
14
|
const packageJson = require('../package.json');
|
|
15
15
|
const API_URL = 'https://chatgpt.com/backend-api/codex/responses';
|
|
16
16
|
const APP_VERSION = packageJson.version;
|
|
17
|
-
|
|
18
|
-
function shouldLogRawProxyPayloads() {
|
|
19
|
-
return getServerSettings().logRawProxyPayloads === true;
|
|
20
|
-
}
|
|
17
|
+
const UPSTREAM_REQUEST_TIMEOUT_MS = 120000;
|
|
21
18
|
|
|
22
19
|
function createAnthropicUsage(upstreamUsage = {}) {
|
|
23
20
|
const usage = {
|
|
@@ -30,6 +27,10 @@ function createAnthropicUsage(upstreamUsage = {}) {
|
|
|
30
27
|
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
31
28
|
enumerable: false
|
|
32
29
|
});
|
|
30
|
+
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
31
|
+
value: upstreamUsage.input_tokens_details?.cache_write_tokens || 0,
|
|
32
|
+
enumerable: false
|
|
33
|
+
});
|
|
33
34
|
return usage;
|
|
34
35
|
}
|
|
35
36
|
|
|
@@ -128,15 +129,14 @@ async function createResponsesAPIStreamResponse(anthropicRequest, accessToken, a
|
|
|
128
129
|
const response = await fetch(API_URL, {
|
|
129
130
|
method: 'POST',
|
|
130
131
|
headers: buildOpencodeHeaders(accessToken, accountId, context),
|
|
131
|
-
body: JSON.stringify(request)
|
|
132
|
+
body: JSON.stringify(request),
|
|
133
|
+
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
132
134
|
});
|
|
133
135
|
|
|
134
136
|
if (response.ok) return response;
|
|
135
137
|
|
|
136
138
|
const errorText = await response.text();
|
|
137
|
-
|
|
138
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
139
|
-
}
|
|
139
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
140
140
|
|
|
141
141
|
if (response.status === 401) {
|
|
142
142
|
if (accountRotator && currentEmail) {
|
|
@@ -197,14 +197,13 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
197
197
|
const response = await fetch(API_URL, {
|
|
198
198
|
method: 'POST',
|
|
199
199
|
headers: buildOpencodeHeaders(accessToken, accountId, context),
|
|
200
|
-
body: JSON.stringify(request)
|
|
200
|
+
body: JSON.stringify(request),
|
|
201
|
+
signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
|
|
201
202
|
});
|
|
202
203
|
|
|
203
204
|
if (!response.ok) {
|
|
204
205
|
const errorText = await response.text();
|
|
205
|
-
|
|
206
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
207
|
-
}
|
|
206
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
208
207
|
|
|
209
208
|
if (response.status === 401) {
|
|
210
209
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
package/src/middleware/auth.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
-
import { getServerSettings } from '../server-settings.js';
|
|
3
|
+
import { getServerSettings, DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
4
|
+
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
4
5
|
|
|
5
6
|
function timingSafeEqualString(a, b) {
|
|
6
7
|
const left = Buffer.from(String(a));
|
|
@@ -44,10 +45,8 @@ function sendUnauthorized(req, res) {
|
|
|
44
45
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
function
|
|
48
|
-
return
|
|
49
|
-
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
50
|
-
));
|
|
48
|
+
function matchesKey(requestKey, expectedKey) {
|
|
49
|
+
return expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey);
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
function requireKeys(getExpectedKeys) {
|
|
@@ -58,7 +57,7 @@ function requireKeys(getExpectedKeys) {
|
|
|
58
57
|
|
|
59
58
|
const expectedKeys = getExpectedKeys();
|
|
60
59
|
const requestKey = getRequestApiKey(req);
|
|
61
|
-
if (!
|
|
60
|
+
if (!expectedKeys.some((expectedKey) => matchesKey(requestKey, expectedKey))) {
|
|
62
61
|
return sendUnauthorized(req, res);
|
|
63
62
|
}
|
|
64
63
|
|
|
@@ -66,14 +65,50 @@ function requireKeys(getExpectedKeys) {
|
|
|
66
65
|
};
|
|
67
66
|
}
|
|
68
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
|
+
|
|
69
82
|
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
83
|
|
|
75
84
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
76
|
-
|
|
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
|
+
}
|
|
77
112
|
|
|
78
113
|
export { isPublicDeployment };
|
|
79
114
|
|
package/src/model-api.js
CHANGED
|
@@ -100,6 +100,64 @@ export async function fetchUsage(accessToken, accountId) {
|
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/**
|
|
104
|
+
* Lists the account's available rate-limit reset credits.
|
|
105
|
+
* @param {string} accessToken
|
|
106
|
+
* @param {string} accountId
|
|
107
|
+
* @returns {Promise<object>}
|
|
108
|
+
*/
|
|
109
|
+
export async function fetchRateLimitResetCredits(accessToken, accountId) {
|
|
110
|
+
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits`, {
|
|
111
|
+
method: 'GET',
|
|
112
|
+
headers: {
|
|
113
|
+
'Authorization': `Bearer ${accessToken}`,
|
|
114
|
+
'ChatGPT-Account-ID': accountId,
|
|
115
|
+
'Accept': 'application/json',
|
|
116
|
+
'User-Agent': 'codex-cli'
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (!response.ok) {
|
|
121
|
+
const errorText = await response.text();
|
|
122
|
+
throw new Error(`Failed to fetch rate-limit reset credits: ${response.status} - ${errorText}`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return await response.json();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Redeems a rate-limit reset credit for an account.
|
|
130
|
+
* @param {string} accessToken
|
|
131
|
+
* @param {string} accountId
|
|
132
|
+
* @param {string} redeemRequestId Stable idempotency key for retries of this redemption.
|
|
133
|
+
* @param {string|null} creditId Specific credit to redeem, or null for server selection.
|
|
134
|
+
* @returns {Promise<object>}
|
|
135
|
+
*/
|
|
136
|
+
export async function consumeRateLimitResetCredit(accessToken, accountId, redeemRequestId, creditId = null) {
|
|
137
|
+
const body = { redeem_request_id: redeemRequestId };
|
|
138
|
+
if (creditId) body.credit_id = creditId;
|
|
139
|
+
|
|
140
|
+
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits/consume`, {
|
|
141
|
+
method: 'POST',
|
|
142
|
+
headers: {
|
|
143
|
+
'Authorization': `Bearer ${accessToken}`,
|
|
144
|
+
'ChatGPT-Account-ID': accountId,
|
|
145
|
+
'Content-Type': 'application/json',
|
|
146
|
+
'Accept': 'application/json',
|
|
147
|
+
'User-Agent': 'codex-cli'
|
|
148
|
+
},
|
|
149
|
+
body: JSON.stringify(body)
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
if (!response.ok) {
|
|
153
|
+
const errorText = await response.text();
|
|
154
|
+
throw new Error(`Failed to redeem rate-limit reset credit: ${response.status} - ${errorText}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const text = await response.text();
|
|
158
|
+
return text ? JSON.parse(text) : {};
|
|
159
|
+
}
|
|
160
|
+
|
|
103
161
|
export async function fetchAccountCheck(accessToken, accountId) {
|
|
104
162
|
const url = `${CHATGPT_API_BASE}/wham/accounts/check`;
|
|
105
163
|
|
|
@@ -182,6 +240,8 @@ export function clearModelCache() {
|
|
|
182
240
|
export default {
|
|
183
241
|
fetchModels,
|
|
184
242
|
fetchUsage,
|
|
243
|
+
fetchRateLimitResetCredits,
|
|
244
|
+
consumeRateLimitResetCredit,
|
|
185
245
|
fetchAccountCheck,
|
|
186
246
|
getAccountQuota,
|
|
187
247
|
getModelsAndQuota,
|
|
@@ -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/oauth.js
CHANGED
|
@@ -8,8 +8,6 @@ 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
|
-
|
|
13
11
|
const execAsync = promisify(exec);
|
|
14
12
|
|
|
15
13
|
// OpenAI OAuth Configuration (from Codex app)
|
|
@@ -20,7 +18,7 @@ const OAUTH_CONFIG = {
|
|
|
20
18
|
logoutUrl: 'https://auth.openai.com/logout',
|
|
21
19
|
userInfoUrl: 'https://api.openai.com/v1/me',
|
|
22
20
|
scopes: ['openid', 'profile', 'email', 'offline_access'],
|
|
23
|
-
callbackPort:
|
|
21
|
+
callbackPort: 1455,
|
|
24
22
|
callbackFallbackPorts: [1456, 1457, 1458, 1459, 1460],
|
|
25
23
|
callbackPath: '/auth/callback'
|
|
26
24
|
};
|
|
@@ -93,11 +91,11 @@ function extractAccountInfo(accessToken) {
|
|
|
93
91
|
* @param {number} port - Callback server port
|
|
94
92
|
* @returns {string} Authorization URL
|
|
95
93
|
*/
|
|
96
|
-
function getAuthorizationUrl(verifier, state, port
|
|
94
|
+
function getAuthorizationUrl(verifier, state, port) {
|
|
97
95
|
const { challenge } = generatePKCEFromVerifier(verifier);
|
|
98
|
-
const redirectUri =
|
|
99
|
-
|
|
100
|
-
pkceStore.set(state, { verifier, port,
|
|
96
|
+
const redirectUri = `http://localhost:${port}${OAUTH_CONFIG.callbackPath}`;
|
|
97
|
+
|
|
98
|
+
pkceStore.set(state, { verifier, port, createdAt: Date.now() });
|
|
101
99
|
|
|
102
100
|
// Clean up old entries
|
|
103
101
|
for (const [key, value] of pkceStore.entries()) {
|
|
@@ -215,29 +213,6 @@ function generatePKCEFromVerifier(verifier) {
|
|
|
215
213
|
return { challenge };
|
|
216
214
|
}
|
|
217
215
|
|
|
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
|
-
|
|
241
216
|
/**
|
|
242
217
|
* Get stored PKCE data for a state
|
|
243
218
|
* @param {string} state - OAuth state
|
|
@@ -274,27 +249,21 @@ function tryBindPort(server, port, host = '0.0.0.0') {
|
|
|
274
249
|
* Start local callback server with port fallback and abort support
|
|
275
250
|
* @param {string} expectedState - Expected state for validation
|
|
276
251
|
* @param {number} timeoutMs - Timeout in milliseconds
|
|
277
|
-
* @returns {{promise: Promise<string>,
|
|
252
|
+
* @returns {{promise: Promise<string>, abort: Function, getPort: Function}}
|
|
278
253
|
*/
|
|
279
|
-
function startCallbackServer(expectedState, timeoutMs = 120000
|
|
254
|
+
function startCallbackServer(expectedState, timeoutMs = 120000) {
|
|
280
255
|
let server = null;
|
|
281
256
|
let timeoutId = null;
|
|
282
257
|
let isAborted = false;
|
|
283
|
-
let actualPort =
|
|
284
|
-
const host = process.env.
|
|
285
|
-
let resolveReady;
|
|
286
|
-
let rejectReady;
|
|
287
|
-
const ready = new Promise((resolve, reject) => {
|
|
288
|
-
resolveReady = resolve;
|
|
289
|
-
rejectReady = reject;
|
|
290
|
-
});
|
|
258
|
+
let actualPort = OAUTH_CONFIG.callbackPort;
|
|
259
|
+
const host = process.env.HOST || '0.0.0.0';
|
|
291
260
|
|
|
292
261
|
const promise = new Promise(async (resolve, reject) => {
|
|
293
|
-
const portsToTry = [
|
|
262
|
+
const portsToTry = [OAUTH_CONFIG.callbackPort, ...(OAUTH_CONFIG.callbackFallbackPorts || [])];
|
|
294
263
|
const errors = [];
|
|
295
264
|
|
|
296
265
|
server = http.createServer((req, res) => {
|
|
297
|
-
const url = new URL(req.url,
|
|
266
|
+
const url = new URL(req.url, `http://${host === '0.0.0.0' ? 'localhost' : host}:${actualPort}`);
|
|
298
267
|
console.log(`[OAuth] Received request: ${req.method} ${req.url}`);
|
|
299
268
|
|
|
300
269
|
if (url.pathname !== OAUTH_CONFIG.callbackPath && url.pathname !== '/success') {
|
|
@@ -358,8 +327,8 @@ function startCallbackServer(expectedState, timeoutMs = 120000, callbackHost = g
|
|
|
358
327
|
actualPort = port;
|
|
359
328
|
boundSuccessfully = true;
|
|
360
329
|
|
|
361
|
-
if (port !==
|
|
362
|
-
console.log(`[OAuth] Primary port ${
|
|
330
|
+
if (port !== OAUTH_CONFIG.callbackPort) {
|
|
331
|
+
console.log(`[OAuth] Primary port ${OAUTH_CONFIG.callbackPort} unavailable, using fallback port ${port}`);
|
|
363
332
|
} else {
|
|
364
333
|
console.log(`[OAuth] Callback server listening on ${host}:${port}`);
|
|
365
334
|
}
|
|
@@ -397,13 +366,10 @@ Option 3: Check reserved port ranges
|
|
|
397
366
|
errorMsg += `\n\nTry setting a custom port via environment variable.`;
|
|
398
367
|
}
|
|
399
368
|
|
|
400
|
-
rejectReady(new Error(errorMsg));
|
|
401
369
|
reject(new Error(errorMsg));
|
|
402
370
|
return;
|
|
403
371
|
}
|
|
404
372
|
|
|
405
|
-
resolveReady(actualPort);
|
|
406
|
-
|
|
407
373
|
timeoutId = setTimeout(() => {
|
|
408
374
|
if (!isAborted) {
|
|
409
375
|
server.close();
|
|
@@ -426,7 +392,7 @@ Option 3: Check reserved port ranges
|
|
|
426
392
|
|
|
427
393
|
const getPort = () => actualPort;
|
|
428
394
|
|
|
429
|
-
return { promise,
|
|
395
|
+
return { promise, abort, getPort };
|
|
430
396
|
}
|
|
431
397
|
|
|
432
398
|
/**
|
|
@@ -436,9 +402,9 @@ Option 3: Check reserved port ranges
|
|
|
436
402
|
* @param {number} port - Callback port used
|
|
437
403
|
* @returns {Promise<{accessToken: string, refreshToken: string, idToken: string, expiresIn: number}>}
|
|
438
404
|
*/
|
|
439
|
-
async function exchangeCodeForTokens(code, verifier, port
|
|
440
|
-
const redirectUri =
|
|
441
|
-
|
|
405
|
+
async function exchangeCodeForTokens(code, verifier, port) {
|
|
406
|
+
const redirectUri = `http://localhost:${port}${OAUTH_CONFIG.callbackPath}`;
|
|
407
|
+
|
|
442
408
|
const response = await fetch(OAUTH_CONFIG.tokenUrl, {
|
|
443
409
|
method: 'POST',
|
|
444
410
|
headers: {
|
|
@@ -532,18 +498,17 @@ async function openBrowser(url) {
|
|
|
532
498
|
*/
|
|
533
499
|
async function performOAuthFlow(customPort) {
|
|
534
500
|
const port = customPort || OAUTH_CONFIG.callbackPort;
|
|
535
|
-
const callbackHost = getOAuthCallbackHost();
|
|
536
501
|
const { verifier } = generatePKCE();
|
|
537
502
|
const state = generateState();
|
|
538
|
-
|
|
503
|
+
|
|
539
504
|
// Get authorization URL
|
|
540
|
-
const authUrl = getAuthorizationUrl(verifier, state, port
|
|
541
|
-
|
|
505
|
+
const authUrl = getAuthorizationUrl(verifier, state, port);
|
|
506
|
+
|
|
542
507
|
// Start callback server
|
|
543
|
-
const { promise: callbackPromise } = startCallbackServer(state
|
|
544
|
-
|
|
508
|
+
const { promise: callbackPromise } = startCallbackServer(state);
|
|
509
|
+
|
|
545
510
|
console.log(`\n[OAuth] Starting authentication flow...`);
|
|
546
|
-
console.log(`[OAuth] Callback URL:
|
|
511
|
+
console.log(`[OAuth] Callback URL: http://localhost:${port}${OAUTH_CONFIG.callbackPath}`);
|
|
547
512
|
|
|
548
513
|
// Open browser
|
|
549
514
|
await openBrowser(authUrl);
|
|
@@ -557,7 +522,7 @@ async function performOAuthFlow(customPort) {
|
|
|
557
522
|
|
|
558
523
|
// Exchange code for tokens
|
|
559
524
|
console.log(`[OAuth] Exchanging code for tokens...`);
|
|
560
|
-
const tokens = await exchangeCodeForTokens(code, verifier, port
|
|
525
|
+
const tokens = await exchangeCodeForTokens(code, verifier, port);
|
|
561
526
|
console.log(`[OAuth] Token exchange successful`);
|
|
562
527
|
|
|
563
528
|
// Extract account info from access token
|
|
@@ -586,7 +551,7 @@ async function handleOAuthCallback(code, state) {
|
|
|
586
551
|
throw new Error('Invalid or expired OAuth state');
|
|
587
552
|
}
|
|
588
553
|
|
|
589
|
-
const tokens = await exchangeCodeForTokens(code, pkceData.verifier, pkceData.port
|
|
554
|
+
const tokens = await exchangeCodeForTokens(code, pkceData.verifier, pkceData.port);
|
|
590
555
|
const accountInfo = extractAccountInfo(tokens.accessToken);
|
|
591
556
|
|
|
592
557
|
// Clean up
|
|
@@ -649,8 +614,6 @@ export {
|
|
|
649
614
|
extractAccountInfo,
|
|
650
615
|
getAuthorizationUrl,
|
|
651
616
|
getLogoutThenAuthUrl,
|
|
652
|
-
getOAuthCallbackHost,
|
|
653
|
-
getOAuthRedirectUri,
|
|
654
617
|
startCallbackServer,
|
|
655
618
|
exchangeCodeForTokens,
|
|
656
619
|
refreshAccessToken,
|
|
@@ -665,7 +628,5 @@ export default {
|
|
|
665
628
|
handleOAuthCallback,
|
|
666
629
|
refreshAccessToken,
|
|
667
630
|
extractAccountInfo,
|
|
668
|
-
extractCodeFromInput
|
|
669
|
-
getOAuthCallbackHost,
|
|
670
|
-
getOAuthRedirectUri
|
|
631
|
+
extractCodeFromInput
|
|
671
632
|
};
|
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
|