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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +0 -272
  2. package/bin/cli.js +37 -2
  3. package/package.json +1 -1
  4. package/public/css/style.css +132 -0
  5. package/public/index.html +60 -60
  6. package/public/js/app.js +194 -116
  7. package/public/login.html +32 -32
  8. package/public/views/accounts-modals.html +61 -2
  9. package/public/views/accounts.html +29 -10
  10. package/public/views/client-api-keys-modals.html +15 -1
  11. package/public/views/client-api-keys.html +68 -31
  12. package/public/views/logs.html +10 -3
  13. package/src/account-manager.js +34 -3
  14. package/src/account-rotation/rate-limits.js +4 -0
  15. package/src/account-rotation/strategies/base-strategy.js +4 -0
  16. package/src/account-rotation/strategies/sticky-strategy.js +7 -0
  17. package/src/admin-path.js +33 -0
  18. package/src/client-key-usage.js +193 -0
  19. package/src/deployment.js +49 -49
  20. package/src/direct-api.js +11 -11
  21. package/src/format-converter.js +83 -48
  22. package/src/index.js +13 -4
  23. package/src/middleware/auth.js +54 -16
  24. package/src/middleware/credentials.js +17 -7
  25. package/src/middleware/sse.js +69 -29
  26. package/src/model-api.js +60 -0
  27. package/src/model-pricing.js +127 -0
  28. package/src/response-streamer.js +23 -7
  29. package/src/routes/accounts-route.js +106 -2
  30. package/src/routes/api-routes.js +59 -42
  31. package/src/routes/chat-route.js +25 -4
  32. package/src/routes/claude-config-route.js +19 -10
  33. package/src/routes/client-quota-route.js +31 -0
  34. package/src/routes/logs-route.js +21 -2
  35. package/src/routes/messages-route.js +100 -51
  36. package/src/routes/settings-route.js +66 -5
  37. package/src/server-settings.js +25 -2
  38. package/src/utils/logger.js +30 -0
  39. package/src/utils/proxy-logging.js +5 -0
@@ -39,21 +39,22 @@
39
39
  </div>
40
40
 
41
41
  <div class="view-card !p-0 overflow-x-auto">
42
- <table class="w-full min-w-[860px]">
42
+ <table class="w-full min-w-[980px]">
43
43
  <thead x-show="filteredAccounts.length > 0">
44
44
  <tr class="bg-space-900/50 border-b border-space-border/50">
45
45
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-20">Status</th>
46
- <th class="py-3 text-center text-[10px] font-bold text-gray-500 uppercase tracking-wider flex-1 min-w-[200px]">Account (Email)</th>
46
+ <th class="w-56 py-3 text-center text-[10px] font-bold text-gray-500 uppercase tracking-wider">Account (Email)</th>
47
47
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-20">Plan</th>
48
48
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-32">Token</th>
49
49
  <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider w-24">Quota</th>
50
+ <th class="w-52 min-w-[13rem] py-3 text-center text-[10px] font-bold text-gray-500 uppercase tracking-wider">Account Expiry</th>
50
51
  <th class="py-3 pr-6 text-right text-[10px] font-bold text-gray-500 uppercase tracking-wider w-40">Operations</th>
51
52
  </tr>
52
53
  </thead>
53
54
  <tbody>
54
55
  <template x-if="filteredAccounts.length === 0 && accounts.length === 0">
55
56
  <tr>
56
- <td colspan="6" class="py-16 text-center flex justify-center">
57
+ <td colspan="7" class="py-16 text-center flex justify-center">
57
58
  <div class="flex flex-col items-center gap-4 max-w-lg mx-auto">
58
59
  <svg class="w-20 h-20 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
59
60
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
@@ -83,16 +84,16 @@
83
84
  <td class="py-4 pl-6">
84
85
  <div class="flex items-center gap-2">
85
86
  <div class="w-2 h-2 rounded-full flex-shrink-0"
86
- :class="acc.isActive ? 'bg-neon-green shadow-[0_0_8px_rgba(34,197,94,0.6)] animate-pulse' : 'bg-gray-500'">
87
+ :class="acc.accountExpired ? 'bg-red-500' : acc.isActive ? 'bg-neon-green shadow-[0_0_8px_rgba(34,197,94,0.6)] animate-pulse' : 'bg-gray-500'">
87
88
  </div>
88
89
  <span class="text-xs font-mono font-semibold"
89
- :class="acc.isActive ? 'text-neon-green' : 'text-gray-500'"
90
- x-text="acc.isActive ? 'ACTIVE' : 'IDLE'">
90
+ :class="acc.accountExpired ? 'text-red-400' : acc.isActive ? 'text-neon-green' : 'text-gray-500'"
91
+ x-text="acc.accountExpired ? 'EXPIRED' : acc.isActive ? 'ACTIVE' : 'IDLE'">
91
92
  </span>
92
93
  </div>
93
94
  </td>
94
- <td class="py-4 text-center">
95
- <span class="font-mono text-sm text-gray-300 truncate max-w-[320px] inline-block group-hover:text-white transition-colors"
95
+ <td class="w-56 max-w-56 py-4 text-center">
96
+ <span class="inline-block max-w-[13rem] truncate font-mono text-sm text-gray-300 transition-colors group-hover:text-white"
96
97
  x-text="acc.email"></span>
97
98
  </td>
98
99
  <td class="py-4">
@@ -146,9 +147,27 @@
146
147
  <span class="text-xs text-gray-600">-</span>
147
148
  </template>
148
149
  </td>
150
+ <td class="w-52 min-w-[13rem] py-4 text-center">
151
+ <div class="inline-flex items-center justify-center gap-1">
152
+ <div>
153
+ <span class="block whitespace-nowrap text-xs font-mono"
154
+ :class="acc.accountExpired ? 'text-red-400' : acc.accountExpiresAt ? 'text-gray-300' : 'text-gray-500'"
155
+ x-text="accountExpirationLabel(acc)"></span>
156
+ <span class="mt-1 block text-[10px]"
157
+ :class="acc.accountExpired ? 'text-red-500/70' : 'text-gray-600'"
158
+ x-text="acc.accountExpired ? 'Expired' : acc.accountExpiresAt ? 'Local time' : 'Not set'"></span>
159
+ </div>
160
+ <button class="btn btn-xs btn-ghost shrink-0 rounded p-1.5 text-gray-600 transition-colors hover:bg-white/10 hover:text-neon-cyan"
161
+ @click="showAccountExpirationModal(acc)" title="Configure account expiration">
162
+ <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
163
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536M9 11l6.232-6.232a2.5 2.5 0 013.536 3.536L12.536 14.536 9 15l.464-3.536zM5 19h14" />
164
+ </svg>
165
+ </button>
166
+ </div>
167
+ </td>
149
168
  <td class="py-4 pr-6">
150
169
  <div class="flex justify-end gap-2">
151
- <button x-show="!acc.isActive"
170
+ <button x-show="!acc.isActive && !acc.accountExpired"
152
171
  class="cursor-pointer px-3 py-1 text-[10px] font-bold font-mono uppercase tracking-wider rounded bg-neon-purple/10 text-neon-purple hover:bg-neon-purple/20 border border-neon-purple/30 hover:border-neon-purple/50 transition-all"
153
172
  @click="switchAccount(acc.email)">
154
173
  SWITCH
@@ -166,7 +185,7 @@
166
185
 
167
186
  <template x-if="accounts.length > 0 && filteredAccounts.length === 0">
168
187
  <tr>
169
- <td colspan="6" class="py-12 text-center">
188
+ <td colspan="7" class="py-12 text-center">
170
189
  <div class="flex flex-col items-center gap-3">
171
190
  <svg class="w-12 h-12 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
172
191
  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
@@ -14,6 +14,20 @@
14
14
  <input type="text" x-model="clientApiKeyRemark" placeholder="Optional note"
15
15
  class="input w-full bg-space-800 border-space-border text-white font-mono text-sm" @keydown.enter="createClientApiKey()">
16
16
  </label>
17
+ <label class="block">
18
+ <span class="block text-xs text-gray-400 mb-2">Weekly limit (USD)</span>
19
+ <input type="number" min="0" step="0.01" x-model="clientApiKeyWeeklyLimitUsd"
20
+ class="input w-full bg-space-800 border-space-border text-white font-mono text-sm" @keydown.enter="createClientApiKey()">
21
+ </label>
22
+ <label class="flex items-center justify-between gap-4 rounded-lg border border-space-border bg-space-800 px-3 py-2.5">
23
+ <span class="text-xs text-gray-300">Enable fixed 5-hour limit</span>
24
+ <input type="checkbox" x-model="clientApiKeyFiveHourLimitEnabled" class="h-4 w-4 accent-purple-500">
25
+ </label>
26
+ <label class="block">
27
+ <span class="block text-xs text-gray-400 mb-2">5-hour limit (USD)</span>
28
+ <input type="number" min="0" step="0.01" x-model="clientApiKeyFiveHourLimitUsd" :disabled="!clientApiKeyFiveHourLimitEnabled"
29
+ class="input w-full bg-space-800 border-space-border text-white font-mono text-sm disabled:opacity-40" @keydown.enter="createClientApiKey()">
30
+ </label>
17
31
  </div>
18
32
  <div class="mt-6 flex justify-end gap-2">
19
33
  <button class="btn btn-outline btn-sm text-gray-400" @click="showCreateClientApiKeyModal = false" :disabled="clientApiKeySaving">Cancel</button>
@@ -35,8 +49,8 @@
35
49
  <p class="text-xs font-semibold uppercase tracking-wider text-gray-400">Claude Code configuration</p>
36
50
  <div class="rounded-lg border border-space-border bg-space-800 p-3 font-mono text-xs text-gray-300 space-y-2">
37
51
  <div><span class="text-gray-500">ANTHROPIC_BASE_URL=</span><span class="break-all" x-text="clientProxyConfig.env.ANTHROPIC_BASE_URL"></span></div>
52
+ <div><span class="text-gray-500">ANTHROPIC_AUTH_TOKEN=</span><span class="break-all" x-text="revealedClientApiKey"></span></div>
38
53
  <div><span class="text-gray-500">ANTHROPIC_API_KEY=</span><span class="break-all" x-text="revealedClientApiKey"></span></div>
39
- <div><span class="text-gray-500">CLAUDE_CODE_AUTO_COMPACT_WINDOW=</span><span x-text="clientProxyConfig.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW"></span></div>
40
54
  </div>
41
55
  <p class="text-xs text-gray-500" x-text="clientProxyConfig.message"></p>
42
56
  <button class="btn btn-outline btn-sm text-gray-300" @click="copyClientProxyCommands()">Copy PowerShell Commands</button>
@@ -8,39 +8,76 @@
8
8
  </div>
9
9
  </div>
10
10
 
11
- <div class="view-card !p-0 overflow-x-auto">
12
- <div class="flex items-center justify-between gap-4 px-6 py-4 border-b border-space-border/50">
13
- <h2 class="text-sm font-semibold text-gray-200">Client API Keys</h2>
14
- <button class="btn btn-sm bg-neon-purple hover:bg-purple-600 border-none text-white" @click="revealedClientApiKey = ''; clientProxyConfig = null; showCreateClientApiKeyModal = true">
15
- New API Key
16
- </button>
11
+ <div class="client-keys-panel">
12
+ <div class="client-keys-toolbar">
13
+ <div>
14
+ <h2>Access keys</h2>
15
+ <p>Edit a key, then save its changes.</p>
16
+ </div>
17
+ <div class="client-keys-toolbar-actions">
18
+ <div x-show="clientApiKeys.length" class="client-keys-reset">
19
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M12 8v4l2.5 2.5M21 12a9 9 0 11-2.64-6.36M21 4v5h-5"/></svg>
20
+ <div><span>Next weekly reset</span><strong x-text="clientApiKeys[0]?.quota?.nextPeriodStart ? new Date(clientApiKeys[0].quota.nextPeriodStart).toLocaleString() : '-'"></strong></div>
21
+ </div>
22
+ <button class="client-keys-new" @click="revealedClientApiKey = ''; clientProxyConfig = null; showCreateClientApiKeyModal = true">
23
+ <span>+</span> New API Key
24
+ </button>
25
+ </div>
17
26
  </div>
27
+
18
28
  <template x-if="clientApiKeysLoading">
19
- <div class="text-xs text-gray-500 font-mono py-8 text-center">Loading client API keys...</div>
29
+ <div class="client-keys-empty">Loading client API keys...</div>
20
30
  </template>
21
- <table class="w-full min-w-[760px]" x-show="!clientApiKeysLoading && clientApiKeys.length">
22
- <thead>
23
- <tr class="bg-space-900/50 border-b border-space-border/50">
24
- <th class="py-3 pl-6 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Client Name</th>
25
- <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Remark</th>
26
- <th class="py-3 text-left text-[10px] font-bold text-gray-500 uppercase tracking-wider">Created</th>
27
- <th class="py-3 pr-6 text-right text-[10px] font-bold text-gray-500 uppercase tracking-wider">Operations</th>
28
- </tr>
29
- </thead>
30
- <tbody>
31
- <template x-for="clientApiKey in clientApiKeys" :key="clientApiKey.id">
32
- <tr class="border-b border-space-border/30 last:border-0 hover:bg-white/5 transition-colors">
33
- <td class="py-3 pl-6"><input type="text" x-model="clientApiKey.name" placeholder="Unnamed" class="input input-sm w-48 bg-space-800 border-space-border text-white"></td>
34
- <td class="py-3"><input type="text" x-model="clientApiKey.remark" placeholder="No remark" class="input input-sm w-48 bg-space-800 border-space-border text-white"></td>
35
- <td class="py-3 text-xs font-mono text-gray-500 whitespace-nowrap" x-text="new Date(clientApiKey.createdAt).toLocaleString()"></td>
36
- <td class="py-3 pr-6"><div class="flex justify-end gap-2 whitespace-nowrap">
37
- <button class="btn btn-xs btn-outline text-gray-300" @click="updateClientApiKey(clientApiKey)" :disabled="clientApiKeySaving">Save</button>
38
- <button class="btn btn-xs btn-outline text-red-400" @click="deleteClientApiKey(clientApiKey)" :disabled="clientApiKeySaving">Delete</button>
39
- </div></td>
40
- </tr>
41
- </template>
42
- </tbody>
43
- </table>
44
- <div x-show="!clientApiKeysLoading && !clientApiKeys.length" class="text-sm text-gray-500 font-mono py-16 text-center">No client API keys. Create one to connect Claude Code clients.</div>
31
+
32
+ <div class="client-keys-list" x-show="!clientApiKeysLoading && clientApiKeys.length">
33
+ <template x-for="clientApiKey in clientApiKeys" :key="clientApiKey.id">
34
+ <article class="client-key-card">
35
+ <div class="client-key-identity">
36
+ <div class="client-key-icon">
37
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><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 7z"/></svg>
38
+ </div>
39
+ <div class="client-key-fields">
40
+ <label><span>Client name</span><input type="text" x-model="clientApiKey.name" placeholder="Unnamed"></label>
41
+ <label><span>Remark</span><input type="text" x-model="clientApiKey.remark" placeholder="No remark"></label>
42
+ </div>
43
+ </div>
44
+
45
+ <div class="client-key-quotas">
46
+ <div class="client-key-quota">
47
+ <div class="client-key-quota-heading">
48
+ <span>Weekly usage</span>
49
+ <strong><span x-text="`$${(clientApiKey.quota?.consumedUsd ?? 0).toFixed(2)}`"></span><small x-text="` / $${Number(clientApiKey.weeklyLimitUsd || 0).toFixed(2)}`"></small></strong>
50
+ </div>
51
+ <div class="client-key-progress"><i :style="`width: ${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100))}%`"></i></div>
52
+ <div class="client-key-quota-foot"><span x-text="`$${(clientApiKey.quota?.remainingUsd ?? (Number(clientApiKey.weeklyLimitUsd) || 0)).toFixed(2)} remaining`"></span><span x-text="`${Math.min(100, Math.max(0, ((clientApiKey.quota?.consumedUsd ?? 0) / Math.max(Number(clientApiKey.weeklyLimitUsd) || 0, 0.000001)) * 100)).toFixed(1)}% used`"></span></div>
53
+ </div>
54
+ <div class="client-key-quota" :class="{ 'client-key-quota-disabled': !clientApiKey.fiveHourLimitEnabled }">
55
+ <div class="client-key-quota-heading">
56
+ <span>5-hour usage</span>
57
+ <strong x-text="clientApiKey.fiveHourLimitEnabled ? `$${(clientApiKey.quota?.fiveHourConsumedUsd ?? 0).toFixed(2)} / $${Number(clientApiKey.fiveHourLimitUsd || 0).toFixed(2)}` : 'Off'"></strong>
58
+ </div>
59
+ <div class="client-key-progress"><i :style="`width: ${clientApiKey.fiveHourLimitEnabled ? Math.min(100, Math.max(0, ((clientApiKey.quota?.fiveHourConsumedUsd ?? 0) / Math.max(Number(clientApiKey.fiveHourLimitUsd) || 0, 0.000001)) * 100)) : 0}%`"></i></div>
60
+ <div class="client-key-quota-foot"><span x-text="clientApiKey.fiveHourLimitEnabled ? `$${(clientApiKey.quota?.fiveHourRemainingUsd ?? (Number(clientApiKey.fiveHourLimitUsd) || 0)).toFixed(2)} remaining` : 'Limit disabled'"></span><span x-text="clientApiKey.fiveHourLimitEnabled && clientApiKey.quota?.nextFiveHourPeriodStart ? new Date(clientApiKey.quota.nextFiveHourPeriodStart).toLocaleTimeString() : ''"></span></div>
61
+ </div>
62
+ </div>
63
+
64
+ <div class="client-key-limits">
65
+ <label class="client-key-limit"><span>Weekly limit</span><div><b>$</b><input type="number" min="0" step="0.01" x-model="clientApiKey.weeklyLimitUsd"></div></label>
66
+ <label class="client-key-limit-toggle"><input type="checkbox" x-model="clientApiKey.fiveHourLimitEnabled"><span>5-hour limit</span></label>
67
+ <label class="client-key-limit"><div><b>$</b><input type="number" min="0" step="0.01" x-model="clientApiKey.fiveHourLimitUsd" :disabled="!clientApiKey.fiveHourLimitEnabled"></div></label>
68
+ </div>
69
+
70
+ <div class="client-key-meta"><span>Created</span><strong x-text="new Date(clientApiKey.createdAt).toLocaleDateString()"></strong><small x-text="new Date(clientApiKey.createdAt).toLocaleTimeString()"></small></div>
71
+
72
+ <div class="client-key-actions">
73
+ <button class="client-key-save" @click="updateClientApiKey(clientApiKey)" :disabled="clientApiKeySaving">Save changes</button>
74
+ <button class="client-key-delete" @click="deleteClientApiKey(clientApiKey)" :disabled="clientApiKeySaving" aria-label="Delete API key" title="Delete">
75
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="M4 7h16M9 7V4h6v3m-8 0 1 13h8l1-13M10 11v5m4-5v5"/></svg>
76
+ </button>
77
+ </div>
78
+ </article>
79
+ </template>
80
+ </div>
81
+ <div x-show="!clientApiKeysLoading && !clientApiKeys.length" class="client-keys-empty">No client API keys. Create one to connect Claude Code clients.</div>
45
82
  </div>
46
83
  </div>
@@ -8,7 +8,7 @@
8
8
  </div>
9
9
  <div class="flex items-center gap-3">
10
10
  <div class="text-[10px] font-mono text-gray-600">
11
- <span x-text="logs.length"></span> entries
11
+ <span x-text="logTotal"></span> entries
12
12
  </div>
13
13
  <button class="btn btn-xs btn-ghost text-gray-400 hover:text-white" @click="clearLogs()" title="Clear logs">
14
14
  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -54,7 +54,7 @@
54
54
  </div>
55
55
 
56
56
  <div id="logs-container" class="flex-1 overflow-auto p-4 font-mono text-[11px] leading-relaxed bg-space-950 custom-scrollbar">
57
- <template x-for="(log, idx) in filteredLogs" :key="idx">
57
+ <template x-for="(log, idx) in filteredLogs" :key="`${log.timestamp}-${idx}`">
58
58
  <div class="flex gap-3 px-2 py-1 -mx-2 hover:bg-white/[0.03] transition-colors group border-b border-space-border/10">
59
59
  <span class="text-zinc-600 w-16 shrink-0 select-none group-hover:text-zinc-500 transition-colors"
60
60
  x-text="new Date(log.timestamp).toLocaleTimeString([], {hour12:false})"></span>
@@ -83,10 +83,17 @@
83
83
  </div>
84
84
  </div>
85
85
  </template>
86
- <div class="h-3 w-1.5 bg-zinc-600 animate-pulse mt-1 inline-block" x-show="filteredLogs.length === logs.length && !logSearchQuery"></div>
86
+ <div class="h-3 w-1.5 bg-zinc-600 animate-pulse mt-1 inline-block" x-show="logPage === 1 && filteredLogs.length === logs.length && !logSearchQuery"></div>
87
87
  <div x-show="filteredLogs.length === 0 && logs.length > 0" class="text-zinc-700 italic mt-8 text-center">
88
88
  No logs match filter
89
89
  </div>
90
90
  </div>
91
+ <div class="flex items-center justify-between gap-3 px-4 py-3 border-t border-space-border bg-space-900/60 text-xs font-mono">
92
+ <span class="text-gray-500" x-text="logTotalPages ? `Page ${logPage} of ${logTotalPages} · 30 per page` : 'No logs' "></span>
93
+ <div class="flex items-center gap-2">
94
+ <button class="btn btn-xs btn-ghost" :disabled="logPage <= 1 || logLoading" @click="changeLogPage(logPage - 1)">Previous</button>
95
+ <button class="btn btn-xs btn-ghost" :disabled="logPage >= logTotalPages || logLoading" @click="changeLogPage(logPage + 1)">Next</button>
96
+ </div>
97
+ </div>
91
98
  </div>
92
99
  </div>
@@ -98,6 +98,25 @@ function getActiveAccount() {
98
98
  return data.accounts.find(a => a.email === data.activeAccount) || null;
99
99
  }
100
100
 
101
+ function isAccountExpired(account, now = Date.now()) {
102
+ if (!account?.accountExpiresAt) return false;
103
+ const expiresAt = Date.parse(account.accountExpiresAt);
104
+ return Number.isFinite(expiresAt) && expiresAt <= now;
105
+ }
106
+
107
+ function updateAccountExpiration(email, accountExpiresAt) {
108
+ const data = loadAccounts();
109
+ const account = data.accounts.find(a => a.email === email);
110
+
111
+ if (!account) {
112
+ return { success: false, message: `Account not found: ${email}` };
113
+ }
114
+
115
+ account.accountExpiresAt = accountExpiresAt;
116
+ saveAccounts(data);
117
+ return { success: true, message: `Account expiration updated: ${email}` };
118
+ }
119
+
101
120
  function updateAccountAuth(account) {
102
121
  if (!account) return;
103
122
 
@@ -131,11 +150,15 @@ function updateAccountAuth(account) {
131
150
  function setActiveAccount(email) {
132
151
  const data = loadAccounts();
133
152
  const account = data.accounts.find(a => a.email === email);
134
-
153
+
135
154
  if (!account) {
136
155
  return { success: false, message: `Account not found: ${email}` };
137
156
  }
138
-
157
+
158
+ if (isAccountExpired(account)) {
159
+ return { success: false, message: `Account has expired: ${email}` };
160
+ }
161
+
139
162
  data.activeAccount = email;
140
163
  saveAccounts(data);
141
164
 
@@ -190,6 +213,8 @@ function listAccounts() {
190
213
  lastUsed: account.lastUsed,
191
214
  isActive: account.email === data.activeAccount,
192
215
  tokenExpired: info?.expiresAt ? info.expiresAt < Date.now() : false,
216
+ accountExpiresAt: account.accountExpiresAt || null,
217
+ accountExpired: isAccountExpired(account),
193
218
  quota: account.quota || null
194
219
  };
195
220
  });
@@ -476,7 +501,7 @@ function importFromCodex() {
476
501
 
477
502
  const existingIndex = data.accounts.findIndex(a => a.email === newAccount.email);
478
503
  if (existingIndex >= 0) {
479
- data.accounts[existingIndex] = newAccount;
504
+ data.accounts[existingIndex] = { ...data.accounts[existingIndex], ...newAccount };
480
505
  } else {
481
506
  data.accounts.push(newAccount);
482
507
  }
@@ -507,6 +532,8 @@ function getStatus() {
507
532
  isActive: a.email === data.activeAccount,
508
533
  quota: a.quota || null,
509
534
  tokenExpired: info?.expiresAt ? info.expiresAt < Date.now() : false,
535
+ accountExpiresAt: a.accountExpiresAt || null,
536
+ accountExpired: isAccountExpired(a),
510
537
  lastUsed: a.lastUsed
511
538
  };
512
539
  });
@@ -548,6 +575,8 @@ export {
548
575
  ensureAccountsPersist,
549
576
  updateAccountQuota,
550
577
  getAccountQuota,
578
+ updateAccountExpiration,
579
+ isAccountExpired,
551
580
  startAutoRefresh,
552
581
  stopAutoRefresh,
553
582
  isTokenExpiredOrExpiringSoon,
@@ -574,6 +603,8 @@ export default {
574
603
  ensureAccountsPersist,
575
604
  updateAccountQuota,
576
605
  getAccountQuota,
606
+ updateAccountExpiration,
607
+ isAccountExpired,
577
608
  startAutoRefresh,
578
609
  stopAutoRefresh,
579
610
  isTokenExpiredOrExpiringSoon,
@@ -33,6 +33,10 @@ export function getAvailableAccounts(accounts, modelId) {
33
33
  return accounts.filter(account => {
34
34
  if (account.isInvalid) return false;
35
35
  if (account.enabled === false) return false;
36
+ if (account.accountExpiresAt) {
37
+ const expiresAt = Date.parse(account.accountExpiresAt);
38
+ if (Number.isFinite(expiresAt) && expiresAt <= now) return false;
39
+ }
36
40
  if (isAccountCoolingDown(account)) return false;
37
41
  if (isQuotaLimitReached(account)) return false;
38
42
  const rateLimit = account.modelRateLimits?.[modelId];
@@ -23,6 +23,10 @@ export class BaseStrategy {
23
23
  if (!account) return false;
24
24
  if (account.isInvalid) return false;
25
25
  if (account.enabled === false) return false;
26
+ if (account.accountExpiresAt) {
27
+ const expiresAt = Date.parse(account.accountExpiresAt);
28
+ if (Number.isFinite(expiresAt) && expiresAt <= Date.now()) return false;
29
+ }
26
30
  if (isAccountCoolingDown(account)) return false;
27
31
  if (isQuotaLimitReached(account)) return false;
28
32
 
@@ -56,6 +56,13 @@ export class StickyStrategy extends BaseStrategy {
56
56
  return { shouldWait: false, waitMs: 0 };
57
57
  }
58
58
 
59
+ if (account.accountExpiresAt) {
60
+ const expiresAt = Date.parse(account.accountExpiresAt);
61
+ if (Number.isFinite(expiresAt) && expiresAt <= Date.now()) {
62
+ return { shouldWait: false, waitMs: 0 };
63
+ }
64
+ }
65
+
59
66
  // Check model-specific rate limit
60
67
  if (modelId && account.modelRateLimits && account.modelRateLimits[modelId]) {
61
68
  const limit = account.modelRateLimits[modelId];
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Resolves the non-public prefix used for the management UI and its APIs.
3
+ */
4
+
5
+ const DEFAULT_ADMIN_PATH = '/admin';
6
+ const VALID_ADMIN_PATH = /^\/[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
7
+ const RESERVED_PATHS = ['/v1', '/health', '/claude'];
8
+
9
+ /**
10
+ * Returns the validated management UI path prefix.
11
+ * @returns {string}
12
+ */
13
+ export function getAdminPath() {
14
+ const adminPath = process.env.PROXY_ADMIN_PATH || DEFAULT_ADMIN_PATH;
15
+ if (!VALID_ADMIN_PATH.test(adminPath)) {
16
+ throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". Use an absolute path without trailing slashes, query strings, or ".." segments.`);
17
+ }
18
+
19
+ const overlapsReservedPath = RESERVED_PATHS.some((reservedPath) => (
20
+ adminPath === reservedPath
21
+ || adminPath.startsWith(`${reservedPath}/`)
22
+ || reservedPath.startsWith(`${adminPath}/`)
23
+ ));
24
+ if (overlapsReservedPath) {
25
+ throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". The path must not overlap reserved routes: ${RESERVED_PATHS.join(', ')}.`);
26
+ }
27
+
28
+ return adminPath;
29
+ }
30
+
31
+ export { DEFAULT_ADMIN_PATH };
32
+
33
+ export default { getAdminPath, DEFAULT_ADMIN_PATH };
@@ -0,0 +1,193 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';
2
+ import { randomUUID } from 'crypto';
3
+ import { dirname, join } from 'path';
4
+ import { CONFIG_DIR } from './account-manager.js';
5
+
6
+ const USAGE_FILE = join(CONFIG_DIR, 'client-key-usage.json');
7
+ export const MICRO_USD_PER_USD = 1_000_000;
8
+
9
+ function loadUsage(usageFile = USAGE_FILE) {
10
+ if (!existsSync(usageFile)) return {};
11
+
12
+ try {
13
+ const data = JSON.parse(readFileSync(usageFile, 'utf8'));
14
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
15
+ throw new Error('usage file must contain a JSON object');
16
+ }
17
+ return data;
18
+ } catch (error) {
19
+ throw new Error(`[ClientKeyUsage] Failed to read ${usageFile}: ${error.message}`, { cause: error });
20
+ }
21
+ }
22
+
23
+ function saveUsage(usage, usageFile = USAGE_FILE) {
24
+ const usageDirectory = dirname(usageFile);
25
+ if (!existsSync(usageDirectory)) {
26
+ mkdirSync(usageDirectory, { recursive: true, mode: 0o700 });
27
+ }
28
+
29
+ const tempFile = `${usageFile}.${process.pid}.${randomUUID()}.tmp`;
30
+ try {
31
+ writeFileSync(tempFile, JSON.stringify(usage, null, 2), { mode: 0o600 });
32
+ renameSync(tempFile, usageFile);
33
+ } catch (error) {
34
+ try {
35
+ rmSync(tempFile, { force: true });
36
+ } catch {
37
+ // Preserve the original write error.
38
+ }
39
+ throw error;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Returns the current weekly period start in the server's local time zone.
45
+ * A period begins at Monday 08:00 and ends at the following Monday 08:00.
46
+ */
47
+ export function getCurrentPeriodStart(now = new Date()) {
48
+ const periodStart = new Date(now);
49
+ const daysSinceMonday = (periodStart.getDay() + 6) % 7;
50
+ periodStart.setDate(periodStart.getDate() - daysSinceMonday);
51
+ periodStart.setHours(8, 0, 0, 0);
52
+
53
+ if (now < periodStart) {
54
+ periodStart.setDate(periodStart.getDate() - 7);
55
+ }
56
+
57
+ return periodStart.toISOString();
58
+ }
59
+
60
+ export function getNextPeriodStart(now = new Date()) {
61
+ const nextPeriodStart = new Date(getCurrentPeriodStart(now));
62
+ nextPeriodStart.setDate(nextPeriodStart.getDate() + 7);
63
+ return nextPeriodStart.toISOString();
64
+ }
65
+
66
+ const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
67
+
68
+ /**
69
+ * Returns the start of the current globally aligned five-hour window.
70
+ * Boundaries occur every five hours from the Unix epoch and always fall on
71
+ * an exact hour.
72
+ */
73
+ export function getCurrentFiveHourPeriodStart(now = new Date()) {
74
+ return new Date(Math.floor(now.getTime() / FIVE_HOURS_MS) * FIVE_HOURS_MS).toISOString();
75
+ }
76
+
77
+ export function getNextFiveHourPeriodStart(now = new Date()) {
78
+ return new Date(new Date(getCurrentFiveHourPeriodStart(now)).getTime() + FIVE_HOURS_MS).toISOString();
79
+ }
80
+
81
+ export function usdToMicrousd(usd) {
82
+ return Math.round(Number(usd) * MICRO_USD_PER_USD);
83
+ }
84
+
85
+ export function microusdToUsd(microusd) {
86
+ return Number(microusd) / MICRO_USD_PER_USD;
87
+ }
88
+
89
+ /**
90
+ * Returns a key's usage after lazily resetting it for a new weekly period.
91
+ */
92
+ export function getClientKeyUsage(keyId, now = new Date()) {
93
+ const usage = loadUsage();
94
+ const periodStart = getCurrentPeriodStart(now);
95
+ const fiveHourPeriodStart = getCurrentFiveHourPeriodStart(now);
96
+ const entry = usage[keyId];
97
+ const consumedMicrousd = entry?.periodStart === periodStart && Number.isSafeInteger(entry.consumedMicrousd)
98
+ ? Math.max(0, entry.consumedMicrousd)
99
+ : 0;
100
+ const fiveHourConsumedMicrousd = entry?.fiveHourPeriodStart === fiveHourPeriodStart
101
+ && Number.isSafeInteger(entry.fiveHourConsumedMicrousd)
102
+ ? Math.max(0, entry.fiveHourConsumedMicrousd)
103
+ : 0;
104
+
105
+ if (!entry
106
+ || entry.periodStart !== periodStart
107
+ || entry.consumedMicrousd !== consumedMicrousd
108
+ || entry.fiveHourPeriodStart !== fiveHourPeriodStart
109
+ || entry.fiveHourConsumedMicrousd !== fiveHourConsumedMicrousd) {
110
+ usage[keyId] = {
111
+ periodStart,
112
+ consumedMicrousd,
113
+ fiveHourPeriodStart,
114
+ fiveHourConsumedMicrousd
115
+ };
116
+ saveUsage(usage);
117
+ }
118
+
119
+ return {
120
+ periodStart,
121
+ nextPeriodStart: getNextPeriodStart(now),
122
+ consumedMicrousd,
123
+ fiveHourPeriodStart,
124
+ nextFiveHourPeriodStart: getNextFiveHourPeriodStart(now),
125
+ fiveHourConsumedMicrousd
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Records actual USD consumption for a client key. Call this only after an
131
+ * upstream response provides a verified per-request charge.
132
+ */
133
+ export function recordClientKeyUsage(keyId, consumedMicrousd, now = new Date()) {
134
+ if (!Number.isSafeInteger(consumedMicrousd) || consumedMicrousd < 0) {
135
+ throw new TypeError('consumedMicrousd must be a non-negative safe integer');
136
+ }
137
+
138
+ const current = getClientKeyUsage(keyId, now);
139
+ const usage = loadUsage();
140
+ usage[keyId] = {
141
+ periodStart: current.periodStart,
142
+ consumedMicrousd: current.consumedMicrousd + consumedMicrousd,
143
+ fiveHourPeriodStart: current.fiveHourPeriodStart,
144
+ fiveHourConsumedMicrousd: current.fiveHourConsumedMicrousd + consumedMicrousd
145
+ };
146
+ saveUsage(usage);
147
+ return usage[keyId];
148
+ }
149
+
150
+ export function deleteClientKeyUsage(keyId) {
151
+ const usage = loadUsage();
152
+ if (!(keyId in usage)) return;
153
+ delete usage[keyId];
154
+ saveUsage(usage);
155
+ }
156
+
157
+ /**
158
+ * Returns a key's current quota summary without charging any request.
159
+ */
160
+ export function getClientKeyQuota(keyId, weeklyLimitUsd, fiveHourLimit = {}, now = new Date()) {
161
+ // Preserve the previous third-argument `now` form for internal callers and tests.
162
+ if (fiveHourLimit instanceof Date) {
163
+ now = fiveHourLimit;
164
+ fiveHourLimit = {};
165
+ }
166
+
167
+ const usage = getClientKeyUsage(keyId, now);
168
+ const weeklyLimitMicrousd = usdToMicrousd(weeklyLimitUsd);
169
+ const remainingMicrousd = Math.max(0, weeklyLimitMicrousd - usage.consumedMicrousd);
170
+ const fiveHourLimitEnabled = fiveHourLimit.enabled === true;
171
+ const fiveHourLimitMicrousd = usdToMicrousd(fiveHourLimit.usd ?? 0);
172
+ const fiveHourRemainingMicrousd = Math.max(
173
+ 0,
174
+ fiveHourLimitMicrousd - usage.fiveHourConsumedMicrousd
175
+ );
176
+
177
+ return {
178
+ ...usage,
179
+ weeklyLimitMicrousd,
180
+ remainingMicrousd,
181
+ weeklyLimitUsd: microusdToUsd(weeklyLimitMicrousd),
182
+ consumedUsd: microusdToUsd(usage.consumedMicrousd),
183
+ remainingUsd: microusdToUsd(remainingMicrousd),
184
+ fiveHourLimitEnabled,
185
+ fiveHourLimitMicrousd,
186
+ fiveHourRemainingMicrousd,
187
+ fiveHourLimitUsd: microusdToUsd(fiveHourLimitMicrousd),
188
+ fiveHourConsumedUsd: microusdToUsd(usage.fiveHourConsumedMicrousd),
189
+ fiveHourRemainingUsd: microusdToUsd(fiveHourRemainingMicrousd)
190
+ };
191
+ }
192
+
193
+ export { USAGE_FILE, loadUsage, saveUsage };