claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.5
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/package.json +1 -1
- package/public/css/style.css +127 -0
- package/public/index.html +60 -60
- package/public/js/app.js +116 -116
- package/public/login.html +32 -32
- package/public/views/client-api-keys-modals.html +5 -0
- package/public/views/client-api-keys.html +54 -31
- 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-pricing.js +96 -0
- package/src/response-streamer.js +5 -5
- package/src/routes/chat-route.js +25 -4
- 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/proxy-logging.js +5 -0
package/public/login.html
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
<!DOCTYPE html>
|
|
2
|
-
<html lang="en" data-theme="codex" class="dark">
|
|
3
|
-
<head>
|
|
4
|
-
<meta charset="UTF-8">
|
|
5
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
|
-
<title>Sign in · Claude Codex Proxy</title>
|
|
7
|
-
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
|
|
8
|
-
<link rel="stylesheet" href="/css/style.css">
|
|
9
|
-
</head>
|
|
10
|
-
<body class="bg-space-950 text-gray-300 font-sans antialiased min-h-screen" x-data="app" x-init="init()">
|
|
11
|
-
<main x-cloak x-show="authChecked" class="min-h-screen flex items-center justify-center px-4">
|
|
12
|
-
<div class="w-full max-w-md bg-space-900/70 border border-space-border rounded-2xl p-6 shadow-2xl backdrop-blur-md">
|
|
13
|
-
<div class="flex items-center gap-3 mb-6">
|
|
14
|
-
<div class="w-10 h-10 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
|
|
15
|
-
<div>
|
|
16
|
-
<h1 class="text-xl font-bold text-white">Access Required</h1>
|
|
17
|
-
<p class="text-sm text-gray-500">Enter the server access key to open the management UI.</p>
|
|
18
|
-
</div>
|
|
19
|
-
</div>
|
|
20
|
-
<form @submit.prevent="login" class="space-y-4">
|
|
21
|
-
<label class="form-control w-full">
|
|
22
|
-
<span class="label-text text-gray-400 mb-1">Access Key</span>
|
|
23
|
-
<input type="password" x-model="loginApiKey" class="input input-bordered w-full bg-space-950 border-space-border text-white" placeholder="Enter access key" autocomplete="current-password" autofocus>
|
|
24
|
-
</label>
|
|
25
|
-
<p x-show="loginError" x-text="loginError" class="text-sm text-red-400"></p>
|
|
26
|
-
<button type="submit" class="btn w-full bg-neon-purple hover:bg-purple-600 border-0 text-white">Unlock UI</button>
|
|
27
|
-
</form>
|
|
28
|
-
</div>
|
|
29
|
-
</main>
|
|
30
|
-
<script src="/js/app.js"></script>
|
|
31
|
-
</body>
|
|
32
|
-
</html>
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en" data-theme="codex" class="dark">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
|
+
<title>Sign in · Claude Codex Proxy</title>
|
|
7
|
+
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
|
|
8
|
+
<link rel="stylesheet" href="/css/style.css">
|
|
9
|
+
</head>
|
|
10
|
+
<body class="bg-space-950 text-gray-300 font-sans antialiased min-h-screen" x-data="app" x-init="init()">
|
|
11
|
+
<main x-cloak x-show="authChecked" class="min-h-screen flex items-center justify-center px-4">
|
|
12
|
+
<div class="w-full max-w-md bg-space-900/70 border border-space-border rounded-2xl p-6 shadow-2xl backdrop-blur-md">
|
|
13
|
+
<div class="flex items-center gap-3 mb-6">
|
|
14
|
+
<div class="w-10 h-10 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
|
|
15
|
+
<div>
|
|
16
|
+
<h1 class="text-xl font-bold text-white">Access Required</h1>
|
|
17
|
+
<p class="text-sm text-gray-500">Enter the server access key to open the management UI.</p>
|
|
18
|
+
</div>
|
|
19
|
+
</div>
|
|
20
|
+
<form @submit.prevent="login" class="space-y-4">
|
|
21
|
+
<label class="form-control w-full">
|
|
22
|
+
<span class="label-text text-gray-400 mb-1">Access Key</span>
|
|
23
|
+
<input type="password" x-model="loginApiKey" class="input input-bordered w-full bg-space-950 border-space-border text-white" placeholder="Enter access key" autocomplete="current-password" autofocus>
|
|
24
|
+
</label>
|
|
25
|
+
<p x-show="loginError" x-text="loginError" class="text-sm text-red-400"></p>
|
|
26
|
+
<button type="submit" class="btn w-full bg-neon-purple hover:bg-purple-600 border-0 text-white">Unlock UI</button>
|
|
27
|
+
</form>
|
|
28
|
+
</div>
|
|
29
|
+
</main>
|
|
30
|
+
<script src="/js/app.js"></script>
|
|
31
|
+
</body>
|
|
32
|
+
</html>
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
<input type="text" x-model="clientApiKeyRemark" placeholder="Optional note"
|
|
15
15
|
class="input w-full bg-space-800 border-space-border text-white font-mono text-sm" @keydown.enter="createClientApiKey()">
|
|
16
16
|
</label>
|
|
17
|
+
<label class="block">
|
|
18
|
+
<span class="block text-xs text-gray-400 mb-2">Weekly limit (USD)</span>
|
|
19
|
+
<input type="number" min="0" step="0.01" x-model="clientApiKeyWeeklyLimitUsd"
|
|
20
|
+
class="input w-full bg-space-800 border-space-border text-white font-mono text-sm" @keydown.enter="createClientApiKey()">
|
|
21
|
+
</label>
|
|
17
22
|
</div>
|
|
18
23
|
<div class="mt-6 flex justify-end gap-2">
|
|
19
24
|
<button class="btn btn-outline btn-sm text-gray-400" @click="showCreateClientApiKeyModal = false" :disabled="clientApiKeySaving">Cancel</button>
|
|
@@ -8,39 +8,62 @@
|
|
|
8
8
|
</div>
|
|
9
9
|
</div>
|
|
10
10
|
|
|
11
|
-
<div class="
|
|
12
|
-
<div class="
|
|
13
|
-
<
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
</
|
|
11
|
+
<div class="client-keys-panel">
|
|
12
|
+
<div class="client-keys-toolbar">
|
|
13
|
+
<div>
|
|
14
|
+
<h2>Access keys</h2>
|
|
15
|
+
<p>Edit a key, then save its changes.</p>
|
|
16
|
+
</div>
|
|
17
|
+
<div class="client-keys-toolbar-actions">
|
|
18
|
+
<div x-show="clientApiKeys.length" class="client-keys-reset">
|
|
19
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 8v4l2.5 2.5M21 12a9 9 0 11-2.64-6.36M21 4v5h-5"/></svg>
|
|
20
|
+
<div><span>Next weekly reset</span><strong x-text="clientApiKeys[0]?.quota?.nextPeriodStart ? new Date(clientApiKeys[0].quota.nextPeriodStart).toLocaleString() : '-'"></strong></div>
|
|
21
|
+
</div>
|
|
22
|
+
<button class="client-keys-new" @click="revealedClientApiKey = ''; clientProxyConfig = null; showCreateClientApiKeyModal = true">
|
|
23
|
+
<span>+</span> New API Key
|
|
24
|
+
</button>
|
|
25
|
+
</div>
|
|
17
26
|
</div>
|
|
27
|
+
|
|
18
28
|
<template x-if="clientApiKeysLoading">
|
|
19
|
-
<div class="
|
|
29
|
+
<div class="client-keys-empty">Loading client API keys...</div>
|
|
20
30
|
</template>
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
<
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
<
|
|
37
|
-
<
|
|
38
|
-
<
|
|
39
|
-
</div
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
31
|
+
|
|
32
|
+
<div class="client-keys-list" x-show="!clientApiKeysLoading && clientApiKeys.length">
|
|
33
|
+
<template x-for="clientApiKey in clientApiKeys" :key="clientApiKey.id">
|
|
34
|
+
<article class="client-key-card">
|
|
35
|
+
<div class="client-key-identity">
|
|
36
|
+
<div class="client-key-icon">
|
|
37
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M15 7a5 5 0 11-9.6 2H3v4h3v3h3v-3h2.4A5 5 0 0115 7z"/></svg>
|
|
38
|
+
</div>
|
|
39
|
+
<div class="client-key-fields">
|
|
40
|
+
<label><span>Client name</span><input type="text" x-model="clientApiKey.name" placeholder="Unnamed"></label>
|
|
41
|
+
<label><span>Remark</span><input type="text" x-model="clientApiKey.remark" placeholder="No remark"></label>
|
|
42
|
+
</div>
|
|
43
|
+
</div>
|
|
44
|
+
|
|
45
|
+
<div class="client-key-quota">
|
|
46
|
+
<div class="client-key-quota-heading">
|
|
47
|
+
<span>Weekly usage</span>
|
|
48
|
+
<strong><span x-text="`$${(clientApiKey.quota?.consumedUsd ?? 0).toFixed(2)}`"></span><small x-text="` / $${Number(clientApiKey.weeklyLimitUsd || 0).toFixed(2)}`"></small></strong>
|
|
49
|
+
</div>
|
|
50
|
+
<div class="client-key-progress"><i :style="`width: ${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100))}%`"></i></div>
|
|
51
|
+
<div class="client-key-quota-foot"><span x-text="`$${(clientApiKey.quota?.remainingUsd ?? (Number(clientApiKey.weeklyLimitUsd) || 0)).toFixed(2)} remaining`"></span><span x-text="`${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100)).toFixed(1)}% used`"></span></div>
|
|
52
|
+
</div>
|
|
53
|
+
|
|
54
|
+
<label class="client-key-limit"><span>Weekly limit</span><div><b>$</b><input type="number" min="0" step="0.01" x-model="clientApiKey.weeklyLimitUsd"></div></label>
|
|
55
|
+
|
|
56
|
+
<div class="client-key-meta"><span>Created</span><strong x-text="new Date(clientApiKey.createdAt).toLocaleDateString()"></strong><small x-text="new Date(clientApiKey.createdAt).toLocaleTimeString()"></small></div>
|
|
57
|
+
|
|
58
|
+
<div class="client-key-actions">
|
|
59
|
+
<button class="client-key-save" @click="updateClientApiKey(clientApiKey)" :disabled="clientApiKeySaving">Save changes</button>
|
|
60
|
+
<button class="client-key-delete" @click="deleteClientApiKey(clientApiKey)" :disabled="clientApiKeySaving" aria-label="Delete API key" title="Delete">
|
|
61
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 7h16M9 7V4h6v3m-8 0 1 13h8l1-13M10 11v5m4-5v5"/></svg>
|
|
62
|
+
</button>
|
|
63
|
+
</div>
|
|
64
|
+
</article>
|
|
65
|
+
</template>
|
|
66
|
+
</div>
|
|
67
|
+
<div x-show="!clientApiKeysLoading && !clientApiKeys.length" class="client-keys-empty">No client API keys. Create one to connect Claude Code clients.</div>
|
|
45
68
|
</div>
|
|
46
69
|
</div>
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { CONFIG_DIR } from './account-manager.js';
|
|
4
|
+
|
|
5
|
+
const USAGE_FILE = join(CONFIG_DIR, 'client-key-usage.json');
|
|
6
|
+
export const MICRO_USD_PER_USD = 1_000_000;
|
|
7
|
+
|
|
8
|
+
function loadUsage() {
|
|
9
|
+
if (!existsSync(USAGE_FILE)) return {};
|
|
10
|
+
|
|
11
|
+
try {
|
|
12
|
+
const data = JSON.parse(readFileSync(USAGE_FILE, 'utf8'));
|
|
13
|
+
return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
|
|
14
|
+
} catch (error) {
|
|
15
|
+
console.error('[ClientKeyUsage] Failed to read usage:', error.message);
|
|
16
|
+
return {};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function saveUsage(usage) {
|
|
21
|
+
if (!existsSync(CONFIG_DIR)) {
|
|
22
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
23
|
+
}
|
|
24
|
+
writeFileSync(USAGE_FILE, JSON.stringify(usage, null, 2), { mode: 0o600 });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Returns the current weekly period start in the server's local time zone.
|
|
29
|
+
* A period begins at Monday 08:00 and ends at the following Monday 08:00.
|
|
30
|
+
*/
|
|
31
|
+
export function getCurrentPeriodStart(now = new Date()) {
|
|
32
|
+
const periodStart = new Date(now);
|
|
33
|
+
const daysSinceMonday = (periodStart.getDay() + 6) % 7;
|
|
34
|
+
periodStart.setDate(periodStart.getDate() - daysSinceMonday);
|
|
35
|
+
periodStart.setHours(8, 0, 0, 0);
|
|
36
|
+
|
|
37
|
+
if (now < periodStart) {
|
|
38
|
+
periodStart.setDate(periodStart.getDate() - 7);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return periodStart.toISOString();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function getNextPeriodStart(now = new Date()) {
|
|
45
|
+
const nextPeriodStart = new Date(getCurrentPeriodStart(now));
|
|
46
|
+
nextPeriodStart.setDate(nextPeriodStart.getDate() + 7);
|
|
47
|
+
return nextPeriodStart.toISOString();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function usdToMicrousd(usd) {
|
|
51
|
+
return Math.round(Number(usd) * MICRO_USD_PER_USD);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function microusdToUsd(microusd) {
|
|
55
|
+
return Number(microusd) / MICRO_USD_PER_USD;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Returns a key's usage after lazily resetting it for a new weekly period.
|
|
60
|
+
*/
|
|
61
|
+
export function getClientKeyUsage(keyId, now = new Date()) {
|
|
62
|
+
const usage = loadUsage();
|
|
63
|
+
const periodStart = getCurrentPeriodStart(now);
|
|
64
|
+
const entry = usage[keyId];
|
|
65
|
+
const consumedMicrousd = entry?.periodStart === periodStart && Number.isSafeInteger(entry.consumedMicrousd)
|
|
66
|
+
? Math.max(0, entry.consumedMicrousd)
|
|
67
|
+
: 0;
|
|
68
|
+
|
|
69
|
+
if (!entry || entry.periodStart !== periodStart || entry.consumedMicrousd !== consumedMicrousd) {
|
|
70
|
+
usage[keyId] = { periodStart, consumedMicrousd };
|
|
71
|
+
saveUsage(usage);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
periodStart,
|
|
76
|
+
nextPeriodStart: getNextPeriodStart(now),
|
|
77
|
+
consumedMicrousd
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Records actual USD consumption for a client key. Call this only after an
|
|
83
|
+
* upstream response provides a verified per-request charge.
|
|
84
|
+
*/
|
|
85
|
+
export function recordClientKeyUsage(keyId, consumedMicrousd, now = new Date()) {
|
|
86
|
+
if (!Number.isSafeInteger(consumedMicrousd) || consumedMicrousd < 0) {
|
|
87
|
+
throw new TypeError('consumedMicrousd must be a non-negative safe integer');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const current = getClientKeyUsage(keyId, now);
|
|
91
|
+
const usage = loadUsage();
|
|
92
|
+
usage[keyId] = {
|
|
93
|
+
periodStart: current.periodStart,
|
|
94
|
+
consumedMicrousd: current.consumedMicrousd + consumedMicrousd
|
|
95
|
+
};
|
|
96
|
+
saveUsage(usage);
|
|
97
|
+
return usage[keyId];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function deleteClientKeyUsage(keyId) {
|
|
101
|
+
const usage = loadUsage();
|
|
102
|
+
if (!(keyId in usage)) return;
|
|
103
|
+
delete usage[keyId];
|
|
104
|
+
saveUsage(usage);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Returns a key's current quota summary without charging any request.
|
|
109
|
+
*/
|
|
110
|
+
export function getClientKeyQuota(keyId, weeklyLimitUsd, now = new Date()) {
|
|
111
|
+
const usage = getClientKeyUsage(keyId, now);
|
|
112
|
+
const weeklyLimitMicrousd = usdToMicrousd(weeklyLimitUsd);
|
|
113
|
+
const remainingMicrousd = Math.max(0, weeklyLimitMicrousd - usage.consumedMicrousd);
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
...usage,
|
|
117
|
+
weeklyLimitMicrousd,
|
|
118
|
+
remainingMicrousd,
|
|
119
|
+
weeklyLimitUsd: microusdToUsd(weeklyLimitMicrousd),
|
|
120
|
+
consumedUsd: microusdToUsd(usage.consumedMicrousd),
|
|
121
|
+
remainingUsd: microusdToUsd(remainingMicrousd)
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export { USAGE_FILE };
|
package/src/deployment.js
CHANGED
|
@@ -1,49 +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 };
|
|
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
|
@@ -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
|
+
if (!isPublicDeployment()) {
|
|
88
|
+
return next();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const requestKey = getRequestApiKey(req);
|
|
92
|
+
const clientKey = findClientKey(requestKey);
|
|
93
|
+
if (!clientKey) {
|
|
94
|
+
return sendUnauthorized(req, res);
|
|
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
|
|
|
@@ -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 };
|