claude-codex-proxy 1.0.5-beta.2 → 1.0.5-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/js/app.js CHANGED
@@ -1,762 +1,116 @@
1
1
  document.addEventListener('alpine:init', () => {
2
2
  Alpine.data('app', () => ({
3
- version: '',
4
- connectionStatus: 'connecting',
5
- activeTab: 'dashboard',
6
- sidebarOpen: window.innerWidth >= 1024,
7
- loading: false,
8
- refreshingTokenEmails: [],
9
- toast: null,
10
- currentTime: '',
11
- authRequired: false,
12
- authChecked: false,
13
- apiKey: localStorage.getItem('codexProxyApiKey') || '',
14
- loginApiKey: '',
15
-
16
- accounts: [],
17
- searchQuery: '',
18
- stats: { total: 0, active: 0, expired: 0, planType: '-' },
19
-
20
- accountStrategy: 'sticky',
21
- modelMappings: {
22
- sonnet: '',
23
- opus: '',
24
- haiku: ''
25
- },
26
- modelMapLoading: false,
27
- modelMapSaving: false,
28
- strategySaving: false,
29
- logRawProxyPayloads: false,
30
- rawProxyLogsSaving: false,
31
- clientApiKeys: [],
32
- clientApiKeyName: '',
33
- clientApiKeyRemark: '',
34
- clientApiKeysLoading: false,
35
- clientApiKeySaving: false,
36
- revealedClientApiKey: '',
37
- showCreateClientApiKeyModal: false,
38
-
39
- showAddModal: false,
40
- showDeleteModal: false,
41
- deleteTarget: '',
42
- showQuotaModalView: false,
43
- selectedAccount: null,
44
-
45
- oauthManualMode: false,
46
- oauthManualUrl: '',
47
- oauthManualVerifier: '',
48
- oauthManualCode: '',
49
-
50
- testPrompt: 'Say hello',
51
- testResponse: '',
52
- testing: false,
53
-
54
- configPath: '~/.claude-codex-proxy/accounts.json',
55
- serverUrl: window.location.origin,
56
-
57
- logs: [],
58
- logSearchQuery: '',
59
- logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false },
60
- logEventSource: null,
61
-
62
- get isAuthenticated() {
63
- return !this.authRequired || Boolean(this.apiKey);
64
- },
65
-
66
- get filteredLogs() {
67
- const query = this.logSearchQuery.trim().toLowerCase();
68
- return this.logs.filter(log => {
69
- if (!this.logFilters[log.level]) return false;
70
- if (query && !log.message.toLowerCase().includes(query)) return false;
71
- return true;
72
- });
73
- },
74
-
75
- get filteredAccounts() {
76
- if (!this.searchQuery) return this.accounts;
77
- const q = this.searchQuery.toLowerCase();
78
- return this.accounts.filter(a => a.email.toLowerCase().includes(q));
79
- },
3
+ version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
4
+ loading: false, refreshingTokenEmails: [], toast: null, currentTime: '', authRequired: false,
5
+ authChecked: false, apiKey: localStorage.getItem('codexProxyApiKey') || '', loginApiKey: '', loginError: '',
6
+ accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
7
+ accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
8
+ modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
9
+ clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50, clientApiKeysLoading: false,
10
+ clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
11
+ showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
12
+ oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
13
+ testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
14
+ serverUrl: window.location.origin, logs: [], logSearchQuery: '',
15
+ logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false }, logEventSource: null,
16
+
17
+ get isAuthenticated() { return !this.authRequired || Boolean(this.apiKey); },
18
+ get filteredLogs() { const query = this.logSearchQuery.trim().toLowerCase(); return this.logs.filter(log => this.logFilters[log.level] && (!query || log.message.toLowerCase().includes(query))); },
19
+ get filteredAccounts() { if (!this.searchQuery) return this.accounts; const q = this.searchQuery.toLowerCase(); return this.accounts.filter(a => a.email.toLowerCase().includes(q)); },
80
20
 
81
21
  async init() {
82
- this.updateTime();
83
- setInterval(() => this.updateTime(), 1000);
84
22
  await this.checkHealth();
85
- if (this.isAuthenticated) {
86
- this.loadProtectedData();
23
+ this.authChecked = true;
24
+ if (this.isLoginPage()) {
25
+ if (this.isAuthenticated) window.location.replace('/dashboard');
26
+ return;
87
27
  }
28
+ if (!this.isAuthenticated) { window.location.replace('/login'); return; }
29
+ await this.loadCurrentView();
30
+ this.updateTime();
31
+ setInterval(() => this.updateTime(), 1000);
88
32
  setInterval(() => this.checkHealth(), 30000);
89
-
90
- window.addEventListener('resize', () => {
91
- this.sidebarOpen = window.innerWidth >= 1024;
92
- });
93
-
94
- window.addEventListener('message', (event) => {
95
- if (event.data && event.data.type === 'oauth-success') {
96
- this.showToast(`Account ${event.data.email} added!`, 'success');
97
- this.showAddModal = false;
98
- this.refreshAccounts();
99
- }
100
- });
101
- },
102
-
103
- loadProtectedData() {
104
- this.refreshAccounts();
105
- this.startLogStream();
106
- this.loadAccountStrategySetting();
107
- this.loadModelMapSetting();
108
- this.loadRawProxyLogsSetting();
109
- this.loadClientApiKeys();
110
- },
111
-
112
- updateTime() {
113
- this.currentTime = new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', second: '2-digit'});
114
- },
115
-
116
- setActiveTab(tab) {
117
- this.activeTab = tab;
118
- if (window.innerWidth < 1024) {
119
- this.sidebarOpen = false;
120
- }
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]?.();
121
63
  },
122
-
64
+ updateTime() { this.currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); },
123
65
  async api(endpoint, options = {}) {
124
66
  try {
125
- const headers = {
126
- 'Content-Type': 'application/json',
127
- ...(options.headers || {})
128
- };
129
-
130
- if (this.apiKey) {
131
- headers.Authorization = `Bearer ${this.apiKey}`;
132
- }
133
-
134
- const response = await fetch(endpoint, {
135
- ...options,
136
- headers
137
- });
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 });
138
70
  const data = await response.json();
139
-
140
- if (response.status === 401 && endpoint !== '/health') {
141
- this.logout(false);
142
- this.showToast('Access key is invalid or expired', 'error');
143
- }
144
-
71
+ if (response.status === 401 && endpoint !== '/health') this.logout(false);
145
72
  return { ok: response.ok, data };
146
- } catch (error) {
147
- return { ok: false, error: error.message };
148
- }
73
+ } catch (error) { return { ok: false, error: error.message }; }
149
74
  },
150
-
151
- login() {
75
+ async login() {
152
76
  const key = this.loginApiKey.trim();
153
- if (!key) {
154
- this.showToast('Access key is required', 'error');
155
- return;
156
- }
157
-
77
+ if (!key) { this.loginError = 'Access key is required'; return; }
158
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; }
159
81
  localStorage.setItem('codexProxyApiKey', key);
160
- this.loginApiKey = '';
161
- this.showToast('Access key saved', 'success');
162
- this.loadProtectedData();
163
- },
164
-
165
- logout(showMessage = true) {
166
- this.apiKey = '';
167
- this.loginApiKey = '';
168
- localStorage.removeItem('codexProxyApiKey');
169
- if (this.logEventSource) {
170
- this.logEventSource.close();
171
- this.logEventSource = null;
172
- }
173
- if (showMessage) this.showToast('Logged out', 'info');
174
- },
175
-
176
- async checkHealth() {
177
- const { ok, data } = await this.api('/health');
178
- this.connectionStatus = ok ? 'connected' : 'disconnected';
179
- if (ok && data?.version) this.version = data.version;
180
- if (ok && typeof data?.publicMode === 'boolean') {
181
- this.authRequired = data.publicMode;
182
- this.authChecked = true;
183
- }
184
- },
185
-
186
- async refreshAccounts() {
187
- this.loading = true;
188
- const { ok, data } = await this.api('/accounts');
189
-
190
- if (ok && data.accounts) {
191
- this.accounts = data.accounts;
192
- this.stats = {
193
- total: data.total || data.accounts.length,
194
- active: data.accounts.filter(a => a.isActive).length,
195
- expired: data.accounts.filter(a => a.tokenExpired).length,
196
- planType: data.accounts.find(a => a.isActive)?.planType || '-'
197
- };
198
-
199
- await this.refreshAllQuotaData();
200
- }
201
- this.loading = false;
202
- },
203
-
204
- async refreshAllQuotaData() {
205
- if (!this.accounts.length) return;
206
- const { ok, data } = await this.api('/accounts/quota/all');
207
- if (!ok || !data?.accounts) return;
208
-
209
- const quotaMap = new Map(
210
- data.accounts.map((entry) => [entry.email, entry.quota || null])
211
- );
212
-
213
- this.accounts = this.accounts.map((account) => ({
214
- ...account,
215
- quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota
216
- }));
217
-
218
- if (this.selectedAccount?.email) {
219
- const refreshed = this.accounts.find((account) => account.email === this.selectedAccount.email);
220
- if (refreshed) this.selectedAccount = refreshed;
221
- }
222
- },
223
-
224
- getRemainingPercentage(account) {
225
- const usage = account?.quota?.usage;
226
- if (!usage) return null;
227
-
228
- const percentage = Number(usage.percentage);
229
- const usedFromTotal = Number(usage.totalTokenUsage);
230
- const remainingFromApi = Number(usage.remaining);
231
-
232
- let used = null;
233
- if (Number.isFinite(percentage)) {
234
- used = percentage;
235
- } else if (Number.isFinite(usedFromTotal)) {
236
- used = usedFromTotal;
237
- } else if (Number.isFinite(remainingFromApi)) {
238
- used = 100 - remainingFromApi;
239
- } else if (usage.limitReached === true || usage.allowed === false) {
240
- used = 100;
241
- }
242
-
243
- if (!Number.isFinite(used)) return null;
244
- const clampedUsed = Math.max(0, Math.min(100, used));
245
- return Math.max(0, Math.round(100 - clampedUsed));
246
- },
247
-
248
- isQuotaExhausted(account) {
249
- const remaining = this.getRemainingPercentage(account);
250
- if (remaining === null) return false;
251
- const usage = account?.quota?.usage;
252
- return remaining <= 0 || usage?.limitReached === true || usage?.allowed === false;
253
- },
254
-
255
- quotaBarClass(account) {
256
- const remaining = this.getRemainingPercentage(account);
257
- if (remaining === null) return 'bg-gray-500';
258
- if (remaining > 50) return 'bg-neon-green';
259
- if (remaining > 20) return 'bg-yellow-500';
260
- return 'bg-red-500';
261
- },
262
-
263
- quotaTextClass(account) {
264
- const remaining = this.getRemainingPercentage(account);
265
- if (remaining === null) return 'text-gray-500';
266
- return remaining <= 20 ? 'text-red-400' : 'text-gray-400';
267
- },
268
-
269
- quotaLabel(account) {
270
- const remaining = this.getRemainingPercentage(account);
271
- if (remaining === null) return '-';
272
- return `${remaining}%`;
273
- },
274
-
275
- getQuotaResetAt(account) {
276
- const usage = account?.quota?.usage;
277
- if (!usage) return null;
278
-
279
- if (usage.resetAt) return usage.resetAt;
280
-
281
- const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at);
282
- if (Number.isFinite(epoch)) {
283
- return new Date(epoch * 1000).toISOString();
284
- }
285
-
286
- const resetAfter = Number(
287
- usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds
288
- );
289
- if (Number.isFinite(resetAfter) && resetAfter > 0) {
290
- return new Date(Date.now() + resetAfter * 1000).toISOString();
291
- }
292
-
293
- return null;
294
- },
295
-
296
- quotaResetAtLabel(account) {
297
- const resetAt = this.getQuotaResetAt(account);
298
- if (!resetAt) return null;
299
- const date = new Date(resetAt);
300
- if (Number.isNaN(date.getTime())) return null;
301
- return date.toLocaleString();
302
- },
303
-
304
- quotaResetSummary(account) {
305
- const resetAt = this.getQuotaResetAt(account);
306
- if (!resetAt) return null;
307
-
308
- const resetMs = new Date(resetAt).getTime();
309
- if (!Number.isFinite(resetMs)) return null;
310
-
311
- const deltaSec = Math.max(0, Math.floor((resetMs - Date.now()) / 1000));
312
- if (deltaSec === 0) return 'Reset due now';
313
-
314
- const days = Math.floor(deltaSec / 86400);
315
- const hours = Math.floor((deltaSec % 86400) / 3600);
316
- const minutes = Math.floor((deltaSec % 3600) / 60);
317
-
318
- if (days > 0) return `Resets in ${days}d ${hours}h`;
319
- if (hours > 0) return `Resets in ${hours}h ${minutes}m`;
320
- return `Resets in ${minutes}m`;
321
- },
322
-
323
- async startOAuth() {
324
- await this.api('/accounts/oauth/cleanup', { method: 'POST' });
325
- const { ok, data } = await this.api('/accounts/add', { method: 'POST' });
326
-
327
- if (ok && data.oauth_url) {
328
- const width = 500, height = 700;
329
- const left = (screen.width - width) / 2;
330
- const top = (screen.height - height) / 2;
331
- window.open(data.oauth_url, 'ChatGPT Login', `width=${width},height=${height},left=${left},top=${top}`);
332
-
333
- const checkAdded = setInterval(async () => {
334
- const { ok, data } = await this.api('/accounts');
335
- if (ok && data.accounts?.length > this.accounts.length) {
336
- clearInterval(checkAdded);
337
- this.showAddModal = false;
338
- this.refreshAccounts();
339
- }
340
- }, 2000);
341
-
342
- setTimeout(() => clearInterval(checkAdded), 120000);
343
- } else {
344
- this.showToast(data?.message || 'Failed to start OAuth', 'error');
345
- }
346
- },
347
-
348
- async startManualOAuth() {
349
- await this.api('/accounts/oauth/cleanup', { method: 'POST' });
350
- const { ok, data } = await this.api('/accounts/add', { method: 'POST' });
351
-
352
- if (ok && data.oauth_url) {
353
- this.oauthManualUrl = data.oauth_url;
354
- this.oauthManualVerifier = data.verifier;
355
- this.oauthManualCode = '';
356
- this.oauthManualMode = true;
357
- } else {
358
- this.showToast(data?.message || 'Failed to start OAuth', 'error');
359
- }
360
- },
361
-
362
- async submitManualOAuth() {
363
- if (!this.oauthManualCode) return;
364
-
365
- const { ok, data } = await this.api('/accounts/add/manual', {
366
- method: 'POST',
367
- body: JSON.stringify({
368
- code: this.oauthManualCode,
369
- verifier: this.oauthManualVerifier
370
- })
371
- });
372
-
373
- if (ok && data.success) {
374
- this.showToast(data.message, 'success');
375
- this.showAddModal = false;
376
- this.oauthManualMode = false;
377
- this.refreshAccounts();
378
- } else {
379
- this.showToast(data?.error || 'Failed to add account', 'error');
380
- }
381
- },
382
-
383
- async copyToClipboard(text) {
384
- try {
385
- await navigator.clipboard.writeText(text);
386
- this.showToast('Copied to clipboard', 'success');
387
- } catch (e) {
388
- this.showToast('Failed to copy', 'error');
389
- }
390
- },
391
-
392
- async importFromCodex() {
393
- const { ok, data } = await this.api('/accounts/import', { method: 'POST' });
394
- if (ok && data.success) {
395
- this.showToast(data.message, 'success');
396
- this.showAddModal = false;
397
- this.refreshAccounts();
398
- } else {
399
- this.showToast(data?.message || 'Import failed', 'error');
400
- }
401
- },
402
-
403
- async switchAccount(email) {
404
- const { ok, data } = await this.api('/accounts/switch', {
405
- method: 'POST',
406
- body: JSON.stringify({ email })
407
- });
408
- if (ok && data.success) {
409
- this.showToast(data.message, 'success');
410
- this.refreshAccounts();
411
- } else {
412
- this.showToast(data?.message || 'Failed to switch', 'error');
413
- }
414
- },
415
-
416
- async refreshToken(email) {
417
- if (this.refreshingTokenEmails.includes(email)) return;
418
-
419
- this.refreshingTokenEmails.push(email);
420
- try {
421
- const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' });
422
- if (ok && data.success) {
423
- this.showToast(data.message, 'success');
424
- await this.refreshAccounts();
425
- } else {
426
- this.showToast(data?.message || 'Refresh failed', 'error');
427
- }
428
- } finally {
429
- this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email);
430
- }
431
- },
432
-
433
- async refreshAllTokens() {
434
- this.showToast('Refreshing all tokens...', 'info');
435
- const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' });
436
- if (ok) {
437
- this.showToast(data.message, 'success');
438
- this.refreshAccounts();
439
- } else {
440
- this.showToast(data?.message || 'Failed', 'error');
441
- }
442
- },
443
-
444
- confirmDelete(email) {
445
- this.deleteTarget = email;
446
- this.showDeleteModal = true;
447
- },
448
-
449
- async executeDelete() {
450
- const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' });
451
- this.showDeleteModal = false;
452
- if (ok && data.success) {
453
- this.showToast(data.message, 'success');
454
- this.refreshAccounts();
455
- } else {
456
- this.showToast(data?.message || 'Delete failed', 'error');
457
- }
458
- },
459
-
460
- showQuotaModal(acc) {
461
- this.selectedAccount = acc;
462
- this.showQuotaModalView = true;
463
- },
464
-
465
- async testChat() {
466
- if (!this.testPrompt.trim()) return;
467
-
468
- this.testing = true;
469
- this.testResponse = '';
470
-
471
- const testModel = this.modelMappings?.sonnet || 'gpt-5.5';
472
-
473
- const { ok, data } = await this.api('/v1/chat/completions', {
474
- method: 'POST',
475
- body: JSON.stringify({
476
- model: testModel,
477
- messages: [{ role: 'user', content: this.testPrompt }]
478
- })
479
- });
480
-
481
- this.testing = false;
482
-
483
- if (ok && data.choices) {
484
- const content = data.choices[0]?.message?.content;
485
-
486
- this.testResponse = content && content.trim()
487
- ? content
488
- : `[Empty response]\n\n${JSON.stringify(data, null, 2)}`;
489
- } else {
490
- this.testResponse = data?.error?.message || data?.error || 'Request failed';
491
- }
492
- },
493
-
494
- async loadAccountStrategySetting() {
495
- const { ok, data } = await this.api('/settings/account-strategy');
496
- if (ok && data?.accountStrategy) {
497
- this.accountStrategy = data.accountStrategy;
498
- }
499
- },
500
-
501
- async setAccountStrategy(strategy) {
502
- if (this.strategySaving || this.accountStrategy === strategy) return;
503
- this.strategySaving = true;
504
- const { ok, data } = await this.api('/settings/account-strategy', {
505
- method: 'POST',
506
- body: JSON.stringify({ accountStrategy: strategy })
507
- });
508
- this.strategySaving = false;
509
- if (ok && data?.accountStrategy) {
510
- this.accountStrategy = data.accountStrategy;
511
- this.showToast(`Account strategy set to ${data.accountStrategy === 'sticky' ? 'Sticky' : 'Round-Robin'}`, 'success');
512
- } else {
513
- this.showToast(data?.error || 'Failed to update strategy', 'error');
514
- }
515
- },
516
-
517
- async loadRawProxyLogsSetting() {
518
- const { ok, data } = await this.api('/settings/raw-proxy-logs');
519
- if (ok && typeof data?.logRawProxyPayloads === 'boolean') {
520
- this.logRawProxyPayloads = data.logRawProxyPayloads;
521
- }
522
- },
523
-
524
- async setRawProxyLogs(enabled) {
525
- if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return;
526
- this.rawProxyLogsSaving = true;
527
- const { ok, data } = await this.api('/settings/raw-proxy-logs', {
528
- method: 'POST',
529
- body: JSON.stringify({ enabled })
530
- });
531
- this.rawProxyLogsSaving = false;
532
-
533
- if (ok && typeof data?.logRawProxyPayloads === 'boolean') {
534
- this.logRawProxyPayloads = data.logRawProxyPayloads;
535
- this.showToast(data.logRawProxyPayloads ? 'Raw proxy payload logging enabled' : 'Raw proxy payload logging disabled', 'success');
536
- } else {
537
- this.showToast(data?.error || 'Failed to update raw proxy logging', 'error');
538
- }
539
- },
540
-
541
- async loadModelMapSetting() {
542
- this.modelMapLoading = true;
543
- const { ok, data } = await this.api('/settings/model-map');
544
- this.modelMapLoading = false;
545
-
546
- if (ok && data?.modelMap) {
547
- this.modelMappings = {
548
- sonnet: data.modelMap.sonnet || this.modelMappings.sonnet,
549
- opus: data.modelMap.opus || this.modelMappings.opus,
550
- haiku: data.modelMap.haiku || this.modelMappings.haiku
551
- };
552
- }
553
- },
554
-
555
- async saveModelMapSetting() {
556
- if (this.modelMapSaving) return;
557
-
558
- const modelMap = {
559
- sonnet: this.modelMappings.sonnet.trim(),
560
- opus: this.modelMappings.opus.trim(),
561
- haiku: this.modelMappings.haiku.trim()
562
- };
563
-
564
- if (!modelMap.sonnet || !modelMap.opus || !modelMap.haiku) {
565
- this.showToast('All Claude model mappings are required.', 'error');
566
- return;
567
- }
568
-
569
- this.modelMapSaving = true;
570
- const { ok, data } = await this.api('/settings/model-map', {
571
- method: 'POST',
572
- body: JSON.stringify({
573
- modelMap,
574
- reset: true
575
- })
576
- });
577
- this.modelMapSaving = false;
578
-
579
- if (ok && data?.modelMap) {
580
- this.modelMappings = {
581
- sonnet: data.modelMap.sonnet || modelMap.sonnet,
582
- opus: data.modelMap.opus || modelMap.opus,
583
- haiku: data.modelMap.haiku || modelMap.haiku
584
- };
585
- this.showToast('Model mapping updated', 'success');
586
- } else {
587
- this.showToast(data?.error || 'Failed to update model mapping', 'error');
588
- }
589
- },
590
-
591
- async resetModelMapSetting() {
592
- if (this.modelMapSaving) return;
593
- this.modelMapSaving = true;
594
- const { ok, data } = await this.api('/settings/model-map', {
595
- method: 'POST',
596
- body: JSON.stringify({ reset: true })
597
- });
598
- this.modelMapSaving = false;
599
-
600
- if (ok && data?.modelMap) {
601
- this.modelMappings = {
602
- sonnet: data.modelMap.sonnet || 'gpt-5.5',
603
- opus: data.modelMap.opus || 'gpt-5.5',
604
- haiku: data.modelMap.haiku || 'gpt-5.4-mini'
605
- };
606
- this.showToast('Model mapping reset', 'success');
607
- } else {
608
- this.showToast(data?.error || 'Failed to reset model mapping', 'error');
609
- }
610
- },
611
-
612
- async loadClientApiKeys() {
613
- this.clientApiKeysLoading = true;
614
- const { ok, data } = await this.api('/settings/client-api-keys');
615
- this.clientApiKeysLoading = false;
616
- if (ok && Array.isArray(data?.clientApiKeys)) {
617
- this.clientApiKeys = data.clientApiKeys;
618
- } else {
619
- this.showToast(data?.error || 'Failed to load client API keys', 'error');
620
- }
621
- },
622
-
623
- async createClientApiKey() {
624
- if (this.clientApiKeySaving) return;
625
- this.clientApiKeySaving = true;
626
- const { ok, data } = await this.api('/settings/client-api-keys', {
627
- method: 'POST',
628
- body: JSON.stringify({
629
- name: this.clientApiKeyName,
630
- remark: this.clientApiKeyRemark
631
- })
632
- });
633
- this.clientApiKeySaving = false;
634
-
635
- if (ok && data?.clientApiKey?.key) {
636
- this.revealedClientApiKey = data.clientApiKey.key;
637
- this.clientApiKeyName = '';
638
- this.clientApiKeyRemark = '';
639
- this.showCreateClientApiKeyModal = false;
640
- await this.loadClientApiKeys();
641
- this.showToast('Client API key created. Copy it now; it will not be shown again.', 'success');
642
- } else {
643
- this.showToast(data?.error || 'Failed to create client API key', 'error');
644
- }
645
- },
646
-
647
- async updateClientApiKey(clientApiKey) {
648
- if (this.clientApiKeySaving) return;
649
- this.clientApiKeySaving = true;
650
- const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, {
651
- method: 'PUT',
652
- body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark })
653
- });
654
- this.clientApiKeySaving = false;
655
- if (ok) {
656
- this.showToast('Client API key updated', 'success');
657
- await this.loadClientApiKeys();
658
- } else {
659
- this.showToast(data?.error || 'Failed to update client API key', 'error');
660
- }
661
- },
662
-
663
- async deleteClientApiKey(clientApiKey) {
664
- if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return;
665
- this.clientApiKeySaving = true;
666
- const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' });
667
- this.clientApiKeySaving = false;
668
- if (ok) {
669
- await this.loadClientApiKeys();
670
- this.showToast('Client API key deleted', 'success');
671
- } else {
672
- this.showToast(data?.error || 'Failed to delete client API key', 'error');
673
- }
674
- },
675
-
676
- async setClaudeCodeProxyTestConfig() {
677
- const { ok, data, error } = await this.api('/claude/config/set', {
678
- method: 'POST',
679
- body: JSON.stringify({
680
- apiUrl: this.serverUrl,
681
- apiKey: 'test'
682
- })
683
- });
684
-
685
- if (ok && data?.success) {
686
- this.showToast('Updated Claude Code settings.json (API URL + API key).', 'success');
687
- } else {
688
- this.showToast(data?.error || error || 'Failed to update Claude Code settings.json', 'error');
689
- }
690
- },
691
-
692
- showToast(message, type = 'success') {
693
- this.toast = { message, type };
694
- setTimeout(() => { this.toast = null; }, 3000);
695
- },
696
-
697
- startLogStream() {
698
- if (!this.isAuthenticated) return;
699
- if (this.logEventSource) this.logEventSource.close();
700
-
701
- const params = new URLSearchParams({ history: 'true' });
702
- if (this.apiKey) params.set('api_key', this.apiKey);
703
- this.logEventSource = new EventSource(`/api/logs/stream?${params.toString()}`);
704
- this.logEventSource.onmessage = (event) => {
705
- try {
706
- const log = JSON.parse(event.data);
707
- this.logs.unshift(log);
708
-
709
- if (this.logs.length > 500) {
710
- this.logs = this.logs.slice(0, 500);
711
- }
712
- } catch (e) {}
713
- };
714
-
715
- this.logEventSource.onerror = () => {
716
- setTimeout(() => this.startLogStream(), 3000);
717
- };
718
- },
719
-
720
- clearLogs() {
721
- this.logs = [];
722
- },
723
-
724
- formatLogMessage(message) {
725
- if (!message) return '';
726
- const match = message.match(/^\[(\w+)\]\s*/);
727
- if (match) {
728
- return message.replace(match[0], '');
729
- }
730
- return message;
731
- },
732
-
733
- getLogDetails(message) {
734
- if (!message) return null;
735
- const details = {};
736
-
737
- const patterns = [
738
- ['model', /model=([^\s|,]+)/],
739
- ['account', /account=([^\s|,]+)/],
740
- ['stream', /stream=(true|false)/],
741
- ['messages', /messages=(\d+)/],
742
- ['tools', /tools=(\d+)/],
743
- ['tokens', /tokens=(\d+)/],
744
- ['cache_read_input_tokens', /cache_read_input_tokens=(\d+)/],
745
- ['input_tokens', /input_tokens=(\d+)/],
746
- ['output_tokens', /output_tokens=(\d+)/],
747
- ['duration', /(\d+)ms/],
748
- ['status', /status=(\d+)/],
749
- ['error', /error=([^\s|]+)/]
750
- ];
751
-
752
- for (const [key, pattern] of patterns) {
753
- const match = message.match(pattern);
754
- if (match) {
755
- details[key] = match[1];
756
- }
757
- }
758
-
759
- return Object.keys(details).length > 0 ? details : null;
760
- }
82
+ window.location.replace('/dashboard');
83
+ },
84
+ logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace('/login'); },
85
+ async checkHealth() { const { ok, data } = await this.api('/health'); this.connectionStatus = ok ? 'connected' : 'disconnected'; if (ok && data?.version) this.version = data.version; if (ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; },
86
+ async refreshAccounts() { this.loading = true; const { ok, data } = await this.api('/accounts'); if (ok && data.accounts) { this.accounts = data.accounts; this.stats = { total: data.total || data.accounts.length, active: data.accounts.filter(a => a.isActive).length, expired: data.accounts.filter(a => a.tokenExpired).length, planType: data.accounts.find(a => a.isActive)?.planType || '-' }; await this.refreshAllQuotaData(); } this.loading = false; },
87
+ async refreshAllQuotaData() { if (!this.accounts.length) return; const { ok, data } = await this.api('/accounts/quota/all'); if (!ok || !data?.accounts) return; const quotaMap = new Map(data.accounts.map(entry => [entry.email, entry.quota || null])); this.accounts = this.accounts.map(account => ({ ...account, quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota })); if (this.selectedAccount?.email) this.selectedAccount = this.accounts.find(account => account.email === this.selectedAccount.email) || this.selectedAccount; },
88
+ getRemainingPercentage(account) { const usage = account?.quota?.usage; if (!usage) return null; const values = [Number(usage.percentage), Number(usage.totalTokenUsage), Number.isFinite(Number(usage.remaining)) ? 100 - Number(usage.remaining) : NaN]; const used = values.find(Number.isFinite); if (!Number.isFinite(used)) return usage.limitReached === true || usage.allowed === false ? 0 : null; return Math.max(0, Math.round(100 - Math.max(0, Math.min(100, used)))); },
89
+ isQuotaExhausted(account) { const remaining = this.getRemainingPercentage(account); return remaining !== null && (remaining <= 0 || account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false); },
90
+ quotaBarClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
91
+ quotaTextClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? '-' : `${remaining}%`; },
92
+ getQuotaResetAt(account) { const usage = account?.quota?.usage; if (!usage) return null; if (usage.resetAt) return usage.resetAt; const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at); if (Number.isFinite(epoch)) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
93
+ quotaResetAtLabel(account) { const resetAt = this.getQuotaResetAt(account); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
94
+ quotaResetSummary(account) { const resetAt = this.getQuotaResetAt(account); if (!resetAt) return null; const seconds = Math.max(0, Math.floor((new Date(resetAt).getTime() - Date.now()) / 1000)); if (!seconds) return 'Reset due now'; const hours = Math.floor(seconds / 3600), minutes = Math.floor((seconds % 3600) / 60); return hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
95
+ async startOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) window.open(data.oauth_url, 'ChatGPT Login', 'width=500,height=700'); else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
96
+ async startManualOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) { this.oauthManualUrl = data.oauth_url; this.oauthManualVerifier = data.verifier; this.oauthManualCode = ''; this.oauthManualMode = true; } else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
97
+ async submitManualOAuth() { if (!this.oauthManualCode) return; const { ok, data } = await this.api('/accounts/add/manual', { method: 'POST', body: JSON.stringify({ code: this.oauthManualCode, verifier: this.oauthManualVerifier }) }); if (ok && data.success) { this.showAddModal = false; this.oauthManualMode = false; this.refreshAccounts(); } else this.showToast(data?.error || 'Failed to add account', 'error'); },
98
+ async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
99
+ async importFromCodex() { const { ok, data } = await this.api('/accounts/import', { method: 'POST' }); if (ok && data.success) { this.showAddModal = false; this.refreshAccounts(); } else this.showToast(data?.message || 'Import failed', 'error'); },
100
+ async switchAccount(email) { const { ok, data } = await this.api('/accounts/switch', { method: 'POST', body: JSON.stringify({ email }) }); if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Failed to switch', 'error'); },
101
+ async refreshToken(email) { if (this.refreshingTokenEmails.includes(email)) return; this.refreshingTokenEmails.push(email); try { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }); if (ok && data.success) await this.refreshAccounts(); else this.showToast(data?.message || 'Refresh failed', 'error'); } finally { this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email); } },
102
+ async refreshAllTokens() { const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' }); if (ok) this.refreshAccounts(); else this.showToast(data?.message || 'Failed', 'error'); }, confirmDelete(email) { this.deleteTarget = email; this.showDeleteModal = true; },
103
+ async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; },
104
+ async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
105
+ async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
106
+ async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
107
+ async loadModelMapSetting() { this.modelMapLoading = true; const { ok, data } = await this.api('/settings/model-map'); this.modelMapLoading = false; if (ok && data?.modelMap) this.modelMappings = { sonnet: data.modelMap.sonnet || this.modelMappings.sonnet, opus: data.modelMap.opus || this.modelMappings.opus, haiku: data.modelMap.haiku || this.modelMappings.haiku }; },
108
+ async saveModelMapSetting() { if (this.modelMapSaving) return; const modelMap = Object.fromEntries(Object.entries(this.modelMappings).map(([key, value]) => [key, value.trim()])); if (Object.values(modelMap).some(value => !value)) { this.showToast('All Claude model mappings are required.', 'error'); return; } this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ modelMap, reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to update model mapping', 'error'); },
109
+ async resetModelMapSetting() { if (this.modelMapSaving) return; this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to reset model mapping', 'error'); },
110
+ async loadClientApiKeys() { this.clientApiKeysLoading = true; const { ok, data } = await this.api('/settings/client-api-keys'); this.clientApiKeysLoading = false; if (ok && Array.isArray(data?.clientApiKeys)) this.clientApiKeys = data.clientApiKeys; else this.showToast(data?.error || 'Failed to load client API keys', 'error'); },
111
+ async createClientApiKey() { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(this.clientApiKeyWeeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api('/settings/client-api-keys', { method: 'POST', body: JSON.stringify({ name: this.clientApiKeyName, remark: this.clientApiKeyRemark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.clientApiKeyWeeklyLimitUsd = 50; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
112
+ async loadClientProxyConfig() { const { ok, data } = await this.api('/claude/config/proxy', { method: 'POST' }); if (ok && data?.success && data?.env) this.clientProxyConfig = data; }, async copyClientText(text, successMessage) { if (!text) return; try { await navigator.clipboard.writeText(text); this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const commands = this.clientProxyConfig?.commands?.powershell; return Array.isArray(commands) ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
113
+ async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(clientApiKey.weeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'PUT', body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to update client API key', 'error'); }, async deleteClientApiKey(clientApiKey) { if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to delete client API key', 'error'); },
114
+ showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, startLogStream() { if (!this.isAuthenticated) return; this.logEventSource?.close(); const params = new URLSearchParams({ history: 'true' }); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(`/api/logs/stream?${params}`); this.logEventSource.onmessage = event => { try { this.logs.unshift(JSON.parse(event.data)); this.logs = this.logs.slice(0, 500); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
761
115
  }));
762
116
  });