claude-codex-proxy 1.0.5-beta.3 โ†’ 1.0.5-beta.4

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.3",
3
+ "version": "1.0.5-beta.4",
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
@@ -1,116 +1,116 @@
1
- document.addEventListener('alpine:init', () => {
2
- Alpine.data('app', () => ({
3
- version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
4
- loading: false, refreshingTokenEmails: [], toast: null, currentTime: '', authRequired: false,
5
- authChecked: false, apiKey: localStorage.getItem('codexProxyApiKey') || '', loginApiKey: '', loginError: '',
6
- accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
7
- accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
8
- modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
9
- clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeysLoading: false,
10
- clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
11
- showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
12
- oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
13
- testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
14
- serverUrl: window.location.origin, logs: [], logSearchQuery: '',
15
- logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false }, logEventSource: null,
16
-
17
- get isAuthenticated() { return !this.authRequired || Boolean(this.apiKey); },
18
- get filteredLogs() { const query = this.logSearchQuery.trim().toLowerCase(); return this.logs.filter(log => this.logFilters[log.level] && (!query || log.message.toLowerCase().includes(query))); },
19
- get filteredAccounts() { if (!this.searchQuery) return this.accounts; const q = this.searchQuery.toLowerCase(); return this.accounts.filter(a => a.email.toLowerCase().includes(q)); },
20
-
21
- async init() {
22
- await this.checkHealth();
23
- this.authChecked = true;
24
- if (this.isLoginPage()) {
25
- if (this.isAuthenticated) window.location.replace('/dashboard');
26
- return;
27
- }
28
- if (!this.isAuthenticated) { window.location.replace('/login'); return; }
29
- await this.loadCurrentView();
30
- this.updateTime();
31
- setInterval(() => this.updateTime(), 1000);
32
- setInterval(() => this.checkHealth(), 30000);
33
- window.addEventListener('resize', () => { this.sidebarOpen = window.innerWidth >= 1024; });
34
- window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
35
- },
36
-
37
- isLoginPage() { return window.location.pathname === '/login' || window.location.pathname === '/login.html'; },
38
- async loadCurrentView() {
39
- const route = window.location.pathname.replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
40
- const tab = route === 'account-management' ? 'accounts' : route;
41
- const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
42
- this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
43
- if (this.activeTab !== tab) { window.location.replace('/dashboard'); return; }
44
- const [viewResponse, modalResponse] = await Promise.all([
45
- fetch(`/views/${this.activeTab}.html`),
46
- fetch(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html')
47
- ]);
48
- if (!viewResponse.ok) { window.location.replace('/dashboard'); return; }
49
- document.querySelector('#view-content').innerHTML = await viewResponse.text();
50
- document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
51
- Alpine.initTree(document.querySelector('#view-content'));
52
- Alpine.initTree(document.querySelector('#modal-content'));
53
- this.loadViewData();
54
- },
55
- loadViewData() {
56
- const loaders = {
57
- dashboard: () => Promise.all([this.refreshAccounts(), this.loadModelMapSetting()]),
58
- accounts: () => this.refreshAccounts(), logs: () => this.startLogStream(),
59
- 'client-api-keys': () => this.loadClientApiKeys(),
60
- settings: () => Promise.all([this.loadAccountStrategySetting(), this.loadModelMapSetting(), this.loadRawProxyLogsSetting()])
61
- };
62
- return loaders[this.activeTab]?.();
63
- },
64
- updateTime() { this.currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); },
65
- async api(endpoint, options = {}) {
66
- try {
67
- const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
68
- if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
69
- const response = await fetch(endpoint, { ...options, headers });
70
- const data = await response.json();
71
- if (response.status === 401 && endpoint !== '/health') this.logout(false);
72
- return { ok: response.ok, data };
73
- } catch (error) { return { ok: false, error: error.message }; }
74
- },
75
- async login() {
76
- const key = this.loginApiKey.trim();
77
- if (!key) { this.loginError = 'Access key is required'; return; }
78
- this.apiKey = key;
79
- const { ok } = await this.api('/settings/account-strategy');
80
- if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
81
- localStorage.setItem('codexProxyApiKey', key);
82
- window.location.replace('/dashboard');
83
- },
84
- logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace('/login'); },
85
- async checkHealth() { const { ok, data } = await this.api('/health'); this.connectionStatus = ok ? 'connected' : 'disconnected'; if (ok && data?.version) this.version = data.version; if (ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; },
86
- async refreshAccounts() { this.loading = true; const { ok, data } = await this.api('/accounts'); if (ok && data.accounts) { this.accounts = data.accounts; this.stats = { total: data.total || data.accounts.length, active: data.accounts.filter(a => a.isActive).length, expired: data.accounts.filter(a => a.tokenExpired).length, planType: data.accounts.find(a => a.isActive)?.planType || '-' }; await this.refreshAllQuotaData(); } this.loading = false; },
87
- async refreshAllQuotaData() { if (!this.accounts.length) return; const { ok, data } = await this.api('/accounts/quota/all'); if (!ok || !data?.accounts) return; const quotaMap = new Map(data.accounts.map(entry => [entry.email, entry.quota || null])); this.accounts = this.accounts.map(account => ({ ...account, quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota })); if (this.selectedAccount?.email) this.selectedAccount = this.accounts.find(account => account.email === this.selectedAccount.email) || this.selectedAccount; },
88
- getRemainingPercentage(account) { const usage = account?.quota?.usage; if (!usage) return null; const values = [Number(usage.percentage), Number(usage.totalTokenUsage), Number.isFinite(Number(usage.remaining)) ? 100 - Number(usage.remaining) : NaN]; const used = values.find(Number.isFinite); if (!Number.isFinite(used)) return usage.limitReached === true || usage.allowed === false ? 0 : null; return Math.max(0, Math.round(100 - Math.max(0, Math.min(100, used)))); },
89
- isQuotaExhausted(account) { const remaining = this.getRemainingPercentage(account); return remaining !== null && (remaining <= 0 || account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false); },
90
- quotaBarClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
91
- quotaTextClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? '-' : `${remaining}%`; },
92
- getQuotaResetAt(account) { const usage = account?.quota?.usage; if (!usage) return null; if (usage.resetAt) return usage.resetAt; const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at); if (Number.isFinite(epoch)) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
93
- quotaResetAtLabel(account) { const resetAt = this.getQuotaResetAt(account); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
94
- quotaResetSummary(account) { const resetAt = this.getQuotaResetAt(account); if (!resetAt) return null; const seconds = Math.max(0, Math.floor((new Date(resetAt).getTime() - Date.now()) / 1000)); if (!seconds) return 'Reset due now'; const hours = Math.floor(seconds / 3600), minutes = Math.floor((seconds % 3600) / 60); return hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
95
- async startOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) window.open(data.oauth_url, 'ChatGPT Login', 'width=500,height=700'); else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
96
- async startManualOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) { this.oauthManualUrl = data.oauth_url; this.oauthManualVerifier = data.verifier; this.oauthManualCode = ''; this.oauthManualMode = true; } else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
97
- async submitManualOAuth() { if (!this.oauthManualCode) return; const { ok, data } = await this.api('/accounts/add/manual', { method: 'POST', body: JSON.stringify({ code: this.oauthManualCode, verifier: this.oauthManualVerifier }) }); if (ok && data.success) { this.showAddModal = false; this.oauthManualMode = false; this.refreshAccounts(); } else this.showToast(data?.error || 'Failed to add account', 'error'); },
98
- async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
99
- async importFromCodex() { const { ok, data } = await this.api('/accounts/import', { method: 'POST' }); if (ok && data.success) { this.showAddModal = false; this.refreshAccounts(); } else this.showToast(data?.message || 'Import failed', 'error'); },
100
- async switchAccount(email) { const { ok, data } = await this.api('/accounts/switch', { method: 'POST', body: JSON.stringify({ email }) }); if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Failed to switch', 'error'); },
101
- async refreshToken(email) { if (this.refreshingTokenEmails.includes(email)) return; this.refreshingTokenEmails.push(email); try { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }); if (ok && data.success) await this.refreshAccounts(); else this.showToast(data?.message || 'Refresh failed', 'error'); } finally { this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email); } },
102
- async refreshAllTokens() { const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' }); if (ok) this.refreshAccounts(); else this.showToast(data?.message || 'Failed', 'error'); }, confirmDelete(email) { this.deleteTarget = email; this.showDeleteModal = true; },
103
- async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; },
104
- async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
105
- async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
106
- async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
107
- async loadModelMapSetting() { this.modelMapLoading = true; const { ok, data } = await this.api('/settings/model-map'); this.modelMapLoading = false; if (ok && data?.modelMap) this.modelMappings = { sonnet: data.modelMap.sonnet || this.modelMappings.sonnet, opus: data.modelMap.opus || this.modelMappings.opus, haiku: data.modelMap.haiku || this.modelMappings.haiku }; },
108
- async saveModelMapSetting() { if (this.modelMapSaving) return; const modelMap = Object.fromEntries(Object.entries(this.modelMappings).map(([key, value]) => [key, value.trim()])); if (Object.values(modelMap).some(value => !value)) { this.showToast('All Claude model mappings are required.', 'error'); return; } this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ modelMap, reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to update model mapping', 'error'); },
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
- 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
- async createClientApiKey() { if (this.clientApiKeySaving) 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 }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; 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; },
113
- async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) 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 }) }); 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
- 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
- }));
116
- });
1
+ document.addEventListener('alpine:init', () => {
2
+ Alpine.data('app', () => ({
3
+ version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
4
+ loading: false, refreshingTokenEmails: [], toast: null, currentTime: '', authRequired: false,
5
+ authChecked: false, apiKey: localStorage.getItem('codexProxyApiKey') || '', loginApiKey: '', loginError: '',
6
+ accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
7
+ accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
8
+ modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
9
+ clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50, clientApiKeysLoading: false,
10
+ clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
11
+ showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
12
+ oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
13
+ testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
14
+ serverUrl: window.location.origin, logs: [], logSearchQuery: '',
15
+ logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false }, logEventSource: null,
16
+
17
+ get isAuthenticated() { return !this.authRequired || Boolean(this.apiKey); },
18
+ get filteredLogs() { const query = this.logSearchQuery.trim().toLowerCase(); return this.logs.filter(log => this.logFilters[log.level] && (!query || log.message.toLowerCase().includes(query))); },
19
+ get filteredAccounts() { if (!this.searchQuery) return this.accounts; const q = this.searchQuery.toLowerCase(); return this.accounts.filter(a => a.email.toLowerCase().includes(q)); },
20
+
21
+ async init() {
22
+ await this.checkHealth();
23
+ this.authChecked = true;
24
+ if (this.isLoginPage()) {
25
+ if (this.isAuthenticated) window.location.replace('/dashboard');
26
+ return;
27
+ }
28
+ if (!this.isAuthenticated) { window.location.replace('/login'); return; }
29
+ await this.loadCurrentView();
30
+ this.updateTime();
31
+ setInterval(() => this.updateTime(), 1000);
32
+ setInterval(() => this.checkHealth(), 30000);
33
+ window.addEventListener('resize', () => { this.sidebarOpen = window.innerWidth >= 1024; });
34
+ window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
35
+ },
36
+
37
+ isLoginPage() { return window.location.pathname === '/login' || window.location.pathname === '/login.html'; },
38
+ async loadCurrentView() {
39
+ const route = window.location.pathname.replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
40
+ const tab = route === 'account-management' ? 'accounts' : route;
41
+ const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
42
+ this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
43
+ if (this.activeTab !== tab) { window.location.replace('/dashboard'); return; }
44
+ const [viewResponse, modalResponse] = await Promise.all([
45
+ fetch(`/views/${this.activeTab}.html`),
46
+ fetch(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html')
47
+ ]);
48
+ if (!viewResponse.ok) { window.location.replace('/dashboard'); return; }
49
+ document.querySelector('#view-content').innerHTML = await viewResponse.text();
50
+ document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
51
+ Alpine.initTree(document.querySelector('#view-content'));
52
+ Alpine.initTree(document.querySelector('#modal-content'));
53
+ this.loadViewData();
54
+ },
55
+ loadViewData() {
56
+ const loaders = {
57
+ dashboard: () => Promise.all([this.refreshAccounts(), this.loadModelMapSetting()]),
58
+ accounts: () => this.refreshAccounts(), logs: () => this.startLogStream(),
59
+ 'client-api-keys': () => this.loadClientApiKeys(),
60
+ settings: () => Promise.all([this.loadAccountStrategySetting(), this.loadModelMapSetting(), this.loadRawProxyLogsSetting()])
61
+ };
62
+ return loaders[this.activeTab]?.();
63
+ },
64
+ updateTime() { this.currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); },
65
+ async api(endpoint, options = {}) {
66
+ try {
67
+ const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
68
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
69
+ const response = await fetch(endpoint, { ...options, headers });
70
+ const data = await response.json();
71
+ if (response.status === 401 && endpoint !== '/health') this.logout(false);
72
+ return { ok: response.ok, data };
73
+ } catch (error) { return { ok: false, error: error.message }; }
74
+ },
75
+ async login() {
76
+ const key = this.loginApiKey.trim();
77
+ if (!key) { this.loginError = 'Access key is required'; return; }
78
+ this.apiKey = key;
79
+ const { ok } = await this.api('/settings/account-strategy');
80
+ if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
81
+ localStorage.setItem('codexProxyApiKey', key);
82
+ window.location.replace('/dashboard');
83
+ },
84
+ logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace('/login'); },
85
+ async checkHealth() { const { ok, data } = await this.api('/health'); this.connectionStatus = ok ? 'connected' : 'disconnected'; if (ok && data?.version) this.version = data.version; if (ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; },
86
+ async refreshAccounts() { this.loading = true; const { ok, data } = await this.api('/accounts'); if (ok && data.accounts) { this.accounts = data.accounts; this.stats = { total: data.total || data.accounts.length, active: data.accounts.filter(a => a.isActive).length, expired: data.accounts.filter(a => a.tokenExpired).length, planType: data.accounts.find(a => a.isActive)?.planType || '-' }; await this.refreshAllQuotaData(); } this.loading = false; },
87
+ async refreshAllQuotaData() { if (!this.accounts.length) return; const { ok, data } = await this.api('/accounts/quota/all'); if (!ok || !data?.accounts) return; const quotaMap = new Map(data.accounts.map(entry => [entry.email, entry.quota || null])); this.accounts = this.accounts.map(account => ({ ...account, quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota })); if (this.selectedAccount?.email) this.selectedAccount = this.accounts.find(account => account.email === this.selectedAccount.email) || this.selectedAccount; },
88
+ getRemainingPercentage(account) { const usage = account?.quota?.usage; if (!usage) return null; const values = [Number(usage.percentage), Number(usage.totalTokenUsage), Number.isFinite(Number(usage.remaining)) ? 100 - Number(usage.remaining) : NaN]; const used = values.find(Number.isFinite); if (!Number.isFinite(used)) return usage.limitReached === true || usage.allowed === false ? 0 : null; return Math.max(0, Math.round(100 - Math.max(0, Math.min(100, used)))); },
89
+ isQuotaExhausted(account) { const remaining = this.getRemainingPercentage(account); return remaining !== null && (remaining <= 0 || account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false); },
90
+ quotaBarClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
91
+ quotaTextClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? '-' : `${remaining}%`; },
92
+ getQuotaResetAt(account) { const usage = account?.quota?.usage; if (!usage) return null; if (usage.resetAt) return usage.resetAt; const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at); if (Number.isFinite(epoch)) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
93
+ quotaResetAtLabel(account) { const resetAt = this.getQuotaResetAt(account); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
94
+ quotaResetSummary(account) { const resetAt = this.getQuotaResetAt(account); if (!resetAt) return null; const seconds = Math.max(0, Math.floor((new Date(resetAt).getTime() - Date.now()) / 1000)); if (!seconds) return 'Reset due now'; const hours = Math.floor(seconds / 3600), minutes = Math.floor((seconds % 3600) / 60); return hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
95
+ async startOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) window.open(data.oauth_url, 'ChatGPT Login', 'width=500,height=700'); else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
96
+ async startManualOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) { this.oauthManualUrl = data.oauth_url; this.oauthManualVerifier = data.verifier; this.oauthManualCode = ''; this.oauthManualMode = true; } else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
97
+ async submitManualOAuth() { if (!this.oauthManualCode) return; const { ok, data } = await this.api('/accounts/add/manual', { method: 'POST', body: JSON.stringify({ code: this.oauthManualCode, verifier: this.oauthManualVerifier }) }); if (ok && data.success) { this.showAddModal = false; this.oauthManualMode = false; this.refreshAccounts(); } else this.showToast(data?.error || 'Failed to add account', 'error'); },
98
+ async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
99
+ async importFromCodex() { const { ok, data } = await this.api('/accounts/import', { method: 'POST' }); if (ok && data.success) { this.showAddModal = false; this.refreshAccounts(); } else this.showToast(data?.message || 'Import failed', 'error'); },
100
+ async switchAccount(email) { const { ok, data } = await this.api('/accounts/switch', { method: 'POST', body: JSON.stringify({ email }) }); if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Failed to switch', 'error'); },
101
+ async refreshToken(email) { if (this.refreshingTokenEmails.includes(email)) return; this.refreshingTokenEmails.push(email); try { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }); if (ok && data.success) await this.refreshAccounts(); else this.showToast(data?.message || 'Refresh failed', 'error'); } finally { this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email); } },
102
+ async refreshAllTokens() { const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' }); if (ok) this.refreshAccounts(); else this.showToast(data?.message || 'Failed', 'error'); }, confirmDelete(email) { this.deleteTarget = email; this.showDeleteModal = true; },
103
+ async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; },
104
+ async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
105
+ async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
106
+ async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
107
+ async loadModelMapSetting() { this.modelMapLoading = true; const { ok, data } = await this.api('/settings/model-map'); this.modelMapLoading = false; if (ok && data?.modelMap) this.modelMappings = { sonnet: data.modelMap.sonnet || this.modelMappings.sonnet, opus: data.modelMap.opus || this.modelMappings.opus, haiku: data.modelMap.haiku || this.modelMappings.haiku }; },
108
+ async saveModelMapSetting() { if (this.modelMapSaving) return; const modelMap = Object.fromEntries(Object.entries(this.modelMappings).map(([key, value]) => [key, value.trim()])); if (Object.values(modelMap).some(value => !value)) { this.showToast('All Claude model mappings are required.', 'error'); return; } this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ modelMap, reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to update model mapping', 'error'); },
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
+ 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
+ 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; },
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
+ 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
+ }));
116
+ });
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>
@@ -18,11 +18,15 @@
18
18
  <template x-if="clientApiKeysLoading">
19
19
  <div class="text-xs text-gray-500 font-mono py-8 text-center">Loading client API keys...</div>
20
20
  </template>
21
- <table class="w-full min-w-[760px]" x-show="!clientApiKeysLoading && clientApiKeys.length">
21
+ <table class="w-full min-w-[1100px]" x-show="!clientApiKeysLoading && clientApiKeys.length">
22
22
  <thead>
23
23
  <tr class="bg-space-900/50 border-b border-space-border/50">
24
24
  <th class="py-3 pl-6 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Client Name</th>
25
25
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Remark</th>
26
+ <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Weekly limit</th>
27
+ <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Used</th>
28
+ <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Remaining</th>
29
+ <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Resets</th>
26
30
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Created</th>
27
31
  <th class="py-3 pr-6 text-right text-[10px] font-bold text-gray-500 uppercase tracking-wider">Operations</th>
28
32
  </tr>
@@ -32,6 +36,10 @@
32
36
  <tr class="border-b border-space-border/30 last:border-0 hover:bg-white/5 transition-colors">
33
37
  <td class="py-3 pl-6"><input type="text" x-model="clientApiKey.name" placeholder="Unnamed" class="input input-sm w-48 bg-space-800 border-space-border text-white"></td>
34
38
  <td class="py-3"><input type="text" x-model="clientApiKey.remark" placeholder="No remark" class="input input-sm w-48 bg-space-800 border-space-border text-white"></td>
39
+ <td class="py-3"><div class="join"><span class="join-item flex items-center px-2 border border-space-border bg-space-800 text-xs text-gray-400">$</span><input type="number" min="0" step="0.01" x-model="clientApiKey.weeklyLimitUsd" class="input input-sm join-item w-24 bg-space-800 border-space-border text-white"></div></td>
40
+ <td class="py-3 text-xs font-mono text-yellow-300 whitespace-nowrap" x-text="`$${(clientApiKey.quota?.consumedUsd ?? 0).toFixed(6)}`"></td>
41
+ <td class="py-3 text-xs font-mono text-neon-green whitespace-nowrap" x-text="`$${(clientApiKey.quota?.remainingUsd ?? clientApiKey.weeklyLimitUsd).toFixed(6)}`"></td>
42
+ <td class="py-3 text-xs font-mono text-gray-500 whitespace-nowrap" x-text="clientApiKey.quota?.nextPeriodStart ? new Date(clientApiKey.quota.nextPeriodStart).toLocaleString() : '-'"></td>
35
43
  <td class="py-3 text-xs font-mono text-gray-500 whitespace-nowrap" x-text="new Date(clientApiKey.createdAt).toLocaleString()"></td>
36
44
  <td class="py-3 pr-6"><div class="flex justify-end gap-2 whitespace-nowrap">
37
45
  <button class="btn btn-xs btn-outline text-gray-300" @click="updateClientApiKey(clientApiKey)" :disabled="clientApiKeySaving">Save</button>