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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.5-beta.3",
3
+ "version": "1.0.5-beta.5",
4
4
  "description": "Multi-account proxy server for OpenAI Codex CLI with Claude API compatibility",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -396,6 +396,133 @@ table .btn-outline:hover {
396
396
  color: white;
397
397
  }
398
398
 
399
+ .client-keys-panel {
400
+ overflow: hidden;
401
+ border: 1px solid rgba(42, 42, 62, 0.72);
402
+ border-radius: 0.875rem;
403
+ background: rgba(12, 12, 20, 0.72);
404
+ box-shadow: 0 18px 42px rgba(0, 0, 0, 0.28);
405
+ }
406
+
407
+ .client-keys-toolbar {
408
+ display: flex;
409
+ align-items: center;
410
+ justify-content: space-between;
411
+ gap: 1.5rem;
412
+ padding: 1.25rem 1.5rem;
413
+ border-bottom: 1px solid rgba(42, 42, 62, 0.55);
414
+ }
415
+
416
+ .client-keys-toolbar h2 { color: #f8fafc; font-size: 0.9375rem; font-weight: 600; }
417
+ .client-keys-toolbar p { margin-top: 0.25rem; color: #64748b; font-size: 0.75rem; }
418
+ .client-keys-toolbar-actions { display: flex; align-items: center; gap: 1rem; }
419
+
420
+ .client-keys-reset { display: flex; align-items: center; gap: 0.625rem; color: #64748b; }
421
+ .client-keys-reset svg { width: 1rem; height: 1rem; color: #8b5cf6; }
422
+ .client-keys-reset div { display: flex; flex-direction: column; gap: 0.125rem; }
423
+ .client-keys-reset span { font-size: 0.625rem; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; }
424
+ .client-keys-reset strong { color: #a1a1aa; font-family: 'JetBrains Mono', monospace; font-size: 0.6875rem; font-weight: 500; }
425
+
426
+ .client-keys-new {
427
+ display: inline-flex;
428
+ align-items: center;
429
+ gap: 0.5rem;
430
+ padding: 0.55rem 0.9rem;
431
+ border: 1px solid rgba(168, 85, 247, 0.65);
432
+ border-radius: 0.5rem;
433
+ background: linear-gradient(135deg, #9333ea, #7c3aed);
434
+ box-shadow: 0 8px 20px rgba(126, 34, 206, 0.22);
435
+ color: #fff;
436
+ font-size: 0.75rem;
437
+ font-weight: 600;
438
+ cursor: pointer;
439
+ }
440
+ .client-keys-new:hover { background: linear-gradient(135deg, #a855f7, #8b5cf6); }
441
+ .client-keys-new span { font-size: 1rem; font-weight: 400; line-height: 1; }
442
+
443
+ .client-keys-list { padding: 0.75rem; }
444
+ .client-key-card {
445
+ display: grid;
446
+ grid-template-columns: minmax(270px, 1.45fr) minmax(230px, 1.15fr) 130px 110px auto;
447
+ align-items: center;
448
+ gap: 1.5rem;
449
+ padding: 1.1rem 1rem;
450
+ border: 1px solid transparent;
451
+ border-radius: 0.7rem;
452
+ transition: border-color 160ms ease, background-color 160ms ease, box-shadow 160ms ease;
453
+ }
454
+ .client-key-card + .client-key-card { margin-top: 0.375rem; }
455
+ .client-key-card:hover {
456
+ border-color: rgba(42, 42, 62, 0.72);
457
+ background: rgba(26, 26, 40, 0.48);
458
+ box-shadow: inset 3px 0 0 rgba(168, 85, 247, 0.72);
459
+ }
460
+
461
+ .client-key-identity { display: flex; align-items: center; gap: 0.875rem; min-width: 0; }
462
+ .client-key-icon { display: grid; width: 2.4rem; height: 2.4rem; flex: 0 0 auto; place-items: center; border: 1px solid rgba(168, 85, 247, 0.2); border-radius: 0.65rem; background: rgba(168, 85, 247, 0.08); color: #c084fc; }
463
+ .client-key-icon svg { width: 1.15rem; height: 1.15rem; }
464
+ .client-key-fields { display: grid; grid-template-columns: minmax(110px, 1fr) minmax(100px, 0.85fr); gap: 0.625rem; min-width: 0; }
465
+ .client-key-fields label, .client-key-limit { display: block; min-width: 0; }
466
+ .client-key-fields label > span, .client-key-limit > span, .client-key-meta > span, .client-key-quota-heading > span { display: block; margin-bottom: 0.35rem; color: #64748b; font-size: 0.6rem; font-weight: 600; letter-spacing: 0.07em; text-transform: uppercase; }
467
+ .client-key-fields input, .client-key-limit input {
468
+ width: 100%;
469
+ height: 2.15rem;
470
+ border: 1px solid rgba(42, 42, 62, 0.75);
471
+ border-radius: 0.45rem;
472
+ outline: none;
473
+ background: rgba(15, 15, 26, 0.62);
474
+ color: #e5e7eb;
475
+ font-size: 0.75rem;
476
+ transition: border-color 150ms ease, background-color 150ms ease;
477
+ }
478
+ .client-key-fields input { padding: 0 0.7rem; }
479
+ .client-key-fields input:focus, .client-key-limit input:focus { border-color: rgba(168, 85, 247, 0.72); background: rgba(26, 26, 40, 0.9); }
480
+
481
+ .client-key-quota-heading { display: flex; align-items: end; justify-content: space-between; gap: 1rem; }
482
+ .client-key-quota-heading strong { color: #f8fafc; font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; font-weight: 600; white-space: nowrap; }
483
+ .client-key-quota-heading small { color: #64748b; font-size: 0.6875rem; font-weight: 400; }
484
+ .client-key-progress { overflow: hidden; height: 0.35rem; border-radius: 999px; background: rgba(42, 42, 62, 0.72); }
485
+ .client-key-progress i { display: block; height: 100%; min-width: 2px; border-radius: inherit; background: linear-gradient(90deg, #8b5cf6, #22d3ee); box-shadow: 0 0 10px rgba(34, 211, 238, 0.25); }
486
+ .client-key-quota-foot { display: flex; justify-content: space-between; margin-top: 0.4rem; color: #64748b; font-family: 'JetBrains Mono', monospace; font-size: 0.6rem; }
487
+
488
+ .client-key-limit > div { display: flex; height: 2.15rem; border: 1px solid rgba(42, 42, 62, 0.75); border-radius: 0.45rem; background: rgba(15, 15, 26, 0.62); }
489
+ .client-key-limit b { display: grid; width: 1.9rem; place-items: center; border-right: 1px solid rgba(42, 42, 62, 0.75); color: #64748b; font-size: 0.75rem; font-weight: 500; }
490
+ .client-key-limit input { height: auto; padding: 0 0.55rem; border: 0; background: transparent; font-family: 'JetBrains Mono', monospace; }
491
+
492
+ .client-key-meta strong, .client-key-meta small { display: block; font-family: 'JetBrains Mono', monospace; white-space: nowrap; }
493
+ .client-key-meta strong { color: #a1a1aa; font-size: 0.6875rem; font-weight: 500; }
494
+ .client-key-meta small { margin-top: 0.2rem; color: #52525b; font-size: 0.625rem; }
495
+ .client-key-actions { display: flex; align-items: center; justify-content: flex-end; gap: 0.45rem; }
496
+ .client-key-save, .client-key-delete { height: 2.15rem; border-radius: 0.45rem; cursor: pointer; transition: all 150ms ease; }
497
+ .client-key-save { padding: 0 0.75rem; border: 1px solid rgba(168, 85, 247, 0.35); background: rgba(168, 85, 247, 0.1); color: #d8b4fe; font-size: 0.6875rem; font-weight: 600; white-space: nowrap; }
498
+ .client-key-save:hover { border-color: rgba(168, 85, 247, 0.65); background: rgba(168, 85, 247, 0.2); color: #fff; }
499
+ .client-key-delete { display: grid; width: 2.15rem; place-items: center; border: 1px solid transparent; background: transparent; color: #52525b; }
500
+ .client-key-delete svg { width: 1rem; height: 1rem; }
501
+ .client-key-delete:hover { border-color: rgba(239, 68, 68, 0.2); background: rgba(239, 68, 68, 0.08); color: #f87171; }
502
+ .client-key-save:disabled, .client-key-delete:disabled { opacity: 0.45; cursor: not-allowed; }
503
+ .client-keys-empty { padding: 4rem 1.5rem; color: #64748b; font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; text-align: center; }
504
+
505
+ @media (max-width: 1100px) {
506
+ .client-key-card { grid-template-columns: minmax(260px, 1.3fr) minmax(220px, 1fr) 120px auto; }
507
+ .client-key-meta { display: none; }
508
+ }
509
+
510
+ @media (max-width: 800px) {
511
+ .client-keys-toolbar { align-items: flex-start; }
512
+ .client-keys-toolbar-actions { align-items: flex-end; flex-direction: column-reverse; }
513
+ .client-key-card { grid-template-columns: 1fr; gap: 1rem; }
514
+ .client-key-fields { width: 100%; }
515
+ .client-key-actions { justify-content: flex-start; }
516
+ .client-key-save { flex: 1; }
517
+ }
518
+
519
+ @media (max-width: 560px) {
520
+ .client-keys-toolbar { flex-direction: column; }
521
+ .client-keys-toolbar-actions { width: 100%; align-items: stretch; }
522
+ .client-keys-new { justify-content: center; }
523
+ .client-key-fields { grid-template-columns: 1fr; }
524
+ }
525
+
399
526
  .animate-spin {
400
527
  animation: spin 1s linear infinite;
401
528
  }
package/public/index.html CHANGED
@@ -1,60 +1,60 @@
1
- <!DOCTYPE html>
2
- <html lang="en" data-theme="codex" class="dark">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Claude Codex Proxy</title>
7
- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🚀</text></svg>">
8
- <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
9
- <link rel="stylesheet" href="/css/style.css">
10
- </head>
11
- <body class="bg-space-950 text-gray-300 font-sans antialiased min-h-screen selection:bg-neon-purple selection:text-white" x-data="app" x-init="init()">
12
- <div x-cloak class="fixed top-4 right-4 z-[100] flex flex-col gap-2 pointer-events-none">
13
- <template x-if="toast">
14
- <div class="alert shadow-lg border backdrop-blur-md pointer-events-auto min-w-[300px]" :class="{
15
- 'alert-info border-neon-cyan/20 bg-space-900/90 text-neon-cyan': toast.type === 'info',
16
- 'alert-success border-neon-green/20 bg-space-900/90 text-neon-green': toast.type === 'success',
17
- 'alert-error border-red-500/20 bg-space-900/90 text-red-400': toast.type === 'error',
18
- 'alert-warning border-yellow-500/20 bg-space-900/90 text-yellow-400': toast.type === 'warning'
19
- }"><span x-text="toast.message" class="font-mono text-sm"></span></div>
20
- </template>
21
- </div>
22
-
23
- <div x-cloak class="h-14 border-b border-space-border flex items-center px-4 lg:px-6 justify-between bg-space-900/50 backdrop-blur-md z-50 relative" x-show="isAuthenticated">
24
- <div class="flex items-center gap-3">
25
- <button @click="sidebarOpen = !sidebarOpen" class="text-gray-400 hover:text-white focus:outline-none p-1 transition-colors lg:hidden" aria-label="Toggle navigation">☰</button>
26
- <div class="w-8 h-8 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
27
- <div class="flex flex-col"><span class="text-sm font-bold tracking-wide text-white">CODEX PROXY</span><span class="text-[10px] text-gray-500 font-mono tracking-wider" x-text="version ? 'CLAUDE PROXY SYSTEM v' + version : 'CLAUDE PROXY SYSTEM'"></span></div>
28
- </div>
29
- <div class="flex items-center gap-4">
30
- <div class="flex items-center gap-2 px-3 py-1 rounded-full text-xs font-mono border" :class="connectionStatus === 'connected' ? 'bg-neon-green/10 border-neon-green/20 text-neon-green' : 'bg-red-500/10 border-red-500/20 text-red-500'"><span x-text="connectionStatus === 'connected' ? 'Online' : 'Offline'"></span></div>
31
- <button type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="refreshAccounts()" :disabled="loading">Refresh</button>
32
- <button x-show="authRequired" type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="logout()">Logout</button>
33
- </div>
34
- </div>
35
-
36
- <div x-cloak x-show="isAuthenticated" class="flex h-[calc(100vh-56px)] relative">
37
- <div x-show="sidebarOpen" @click="sidebarOpen = false" class="fixed inset-0 bg-black/50 z-40 lg:hidden" style="display: none;"></div>
38
- <aside class="fixed top-14 bottom-0 left-0 z-40 w-64 transform bg-space-900 border-r border-space-border transition-all duration-300 shadow-2xl overflow-hidden lg:static lg:h-auto lg:shadow-none lg:flex-shrink-0 lg:translate-x-0" :class="{'translate-x-0': sidebarOpen, '-translate-x-full': !sidebarOpen}">
39
- <div class="w-64 flex flex-col h-full sidebar-content">
40
- <div class="sidebar-section-title">Workspace</div>
41
- <nav class="sidebar-nav">
42
- <a href="/dashboard" class="nav-item" :class="{'active': activeTab === 'dashboard'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z"/></svg><span>Dashboard</span></a>
43
- <a href="/account-management" class="nav-item" :class="{'active': activeTab === 'accounts'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M16 20v-1a4 4 0 00-4-4H7a4 4 0 00-4 4v1m6-9a4 4 0 100-8 4 4 0 000 8zm6 1a3 3 0 100-6m2 15v-1a4 4 0 00-3-3.87"/></svg><span>Accounts</span></a>
44
- </nav>
45
- <div class="sidebar-section-title">System</div>
46
- <nav class="sidebar-nav">
47
- <a href="/logs" class="nav-item" :class="{'active': activeTab === 'logs'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 5a2 2 0 012-2h8l4 4v12a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm4 7h8m-8 4h6"/></svg><span>Logs</span></a>
48
- <a href="/client-api-keys" class="nav-item" :class="{'active': activeTab === 'client-api-keys'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M15 7a5 5 0 11-9.6 2H3v4h3v3h3v-3h2.4A5 5 0 0115 7zm0 0a1 1 0 100 2 1 1 0 000-2z"/></svg><span>Client API Keys</span></a>
49
- <a href="/settings" class="nav-item" :class="{'active': activeTab === 'settings'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 15.5a3.5 3.5 0 100-7 3.5 3.5 0 000 7zm7.4-3.5a7.4 7.4 0 00-.1-1.1l2-1.5-2-3.4-2.4 1a8 8 0 00-1.8-1L14.8 3h-4l-.3 2.8a8 8 0 00-1.8 1l-2.4-1-2 3.4 2 1.5A7.4 7.4 0 006.6 12c0 .4 0 .7.1 1.1l-2 1.5 2 3.4 2.4-1a8 8 0 001.8 1l.3 2.8h4l.3-2.8a8 8 0 001.8-1l2.4 1 2-3.4-2-1.5c.1-.4.1-.7.1-1.1z"/></svg><span>Settings</span></a>
50
- </nav>
51
- <div class="sidebar-footer"><span class="sidebar-status-dot"></span><span x-text="connectionStatus === 'connected' ? 'Proxy connected' : 'Proxy offline'"></span></div>
52
- </div>
53
- </aside>
54
- <main id="view-content" class="flex-1 overflow-auto bg-space-950 relative custom-scrollbar" aria-live="polite"></main>
55
- </div>
56
-
57
- <div x-cloak id="modal-content"></div>
58
- <script src="/js/app.js"></script>
59
- </body>
60
- </html>
1
+ <!DOCTYPE html>
2
+ <html lang="en" data-theme="codex" class="dark">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Claude Codex Proxy</title>
7
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🚀</text></svg>">
8
+ <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
9
+ <link rel="stylesheet" href="/css/style.css">
10
+ </head>
11
+ <body class="bg-space-950 text-gray-300 font-sans antialiased min-h-screen selection:bg-neon-purple selection:text-white" x-data="app" x-init="init()">
12
+ <div x-cloak class="fixed top-4 right-4 z-[100] flex flex-col gap-2 pointer-events-none">
13
+ <template x-if="toast">
14
+ <div class="alert shadow-lg border backdrop-blur-md pointer-events-auto min-w-[300px]" :class="{
15
+ 'alert-info border-neon-cyan/20 bg-space-900/90 text-neon-cyan': toast.type === 'info',
16
+ 'alert-success border-neon-green/20 bg-space-900/90 text-neon-green': toast.type === 'success',
17
+ 'alert-error border-red-500/20 bg-space-900/90 text-red-400': toast.type === 'error',
18
+ 'alert-warning border-yellow-500/20 bg-space-900/90 text-yellow-400': toast.type === 'warning'
19
+ }"><span x-text="toast.message" class="font-mono text-sm"></span></div>
20
+ </template>
21
+ </div>
22
+
23
+ <div x-cloak class="h-14 border-b border-space-border flex items-center px-4 lg:px-6 justify-between bg-space-900/50 backdrop-blur-md z-50 relative" x-show="isAuthenticated">
24
+ <div class="flex items-center gap-3">
25
+ <button @click="sidebarOpen = !sidebarOpen" class="text-gray-400 hover:text-white focus:outline-none p-1 transition-colors lg:hidden" aria-label="Toggle navigation">☰</button>
26
+ <div class="w-8 h-8 rounded bg-gradient-to-br from-neon-purple to-blue-600 flex items-center justify-center text-white font-bold">CX</div>
27
+ <div class="flex flex-col"><span class="text-sm font-bold tracking-wide text-white">CODEX PROXY</span><span class="text-[10px] text-gray-500 font-mono tracking-wider" x-text="version ? 'CLAUDE PROXY SYSTEM v' + version : 'CLAUDE PROXY SYSTEM'"></span></div>
28
+ </div>
29
+ <div class="flex items-center gap-4">
30
+ <div class="flex items-center gap-2 px-3 py-1 rounded-full text-xs font-mono border" :class="connectionStatus === 'connected' ? 'bg-neon-green/10 border-neon-green/20 text-neon-green' : 'bg-red-500/10 border-red-500/20 text-red-500'"><span x-text="connectionStatus === 'connected' ? 'Online' : 'Offline'"></span></div>
31
+ <button type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="refreshAccounts()" :disabled="loading">Refresh</button>
32
+ <button x-show="authRequired" type="button" class="btn btn-ghost btn-xs text-gray-400 hover:text-white" @click="logout()">Logout</button>
33
+ </div>
34
+ </div>
35
+
36
+ <div x-cloak x-show="isAuthenticated" class="flex h-[calc(100vh-56px)] relative">
37
+ <div x-show="sidebarOpen" @click="sidebarOpen = false" class="fixed inset-0 bg-black/50 z-40 lg:hidden" style="display: none;"></div>
38
+ <aside class="fixed top-14 bottom-0 left-0 z-40 w-64 transform bg-space-900 border-r border-space-border transition-all duration-300 shadow-2xl overflow-hidden lg:static lg:h-auto lg:shadow-none lg:flex-shrink-0 lg:translate-x-0" :class="{'translate-x-0': sidebarOpen, '-translate-x-full': !sidebarOpen}">
39
+ <div class="w-64 flex flex-col h-full sidebar-content">
40
+ <div class="sidebar-section-title">Workspace</div>
41
+ <nav class="sidebar-nav">
42
+ <a href="/dashboard" class="nav-item" :class="{'active': activeTab === 'dashboard'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z"/></svg><span>Dashboard</span></a>
43
+ <a href="/account-management" class="nav-item" :class="{'active': activeTab === 'accounts'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M16 20v-1a4 4 0 00-4-4H7a4 4 0 00-4 4v1m6-9a4 4 0 100-8 4 4 0 000 8zm6 1a3 3 0 100-6m2 15v-1a4 4 0 00-3-3.87"/></svg><span>Accounts</span></a>
44
+ </nav>
45
+ <div class="sidebar-section-title">System</div>
46
+ <nav class="sidebar-nav">
47
+ <a href="/logs" class="nav-item" :class="{'active': activeTab === 'logs'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 5a2 2 0 012-2h8l4 4v12a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm4 7h8m-8 4h6"/></svg><span>Logs</span></a>
48
+ <a href="/client-api-keys" class="nav-item" :class="{'active': activeTab === 'client-api-keys'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M15 7a5 5 0 11-9.6 2H3v4h3v3h3v-3h2.4A5 5 0 0115 7zm0 0a1 1 0 100 2 1 1 0 000-2z"/></svg><span>Client API Keys</span></a>
49
+ <a href="/settings" class="nav-item" :class="{'active': activeTab === 'settings'}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 15.5a3.5 3.5 0 100-7 3.5 3.5 0 000 7zm7.4-3.5a7.4 7.4 0 00-.1-1.1l2-1.5-2-3.4-2.4 1a8 8 0 00-1.8-1L14.8 3h-4l-.3 2.8a8 8 0 00-1.8 1l-2.4-1-2 3.4 2 1.5A7.4 7.4 0 006.6 12c0 .4 0 .7.1 1.1l-2 1.5 2 3.4 2.4-1a8 8 0 001.8 1l.3 2.8h4l.3-2.8a8 8 0 001.8-1l2.4 1 2-3.4-2-1.5c.1-.4.1-.7.1-1.1z"/></svg><span>Settings</span></a>
50
+ </nav>
51
+ <div class="sidebar-footer"><span class="sidebar-status-dot"></span><span x-text="connectionStatus === 'connected' ? 'Proxy connected' : 'Proxy offline'"></span></div>
52
+ </div>
53
+ </aside>
54
+ <main id="view-content" class="flex-1 overflow-auto bg-space-950 relative custom-scrollbar" aria-live="polite"></main>
55
+ </div>
56
+
57
+ <div x-cloak id="modal-content"></div>
58
+ <script src="/js/app.js"></script>
59
+ </body>
60
+ </html>
package/public/js/app.js CHANGED
@@ -1,116 +1,116 @@
1
- document.addEventListener('alpine:init', () => {
2
- Alpine.data('app', () => ({
3
- version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
4
- loading: false, refreshingTokenEmails: [], toast: null, currentTime: '', authRequired: false,
5
- authChecked: false, apiKey: localStorage.getItem('codexProxyApiKey') || '', loginApiKey: '', loginError: '',
6
- accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
7
- accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
8
- modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
9
- clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeysLoading: false,
10
- clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
11
- showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
12
- oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
13
- testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
14
- serverUrl: window.location.origin, logs: [], logSearchQuery: '',
15
- logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false }, logEventSource: null,
16
-
17
- get isAuthenticated() { return !this.authRequired || Boolean(this.apiKey); },
18
- get filteredLogs() { const query = this.logSearchQuery.trim().toLowerCase(); return this.logs.filter(log => this.logFilters[log.level] && (!query || log.message.toLowerCase().includes(query))); },
19
- get filteredAccounts() { if (!this.searchQuery) return this.accounts; const q = this.searchQuery.toLowerCase(); return this.accounts.filter(a => a.email.toLowerCase().includes(q)); },
20
-
21
- async init() {
22
- await this.checkHealth();
23
- this.authChecked = true;
24
- if (this.isLoginPage()) {
25
- if (this.isAuthenticated) window.location.replace('/dashboard');
26
- return;
27
- }
28
- if (!this.isAuthenticated) { window.location.replace('/login'); return; }
29
- await this.loadCurrentView();
30
- this.updateTime();
31
- setInterval(() => this.updateTime(), 1000);
32
- setInterval(() => this.checkHealth(), 30000);
33
- window.addEventListener('resize', () => { this.sidebarOpen = window.innerWidth >= 1024; });
34
- window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
35
- },
36
-
37
- isLoginPage() { return window.location.pathname === '/login' || window.location.pathname === '/login.html'; },
38
- async loadCurrentView() {
39
- const route = window.location.pathname.replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
40
- const tab = route === 'account-management' ? 'accounts' : route;
41
- const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
42
- this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
43
- if (this.activeTab !== tab) { window.location.replace('/dashboard'); return; }
44
- const [viewResponse, modalResponse] = await Promise.all([
45
- fetch(`/views/${this.activeTab}.html`),
46
- fetch(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html')
47
- ]);
48
- if (!viewResponse.ok) { window.location.replace('/dashboard'); return; }
49
- document.querySelector('#view-content').innerHTML = await viewResponse.text();
50
- document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
51
- Alpine.initTree(document.querySelector('#view-content'));
52
- Alpine.initTree(document.querySelector('#modal-content'));
53
- this.loadViewData();
54
- },
55
- loadViewData() {
56
- const loaders = {
57
- dashboard: () => Promise.all([this.refreshAccounts(), this.loadModelMapSetting()]),
58
- accounts: () => this.refreshAccounts(), logs: () => this.startLogStream(),
59
- 'client-api-keys': () => this.loadClientApiKeys(),
60
- settings: () => Promise.all([this.loadAccountStrategySetting(), this.loadModelMapSetting(), this.loadRawProxyLogsSetting()])
61
- };
62
- return loaders[this.activeTab]?.();
63
- },
64
- updateTime() { this.currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); },
65
- async api(endpoint, options = {}) {
66
- try {
67
- const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
68
- if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
69
- const response = await fetch(endpoint, { ...options, headers });
70
- const data = await response.json();
71
- if (response.status === 401 && endpoint !== '/health') this.logout(false);
72
- return { ok: response.ok, data };
73
- } catch (error) { return { ok: false, error: error.message }; }
74
- },
75
- async login() {
76
- const key = this.loginApiKey.trim();
77
- if (!key) { this.loginError = 'Access key is required'; return; }
78
- this.apiKey = key;
79
- const { ok } = await this.api('/settings/account-strategy');
80
- if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
81
- localStorage.setItem('codexProxyApiKey', key);
82
- window.location.replace('/dashboard');
83
- },
84
- logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace('/login'); },
85
- async checkHealth() { const { ok, data } = await this.api('/health'); this.connectionStatus = ok ? 'connected' : 'disconnected'; if (ok && data?.version) this.version = data.version; if (ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; },
86
- async refreshAccounts() { this.loading = true; const { ok, data } = await this.api('/accounts'); if (ok && data.accounts) { this.accounts = data.accounts; this.stats = { total: data.total || data.accounts.length, active: data.accounts.filter(a => a.isActive).length, expired: data.accounts.filter(a => a.tokenExpired).length, planType: data.accounts.find(a => a.isActive)?.planType || '-' }; await this.refreshAllQuotaData(); } this.loading = false; },
87
- async refreshAllQuotaData() { if (!this.accounts.length) return; const { ok, data } = await this.api('/accounts/quota/all'); if (!ok || !data?.accounts) return; const quotaMap = new Map(data.accounts.map(entry => [entry.email, entry.quota || null])); this.accounts = this.accounts.map(account => ({ ...account, quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota })); if (this.selectedAccount?.email) this.selectedAccount = this.accounts.find(account => account.email === this.selectedAccount.email) || this.selectedAccount; },
88
- getRemainingPercentage(account) { const usage = account?.quota?.usage; if (!usage) return null; const values = [Number(usage.percentage), Number(usage.totalTokenUsage), Number.isFinite(Number(usage.remaining)) ? 100 - Number(usage.remaining) : NaN]; const used = values.find(Number.isFinite); if (!Number.isFinite(used)) return usage.limitReached === true || usage.allowed === false ? 0 : null; return Math.max(0, Math.round(100 - Math.max(0, Math.min(100, used)))); },
89
- isQuotaExhausted(account) { const remaining = this.getRemainingPercentage(account); return remaining !== null && (remaining <= 0 || account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false); },
90
- quotaBarClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
91
- quotaTextClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? '-' : `${remaining}%`; },
92
- getQuotaResetAt(account) { const usage = account?.quota?.usage; if (!usage) return null; if (usage.resetAt) return usage.resetAt; const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at); if (Number.isFinite(epoch)) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
93
- quotaResetAtLabel(account) { const resetAt = this.getQuotaResetAt(account); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
94
- quotaResetSummary(account) { const resetAt = this.getQuotaResetAt(account); if (!resetAt) return null; const seconds = Math.max(0, Math.floor((new Date(resetAt).getTime() - Date.now()) / 1000)); if (!seconds) return 'Reset due now'; const hours = Math.floor(seconds / 3600), minutes = Math.floor((seconds % 3600) / 60); return hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
95
- async startOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) window.open(data.oauth_url, 'ChatGPT Login', 'width=500,height=700'); else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
96
- async startManualOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) { this.oauthManualUrl = data.oauth_url; this.oauthManualVerifier = data.verifier; this.oauthManualCode = ''; this.oauthManualMode = true; } else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
97
- async submitManualOAuth() { if (!this.oauthManualCode) return; const { ok, data } = await this.api('/accounts/add/manual', { method: 'POST', body: JSON.stringify({ code: this.oauthManualCode, verifier: this.oauthManualVerifier }) }); if (ok && data.success) { this.showAddModal = false; this.oauthManualMode = false; this.refreshAccounts(); } else this.showToast(data?.error || 'Failed to add account', 'error'); },
98
- async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
99
- async importFromCodex() { const { ok, data } = await this.api('/accounts/import', { method: 'POST' }); if (ok && data.success) { this.showAddModal = false; this.refreshAccounts(); } else this.showToast(data?.message || 'Import failed', 'error'); },
100
- async switchAccount(email) { const { ok, data } = await this.api('/accounts/switch', { method: 'POST', body: JSON.stringify({ email }) }); if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Failed to switch', 'error'); },
101
- async refreshToken(email) { if (this.refreshingTokenEmails.includes(email)) return; this.refreshingTokenEmails.push(email); try { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }); if (ok && data.success) await this.refreshAccounts(); else this.showToast(data?.message || 'Refresh failed', 'error'); } finally { this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email); } },
102
- async refreshAllTokens() { const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' }); if (ok) this.refreshAccounts(); else this.showToast(data?.message || 'Failed', 'error'); }, confirmDelete(email) { this.deleteTarget = email; this.showDeleteModal = true; },
103
- async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; },
104
- async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
105
- async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
106
- async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
107
- async loadModelMapSetting() { this.modelMapLoading = true; const { ok, data } = await this.api('/settings/model-map'); this.modelMapLoading = false; if (ok && data?.modelMap) this.modelMappings = { sonnet: data.modelMap.sonnet || this.modelMappings.sonnet, opus: data.modelMap.opus || this.modelMappings.opus, haiku: data.modelMap.haiku || this.modelMappings.haiku }; },
108
- async saveModelMapSetting() { if (this.modelMapSaving) return; const modelMap = Object.fromEntries(Object.entries(this.modelMappings).map(([key, value]) => [key, value.trim()])); if (Object.values(modelMap).some(value => !value)) { this.showToast('All Claude model mappings are required.', 'error'); return; } this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ modelMap, reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to update model mapping', 'error'); },
109
- async resetModelMapSetting() { if (this.modelMapSaving) return; this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to reset model mapping', 'error'); },
110
- async loadClientApiKeys() { this.clientApiKeysLoading = true; const { ok, data } = await this.api('/settings/client-api-keys'); this.clientApiKeysLoading = false; if (ok && Array.isArray(data?.clientApiKeys)) this.clientApiKeys = data.clientApiKeys; else this.showToast(data?.error || 'Failed to load client API keys', 'error'); },
111
- async createClientApiKey() { if (this.clientApiKeySaving) return; this.clientApiKeySaving = true; const { ok, data } = await this.api('/settings/client-api-keys', { method: 'POST', body: JSON.stringify({ name: this.clientApiKeyName, remark: this.clientApiKeyRemark }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
112
- async loadClientProxyConfig() { const { ok, data } = await this.api('/claude/config/proxy', { method: 'POST' }); if (ok && data?.success && data?.env) this.clientProxyConfig = data; }, async copyClientText(text, successMessage) { if (!text) return; try { await navigator.clipboard.writeText(text); this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const commands = this.clientProxyConfig?.commands?.powershell; return Array.isArray(commands) ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
113
- async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'PUT', body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark }) }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to update client API key', 'error'); }, async deleteClientApiKey(clientApiKey) { if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to delete client API key', 'error'); },
114
- showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, startLogStream() { if (!this.isAuthenticated) return; this.logEventSource?.close(); const params = new URLSearchParams({ history: 'true' }); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(`/api/logs/stream?${params}`); this.logEventSource.onmessage = event => { try { this.logs.unshift(JSON.parse(event.data)); this.logs = this.logs.slice(0, 500); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
115
- }));
116
- });
1
+ document.addEventListener('alpine:init', () => {
2
+ Alpine.data('app', () => ({
3
+ version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
4
+ loading: false, refreshingTokenEmails: [], toast: null, currentTime: '', authRequired: false,
5
+ authChecked: false, apiKey: localStorage.getItem('codexProxyApiKey') || '', loginApiKey: '', loginError: '',
6
+ accounts: [], searchQuery: '', stats: { total: 0, active: 0, expired: 0, planType: '-' },
7
+ accountStrategy: 'sticky', modelMappings: { sonnet: '', opus: '', haiku: '' }, modelMapLoading: false,
8
+ modelMapSaving: false, strategySaving: false, logRawProxyPayloads: false, rawProxyLogsSaving: false,
9
+ clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50, clientApiKeysLoading: false,
10
+ clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
11
+ showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
12
+ oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
13
+ testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
14
+ serverUrl: window.location.origin, logs: [], logSearchQuery: '',
15
+ logFilters: { INFO: true, SUCCESS: true, WARN: true, ERROR: true, DEBUG: false }, logEventSource: null,
16
+
17
+ get isAuthenticated() { return !this.authRequired || Boolean(this.apiKey); },
18
+ get filteredLogs() { const query = this.logSearchQuery.trim().toLowerCase(); return this.logs.filter(log => this.logFilters[log.level] && (!query || log.message.toLowerCase().includes(query))); },
19
+ get filteredAccounts() { if (!this.searchQuery) return this.accounts; const q = this.searchQuery.toLowerCase(); return this.accounts.filter(a => a.email.toLowerCase().includes(q)); },
20
+
21
+ async init() {
22
+ await this.checkHealth();
23
+ this.authChecked = true;
24
+ if (this.isLoginPage()) {
25
+ if (this.isAuthenticated) window.location.replace('/dashboard');
26
+ return;
27
+ }
28
+ if (!this.isAuthenticated) { window.location.replace('/login'); return; }
29
+ await this.loadCurrentView();
30
+ this.updateTime();
31
+ setInterval(() => this.updateTime(), 1000);
32
+ setInterval(() => this.checkHealth(), 30000);
33
+ window.addEventListener('resize', () => { this.sidebarOpen = window.innerWidth >= 1024; });
34
+ window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
35
+ },
36
+
37
+ isLoginPage() { return window.location.pathname === '/login' || window.location.pathname === '/login.html'; },
38
+ async loadCurrentView() {
39
+ const route = window.location.pathname.replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
40
+ const tab = route === 'account-management' ? 'accounts' : route;
41
+ const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
42
+ this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
43
+ if (this.activeTab !== tab) { window.location.replace('/dashboard'); return; }
44
+ const [viewResponse, modalResponse] = await Promise.all([
45
+ fetch(`/views/${this.activeTab}.html`),
46
+ fetch(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html')
47
+ ]);
48
+ if (!viewResponse.ok) { window.location.replace('/dashboard'); return; }
49
+ document.querySelector('#view-content').innerHTML = await viewResponse.text();
50
+ document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
51
+ Alpine.initTree(document.querySelector('#view-content'));
52
+ Alpine.initTree(document.querySelector('#modal-content'));
53
+ this.loadViewData();
54
+ },
55
+ loadViewData() {
56
+ const loaders = {
57
+ dashboard: () => Promise.all([this.refreshAccounts(), this.loadModelMapSetting()]),
58
+ accounts: () => this.refreshAccounts(), logs: () => this.startLogStream(),
59
+ 'client-api-keys': () => this.loadClientApiKeys(),
60
+ settings: () => Promise.all([this.loadAccountStrategySetting(), this.loadModelMapSetting(), this.loadRawProxyLogsSetting()])
61
+ };
62
+ return loaders[this.activeTab]?.();
63
+ },
64
+ updateTime() { this.currentTime = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); },
65
+ async api(endpoint, options = {}) {
66
+ try {
67
+ const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
68
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
69
+ const response = await fetch(endpoint, { ...options, headers });
70
+ const data = await response.json();
71
+ if (response.status === 401 && endpoint !== '/health') this.logout(false);
72
+ return { ok: response.ok, data };
73
+ } catch (error) { return { ok: false, error: error.message }; }
74
+ },
75
+ async login() {
76
+ const key = this.loginApiKey.trim();
77
+ if (!key) { this.loginError = 'Access key is required'; return; }
78
+ this.apiKey = key;
79
+ const { ok } = await this.api('/settings/account-strategy');
80
+ if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
81
+ localStorage.setItem('codexProxyApiKey', key);
82
+ window.location.replace('/dashboard');
83
+ },
84
+ logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace('/login'); },
85
+ async checkHealth() { const { ok, data } = await this.api('/health'); this.connectionStatus = ok ? 'connected' : 'disconnected'; if (ok && data?.version) this.version = data.version; if (ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; },
86
+ async refreshAccounts() { this.loading = true; const { ok, data } = await this.api('/accounts'); if (ok && data.accounts) { this.accounts = data.accounts; this.stats = { total: data.total || data.accounts.length, active: data.accounts.filter(a => a.isActive).length, expired: data.accounts.filter(a => a.tokenExpired).length, planType: data.accounts.find(a => a.isActive)?.planType || '-' }; await this.refreshAllQuotaData(); } this.loading = false; },
87
+ async refreshAllQuotaData() { if (!this.accounts.length) return; const { ok, data } = await this.api('/accounts/quota/all'); if (!ok || !data?.accounts) return; const quotaMap = new Map(data.accounts.map(entry => [entry.email, entry.quota || null])); this.accounts = this.accounts.map(account => ({ ...account, quota: quotaMap.has(account.email) ? quotaMap.get(account.email) : account.quota })); if (this.selectedAccount?.email) this.selectedAccount = this.accounts.find(account => account.email === this.selectedAccount.email) || this.selectedAccount; },
88
+ getRemainingPercentage(account) { const usage = account?.quota?.usage; if (!usage) return null; const values = [Number(usage.percentage), Number(usage.totalTokenUsage), Number.isFinite(Number(usage.remaining)) ? 100 - Number(usage.remaining) : NaN]; const used = values.find(Number.isFinite); if (!Number.isFinite(used)) return usage.limitReached === true || usage.allowed === false ? 0 : null; return Math.max(0, Math.round(100 - Math.max(0, Math.min(100, used)))); },
89
+ isQuotaExhausted(account) { const remaining = this.getRemainingPercentage(account); return remaining !== null && (remaining <= 0 || account?.quota?.usage?.limitReached === true || account?.quota?.usage?.allowed === false); },
90
+ quotaBarClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'bg-gray-500' : remaining > 50 ? 'bg-neon-green' : remaining > 20 ? 'bg-yellow-500' : 'bg-red-500'; },
91
+ quotaTextClass(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? 'text-gray-500' : remaining <= 20 ? 'text-red-400' : 'text-gray-400'; }, quotaLabel(account) { const remaining = this.getRemainingPercentage(account); return remaining === null ? '-' : `${remaining}%`; },
92
+ getQuotaResetAt(account) { const usage = account?.quota?.usage; if (!usage) return null; if (usage.resetAt) return usage.resetAt; const epoch = Number(usage?.raw?.rate_limit?.primary_window?.reset_at); if (Number.isFinite(epoch)) return new Date(epoch * 1000).toISOString(); const resetAfter = Number(usage.resetAfterSeconds ?? usage?.raw?.rate_limit?.primary_window?.reset_after_seconds); return Number.isFinite(resetAfter) && resetAfter > 0 ? new Date(Date.now() + resetAfter * 1000).toISOString() : null; },
93
+ quotaResetAtLabel(account) { const resetAt = this.getQuotaResetAt(account); const date = resetAt && new Date(resetAt); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : null; },
94
+ quotaResetSummary(account) { const resetAt = this.getQuotaResetAt(account); if (!resetAt) return null; const seconds = Math.max(0, Math.floor((new Date(resetAt).getTime() - Date.now()) / 1000)); if (!seconds) return 'Reset due now'; const hours = Math.floor(seconds / 3600), minutes = Math.floor((seconds % 3600) / 60); return hours ? `Resets in ${hours}h ${minutes}m` : `Resets in ${minutes}m`; },
95
+ async startOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) window.open(data.oauth_url, 'ChatGPT Login', 'width=500,height=700'); else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
96
+ async startManualOAuth() { await this.api('/accounts/oauth/cleanup', { method: 'POST' }); const { ok, data } = await this.api('/accounts/add', { method: 'POST' }); if (ok && data.oauth_url) { this.oauthManualUrl = data.oauth_url; this.oauthManualVerifier = data.verifier; this.oauthManualCode = ''; this.oauthManualMode = true; } else this.showToast(data?.message || 'Failed to start OAuth', 'error'); },
97
+ async submitManualOAuth() { if (!this.oauthManualCode) return; const { ok, data } = await this.api('/accounts/add/manual', { method: 'POST', body: JSON.stringify({ code: this.oauthManualCode, verifier: this.oauthManualVerifier }) }); if (ok && data.success) { this.showAddModal = false; this.oauthManualMode = false; this.refreshAccounts(); } else this.showToast(data?.error || 'Failed to add account', 'error'); },
98
+ async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
99
+ async importFromCodex() { const { ok, data } = await this.api('/accounts/import', { method: 'POST' }); if (ok && data.success) { this.showAddModal = false; this.refreshAccounts(); } else this.showToast(data?.message || 'Import failed', 'error'); },
100
+ async switchAccount(email) { const { ok, data } = await this.api('/accounts/switch', { method: 'POST', body: JSON.stringify({ email }) }); if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Failed to switch', 'error'); },
101
+ async refreshToken(email) { if (this.refreshingTokenEmails.includes(email)) return; this.refreshingTokenEmails.push(email); try { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(email)}/refresh`, { method: 'POST' }); if (ok && data.success) await this.refreshAccounts(); else this.showToast(data?.message || 'Refresh failed', 'error'); } finally { this.refreshingTokenEmails = this.refreshingTokenEmails.filter(item => item !== email); } },
102
+ async refreshAllTokens() { const { ok, data } = await this.api('/accounts/refresh/all', { method: 'POST' }); if (ok) this.refreshAccounts(); else this.showToast(data?.message || 'Failed', 'error'); }, confirmDelete(email) { this.deleteTarget = email; this.showDeleteModal = true; },
103
+ async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; },
104
+ async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
105
+ async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
106
+ async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
107
+ async loadModelMapSetting() { this.modelMapLoading = true; const { ok, data } = await this.api('/settings/model-map'); this.modelMapLoading = false; if (ok && data?.modelMap) this.modelMappings = { sonnet: data.modelMap.sonnet || this.modelMappings.sonnet, opus: data.modelMap.opus || this.modelMappings.opus, haiku: data.modelMap.haiku || this.modelMappings.haiku }; },
108
+ async saveModelMapSetting() { if (this.modelMapSaving) return; const modelMap = Object.fromEntries(Object.entries(this.modelMappings).map(([key, value]) => [key, value.trim()])); if (Object.values(modelMap).some(value => !value)) { this.showToast('All Claude model mappings are required.', 'error'); return; } this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ modelMap, reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to update model mapping', 'error'); },
109
+ async resetModelMapSetting() { if (this.modelMapSaving) return; this.modelMapSaving = true; const { ok, data } = await this.api('/settings/model-map', { method: 'POST', body: JSON.stringify({ reset: true }) }); this.modelMapSaving = false; if (ok && data?.modelMap) this.modelMappings = data.modelMap; else this.showToast(data?.error || 'Failed to reset model mapping', 'error'); },
110
+ async loadClientApiKeys() { this.clientApiKeysLoading = true; const { ok, data } = await this.api('/settings/client-api-keys'); this.clientApiKeysLoading = false; if (ok && Array.isArray(data?.clientApiKeys)) this.clientApiKeys = data.clientApiKeys; else this.showToast(data?.error || 'Failed to load client API keys', 'error'); },
111
+ async createClientApiKey() { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(this.clientApiKeyWeeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api('/settings/client-api-keys', { method: 'POST', body: JSON.stringify({ name: this.clientApiKeyName, remark: this.clientApiKeyRemark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok && data?.clientApiKey?.key) { this.revealedClientApiKey = data.clientApiKey.key; this.clientApiKeyName = ''; this.clientApiKeyRemark = ''; this.clientApiKeyWeeklyLimitUsd = 50; this.showCreateClientApiKeyModal = false; await Promise.all([this.loadClientApiKeys(), this.loadClientProxyConfig()]); } else this.showToast(data?.error || 'Failed to create client API key', 'error'); },
112
+ async loadClientProxyConfig() { const { ok, data } = await this.api('/claude/config/proxy', { method: 'POST' }); if (ok && data?.success && data?.env) this.clientProxyConfig = data; }, async copyClientText(text, successMessage) { if (!text) return; try { await navigator.clipboard.writeText(text); this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const commands = this.clientProxyConfig?.commands?.powershell; return Array.isArray(commands) ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
113
+ async updateClientApiKey(clientApiKey) { if (this.clientApiKeySaving) return; const weeklyLimitUsd = Number(clientApiKey.weeklyLimitUsd); if (!Number.isFinite(weeklyLimitUsd) || weeklyLimitUsd < 0) { this.showToast('Weekly limit must be a non-negative USD amount.', 'error'); return; } this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'PUT', body: JSON.stringify({ name: clientApiKey.name, remark: clientApiKey.remark, weeklyLimitUsd }) }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to update client API key', 'error'); }, async deleteClientApiKey(clientApiKey) { if (!confirm(`Delete the key for "${clientApiKey.name || clientApiKey.remark || 'this client'}"? Connected clients will lose access immediately.`)) return; this.clientApiKeySaving = true; const { ok, data } = await this.api(`/settings/client-api-keys/${encodeURIComponent(clientApiKey.id)}`, { method: 'DELETE' }); this.clientApiKeySaving = false; if (ok) await this.loadClientApiKeys(); else this.showToast(data?.error || 'Failed to delete client API key', 'error'); },
114
+ showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, startLogStream() { if (!this.isAuthenticated) return; this.logEventSource?.close(); const params = new URLSearchParams({ history: 'true' }); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(`/api/logs/stream?${params}`); this.logEventSource.onmessage = event => { try { this.logs.unshift(JSON.parse(event.data)); this.logs = this.logs.slice(0, 500); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
115
+ }));
116
+ });