claude-codex-proxy 1.0.5-beta.11 → 1.0.5-beta.13
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/bin/cli.js +9 -2
- package/package.json +1 -1
- package/public/js/app.js +25 -14
- package/public/views/accounts-modals.html +19 -0
- package/public/views/accounts.html +29 -10
- package/src/account-manager.js +34 -3
- package/src/account-rotation/rate-limits.js +4 -0
- package/src/account-rotation/strategies/base-strategy.js +4 -0
- package/src/account-rotation/strategies/sticky-strategy.js +7 -0
- package/src/admin-path.js +33 -0
- package/src/index.js +13 -4
- package/src/middleware/credentials.js +13 -3
- package/src/routes/accounts-route.js +28 -1
- package/src/routes/api-routes.js +54 -43
- package/src/routes/messages-route.js +9 -7
package/bin/cli.js
CHANGED
|
@@ -40,17 +40,19 @@ OPTIONS:
|
|
|
40
40
|
--version, -v Show version number
|
|
41
41
|
--mode <local|public> Deployment mode for the start command
|
|
42
42
|
--admin-key <key> UI/admin access key for public deployment
|
|
43
|
+
--admin-path <path> Management UI path prefix (default: /admin)
|
|
43
44
|
|
|
44
45
|
ENVIRONMENT:
|
|
45
46
|
PORT Server port (default: 8081)
|
|
46
47
|
PROXY_DEPLOYMENT_MODE Deployment mode (local or public)
|
|
47
48
|
PROXY_ADMIN_KEY UI/admin access key for public deployment
|
|
49
|
+
PROXY_ADMIN_PATH Management UI path prefix (default: /admin)
|
|
48
50
|
|
|
49
51
|
EXAMPLES:
|
|
50
52
|
claude-codex-proxy start
|
|
51
53
|
PORT=3000 claude-codex-proxy start
|
|
52
|
-
claude-codex-proxy start --mode public --admin-key "your-admin-key"
|
|
53
|
-
PROXY_DEPLOYMENT_MODE=public PROXY_ADMIN_KEY="your-admin-key" claude-codex-proxy start
|
|
54
|
+
claude-codex-proxy start --mode public --admin-key "your-admin-key" --admin-path /console-7f3a9d2c
|
|
55
|
+
PROXY_DEPLOYMENT_MODE=public PROXY_ADMIN_KEY="your-admin-key" PROXY_ADMIN_PATH=/console-7f3a9d2c claude-codex-proxy start
|
|
54
56
|
claude-codex-proxy accounts add
|
|
55
57
|
claude-codex-proxy accounts add --no-browser
|
|
56
58
|
claude-codex-proxy accounts list
|
|
@@ -124,6 +126,11 @@ function getOptionValue(option) {
|
|
|
124
126
|
}
|
|
125
127
|
|
|
126
128
|
async function configureStartMode() {
|
|
129
|
+
const adminPath = getOptionValue('--admin-path');
|
|
130
|
+
if (adminPath !== undefined) {
|
|
131
|
+
process.env.PROXY_ADMIN_PATH = adminPath;
|
|
132
|
+
}
|
|
133
|
+
|
|
127
134
|
const requestedMode = getOptionValue('--mode') || process.env.PROXY_DEPLOYMENT_MODE;
|
|
128
135
|
if (requestedMode && !['local', 'public'].includes(requestedMode)) {
|
|
129
136
|
throw new Error('Deployment mode must be "local" or "public".');
|
package/package.json
CHANGED
package/public/js/app.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
const adminPath = window.__PROXY_ADMIN_PATH__ || '/admin';
|
|
2
|
+
const adminUrl = (path) => `${adminPath}${path}`;
|
|
3
|
+
|
|
1
4
|
document.addEventListener('alpine:init', () => {
|
|
2
5
|
Alpine.data('app', () => ({
|
|
3
6
|
version: '', connectionStatus: 'connecting', activeTab: '', sidebarOpen: window.innerWidth >= 1024,
|
|
@@ -9,6 +12,7 @@ document.addEventListener('alpine:init', () => {
|
|
|
9
12
|
clientApiKeys: [], clientApiKeyName: '', clientApiKeyRemark: '', clientApiKeyWeeklyLimitUsd: 50, clientApiKeysLoading: false,
|
|
10
13
|
clientApiKeySaving: false, revealedClientApiKey: '', clientProxyConfig: null, showCreateClientApiKeyModal: false,
|
|
11
14
|
showAddModal: false, showDeleteModal: false, deleteTarget: '', showQuotaModalView: false, selectedAccount: null,
|
|
15
|
+
showAccountExpirationModalView: false, expirationTarget: null, accountExpirationInput: '', accountExpirationSaving: false,
|
|
12
16
|
resetCreditsLoading: false, resetCreditsRedeeming: false, resetCredits: [], resetCreditsAccountEmail: '', resetCreditRedeemRequestId: '',
|
|
13
17
|
oauthManualMode: false, oauthManualUrl: '', oauthManualVerifier: '', oauthManualCode: '',
|
|
14
18
|
testPrompt: 'Say hello', testResponse: '', testing: false, configPath: '~/.claude-codex-proxy/accounts.json',
|
|
@@ -23,10 +27,10 @@ document.addEventListener('alpine:init', () => {
|
|
|
23
27
|
await this.checkHealth();
|
|
24
28
|
this.authChecked = true;
|
|
25
29
|
if (this.isLoginPage()) {
|
|
26
|
-
if (this.isAuthenticated) window.location.replace('/dashboard');
|
|
30
|
+
if (this.isAuthenticated) window.location.replace(adminUrl('/dashboard'));
|
|
27
31
|
return;
|
|
28
32
|
}
|
|
29
|
-
if (!this.isAuthenticated) { window.location.replace('/login'); return; }
|
|
33
|
+
if (!this.isAuthenticated) { window.location.replace(adminUrl('/login')); return; }
|
|
30
34
|
await this.loadCurrentView();
|
|
31
35
|
this.updateTime();
|
|
32
36
|
setInterval(() => this.updateTime(), 1000);
|
|
@@ -35,18 +39,18 @@ document.addEventListener('alpine:init', () => {
|
|
|
35
39
|
window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
|
|
36
40
|
},
|
|
37
41
|
|
|
38
|
-
isLoginPage() { return window.location.pathname === '/login' || window.location.pathname === '/login.html'; },
|
|
42
|
+
isLoginPage() { return window.location.pathname === adminUrl('/login') || window.location.pathname === adminUrl('/login.html'); },
|
|
39
43
|
async loadCurrentView() {
|
|
40
|
-
const route = window.location.pathname.replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
|
|
44
|
+
const route = window.location.pathname.slice(adminPath.length).replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
|
|
41
45
|
const tab = route === 'account-management' ? 'accounts' : route;
|
|
42
46
|
const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
|
|
43
47
|
this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
|
|
44
|
-
if (this.activeTab !== tab) { window.location.replace('/dashboard'); return; }
|
|
48
|
+
if (this.activeTab !== tab) { window.location.replace(adminUrl('/dashboard')); return; }
|
|
45
49
|
const [viewResponse, modalResponse] = await Promise.all([
|
|
46
|
-
fetch(`/views/${this.activeTab}.html`),
|
|
47
|
-
fetch(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html')
|
|
50
|
+
fetch(adminUrl(`/views/${this.activeTab}.html`)),
|
|
51
|
+
fetch(adminUrl(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html'))
|
|
48
52
|
]);
|
|
49
|
-
if (!viewResponse.ok) { window.location.replace('/dashboard'); return; }
|
|
53
|
+
if (!viewResponse.ok) { window.location.replace(adminUrl('/dashboard')); return; }
|
|
50
54
|
document.querySelector('#view-content').innerHTML = await viewResponse.text();
|
|
51
55
|
document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
|
|
52
56
|
Alpine.initTree(document.querySelector('#view-content'));
|
|
@@ -67,7 +71,8 @@ document.addEventListener('alpine:init', () => {
|
|
|
67
71
|
try {
|
|
68
72
|
const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
|
|
69
73
|
if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
|
|
70
|
-
const
|
|
74
|
+
const url = endpoint.startsWith('/v1/') ? endpoint : adminUrl(endpoint);
|
|
75
|
+
const response = await fetch(url, { ...options, headers });
|
|
71
76
|
const data = await response.json();
|
|
72
77
|
if (response.status === 401 && endpoint !== '/health') this.logout(false);
|
|
73
78
|
return { ok: response.ok, data };
|
|
@@ -80,10 +85,10 @@ document.addEventListener('alpine:init', () => {
|
|
|
80
85
|
const { ok } = await this.api('/settings/account-strategy');
|
|
81
86
|
if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
|
|
82
87
|
localStorage.setItem('codexProxyApiKey', key);
|
|
83
|
-
window.location.replace('/dashboard');
|
|
88
|
+
window.location.replace(adminUrl('/dashboard'));
|
|
84
89
|
},
|
|
85
|
-
logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace('/login'); },
|
|
86
|
-
async checkHealth() {
|
|
90
|
+
logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace(adminUrl('/login')); },
|
|
91
|
+
async checkHealth() { try { const response = await fetch('/health'); const data = await response.json(); this.connectionStatus = response.ok ? 'connected' : 'disconnected'; if (response.ok && data?.version) this.version = data.version; if (response.ok && typeof data?.publicMode === 'boolean') this.authRequired = data.publicMode; } catch { this.connectionStatus = 'disconnected'; } },
|
|
87
92
|
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; },
|
|
88
93
|
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; },
|
|
89
94
|
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)))); },
|
|
@@ -99,6 +104,12 @@ document.addEventListener('alpine:init', () => {
|
|
|
99
104
|
async copyToClipboard(text) { try { await navigator.clipboard.writeText(text); this.showToast('Copied to clipboard', 'success'); } catch { this.showToast('Failed to copy', 'error'); } },
|
|
100
105
|
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'); },
|
|
101
106
|
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'); },
|
|
107
|
+
accountExpirationLabel(account) { if (!account?.accountExpiresAt) return 'Never'; const date = new Date(account.accountExpiresAt); if (Number.isNaN(date.getTime())) return 'Never'; return date.toLocaleString([], { year: '2-digit', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); },
|
|
108
|
+
showAccountExpirationModal(account) { this.expirationTarget = account; const date = account?.accountExpiresAt ? new Date(account.accountExpiresAt) : null; if (date && !Number.isNaN(date.getTime())) { const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000); this.accountExpirationInput = local.toISOString().slice(0, 16); } else this.accountExpirationInput = ''; this.showAccountExpirationModalView = true; },
|
|
109
|
+
closeAccountExpirationModal() { if (this.accountExpirationSaving) return; this.showAccountExpirationModalView = false; this.expirationTarget = null; this.accountExpirationInput = ''; },
|
|
110
|
+
async updateAccountExpiration(accountExpiresAt) { if (!this.expirationTarget || this.accountExpirationSaving) return; this.accountExpirationSaving = true; const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.expirationTarget.email)}/expiration`, { method: 'PUT', body: JSON.stringify({ accountExpiresAt }) }); this.accountExpirationSaving = false; if (ok && data?.success) { this.closeAccountExpirationModal(); await this.refreshAccounts(); this.showToast(accountExpiresAt ? 'Account expiration updated' : 'Account expiration cleared', 'success'); } else this.showToast(data?.message || 'Failed to update account expiration', 'error'); },
|
|
111
|
+
saveAccountExpiration() { if (!this.accountExpirationInput) return; const expiresAt = new Date(this.accountExpirationInput); if (Number.isNaN(expiresAt.getTime())) { this.showToast('Enter a valid expiration time', 'error'); return; } return this.updateAccountExpiration(expiresAt.toISOString()); },
|
|
112
|
+
clearAccountExpiration() { return this.updateAccountExpiration(null); },
|
|
102
113
|
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); } },
|
|
103
114
|
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; },
|
|
104
115
|
async executeDelete() { const { ok, data } = await this.api(`/accounts/${encodeURIComponent(this.deleteTarget)}`, { method: 'DELETE' }); this.showDeleteModal = false; if (ok && data.success) this.refreshAccounts(); else this.showToast(data?.message || 'Delete failed', 'error'); }, async showQuotaModal(acc) { this.selectedAccount = acc; this.showQuotaModalView = true; await this.loadRateLimitResetCredits(acc.email); },
|
|
@@ -115,8 +126,8 @@ document.addEventListener('alpine:init', () => {
|
|
|
115
126
|
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'); },
|
|
116
127
|
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'); },
|
|
117
128
|
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'); },
|
|
118
|
-
async loadClientProxyConfig() {
|
|
129
|
+
async loadClientProxyConfig() { try { const response = await fetch('/claude/config/proxy', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); const data = await response.json(); if (response.ok && data?.success && data?.env) this.clientProxyConfig = data; } catch {} }, async copyClientText(text, successMessage) { if (!text) return; try { if (navigator.clipboard?.writeText && window.isSecureContext) await navigator.clipboard.writeText(text); else { const textarea = document.createElement('textarea'); textarea.value = text; textarea.setAttribute('readonly', ''); textarea.style.cssText = 'position:absolute;opacity:0;left:-999999px;top:-999999px'; document.body.appendChild(textarea); textarea.focus(); textarea.select(); const copied = document.execCommand('copy'); textarea.remove(); if (!copied) throw new Error('Clipboard copy was rejected'); } this.showToast(successMessage, 'success'); } catch { this.showToast('Copy failed. Select and copy the value manually.', 'error'); } }, copyClientApiKey() { return this.copyClientText(this.revealedClientApiKey, 'Client API key copied'); }, copyClientProxyCommands() { const configureCommands = this.clientProxyConfig?.commands?.powershell; const clearCommands = this.clientProxyConfig?.commands?.clear?.powershell; const commands = [...(Array.isArray(configureCommands) ? configureCommands : []), ...(Array.isArray(clearCommands) ? clearCommands : [])]; return commands.length ? this.copyClientText(commands.map(command => command.replace('<client-api-key>', this.revealedClientApiKey)).join('\n'), 'Claude Code configuration commands copied') : undefined; },
|
|
119
130
|
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'); },
|
|
120
|
-
showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, async loadLogs(page = 1) { if (this.logLoading) return; this.logLoading = true; const { ok, data } = await this.api(`/api/logs?page=${page}&pageSize=${this.logPageSize}`); this.logLoading = false; if (!ok || !Array.isArray(data?.logs)) { this.showToast(data?.error || 'Failed to load logs', 'error'); return; } this.logs = data.logs; this.logPage = data.page; this.logTotal = data.total; this.logTotalPages = data.totalPages; }, async changeLogPage(page) { if (page < 1 || page > this.logTotalPages || page === this.logPage) return; await this.loadLogs(page); }, startLogStream() { if (!this.isAuthenticated) return; this.loadLogs(); this.logEventSource?.close(); const params = new URLSearchParams(); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(`/api/logs/stream?${params}`); this.logEventSource.onmessage = event => { try { this.logTotal += 1; this.logTotalPages = Math.ceil(this.logTotal / this.logPageSize); if (this.logPage === 1) this.logs = [JSON.parse(event.data), ...this.logs].slice(0, this.logPageSize); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; this.logTotal = 0; this.logTotalPages = 0; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
|
|
131
|
+
showToast(message, type = 'success') { this.toast = { message, type }; setTimeout(() => { this.toast = null; }, 3000); }, async loadLogs(page = 1) { if (this.logLoading) return; this.logLoading = true; const { ok, data } = await this.api(`/api/logs?page=${page}&pageSize=${this.logPageSize}`); this.logLoading = false; if (!ok || !Array.isArray(data?.logs)) { this.showToast(data?.error || 'Failed to load logs', 'error'); return; } this.logs = data.logs; this.logPage = data.page; this.logTotal = data.total; this.logTotalPages = data.totalPages; }, async changeLogPage(page) { if (page < 1 || page > this.logTotalPages || page === this.logPage) return; await this.loadLogs(page); }, startLogStream() { if (!this.isAuthenticated) return; this.loadLogs(); this.logEventSource?.close(); const params = new URLSearchParams(); if (this.apiKey) params.set('api_key', this.apiKey); this.logEventSource = new EventSource(adminUrl(`/api/logs/stream?${params}`)); this.logEventSource.onmessage = event => { try { this.logTotal += 1; this.logTotalPages = Math.ceil(this.logTotal / this.logPageSize); if (this.logPage === 1) this.logs = [JSON.parse(event.data), ...this.logs].slice(0, this.logPageSize); } catch {} }; this.logEventSource.onerror = () => setTimeout(() => this.startLogStream(), 3000); }, clearLogs() { this.logs = []; this.logTotal = 0; this.logTotalPages = 0; }, formatLogMessage(message) { return message?.replace(/^\[(\w+)\]\s*/, '') || ''; }, getLogDetails(message) { if (!message) return null; const details = {}; for (const [key, pattern] of [['model', /model=([^\s|,]+)/], ['account', /account=([^\s|,]+)/], ['stream', /stream=(true|false)/], ['messages', /messages=(\d+)/], ['tools', /tools=(\d+)/], ['tokens', /tokens=(\d+)/], ['duration', /(\d+)ms/], ['status', /status=(\d+)/], ['error', /error=([^\s|]+)/]]) { const match = message.match(pattern); if (match) details[key] = match[1]; } return Object.keys(details).length ? details : null; }
|
|
121
132
|
}));
|
|
122
133
|
});
|
|
@@ -86,6 +86,25 @@
|
|
|
86
86
|
</div>
|
|
87
87
|
</div>
|
|
88
88
|
|
|
89
|
+
<div x-show="showAccountExpirationModalView" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;">
|
|
90
|
+
<div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="closeAccountExpirationModal()"></div>
|
|
91
|
+
<div class="relative bg-space-900 border border-space-border rounded-xl shadow-2xl max-w-md w-full p-6">
|
|
92
|
+
<h3 class="font-bold text-lg text-white mb-2">Set Account Expiration</h3>
|
|
93
|
+
<p class="text-sm text-gray-500 font-mono mb-5" x-text="expirationTarget?.email"></p>
|
|
94
|
+
<label class="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-2" for="account-expiration">Expires at</label>
|
|
95
|
+
<input id="account-expiration" type="datetime-local" x-model="accountExpirationInput"
|
|
96
|
+
class="input w-full bg-space-800 border-space-border text-white font-mono text-sm">
|
|
97
|
+
<p class="mt-2 text-xs text-gray-500">The time uses your browser's local timezone. After expiration, this account will not participate in automatic account selection.</p>
|
|
98
|
+
<div class="mt-6 flex justify-between gap-2">
|
|
99
|
+
<button class="btn btn-ghost btn-sm text-gray-400 hover:text-white" @click="clearAccountExpiration()" :disabled="accountExpirationSaving || !expirationTarget?.accountExpiresAt">Clear Expiration</button>
|
|
100
|
+
<div class="flex gap-2">
|
|
101
|
+
<button class="btn btn-outline btn-sm text-gray-400" @click="closeAccountExpirationModal()">Cancel</button>
|
|
102
|
+
<button class="btn bg-neon-purple hover:bg-purple-600 border-none text-white btn-sm" @click="saveAccountExpiration()" :disabled="accountExpirationSaving || !accountExpirationInput" x-text="accountExpirationSaving ? 'Saving...' : 'Save'"></button>
|
|
103
|
+
</div>
|
|
104
|
+
</div>
|
|
105
|
+
</div>
|
|
106
|
+
</div>
|
|
107
|
+
|
|
89
108
|
<div x-show="showDeleteModal" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display: none;">
|
|
90
109
|
<div class="absolute inset-0 bg-black/70 backdrop-blur-sm" @click="showDeleteModal = false"></div>
|
|
91
110
|
<div class="relative bg-space-900 border-2 border-red-500/50 rounded-xl shadow-2xl max-w-md w-full p-6">
|
|
@@ -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-[
|
|
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
|
|
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="
|
|
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
|
|
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="
|
|
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" />
|
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,
|
|
@@ -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 };
|
package/src/index.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
7
|
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
8
|
+
import { getAdminPath } from './admin-path.js';
|
|
8
9
|
import { startServer } from './server.js';
|
|
9
10
|
import { logger } from './utils/logger.js';
|
|
10
11
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -21,6 +22,14 @@ try {
|
|
|
21
22
|
}
|
|
22
23
|
const HOST = getServerHost();
|
|
23
24
|
const BASE_URL = getLocalBaseUrl(PORT);
|
|
25
|
+
let ADMIN_PATH;
|
|
26
|
+
try {
|
|
27
|
+
ADMIN_PATH = getAdminPath();
|
|
28
|
+
} catch (error) {
|
|
29
|
+
console.error(error.message);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
const ADMIN_URL = `${BASE_URL}${ADMIN_PATH}`;
|
|
24
33
|
const BANNER_WIDTH = 62;
|
|
25
34
|
|
|
26
35
|
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
@@ -45,10 +54,10 @@ console.log(`
|
|
|
45
54
|
╠══════════════════════════════════════════════════════════════╣
|
|
46
55
|
${bannerLine('Host:', HOST)}
|
|
47
56
|
${bannerLine('Server:', BASE_URL)}
|
|
48
|
-
${bannerLine('WebUI:',
|
|
57
|
+
${bannerLine('WebUI:', ADMIN_URL)}
|
|
49
58
|
${bannerLine('Health:', `${BASE_URL}/health`)}
|
|
50
|
-
${bannerLine('Accounts:', `${
|
|
51
|
-
${bannerLine('Logs:', `${
|
|
59
|
+
${bannerLine('Accounts:', `${ADMIN_URL}/accounts`)}
|
|
60
|
+
${bannerLine('Logs:', `${ADMIN_URL}/api/logs/stream`)}
|
|
52
61
|
╠══════════════════════════════════════════════════════════════╣
|
|
53
62
|
║ Features: ║
|
|
54
63
|
║ ✓ Native tool calling support ║
|
|
@@ -66,7 +75,7 @@ const status = getStatus();
|
|
|
66
75
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
67
76
|
|
|
68
77
|
if (status.total === 0) {
|
|
69
|
-
logger.warn(`No accounts configured. Open ${
|
|
78
|
+
logger.warn(`No accounts configured. Open ${ADMIN_URL} to add one.`);
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
// Expose config path in logs for convenience
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
getActiveAccount,
|
|
9
9
|
refreshAccountToken,
|
|
10
10
|
isTokenExpiredOrExpiringSoon,
|
|
11
|
+
isAccountExpired,
|
|
11
12
|
loadAccounts
|
|
12
13
|
} from '../account-manager.js';
|
|
13
14
|
import { logger } from '../utils/logger.js';
|
|
@@ -26,6 +27,11 @@ export async function getCredentialsOrError() {
|
|
|
26
27
|
return null;
|
|
27
28
|
}
|
|
28
29
|
|
|
30
|
+
if (isAccountExpired(account)) {
|
|
31
|
+
logger.info(`Account ${account.email} has expired`);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
29
35
|
if (!account.accessToken || !account.accountId) {
|
|
30
36
|
logger.info(`Account ${account.email} missing token or accountId`);
|
|
31
37
|
return null;
|
|
@@ -41,8 +47,8 @@ export async function getCredentialsOrError() {
|
|
|
41
47
|
}
|
|
42
48
|
|
|
43
49
|
const refreshedAccount = getActiveAccount();
|
|
44
|
-
if (!refreshedAccount) {
|
|
45
|
-
logger.error('Failed to get refreshed account');
|
|
50
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) {
|
|
51
|
+
logger.error('Failed to get refreshed active account');
|
|
46
52
|
return null;
|
|
47
53
|
}
|
|
48
54
|
|
|
@@ -74,6 +80,10 @@ export async function getCredentialsForAccount(email) {
|
|
|
74
80
|
return null;
|
|
75
81
|
}
|
|
76
82
|
|
|
83
|
+
if (isAccountExpired(account)) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
77
87
|
if (!account.accessToken || !account.accountId) {
|
|
78
88
|
return null;
|
|
79
89
|
}
|
|
@@ -85,7 +95,7 @@ export async function getCredentialsForAccount(email) {
|
|
|
85
95
|
}
|
|
86
96
|
const refreshedData = loadAccounts();
|
|
87
97
|
const refreshedAccount = refreshedData.accounts.find(a => a.email === email);
|
|
88
|
-
if (!refreshedAccount) return null;
|
|
98
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) return null;
|
|
89
99
|
|
|
90
100
|
return {
|
|
91
101
|
accessToken: refreshedAccount.accessToken,
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* POST /accounts/refresh
|
|
15
15
|
* POST /accounts/refresh/all
|
|
16
16
|
* POST /accounts/:email/refresh
|
|
17
|
+
* PUT /accounts/:email/expiration
|
|
17
18
|
* POST /accounts/oauth/cleanup
|
|
18
19
|
* DELETE /accounts/:email
|
|
19
20
|
*/
|
|
@@ -32,7 +33,8 @@ import {
|
|
|
32
33
|
saveAccounts,
|
|
33
34
|
updateAccountAuth,
|
|
34
35
|
updateAccountQuota,
|
|
35
|
-
getAccountQuota
|
|
36
|
+
getAccountQuota,
|
|
37
|
+
updateAccountExpiration
|
|
36
38
|
} from '../account-manager.js';
|
|
37
39
|
|
|
38
40
|
import {
|
|
@@ -178,6 +180,30 @@ export async function handleRefreshAllAccounts(req, res) {
|
|
|
178
180
|
res.json(result);
|
|
179
181
|
}
|
|
180
182
|
|
|
183
|
+
export function handleUpdateAccountExpiration(req, res) {
|
|
184
|
+
const email = decodeURIComponent(req.params.email);
|
|
185
|
+
const { accountExpiresAt } = req.body || {};
|
|
186
|
+
|
|
187
|
+
if (accountExpiresAt !== null && accountExpiresAt !== undefined) {
|
|
188
|
+
if (typeof accountExpiresAt !== 'string' || !accountExpiresAt.trim()) {
|
|
189
|
+
return res.status(400).json({ success: false, message: 'accountExpiresAt must be an ISO 8601 date or null' });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const normalizedAccountExpiresAt = accountExpiresAt.trim();
|
|
193
|
+
const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
194
|
+
const expiresAt = new Date(normalizedAccountExpiresAt);
|
|
195
|
+
if (!isoDatePattern.test(normalizedAccountExpiresAt) || Number.isNaN(expiresAt.getTime())) {
|
|
196
|
+
return res.status(400).json({ success: false, message: 'accountExpiresAt must be a valid ISO 8601 date' });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const result = updateAccountExpiration(email, expiresAt.toISOString());
|
|
200
|
+
return res.status(result.success ? 200 : 404).json(result);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const result = updateAccountExpiration(email, null);
|
|
204
|
+
return res.status(result.success ? 200 : 404).json(result);
|
|
205
|
+
}
|
|
206
|
+
|
|
181
207
|
export async function handleRefreshActiveAccount(req, res) {
|
|
182
208
|
const result = await refreshActiveAccount();
|
|
183
209
|
res.json(result);
|
|
@@ -379,6 +405,7 @@ export default {
|
|
|
379
405
|
handleSwitchAccount,
|
|
380
406
|
handleRefreshAccount,
|
|
381
407
|
handleRefreshAllAccounts,
|
|
408
|
+
handleUpdateAccountExpiration,
|
|
382
409
|
handleRefreshActiveAccount,
|
|
383
410
|
handleRemoveAccount,
|
|
384
411
|
handleImportAccount,
|
package/src/routes/api-routes.js
CHANGED
|
@@ -7,10 +7,12 @@
|
|
|
7
7
|
import express from 'express';
|
|
8
8
|
import { createRequire } from 'module';
|
|
9
9
|
import { join, dirname } from 'path';
|
|
10
|
+
import { readFileSync } from 'fs';
|
|
10
11
|
import { fileURLToPath } from 'url';
|
|
11
12
|
|
|
12
13
|
import { getStatus, ACCOUNTS_FILE } from '../account-manager.js';
|
|
13
14
|
import { isPublicDeployment, requireAdminAuth, requireClientAuth } from '../middleware/auth.js';
|
|
15
|
+
import { getAdminPath } from '../admin-path.js';
|
|
14
16
|
|
|
15
17
|
// Route handlers
|
|
16
18
|
import { handleMessages } from './messages-route.js';
|
|
@@ -40,6 +42,7 @@ import {
|
|
|
40
42
|
handleSwitchAccount,
|
|
41
43
|
handleRefreshAccount,
|
|
42
44
|
handleRefreshAllAccounts,
|
|
45
|
+
handleUpdateAccountExpiration,
|
|
43
46
|
handleRefreshActiveAccount,
|
|
44
47
|
handleRemoveAccount,
|
|
45
48
|
handleImportAccount,
|
|
@@ -54,17 +57,24 @@ const require = createRequire(import.meta.url);
|
|
|
54
57
|
const packageJson = require('../../package.json');
|
|
55
58
|
|
|
56
59
|
export function registerApiRoutes(app, { port }) {
|
|
57
|
-
|
|
60
|
+
const adminPath = getAdminPath();
|
|
58
61
|
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
59
|
-
|
|
62
|
+
const adminRouter = express.Router();
|
|
63
|
+
const sendAdminHtml = (fileName) => {
|
|
64
|
+
const html = readFileSync(join(publicDirectory, fileName), 'utf8')
|
|
65
|
+
.replace(/(href|src)="\//g, `$1="${adminPath}/`)
|
|
66
|
+
.replace('</head>', `<script>window.__PROXY_ADMIN_PATH__=${JSON.stringify(adminPath)};</script></head>`);
|
|
67
|
+
return (req, res) => res.type('html').send(html);
|
|
68
|
+
};
|
|
60
69
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
});
|
|
70
|
+
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
71
|
+
adminRouter.use(express.static(publicDirectory, { index: false }));
|
|
64
72
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
73
|
+
adminRouter.get(['/', '/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], sendAdminHtml('index.html'));
|
|
74
|
+
|
|
75
|
+
adminRouter.get('/login', sendAdminHtml('login.html'));
|
|
76
|
+
|
|
77
|
+
app.use(adminPath, adminRouter);
|
|
68
78
|
|
|
69
79
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
70
80
|
app.get('/health', (req, res) => {
|
|
@@ -95,50 +105,51 @@ export function registerApiRoutes(app, { port }) {
|
|
|
95
105
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
96
106
|
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
97
107
|
|
|
98
|
-
|
|
108
|
+
adminRouter.use(requireAdminAuth);
|
|
99
109
|
|
|
100
|
-
|
|
101
|
-
|
|
110
|
+
adminRouter.get('/accounts/models', handleAccountModels);
|
|
111
|
+
adminRouter.get('/accounts/usage', handleAccountUsage);
|
|
102
112
|
|
|
103
113
|
// ─── Settings ──────────────────────────────────────────────────────────────
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
+
adminRouter.get('/settings/account-strategy', handleGetAccountStrategy);
|
|
115
|
+
adminRouter.post('/settings/account-strategy', handleSetAccountStrategy);
|
|
116
|
+
adminRouter.get('/settings/model-map', handleGetModelMap);
|
|
117
|
+
adminRouter.post('/settings/model-map', handleSetModelMap);
|
|
118
|
+
adminRouter.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
119
|
+
adminRouter.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
120
|
+
adminRouter.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
121
|
+
adminRouter.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
122
|
+
adminRouter.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
123
|
+
adminRouter.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
114
124
|
|
|
115
125
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
126
|
+
adminRouter.get('/accounts', handleListAccounts);
|
|
127
|
+
adminRouter.get('/accounts/status', handleAccountStatus);
|
|
128
|
+
adminRouter.get('/accounts/quota', handleGetQuota);
|
|
129
|
+
adminRouter.get('/accounts/quota/all', handleGetAllQuotas);
|
|
130
|
+
adminRouter.get('/accounts/rate-limit-reset-credits', handleGetRateLimitResetCredits);
|
|
131
|
+
adminRouter.post('/accounts/rate-limit-reset-credits/consume', handleConsumeRateLimitResetCredit);
|
|
132
|
+
|
|
133
|
+
adminRouter.post('/accounts/add', handleAddAccount);
|
|
134
|
+
adminRouter.post('/accounts/add/manual', handleAddAccountManual);
|
|
135
|
+
adminRouter.post('/accounts/switch', handleSwitchAccount);
|
|
136
|
+
adminRouter.post('/accounts/import', handleImportAccount);
|
|
137
|
+
adminRouter.post('/accounts/refresh', handleRefreshActiveAccount);
|
|
138
|
+
adminRouter.post('/accounts/refresh/all', handleRefreshAllAccounts);
|
|
139
|
+
adminRouter.post('/accounts/oauth/cleanup', handleOAuthCleanup);
|
|
140
|
+
adminRouter.post('/accounts/:email/refresh', handleRefreshAccount);
|
|
141
|
+
adminRouter.put('/accounts/:email/expiration', handleUpdateAccountExpiration);
|
|
142
|
+
|
|
143
|
+
adminRouter.delete('/accounts/:email', handleRemoveAccount);
|
|
133
144
|
|
|
134
145
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
146
|
+
adminRouter.get('/claude/config', handleGetClaudeConfig);
|
|
147
|
+
adminRouter.post('/claude/config/direct', handleSetDirectMode);
|
|
148
|
+
adminRouter.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
138
149
|
|
|
139
150
|
// ─── Logs ──────────────────────────────────────────────────────────────────
|
|
140
|
-
|
|
141
|
-
|
|
151
|
+
adminRouter.get('/api/logs', handleGetLogs);
|
|
152
|
+
adminRouter.get('/api/logs/stream', handleStreamLogs);
|
|
142
153
|
}
|
|
143
154
|
|
|
144
155
|
export default { registerApiRoutes };
|
|
@@ -4,7 +4,7 @@ import { sendAuthError, getCredentialsForAccount } from '../middleware/credentia
|
|
|
4
4
|
import { initSSEResponse, pipeSSEStream, handleStreamError } from '../middleware/sse.js';
|
|
5
5
|
import { logger } from '../utils/logger.js';
|
|
6
6
|
import { AccountRotator } from '../account-rotation/index.js';
|
|
7
|
-
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save } from '../account-manager.js';
|
|
7
|
+
import { listAccounts, loadAccounts, getActiveAccount, setActiveAccount, save, isAccountExpired } from '../account-manager.js';
|
|
8
8
|
import { getServerSettings } from '../server-settings.js';
|
|
9
9
|
import { recordClientKeyUsage } from '../client-key-usage.js';
|
|
10
10
|
import { calculateUsageCostMicrousd } from '../model-pricing.js';
|
|
@@ -68,15 +68,17 @@ export async function handleMessages(req, res) {
|
|
|
68
68
|
const maxAttempts = Math.max(MAX_RETRIES, listAccounts().total);
|
|
69
69
|
|
|
70
70
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
71
|
-
|
|
71
|
+
const { account, waitMs } = rotator.selectAccount(upstreamModel);
|
|
72
|
+
|
|
73
|
+
if (!account && rotator.isAllRateLimited(upstreamModel)) {
|
|
72
74
|
const minWait = rotator.getMinWaitTimeMs(upstreamModel);
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
75
|
+
if (minWait > 0) {
|
|
76
|
+
const waitSeconds = Math.round(minWait / 1000);
|
|
77
|
+
logger.info(`[Messages] All accounts temporarily unavailable. Next possible reset: ${waitSeconds}s`);
|
|
78
|
+
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
79
|
+
}
|
|
76
80
|
}
|
|
77
81
|
|
|
78
|
-
const { account, waitMs } = rotator.selectAccount(upstreamModel);
|
|
79
|
-
|
|
80
82
|
if (!account) {
|
|
81
83
|
if (waitMs > 0) {
|
|
82
84
|
await sleep(waitMs);
|