claude-codex-proxy 1.0.5-beta.5 → 1.0.5-beta.6

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.5-beta.5",
3
+ "version": "1.0.5-beta.6",
4
4
  "description": "Multi-account proxy server for OpenAI Codex CLI with Claude API compatibility",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/public/index.html CHANGED
@@ -1,60 +1,60 @@
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>Claude Codex Proxy</title>
7
- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🚀</text></svg>">
8
- <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
9
- <link rel="stylesheet" href="/css/style.css">
10
- </head>
11
- <body class="bg-space-950 text-gray-300 font-sans antialiased min-h-screen selection:bg-neon-purple selection:text-white" x-data="app" x-init="init()">
12
- <div x-cloak class="fixed top-4 right-4 z-[100] flex flex-col gap-2 pointer-events-none">
13
- <template x-if="toast">
14
- <div class="alert shadow-lg border backdrop-blur-md pointer-events-auto min-w-[300px]" :class="{
15
- 'alert-info border-neon-cyan/20 bg-space-900/90 text-neon-cyan': toast.type === 'info',
16
- 'alert-success border-neon-green/20 bg-space-900/90 text-neon-green': toast.type === 'success',
17
- 'alert-error border-red-500/20 bg-space-900/90 text-red-400': toast.type === 'error',
18
- 'alert-warning border-yellow-500/20 bg-space-900/90 text-yellow-400': toast.type === 'warning'
19
- }"><span x-text="toast.message" class="font-mono text-sm"></span></div>
20
- </template>
21
- </div>
22
-
23
- <div x-cloak class="h-14 border-b border-space-border flex items-center px-4 lg:px-6 justify-between bg-space-900/50 backdrop-blur-md z-50 relative" x-show="isAuthenticated">
24
- <div class="flex items-center gap-3">
25
- <button @click="sidebarOpen = !sidebarOpen" class="text-gray-400 hover:text-white focus:outline-none p-1 transition-colors lg:hidden" aria-label="Toggle navigation">☰</button>
26
- <div class="w-8 h-8 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
27
- <div class="flex flex-col"><span class="text-sm font-bold tracking-wide text-white">CODEX PROXY</span><span class="text-[10px] text-gray-500 font-mono tracking-wider" x-text="version ? 'CLAUDE PROXY SYSTEM v' + version : 'CLAUDE PROXY SYSTEM'"></span></div>
28
- </div>
29
- <div class="flex items-center gap-4">
30
- <div class="flex items-center gap-2 px-3 py-1 rounded-full text-xs font-mono border" :class="connectionStatus === 'connected' ? 'bg-neon-green/10 border-neon-green/20 text-neon-green' : 'bg-red-500/10 border-red-500/20 text-red-500'"><span x-text="connectionStatus === 'connected' ? 'Online' : 'Offline'"></span></div>
31
- <button type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="refreshAccounts()" :disabled="loading">Refresh</button>
32
- <button x-show="authRequired" type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="logout()">Logout</button>
33
- </div>
34
- </div>
35
-
36
- <div x-cloak x-show="isAuthenticated" class="flex h-[calc(100vh-56px)] relative">
37
- <div x-show="sidebarOpen" @click="sidebarOpen = false" class="fixed inset-0 bg-black/50 z-40 lg:hidden" style="display: none;"></div>
38
- <aside class="fixed top-14 bottom-0 left-0 z-40 w-64 transform bg-space-900 border-r border-space-border transition-all duration-300 shadow-2xl overflow-hidden lg:static lg:h-auto lg:shadow-none lg:flex-shrink-0 lg:translate-x-0" :class="{'translate-x-0': sidebarOpen, '-translate-x-full': !sidebarOpen}">
39
- <div class="w-64 flex flex-col h-full sidebar-content">
40
- <div class="sidebar-section-title">Workspace</div>
41
- <nav class="sidebar-nav">
42
- <a href="/dashboard" class="nav-item" :class="{'active': activeTab === 'dashboard'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z"/></svg><span>Dashboard</span></a>
43
- <a href="/account-management" class="nav-item" :class="{'active': activeTab === 'accounts'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M16 20v-1a4 4 0 00-4-4H7a4 4 0 00-4 4v1m6-9a4 4 0 100-8 4 4 0 000 8zm6 1a3 3 0 100-6m2 15v-1a4 4 0 00-3-3.87"/></svg><span>Accounts</span></a>
44
- </nav>
45
- <div class="sidebar-section-title">System</div>
46
- <nav class="sidebar-nav">
47
- <a href="/logs" class="nav-item" :class="{'active': activeTab === 'logs'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 5a2 2 0 012-2h8l4 4v12a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm4 7h8m-8 4h6"/></svg><span>Logs</span></a>
48
- <a href="/client-api-keys" class="nav-item" :class="{'active': activeTab === 'client-api-keys'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><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 7zm0 0a1 1 0 100 2 1 1 0 000-2z"/></svg><span>Client API Keys</span></a>
49
- <a href="/settings" class="nav-item" :class="{'active': activeTab === 'settings'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 15.5a3.5 3.5 0 100-7 3.5 3.5 0 000 7zm7.4-3.5a7.4 7.4 0 00-.1-1.1l2-1.5-2-3.4-2.4 1a8 8 0 00-1.8-1L14.8 3h-4l-.3 2.8a8 8 0 00-1.8 1l-2.4-1-2 3.4 2 1.5A7.4 7.4 0 006.6 12c0 .4 0 .7.1 1.1l-2 1.5 2 3.4 2.4-1a8 8 0 001.8 1l.3 2.8h4l.3-2.8a8 8 0 001.8-1l2.4 1 2-3.4-2-1.5c.1-.4.1-.7.1-1.1z"/></svg><span>Settings</span></a>
50
- </nav>
51
- <div class="sidebar-footer"><span class="sidebar-status-dot"></span><span x-text="connectionStatus === 'connected' ? 'Proxy connected' : 'Proxy offline'"></span></div>
52
- </div>
53
- </aside>
54
- <main id="view-content" class="flex-1 overflow-auto bg-space-950 relative custom-scrollbar" aria-live="polite"></main>
55
- </div>
56
-
57
- <div x-cloak id="modal-content"></div>
58
- <script src="/js/app.js"></script>
59
- </body>
60
- </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>Claude Codex Proxy</title>
7
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🚀</text></svg>">
8
+ <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
9
+ <link rel="stylesheet" href="/css/style.css">
10
+ </head>
11
+ <body class="bg-space-950 text-gray-300 font-sans antialiased min-h-screen selection:bg-neon-purple selection:text-white" x-data="app" x-init="init()">
12
+ <div x-cloak class="fixed top-4 right-4 z-[100] flex flex-col gap-2 pointer-events-none">
13
+ <template x-if="toast">
14
+ <div class="alert shadow-lg border backdrop-blur-md pointer-events-auto min-w-[300px]" :class="{
15
+ 'alert-info border-neon-cyan/20 bg-space-900/90 text-neon-cyan': toast.type === 'info',
16
+ 'alert-success border-neon-green/20 bg-space-900/90 text-neon-green': toast.type === 'success',
17
+ 'alert-error border-red-500/20 bg-space-900/90 text-red-400': toast.type === 'error',
18
+ 'alert-warning border-yellow-500/20 bg-space-900/90 text-yellow-400': toast.type === 'warning'
19
+ }"><span x-text="toast.message" class="font-mono text-sm"></span></div>
20
+ </template>
21
+ </div>
22
+
23
+ <div x-cloak class="h-14 border-b border-space-border flex items-center px-4 lg:px-6 justify-between bg-space-900/50 backdrop-blur-md z-50 relative" x-show="isAuthenticated">
24
+ <div class="flex items-center gap-3">
25
+ <button @click="sidebarOpen = !sidebarOpen" class="text-gray-400 hover:text-white focus:outline-none p-1 transition-colors lg:hidden" aria-label="Toggle navigation">☰</button>
26
+ <div class="w-8 h-8 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
27
+ <div class="flex flex-col"><span class="text-sm font-bold tracking-wide text-white">CODEX PROXY</span><span class="text-[10px] text-gray-500 font-mono tracking-wider" x-text="version ? 'CLAUDE PROXY SYSTEM v' + version : 'CLAUDE PROXY SYSTEM'"></span></div>
28
+ </div>
29
+ <div class="flex items-center gap-4">
30
+ <div class="flex items-center gap-2 px-3 py-1 rounded-full text-xs font-mono border" :class="connectionStatus === 'connected' ? 'bg-neon-green/10 border-neon-green/20 text-neon-green' : 'bg-red-500/10 border-red-500/20 text-red-500'"><span x-text="connectionStatus === 'connected' ? 'Online' : 'Offline'"></span></div>
31
+ <button type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="refreshAccounts()" :disabled="loading">Refresh</button>
32
+ <button x-show="authRequired" type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="logout()">Logout</button>
33
+ </div>
34
+ </div>
35
+
36
+ <div x-cloak x-show="isAuthenticated" class="flex h-[calc(100vh-56px)] relative">
37
+ <div x-show="sidebarOpen" @click="sidebarOpen = false" class="fixed inset-0 bg-black/50 z-40 lg:hidden" style="display: none;"></div>
38
+ <aside class="fixed top-14 bottom-0 left-0 z-40 w-64 transform bg-space-900 border-r border-space-border transition-all duration-300 shadow-2xl overflow-hidden lg:static lg:h-auto lg:shadow-none lg:flex-shrink-0 lg:translate-x-0" :class="{'translate-x-0': sidebarOpen, '-translate-x-full': !sidebarOpen}">
39
+ <div class="w-64 flex flex-col h-full sidebar-content">
40
+ <div class="sidebar-section-title">Workspace</div>
41
+ <nav class="sidebar-nav">
42
+ <a href="/dashboard" class="nav-item" :class="{'active': activeTab === 'dashboard'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z"/></svg><span>Dashboard</span></a>
43
+ <a href="/account-management" class="nav-item" :class="{'active': activeTab === 'accounts'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M16 20v-1a4 4 0 00-4-4H7a4 4 0 00-4 4v1m6-9a4 4 0 100-8 4 4 0 000 8zm6 1a3 3 0 100-6m2 15v-1a4 4 0 00-3-3.87"/></svg><span>Accounts</span></a>
44
+ </nav>
45
+ <div class="sidebar-section-title">System</div>
46
+ <nav class="sidebar-nav">
47
+ <a href="/logs" class="nav-item" :class="{'active': activeTab === 'logs'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 5a2 2 0 012-2h8l4 4v12a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm4 7h8m-8 4h6"/></svg><span>Logs</span></a>
48
+ <a href="/client-api-keys" class="nav-item" :class="{'active': activeTab === 'client-api-keys'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><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 7zm0 0a1 1 0 100 2 1 1 0 000-2z"/></svg><span>Client API Keys</span></a>
49
+ <a href="/settings" class="nav-item" :class="{'active': activeTab === 'settings'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 15.5a3.5 3.5 0 100-7 3.5 3.5 0 000 7zm7.4-3.5a7.4 7.4 0 00-.1-1.1l2-1.5-2-3.4-2.4 1a8 8 0 00-1.8-1L14.8 3h-4l-.3 2.8a8 8 0 00-1.8 1l-2.4-1-2 3.4 2 1.5A7.4 7.4 0 006.6 12c0 .4 0 .7.1 1.1l-2 1.5 2 3.4 2.4-1a8 8 0 001.8 1l.3 2.8h4l.3-2.8a8 8 0 001.8-1l2.4 1 2-3.4-2-1.5c.1-.4.1-.7.1-1.1z"/></svg><span>Settings</span></a>
50
+ </nav>
51
+ <div class="sidebar-footer"><span class="sidebar-status-dot"></span><span x-text="connectionStatus === 'connected' ? 'Proxy connected' : 'Proxy offline'"></span></div>
52
+ </div>
53
+ </aside>
54
+ <main id="view-content" class="flex-1 overflow-auto bg-space-950 relative custom-scrollbar" aria-live="polite"></main>
55
+ </div>
56
+
57
+ <div x-cloak id="modal-content"></div>
58
+ <script src="/js/app.js"></script>
59
+ </body>
60
+ </html>
package/public/js/app.js CHANGED
@@ -109,7 +109,7 @@ document.addEventListener('alpine:init', () => {
109
109
  async resetModelMapSetting() { if (this.modelMapSaving) return; this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to reset model mapping', 'error'); },
110
110
  async loadClientApiKeys() { this.clientApiKeysLoading = true; const { ok, data } = await this.api('/settings/client-api-keys'); this.clientApiKeysLoading = false; if (ok && Array.isArray(data?.clientApiKeys)) this.clientApiKeys = data.clientApiKeys; else this.showToast(data?.error || 'Failed to load client API keys', 'error'); },
111
111
  async createClientApiKey() { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(this.clientApiKeyWeeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api('/settings/client-api-keys', { method: 'POST', body: JSON.stringify({ name: this.clientApiKeyName, remark: this.clientApiKeyRemark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.clientApiKeyWeeklyLimitUsd = 50; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
112
- async loadClientProxyConfig() { const { ok, data } = await this.api('/claude/config/proxy', { method: 'POST' }); if (ok && data?.success && data?.env) this.clientProxyConfig = data; }, async copyClientText(text, successMessage) { if (!text) return; try { await navigator.clipboard.writeText(text); this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const commands = this.clientProxyConfig?.commands?.powershell; return Array.isArray(commands) ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
112
+ async loadClientProxyConfig() { const { ok, data } = await this.api('/claude/config/proxy', { method: 'POST' }); if (ok && data?.success && data?.env) this.clientProxyConfig = data; }, async copyClientText(text, successMessage) { if (!text) return; try { if (navigator.clipboard?.writeText && window.isSecureContext) await navigator.clipboard.writeText(text); else { const textarea = document.createElement('textarea'); textarea.value = text; textarea.setAttribute('readonly', ''); textarea.style.cssText = 'position:absolute;opacity:0;left:-999999px;top:-999999px'; document.body.appendChild(textarea); textarea.focus(); textarea.select(); const copied = document.execCommand('copy'); textarea.remove(); if (!copied) throw new Error('Clipboard copy was rejected'); } this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const commands = this.clientProxyConfig?.commands?.powershell; return Array.isArray(commands) ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
113
113
  async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(clientApiKey.weeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'PUT', body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to update client API key', 'error'); }, async deleteClientApiKey(clientApiKey) { if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to delete client API key', 'error'); },
114
114
  showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, startLogStream() { if (!this.isAuthenticated) return; this.logEventSource?.close(); const params = new URLSearchParams({ history: 'true' }); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(`/api/logs/stream?${params}`); this.logEventSource.onmessage = event => { try { this.logs.unshift(JSON.parse(event.data)); this.logs = this.logs.slice(0, 500); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
115
115
  }));
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>
@@ -1,125 +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 };
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 };
@@ -84,16 +84,16 @@ const getAdminKeys = () => [process.env.PROXY_ADMIN_KEY].filter(Boolean);
84
84
  export const requireAdminAuth = requireKeys(getAdminKeys);
85
85
 
86
86
  export function requireClientAuth(req, res, next) {
87
- if (!isPublicDeployment()) {
88
- return next();
89
- }
90
-
91
87
  const requestKey = getRequestApiKey(req);
92
88
  const clientKey = findClientKey(requestKey);
93
- if (!clientKey) {
89
+ if (isPublicDeployment() && !clientKey) {
94
90
  return sendUnauthorized(req, res);
95
91
  }
96
92
 
93
+ if (!clientKey) {
94
+ return next();
95
+ }
96
+
97
97
  const quota = getClientKeyQuota(
98
98
  clientKey.id,
99
99
  clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
@@ -1,96 +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 };
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 };
@@ -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,
@@ -88,8 +89,9 @@ export function registerApiRoutes(app, { port }) {
88
89
  // ─── OpenAI Chat Completions API ───────────────────────────────────────────
89
90
  app.post('/v1/chat/completions', requireClientAuth, handleChatCompletion);
90
91
 
91
- // ─── Models ────────────────────────────────────────────────────────────────
92
+ // ─── Models and Client Quota ───────────────────────────────────────────────
92
93
  app.get('/v1/models', requireClientAuth, handleListModels);
94
+ app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
93
95
 
94
96
  app.use(requireAdminAuth);
95
97
 
@@ -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
+ }
@@ -1,5 +1,5 @@
1
- import { getServerSettings } from '../server-settings.js';
2
-
3
- export function shouldLogRawProxyPayloads() {
4
- return getServerSettings().logRawProxyPayloads === true;
5
- }
1
+ import { getServerSettings } from '../server-settings.js';
2
+
3
+ export function shouldLogRawProxyPayloads() {
4
+ return getServerSettings().logRawProxyPayloads === true;
5
+ }