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

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 +195 -116
  7. package/public/login.html +32 -32
  8. package/public/views/accounts-modals.html +90 -29
  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 +86 -13
  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,195 @@
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
+ getQuotaWindow(account, windowName = 'primary') { const usage = account?.quota?.usage; if (!usage) return null; const normalized = usage[`${windowName}Window`]; if (normalized) return normalized; return usage?.raw?.rate_limit?.[`${windowName}_window`] || null; },
96
+ getRemainingPercentage(account, windowName = 'primary') { const usage = account?.quota?.usage, window = this.getQuotaWindow(account, windowName); if (!window) return null; const values = [Number(window.remainingPercent), Number.isFinite(Number(window.usedPercent)) ? 100 - Number(window.usedPercent) : NaN, Number.isFinite(Number(window.used_percent)) ? 100 - Number(window.used_percent) : NaN, Number.isFinite(Number(window.remaining)) ? Number(window.remaining) : NaN, windowName === 'primary' && Number.isFinite(Number(usage.remaining)) ? Number(usage.remaining) : NaN]; const remaining = values.find(Number.isFinite); if (!Number.isFinite(remaining)) return windowName === 'primary' && (usage.limitReached === true || usage.allowed === false) ? 0 : null; return Math.max(0, Math.round(Math.min(100, remaining))); },
97
+ isQuotaExhausted(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining !== null && (remaining <= 0 || (windowName === 'primary' && (account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false))); },
98
+ quotaBarClass(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
99
+ quotaTextClass(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account, windowName = 'primary') { const remaining = this.getRemainingPercentage(account, windowName); return remaining === null ? '-' : `${remaining}%`; },
100
+ getQuotaResetAt(account, windowName = 'primary') { const window = this.getQuotaWindow(account, windowName); if (!window) return null; if (window.resetAt) return window.resetAt; const epoch = Number(window.reset_at); if (Number.isFinite(epoch) && epoch > 0) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(window.resetAfterSeconds ?? window.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
101
+ quotaResetAtLabel(account, windowName = 'primary') { const resetAt = this.getQuotaResetAt(account, windowName); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
102
+ quotaResetSummary(account, windowName = 'primary') { const resetAt = this.getQuotaResetAt(account, windowName); 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 days = Math.floor(seconds / 86400), hours = Math.floor((seconds % 86400) / 3600), minutes = Math.floor((seconds % 3600) / 60); return days ? `Resets in ${days}d ${hours}h` : hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
103
+ 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'); },
104
+ 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'); },
105
+ 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'); },
106
+ async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
107
+ 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'); },
108
+ 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'); },
109
+ 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' }); },
110
+ 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; },
111
+ closeAccountExpirationModal() { if (this.accountExpirationSaving) return; this.showAccountExpirationModalView = false; this.expirationTarget = null; this.accountExpirationInput = ''; },
112
+ 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'); },
113
+ 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()); },
114
+ clearAccountExpiration() { return this.updateAccountExpiration(null); },
115
+ 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); } },
116
+ 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; },
117
+ 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); },
118
+ normalizeRateLimitResetCredits(payload) { if (Array.isArray(payload)) return payload; for (const key of ['credits', 'items', 'data']) { if (Array.isArray(payload?.[key])) return payload[key]; } return []; },
119
+ 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'); },
120
+ 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()); },
121
+ resetCreditExpiryLabel(credit) { const date = credit?.expires_at && new Date(credit.expires_at); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : '-'; },
122
+ generateUUID() {
123
+ if (typeof globalThis.crypto?.randomUUID === 'function') {
124
+ return globalThis.crypto.randomUUID();
125
+ }
126
+
127
+ const bytes = new Uint8Array(16);
128
+ globalThis.crypto.getRandomValues(bytes);
129
+
130
+ // UUID v4
131
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
132
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
133
+
134
+ const hex = Array.from(
135
+ bytes,
136
+ byte => byte.toString(16).padStart(2, '0')
137
+ );
138
+
139
+ return [
140
+ hex.slice(0, 4).join(''),
141
+ hex.slice(4, 6).join(''),
142
+ hex.slice(6, 8).join(''),
143
+ hex.slice(8, 10).join(''),
144
+ hex.slice(10, 16).join('')
145
+ ].join('-');
146
+ },
147
+ async redeemRateLimitResetCredit(creditId = null) {
148
+ if (!this.selectedAccount || this.resetCreditsRedeeming) return;
149
+ const email = this.selectedAccount.email;
150
+ this.resetCreditsRedeeming = true;
151
+ this.resetCreditsRefreshPending = false;
152
+ try {
153
+ if (!this.resetCreditRedeemRequestId) this.resetCreditRedeemRequestId = this.generateUUID();
154
+ const { ok, data } = await this.api('/accounts/rate-limit-reset-credits/consume', {
155
+ method: 'POST',
156
+ body: JSON.stringify({ email, creditId: creditId || undefined, redeemRequestId: this.resetCreditRedeemRequestId })
157
+ });
158
+ if (!ok || !data?.success) {
159
+ this.showToast(data?.error || 'Failed to redeem reset credit', 'error');
160
+ return;
161
+ }
162
+
163
+ this.resetCreditRedeemRequestId = '';
164
+ this.resetCreditsRefreshPending = true;
165
+ await this.loadRateLimitResetCredits(email);
166
+ await new Promise(resolve => setTimeout(resolve, 3000));
167
+ const { ok: quotaOk, data: quotaData } = await this.api(`/accounts/quota?email=${encodeURIComponent(email)}&refresh=true`);
168
+ if (!quotaOk || !quotaData?.quota) {
169
+ this.showToast(quotaData?.error || 'Quota reset succeeded, but quota refresh failed', 'error');
170
+ return;
171
+ }
172
+
173
+ this.accounts = this.accounts.map(account => account.email === email ? { ...account, quota: quotaData.quota } : account);
174
+ if (this.selectedAccount?.email === email) {
175
+ this.selectedAccount = { ...this.selectedAccount, quota: quotaData.quota };
176
+ }
177
+ this.showToast('Quota reset and refreshed', 'success');
178
+ } finally {
179
+ this.resetCreditsRefreshPending = false;
180
+ this.resetCreditsRedeeming = false;
181
+ }
182
+ },
183
+ 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'; },
184
+ 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'); },
185
+ 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'); },
186
+ 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 }; },
187
+ 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'); },
188
+ 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'); },
189
+ 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'); },
190
+ 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'); },
191
+ 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; },
192
+ 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'); },
193
+ 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; }
194
+ }));
195
+ });
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>