claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.30

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.
Files changed (39) hide show
  1. package/README.md +0 -272
  2. package/bin/cli.js +37 -2
  3. package/package.json +1 -1
  4. package/public/css/style.css +132 -0
  5. package/public/index.html +60 -60
  6. package/public/js/app.js +194 -116
  7. package/public/login.html +32 -32
  8. package/public/views/accounts-modals.html +61 -2
  9. package/public/views/accounts.html +29 -10
  10. package/public/views/client-api-keys-modals.html +15 -1
  11. package/public/views/client-api-keys.html +68 -31
  12. package/public/views/logs.html +10 -3
  13. package/src/account-manager.js +34 -3
  14. package/src/account-rotation/rate-limits.js +4 -0
  15. package/src/account-rotation/strategies/base-strategy.js +4 -0
  16. package/src/account-rotation/strategies/sticky-strategy.js +7 -0
  17. package/src/admin-path.js +33 -0
  18. package/src/client-key-usage.js +193 -0
  19. package/src/deployment.js +49 -49
  20. package/src/direct-api.js +11 -11
  21. package/src/format-converter.js +83 -48
  22. package/src/index.js +13 -4
  23. package/src/middleware/auth.js +54 -16
  24. package/src/middleware/credentials.js +17 -7
  25. package/src/middleware/sse.js +69 -29
  26. package/src/model-api.js +60 -0
  27. package/src/model-pricing.js +127 -0
  28. package/src/response-streamer.js +23 -7
  29. package/src/routes/accounts-route.js +106 -2
  30. package/src/routes/api-routes.js +59 -42
  31. package/src/routes/chat-route.js +25 -4
  32. package/src/routes/claude-config-route.js +19 -10
  33. package/src/routes/client-quota-route.js +31 -0
  34. package/src/routes/logs-route.js +21 -2
  35. package/src/routes/messages-route.js +100 -51
  36. package/src/routes/settings-route.js +66 -5
  37. package/src/server-settings.js +25 -2
  38. package/src/utils/logger.js +30 -0
  39. package/src/utils/proxy-logging.js +5 -0
package/public/js/app.js CHANGED
@@ -1,116 +1,194 @@
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
+ const adminPath = window.__PROXY_ADMIN_PATH__ || '/admin';
2
+ const adminUrl = (path) => `${adminPath}${path}`;
3
+
4
+ document.addEventListener('alpine:init', () => {
5
+ Alpine.data('app', () => ({
6
+ version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
7
+ loading: false, refreshingTokenEmails: [], toast: null, currentTime: '', authRequired: false,
8
+ authChecked: false, apiKey: localStorage.getItem('codexProxyApiKey') || '', loginApiKey: '', loginError: '',
9
+ accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
10
+ accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
11
+ modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
12
+ clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50,
13
+ clientApiKeyFiveHourLimitEnabled: false, clientApiKeyFiveHourLimitUsd: 0, clientApiKeysLoading: false,
14
+ clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
15
+ showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
16
+ showAccountExpirationModalView: false, expirationTarget: null, accountExpirationInput: '', accountExpirationSaving: false,
17
+ resetCreditsLoading: false, resetCreditsRedeeming: false, resetCreditsRefreshPending: false, resetCredits: [], resetCreditsAccountEmail: '', resetCreditRedeemRequestId: '',
18
+ oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
19
+ testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
20
+ serverUrl: window.location.origin, logs: [], logSearchQuery: '', logPage: 1, logPageSize: 30, logTotal: 0, logTotalPages: 0, logLoading: false,
21
+ logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false }, logEventSource: null,
22
+
23
+ get isAuthenticated() { return !this.authRequired || Boolean(this.apiKey); },
24
+ get filteredLogs() { const query = this.logSearchQuery.trim().toLowerCase(); return this.logs.filter(log => this.logFilters[log.level] && (!query || log.message.toLowerCase().includes(query))); },
25
+ get filteredAccounts() { if (!this.searchQuery) return this.accounts; const q = this.searchQuery.toLowerCase(); return this.accounts.filter(a => a.email.toLowerCase().includes(q)); },
26
+
27
+ async init() {
28
+ await this.checkHealth();
29
+ this.authChecked = true;
30
+ if (this.isLoginPage()) {
31
+ if (this.isAuthenticated) window.location.replace(adminUrl('/dashboard'));
32
+ return;
33
+ }
34
+ if (!this.isAuthenticated) { window.location.replace(adminUrl('/login')); return; }
35
+ await this.loadCurrentView();
36
+ this.updateTime();
37
+ setInterval(() => this.updateTime(), 1000);
38
+ setInterval(() => this.checkHealth(), 30000);
39
+ window.addEventListener('resize', () => { this.sidebarOpen = window.innerWidth >= 1024; });
40
+ window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
41
+ },
42
+
43
+ isLoginPage() { return window.location.pathname === adminUrl('/login') || window.location.pathname === adminUrl('/login.html'); },
44
+ async loadCurrentView() {
45
+ const route = window.location.pathname.slice(adminPath.length).replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
46
+ const tab = route === 'account-management' ? 'accounts' : route;
47
+ const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
48
+ this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
49
+ if (this.activeTab !== tab) { window.location.replace(adminUrl('/dashboard')); return; }
50
+ const [viewResponse, modalResponse] = await Promise.all([
51
+ fetch(adminUrl(`/views/${this.activeTab}.html`)),
52
+ fetch(adminUrl(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html'))
53
+ ]);
54
+ if (!viewResponse.ok) { window.location.replace(adminUrl('/dashboard')); return; }
55
+ document.querySelector('#view-content').innerHTML = await viewResponse.text();
56
+ document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
57
+ Alpine.initTree(document.querySelector('#view-content'));
58
+ Alpine.initTree(document.querySelector('#modal-content'));
59
+ this.loadViewData();
60
+ },
61
+ loadViewData() {
62
+ const loaders = {
63
+ dashboard: () => Promise.all([this.refreshAccounts(), this.loadModelMapSetting()]),
64
+ accounts: () => this.refreshAccounts(), logs: () => this.startLogStream(),
65
+ 'client-api-keys': () => this.loadClientApiKeys(),
66
+ settings: () => Promise.all([this.loadAccountStrategySetting(), this.loadModelMapSetting(), this.loadRawProxyLogsSetting()])
67
+ };
68
+ return loaders[this.activeTab]?.();
69
+ },
70
+ updateTime() { this.currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); },
71
+ async api(endpoint, options = {}) {
72
+ try {
73
+ const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
74
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
75
+ const url = endpoint.startsWith('/v1/') ? endpoint : adminUrl(endpoint);
76
+ const response = await fetch(url, { ...options, headers });
77
+ const data = await response.json();
78
+ if (response.status === 401 && endpoint !== '/health') this.logout(false);
79
+ return { ok: response.ok, data };
80
+ } catch (error) { return { ok: false, error: error.message }; }
81
+ },
82
+ async login() {
83
+ const key = this.loginApiKey.trim();
84
+ if (!key) { this.loginError = 'Access key is required'; return; }
85
+ this.apiKey = key;
86
+ const { ok } = await this.api('/settings/account-strategy');
87
+ if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
88
+ localStorage.setItem('codexProxyApiKey', key);
89
+ window.location.replace(adminUrl('/dashboard'));
90
+ },
91
+ logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace(adminUrl('/login')); },
92
+ async checkHealth() { try { const response = await fetch('/health'); const data = await response.json(); this.connectionStatus = response.ok ? 'connected' : 'disconnected'; if (response.ok && data?.version) this.version = data.version; if (response.ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; } catch { this.connectionStatus = 'disconnected'; } },
93
+ 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; },
94
+ 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; },
95
+ 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)))); },
96
+ isQuotaExhausted(account) { const remaining = this.getRemainingPercentage(account); return remaining !== null && (remaining <= 0 || account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false); },
97
+ 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'; },
98
+ 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}%`; },
99
+ 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; },
100
+ quotaResetAtLabel(account) { const resetAt = this.getQuotaResetAt(account); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
101
+ 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`; },
102
+ 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'); },
103
+ 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'); },
104
+ 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'); },
105
+ async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
106
+ 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'); },
107
+ 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'); },
108
+ accountExpirationLabel(account) { if (!account?.accountExpiresAt) return 'Never'; const date = new Date(account.accountExpiresAt); if (Number.isNaN(date.getTime())) return 'Never'; return date.toLocaleString([], { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); },
109
+ showAccountExpirationModal(account) { this.expirationTarget = account; const date = account?.accountExpiresAt ? new Date(account.accountExpiresAt) : null; if (date && !Number.isNaN(date.getTime())) { const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000); this.accountExpirationInput = local.toISOString().slice(0, 16); } else this.accountExpirationInput = ''; this.showAccountExpirationModalView = true; },
110
+ closeAccountExpirationModal() { if (this.accountExpirationSaving) return; this.showAccountExpirationModalView = false; this.expirationTarget = null; this.accountExpirationInput = ''; },
111
+ async updateAccountExpiration(accountExpiresAt) { if (!this.expirationTarget || this.accountExpirationSaving) return; this.accountExpirationSaving = true; const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.expirationTarget.email)}/expiration`, { method: 'PUT', body: JSON.stringify({ accountExpiresAt }) }); this.accountExpirationSaving = false; if (ok && data?.success) { this.closeAccountExpirationModal(); await this.refreshAccounts(); this.showToast(accountExpiresAt ? 'Account expiration updated' : 'Account expiration cleared', 'success'); } else this.showToast(data?.message || 'Failed to update account expiration', 'error'); },
112
+ saveAccountExpiration() { if (!this.accountExpirationInput) return; const expiresAt = new Date(this.accountExpirationInput); if (Number.isNaN(expiresAt.getTime())) { this.showToast('Enter a valid expiration time', 'error'); return; } return this.updateAccountExpiration(expiresAt.toISOString()); },
113
+ clearAccountExpiration() { return this.updateAccountExpiration(null); },
114
+ 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); } },
115
+ 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; },
116
+ 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'); }, async showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; await this.loadRateLimitResetCredits(acc.email); },
117
+ normalizeRateLimitResetCredits(payload) { if (Array.isArray(payload)) return payload; for (const key of ['credits', 'items', 'data']) { if (Array.isArray(payload?.[key])) return payload[key]; } return []; },
118
+ async loadRateLimitResetCredits(email) { this.resetCreditsLoading = true; this.resetCredits = []; this.resetCreditsAccountEmail = email; this.resetCreditRedeemRequestId = ''; const { ok, data } = await this.api(`/accounts/rate-limit-reset-credits?email=${encodeURIComponent(email)}`); this.resetCreditsLoading = false; if (this.resetCreditsAccountEmail !== email) return; if (ok) this.resetCredits = this.normalizeRateLimitResetCredits(data?.credits); else this.showToast(data?.error || 'Failed to load reset credits', 'error'); },
119
+ availableRateLimitResetCredits() { return this.resetCredits.filter(credit => credit?.status === 'available').sort((a, b) => new Date(b.expires_at || 0).getTime() - new Date(a.expires_at || 0).getTime()); },
120
+ resetCreditExpiryLabel(credit) { const date = credit?.expires_at && new Date(credit.expires_at); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : '-'; },
121
+ generateUUID() {
122
+ if (typeof globalThis.crypto?.randomUUID === 'function') {
123
+ return globalThis.crypto.randomUUID();
124
+ }
125
+
126
+ const bytes = new Uint8Array(16);
127
+ globalThis.crypto.getRandomValues(bytes);
128
+
129
+ // UUID v4
130
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
131
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
132
+
133
+ const hex = Array.from(
134
+ bytes,
135
+ byte => byte.toString(16).padStart(2, '0')
136
+ );
137
+
138
+ return [
139
+ hex.slice(0, 4).join(''),
140
+ hex.slice(4, 6).join(''),
141
+ hex.slice(6, 8).join(''),
142
+ hex.slice(8, 10).join(''),
143
+ hex.slice(10, 16).join('')
144
+ ].join('-');
145
+ },
146
+ async redeemRateLimitResetCredit(creditId = null) {
147
+ if (!this.selectedAccount || this.resetCreditsRedeeming) return;
148
+ const email = this.selectedAccount.email;
149
+ this.resetCreditsRedeeming = true;
150
+ this.resetCreditsRefreshPending = false;
151
+ try {
152
+ if (!this.resetCreditRedeemRequestId) this.resetCreditRedeemRequestId = this.generateUUID();
153
+ const { ok, data } = await this.api('/accounts/rate-limit-reset-credits/consume', {
154
+ method: 'POST',
155
+ body: JSON.stringify({ email, creditId: creditId || undefined, redeemRequestId: this.resetCreditRedeemRequestId })
156
+ });
157
+ if (!ok || !data?.success) {
158
+ this.showToast(data?.error || 'Failed to redeem reset credit', 'error');
159
+ return;
160
+ }
161
+
162
+ this.resetCreditRedeemRequestId = '';
163
+ this.resetCreditsRefreshPending = true;
164
+ await this.loadRateLimitResetCredits(email);
165
+ await new Promise(resolve => setTimeout(resolve, 3000));
166
+ const { ok: quotaOk, data: quotaData } = await this.api(`/accounts/quota?email=${encodeURIComponent(email)}&refresh=true`);
167
+ if (!quotaOk || !quotaData?.quota) {
168
+ this.showToast(quotaData?.error || 'Quota reset succeeded, but quota refresh failed', 'error');
169
+ return;
170
+ }
171
+
172
+ this.accounts = this.accounts.map(account => account.email === email ? { ...account, quota: quotaData.quota } : account);
173
+ if (this.selectedAccount?.email === email) {
174
+ this.selectedAccount = { ...this.selectedAccount, quota: quotaData.quota };
175
+ }
176
+ this.showToast('Quota reset and refreshed', 'success');
177
+ } finally {
178
+ this.resetCreditsRefreshPending = false;
179
+ this.resetCreditsRedeeming = false;
180
+ }
181
+ },
182
+ 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'; },
183
+ 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'); },
184
+ 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'); },
185
+ 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 }; },
186
+ 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'); },
187
+ 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'); },
188
+ 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'); },
189
+ async createClientApiKey() { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(this.clientApiKeyWeeklyLimitUsd); const fiveHourLimitUsd = Number(this.clientApiKeyFiveHourLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } if (!Number.isFinite(fiveHourLimitUsd) || fiveHourLimitUsd < 0) { this.showToast('5-hour 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, fiveHourLimitEnabled: this.clientApiKeyFiveHourLimitEnabled, fiveHourLimitUsd }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.clientApiKeyWeeklyLimitUsd = 50; this.clientApiKeyFiveHourLimitEnabled = false; this.clientApiKeyFiveHourLimitUsd = 0; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
190
+ async loadClientProxyConfig() { try { const response = await fetch('/claude/config/proxy', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); if (response.ok && data?.success && data?.env) this.clientProxyConfig = data; } catch {} }, 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 configureCommands = this.clientProxyConfig?.commands?.powershell; const clearCommands = this.clientProxyConfig?.commands?.clear?.powershell; const commands = [...(Array.isArray(configureCommands) ? configureCommands : []), ...(Array.isArray(clearCommands) ? clearCommands : [])]; return commands.length ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
191
+ async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(clientApiKey.weeklyLimitUsd); const fiveHourLimitUsd = Number(clientApiKey.fiveHourLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } if (!Number.isFinite(fiveHourLimitUsd) || fiveHourLimitUsd < 0) { this.showToast('5-hour 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, fiveHourLimitEnabled: clientApiKey.fiveHourLimitEnabled === true, fiveHourLimitUsd }) }); 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'); },
192
+ showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, async loadLogs(page = 1) { if (this.logLoading) return; this.logLoading = true; const { ok, data } = await this.api(`/api/logs?page=${page}&pageSize=${this.logPageSize}`); this.logLoading = false; if (!ok || !Array.isArray(data?.logs)) { this.showToast(data?.error || 'Failed to load logs', 'error'); return; } this.logs = data.logs; this.logPage = data.page; this.logTotal = data.total; this.logTotalPages = data.totalPages; }, async changeLogPage(page) { if (page < 1 || page > this.logTotalPages || page === this.logPage) return; await this.loadLogs(page); }, startLogStream() { if (!this.isAuthenticated) return; this.loadLogs(); this.logEventSource?.close(); const params = new URLSearchParams(); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(adminUrl(`/api/logs/stream?${params}`)); this.logEventSource.onmessage = event => { try { this.logTotal += 1; this.logTotalPages = Math.ceil(this.logTotal / this.logPageSize); if (this.logPage === 1) this.logs = [JSON.parse(event.data), ...this.logs].slice(0, this.logPageSize); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; this.logTotal = 0; this.logTotalPages = 0; }, 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; }
193
+ }));
194
+ });
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>
@@ -86,6 +86,25 @@
86
86
  </div>
87
87
  </div>
88
88
 
89
+ <div x-show="showAccountExpirationModalView" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;">
90
+ <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="closeAccountExpirationModal()"></div>
91
+ <div class="relative bg-space-900 border border-space-border rounded-xl shadow-2xl max-w-md w-full p-6">
92
+ <h3 class="font-bold text-lg text-white mb-2">Set Account Expiration</h3>
93
+ <p class="text-sm text-gray-500 font-mono mb-5" x-text="expirationTarget?.email"></p>
94
+ <label class="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2" for="account-expiration">Expires at</label>
95
+ <input id="account-expiration" type="datetime-local" x-model="accountExpirationInput"
96
+ class="input w-full bg-space-800 border-space-border text-white font-mono text-sm">
97
+ <p class="mt-2 text-xs text-gray-500">The time uses your browser's local timezone. After expiration, this account will not participate in automatic account selection.</p>
98
+ <div class="mt-6 flex justify-between gap-2">
99
+ <button class="btn btn-ghost btn-sm text-gray-400 hover:text-white" @click="clearAccountExpiration()" :disabled="accountExpirationSaving || !expirationTarget?.accountExpiresAt">Clear Expiration</button>
100
+ <div class="flex gap-2">
101
+ <button class="btn btn-outline btn-sm text-gray-400" @click="closeAccountExpirationModal()">Cancel</button>
102
+ <button class="btn bg-neon-purple hover:bg-purple-600 border-none text-white btn-sm" @click="saveAccountExpiration()" :disabled="accountExpirationSaving || !accountExpirationInput" x-text="accountExpirationSaving ? 'Saving...' : 'Save'"></button>
103
+ </div>
104
+ </div>
105
+ </div>
106
+ </div>
107
+
89
108
  <div x-show="showDeleteModal" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;">
90
109
  <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="showDeleteModal = false"></div>
91
110
  <div class="relative bg-space-900 border-2 border-red-500/50 rounded-xl shadow-2xl max-w-md w-full p-6">
@@ -109,7 +128,7 @@
109
128
  </div>
110
129
 
111
130
  <div x-show="showQuotaModalView" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;">
112
- <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="showQuotaModalView = false"></div>
131
+ <div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="if (!resetCreditsRedeeming) showQuotaModalView = false"></div>
113
132
  <div class="relative bg-space-900 border border-space-border rounded-xl shadow-2xl max-w-lg w-full p-6">
114
133
  <h3 class="font-bold text-lg text-white mb-2 flex items-center gap-2">
115
134
  <svg class="w-6 h-6 text-neon-cyan" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -152,8 +171,48 @@
152
171
  </div>
153
172
  </div>
154
173
 
174
+ <div class="mt-4 p-3 bg-space-800/50 border border-space-border/30 rounded-lg">
175
+ <div class="flex items-center justify-between gap-3 mb-2">
176
+ <div>
177
+ <h4 class="text-sm font-semibold text-gray-200">Rate-limit reset credits</h4>
178
+ <p class="text-xs text-gray-500">Redeeming a credit resets this account's upstream quota.</p>
179
+ </div>
180
+ <button class="btn btn-xs btn-outline text-gray-400" @click="loadRateLimitResetCredits(selectedAccount.email)" :disabled="resetCreditsLoading || resetCreditsRedeeming">Refresh</button>
181
+ </div>
182
+ <template x-if="resetCreditsRefreshPending">
183
+ <p class="text-xs text-neon-cyan">Reset complete. Refreshing quota in 3 seconds...</p>
184
+ </template>
185
+ <template x-if="resetCreditsLoading && !resetCreditsRefreshPending">
186
+ <p class="text-xs text-gray-500">Loading reset credits...</p>
187
+ </template>
188
+ <template x-if="!resetCreditsLoading && !resetCreditsRefreshPending && !availableRateLimitResetCredits().length">
189
+ <p class="text-xs text-gray-500">No available reset credits.</p>
190
+ </template>
191
+ <template x-if="!resetCreditsLoading && !resetCreditsRefreshPending && availableRateLimitResetCredits().length">
192
+ <div class="space-y-2">
193
+ <template x-for="credit in availableRateLimitResetCredits()" :key="credit.id">
194
+ <div class="flex items-center justify-between gap-4 rounded-lg border border-space-border/30 bg-space-900/40 p-3">
195
+ <div class="min-w-0 flex-1">
196
+ <div class="flex items-center gap-2">
197
+ <span class="truncate text-sm font-semibold text-gray-200" x-text="credit.title || 'Full reset'"></span>
198
+ <span class="shrink-0 rounded border border-neon-green/30 bg-neon-green/10 px-1.5 py-0.5 text-[9px] font-bold uppercase text-neon-green">Available</span>
199
+ </div>
200
+ <p class="mt-1 truncate text-xs text-gray-500" x-text="credit.description || credit.id"></p>
201
+ <div class="mt-2 flex items-center gap-1.5 text-[10px] text-gray-500">
202
+ <svg class="h-3 w-3 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 2m6-2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
203
+ <span>Expires</span>
204
+ <span class="font-mono text-gray-400" x-text="resetCreditExpiryLabel(credit)"></span>
205
+ </div>
206
+ </div>
207
+ <button class="btn btn-xs shrink-0 bg-neon-purple hover:bg-purple-600 border-none text-white" @click="redeemRateLimitResetCredit(credit.id)" :disabled="resetCreditsRedeeming" x-text="resetCreditsRefreshPending ? 'Refreshing quota...' : resetCreditsRedeeming ? 'Resetting...' : 'Reset quota'"></button>
208
+ </div>
209
+ </template>
210
+ </div>
211
+ </template>
212
+ </div>
213
+
155
214
  <div class="mt-6 flex justify-end">
156
- <button class="btn btn-outline btn-sm text-gray-400" @click="showQuotaModalView = false">Close</button>
215
+ <button class="btn btn-outline btn-sm text-gray-400" @click="showQuotaModalView = false" :disabled="resetCreditsRedeeming" x-text="resetCreditsRefreshPending ? 'Refreshing quota...' : 'Close'"></button>
157
216
  </div>
158
217
  </div>
159
218
  </div>