claude-codex-proxy 1.0.5-beta.4 → 1.0.5-beta.41
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/README.md +0 -272
- package/bin/cli.js +37 -2
- package/package.json +1 -1
- package/public/css/style.css +132 -0
- package/public/js/app.js +105 -26
- package/public/views/accounts-modals.html +90 -29
- package/public/views/accounts.html +29 -10
- package/public/views/client-api-keys-modals.html +10 -1
- package/public/views/client-api-keys.html +68 -39
- package/public/views/logs.html +10 -3
- package/public/views/settings.html +11 -1
- package/src/account-manager.js +34 -3
- package/src/account-rotation/index.js +6 -0
- package/src/account-rotation/rate-limits.js +4 -0
- package/src/account-rotation/strategies/base-strategy.js +4 -0
- package/src/account-rotation/strategies/round-robin-strategy.js +78 -3
- package/src/account-rotation/strategies/sticky-strategy.js +7 -0
- package/src/admin-path.js +33 -0
- package/src/client-key-usage.js +193 -125
- package/src/daily-anchor-ping.js +149 -0
- package/src/direct-api.js +6 -5
- package/src/format-converter.js +83 -48
- package/src/index.js +13 -4
- package/src/middleware/auth.js +23 -20
- package/src/middleware/credentials.js +17 -7
- package/src/middleware/sse.js +72 -30
- package/src/model-api.js +86 -13
- package/src/model-mapper.js +3 -4
- package/src/model-pricing.js +187 -96
- package/src/response-streamer.js +18 -2
- package/src/routes/accounts-route.js +106 -2
- package/src/routes/api-routes.js +59 -42
- package/src/routes/chat-route.js +5 -4
- package/src/routes/claude-config-route.js +19 -10
- package/src/routes/client-quota-route.js +31 -0
- package/src/routes/logs-route.js +21 -2
- package/src/routes/messages-route.js +135 -55
- package/src/routes/models-route.js +5 -0
- package/src/routes/settings-route.js +40 -10
- package/src/server-settings.js +10 -3
- package/src/server.js +4 -0
- package/src/utils/logger.js +34 -2
- package/src/utils/proxy-logging.js +5 -5
|
@@ -8,47 +8,76 @@
|
|
|
8
8
|
</div>
|
|
9
9
|
</div>
|
|
10
10
|
|
|
11
|
-
<div class="
|
|
12
|
-
<div class="
|
|
13
|
-
<
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
</
|
|
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="
|
|
29
|
+
<div class="client-keys-empty">Loading client API keys...</div>
|
|
20
30
|
</template>
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
<
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
<
|
|
45
|
-
<
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
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>
|
|
53
82
|
</div>
|
|
54
83
|
</div>
|
package/public/views/logs.html
CHANGED
|
@@ -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="
|
|
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>
|
|
@@ -110,7 +110,7 @@
|
|
|
110
110
|
<div class="flex flex-wrap items-center justify-between gap-4">
|
|
111
111
|
<div>
|
|
112
112
|
<div class="text-sm text-gray-300">Strategy</div>
|
|
113
|
-
<div class="text-xs text-gray-500 font-mono">How
|
|
113
|
+
<div class="text-xs text-gray-500 font-mono">How requests are distributed across available accounts</div>
|
|
114
114
|
</div>
|
|
115
115
|
<div class="inline-flex items-center gap-2">
|
|
116
116
|
<button class="btn btn-xs" :class="accountStrategy === 'sticky' ? 'bg-neon-purple text-white' : 'btn-outline text-gray-400'"
|
|
@@ -119,5 +119,15 @@
|
|
|
119
119
|
@click="setAccountStrategy('round-robin')" :disabled="strategySaving">Round-Robin</button>
|
|
120
120
|
</div>
|
|
121
121
|
</div>
|
|
122
|
+
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-4">
|
|
123
|
+
<div class="rounded-lg border p-3" :class="accountStrategy === 'sticky' ? 'border-neon-purple/50 bg-neon-purple/5' : 'border-space-border bg-space-800/40'">
|
|
124
|
+
<div class="text-xs font-mono text-gray-300 mb-1">Sticky · Cache-Optimized</div>
|
|
125
|
+
<div class="text-xs text-gray-500">Keeps using the active account. If it becomes unavailable, switches to another usable account.</div>
|
|
126
|
+
</div>
|
|
127
|
+
<div class="rounded-lg border p-3" :class="accountStrategy === 'round-robin' ? 'border-neon-purple/50 bg-neon-purple/5' : 'border-space-border bg-space-800/40'">
|
|
128
|
+
<div class="text-xs font-mono text-gray-300 mb-1">Round-Robin · Session-Balanced</div>
|
|
129
|
+
<div class="text-xs text-gray-500">Distributes new sessions across accounts, then keeps each session on the same account for cache reuse.</div>
|
|
130
|
+
</div>
|
|
131
|
+
</div>
|
|
122
132
|
</div>
|
|
123
133
|
</div>
|
package/src/account-manager.js
CHANGED
|
@@ -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,
|
|
@@ -75,6 +75,12 @@ export class AccountRotator {
|
|
|
75
75
|
return getMinWaitTimeMs(accounts, modelId);
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
commitSessionBinding(sessionId, email) {
|
|
79
|
+
if (this.strategy.commitSessionBinding) {
|
|
80
|
+
this.strategy.commitSessionBinding(sessionId, email);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
78
84
|
notifySuccess(account, modelId) {
|
|
79
85
|
if (this.strategy.notifySuccess) {
|
|
80
86
|
this.strategy.notifySuccess(account, modelId);
|
|
@@ -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
|
|
|
@@ -1,10 +1,20 @@
|
|
|
1
1
|
import { BaseStrategy } from './base-strategy.js';
|
|
2
2
|
import { logger } from '../../utils/logger.js';
|
|
3
3
|
|
|
4
|
+
const DEFAULT_SESSION_BINDING_TTL_MS = 24 * 60 * 60 * 1000;
|
|
5
|
+
const DEFAULT_SESSION_CLEANUP_INTERVAL_MS = 60 * 1000;
|
|
6
|
+
const DEFAULT_MAX_SESSION_BINDINGS = 10000;
|
|
7
|
+
|
|
4
8
|
export class RoundRobinStrategy extends BaseStrategy {
|
|
5
|
-
constructor(config) {
|
|
9
|
+
constructor(config = {}) {
|
|
6
10
|
super(config, 'round-robin');
|
|
7
11
|
this.cursor = 0;
|
|
12
|
+
this.sessionBindings = new Map();
|
|
13
|
+
this.sessionBindingTtlMs = config.sessionBindingTtlMs ?? DEFAULT_SESSION_BINDING_TTL_MS;
|
|
14
|
+
this.sessionCleanupIntervalMs = config.sessionCleanupIntervalMs ?? DEFAULT_SESSION_CLEANUP_INTERVAL_MS;
|
|
15
|
+
this.maxSessionBindings = config.maxSessionBindings ?? DEFAULT_MAX_SESSION_BINDINGS;
|
|
16
|
+
this.lastSessionCleanupAt = 0;
|
|
17
|
+
this.now = config.now ?? Date.now;
|
|
8
18
|
}
|
|
9
19
|
|
|
10
20
|
selectAccount(accounts, modelId, options = {}) {
|
|
@@ -12,6 +22,32 @@ export class RoundRobinStrategy extends BaseStrategy {
|
|
|
12
22
|
return { account: null, index: 0, waitMs: 0 };
|
|
13
23
|
}
|
|
14
24
|
|
|
25
|
+
const sessionId = this.#normalizeSessionId(options.sessionId);
|
|
26
|
+
const excludedEmails = new Set(options.excludeEmails || []);
|
|
27
|
+
const now = this.now();
|
|
28
|
+
|
|
29
|
+
if (sessionId) {
|
|
30
|
+
this.#cleanupSessionBindingsIfDue(now);
|
|
31
|
+
const binding = this.sessionBindings.get(sessionId);
|
|
32
|
+
if (binding && now - binding.lastUsedAt >= this.sessionBindingTtlMs) {
|
|
33
|
+
this.sessionBindings.delete(sessionId);
|
|
34
|
+
}
|
|
35
|
+
const currentBinding = this.sessionBindings.get(sessionId);
|
|
36
|
+
const boundIndex = currentBinding
|
|
37
|
+
? accounts.findIndex(account => account.email === currentBinding.email)
|
|
38
|
+
: -1;
|
|
39
|
+
const boundAccount = boundIndex >= 0 ? accounts[boundIndex] : null;
|
|
40
|
+
|
|
41
|
+
if (boundAccount
|
|
42
|
+
&& !excludedEmails.has(boundAccount.email)
|
|
43
|
+
&& this.isAccountUsable(boundAccount, modelId)) {
|
|
44
|
+
boundAccount.lastUsed = now;
|
|
45
|
+
this.#storeSessionBinding(sessionId, boundAccount.email, now);
|
|
46
|
+
logger.debug(`RoundRobinStrategy: Reusing session account at index ${boundIndex}`);
|
|
47
|
+
return { account: boundAccount, index: boundIndex, waitMs: 0 };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
15
51
|
// Clamp cursor
|
|
16
52
|
if (this.cursor >= accounts.length) {
|
|
17
53
|
this.cursor = 0;
|
|
@@ -24,9 +60,12 @@ export class RoundRobinStrategy extends BaseStrategy {
|
|
|
24
60
|
const checkIndex = (startIndex + i) % accounts.length;
|
|
25
61
|
const account = accounts[checkIndex];
|
|
26
62
|
|
|
27
|
-
if (this.isAccountUsable(account, modelId)) {
|
|
28
|
-
account.lastUsed =
|
|
63
|
+
if (!excludedEmails.has(account.email) && this.isAccountUsable(account, modelId)) {
|
|
64
|
+
account.lastUsed = now;
|
|
29
65
|
this.cursor = checkIndex;
|
|
66
|
+
if (sessionId && !options.deferSessionBinding) {
|
|
67
|
+
this.#storeSessionBinding(sessionId, account.email, now);
|
|
68
|
+
}
|
|
30
69
|
logger.debug(`RoundRobinStrategy: Using account at index ${checkIndex}`);
|
|
31
70
|
return { account, index: checkIndex, waitMs: 0 };
|
|
32
71
|
}
|
|
@@ -36,7 +75,43 @@ export class RoundRobinStrategy extends BaseStrategy {
|
|
|
36
75
|
return { account: null, index: this.cursor, waitMs: 0 };
|
|
37
76
|
}
|
|
38
77
|
|
|
78
|
+
commitSessionBinding(sessionId, email) {
|
|
79
|
+
const normalizedSessionId = this.#normalizeSessionId(sessionId);
|
|
80
|
+
if (!normalizedSessionId || !email) return;
|
|
81
|
+
|
|
82
|
+
const now = this.now();
|
|
83
|
+
this.#cleanupSessionBindingsIfDue(now);
|
|
84
|
+
this.#storeSessionBinding(normalizedSessionId, email, now);
|
|
85
|
+
}
|
|
86
|
+
|
|
39
87
|
resetCursor() {
|
|
40
88
|
this.cursor = 0;
|
|
41
89
|
}
|
|
90
|
+
|
|
91
|
+
#normalizeSessionId(sessionId) {
|
|
92
|
+
if (typeof sessionId !== 'string' && typeof sessionId !== 'number') return null;
|
|
93
|
+
const normalized = String(sessionId).trim();
|
|
94
|
+
return normalized || null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
#storeSessionBinding(sessionId, email, now) {
|
|
98
|
+
this.sessionBindings.delete(sessionId);
|
|
99
|
+
this.sessionBindings.set(sessionId, { email, lastUsedAt: now });
|
|
100
|
+
|
|
101
|
+
while (this.sessionBindings.size > this.maxSessionBindings) {
|
|
102
|
+
const oldestSessionId = this.sessionBindings.keys().next().value;
|
|
103
|
+
this.sessionBindings.delete(oldestSessionId);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
#cleanupSessionBindingsIfDue(now) {
|
|
108
|
+
if (now - this.lastSessionCleanupAt < this.sessionCleanupIntervalMs) return;
|
|
109
|
+
|
|
110
|
+
for (const [sessionId, binding] of this.sessionBindings) {
|
|
111
|
+
if (now - binding.lastUsedAt >= this.sessionBindingTtlMs) {
|
|
112
|
+
this.sessionBindings.delete(sessionId);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
this.lastSessionCleanupAt = now;
|
|
116
|
+
}
|
|
42
117
|
}
|
|
@@ -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 };
|