claude-codex-proxy 1.0.5-beta.11 → 1.0.5-beta.12
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 +18 -14
- package/src/admin-path.js +33 -0
- package/src/index.js +13 -4
- package/src/routes/api-routes.js +52 -43
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,
|
|
@@ -23,10 +26,10 @@ document.addEventListener('alpine:init', () => {
|
|
|
23
26
|
await this.checkHealth();
|
|
24
27
|
this.authChecked = true;
|
|
25
28
|
if (this.isLoginPage()) {
|
|
26
|
-
if (this.isAuthenticated) window.location.replace('/dashboard');
|
|
29
|
+
if (this.isAuthenticated) window.location.replace(adminUrl('/dashboard'));
|
|
27
30
|
return;
|
|
28
31
|
}
|
|
29
|
-
if (!this.isAuthenticated) { window.location.replace('/login'); return; }
|
|
32
|
+
if (!this.isAuthenticated) { window.location.replace(adminUrl('/login')); return; }
|
|
30
33
|
await this.loadCurrentView();
|
|
31
34
|
this.updateTime();
|
|
32
35
|
setInterval(() => this.updateTime(), 1000);
|
|
@@ -35,18 +38,18 @@ document.addEventListener('alpine:init', () => {
|
|
|
35
38
|
window.addEventListener('message', event => { if (event.data?.type === 'oauth-success') { this.showToast(`Account ${event.data.email} added!`, 'success'); this.showAddModal = false; this.refreshAccounts(); } });
|
|
36
39
|
},
|
|
37
40
|
|
|
38
|
-
isLoginPage() { return window.location.pathname === '/login' || window.location.pathname === '/login.html'; },
|
|
41
|
+
isLoginPage() { return window.location.pathname === adminUrl('/login') || window.location.pathname === adminUrl('/login.html'); },
|
|
39
42
|
async loadCurrentView() {
|
|
40
|
-
const route = window.location.pathname.replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
|
|
43
|
+
const route = window.location.pathname.slice(adminPath.length).replace(/^\//, '').replace(/\.html$/, '') || 'dashboard';
|
|
41
44
|
const tab = route === 'account-management' ? 'accounts' : route;
|
|
42
45
|
const validTabs = ['dashboard', 'accounts', 'logs', 'client-api-keys', 'settings'];
|
|
43
46
|
this.activeTab = validTabs.includes(tab) ? tab : 'dashboard';
|
|
44
|
-
if (this.activeTab !== tab) { window.location.replace('/dashboard'); return; }
|
|
47
|
+
if (this.activeTab !== tab) { window.location.replace(adminUrl('/dashboard')); return; }
|
|
45
48
|
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')
|
|
49
|
+
fetch(adminUrl(`/views/${this.activeTab}.html`)),
|
|
50
|
+
fetch(adminUrl(this.activeTab === 'accounts' ? '/views/accounts-modals.html' : this.activeTab === 'client-api-keys' ? '/views/client-api-keys-modals.html' : '/views/empty.html'))
|
|
48
51
|
]);
|
|
49
|
-
if (!viewResponse.ok) { window.location.replace('/dashboard'); return; }
|
|
52
|
+
if (!viewResponse.ok) { window.location.replace(adminUrl('/dashboard')); return; }
|
|
50
53
|
document.querySelector('#view-content').innerHTML = await viewResponse.text();
|
|
51
54
|
document.querySelector('#modal-content').innerHTML = modalResponse.ok ? await modalResponse.text() : '';
|
|
52
55
|
Alpine.initTree(document.querySelector('#view-content'));
|
|
@@ -67,7 +70,8 @@ document.addEventListener('alpine:init', () => {
|
|
|
67
70
|
try {
|
|
68
71
|
const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
|
|
69
72
|
if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
|
|
70
|
-
const
|
|
73
|
+
const url = endpoint.startsWith('/v1/') ? endpoint : adminUrl(endpoint);
|
|
74
|
+
const response = await fetch(url, { ...options, headers });
|
|
71
75
|
const data = await response.json();
|
|
72
76
|
if (response.status === 401 && endpoint !== '/health') this.logout(false);
|
|
73
77
|
return { ok: response.ok, data };
|
|
@@ -80,10 +84,10 @@ document.addEventListener('alpine:init', () => {
|
|
|
80
84
|
const { ok } = await this.api('/settings/account-strategy');
|
|
81
85
|
if (!ok) { this.apiKey = ''; this.loginError = 'Access key is invalid or expired'; return; }
|
|
82
86
|
localStorage.setItem('codexProxyApiKey', key);
|
|
83
|
-
window.location.replace('/dashboard');
|
|
87
|
+
window.location.replace(adminUrl('/dashboard'));
|
|
84
88
|
},
|
|
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() {
|
|
89
|
+
logout(showMessage = true) { this.apiKey = ''; this.loginApiKey = ''; localStorage.removeItem('codexProxyApiKey'); this.logEventSource?.close(); this.logEventSource = null; if (showMessage) window.location.replace(adminUrl('/login')); },
|
|
90
|
+
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
91
|
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
92
|
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
93
|
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)))); },
|
|
@@ -115,8 +119,8 @@ document.addEventListener('alpine:init', () => {
|
|
|
115
119
|
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
120
|
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
121
|
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() {
|
|
122
|
+
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
123
|
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; }
|
|
124
|
+
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
125
|
}));
|
|
122
126
|
});
|
|
@@ -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
|
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';
|
|
@@ -54,17 +56,24 @@ const require = createRequire(import.meta.url);
|
|
|
54
56
|
const packageJson = require('../../package.json');
|
|
55
57
|
|
|
56
58
|
export function registerApiRoutes(app, { port }) {
|
|
57
|
-
|
|
59
|
+
const adminPath = getAdminPath();
|
|
58
60
|
const publicDirectory = join(__dirname, '..', '..', 'public');
|
|
59
|
-
|
|
61
|
+
const adminRouter = express.Router();
|
|
62
|
+
const sendAdminHtml = (fileName) => {
|
|
63
|
+
const html = readFileSync(join(publicDirectory, fileName), 'utf8')
|
|
64
|
+
.replace(/(href|src)="\//g, `$1="${adminPath}/`)
|
|
65
|
+
.replace('</head>', `<script>window.__PROXY_ADMIN_PATH__=${JSON.stringify(adminPath)};</script></head>`);
|
|
66
|
+
return (req, res) => res.type('html').send(html);
|
|
67
|
+
};
|
|
60
68
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
});
|
|
69
|
+
// ─── Static Web UI ─────────────────────────────────────────────────────────
|
|
70
|
+
adminRouter.use(express.static(publicDirectory, { index: false }));
|
|
64
71
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
72
|
+
adminRouter.get(['/', '/dashboard', '/account-management', '/logs', '/client-api-keys', '/settings'], sendAdminHtml('index.html'));
|
|
73
|
+
|
|
74
|
+
adminRouter.get('/login', sendAdminHtml('login.html'));
|
|
75
|
+
|
|
76
|
+
app.use(adminPath, adminRouter);
|
|
68
77
|
|
|
69
78
|
// ─── Health ────────────────────────────────────────────────────────────────
|
|
70
79
|
app.get('/health', (req, res) => {
|
|
@@ -95,50 +104,50 @@ export function registerApiRoutes(app, { port }) {
|
|
|
95
104
|
app.get('/v1/models', requireClientAuth, handleListModels);
|
|
96
105
|
app.get('/v1/usage', requireClientAuth, handleGetClientQuota);
|
|
97
106
|
|
|
98
|
-
|
|
107
|
+
adminRouter.use(requireAdminAuth);
|
|
99
108
|
|
|
100
|
-
|
|
101
|
-
|
|
109
|
+
adminRouter.get('/accounts/models', handleAccountModels);
|
|
110
|
+
adminRouter.get('/accounts/usage', handleAccountUsage);
|
|
102
111
|
|
|
103
112
|
// ─── Settings ──────────────────────────────────────────────────────────────
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
113
|
+
adminRouter.get('/settings/account-strategy', handleGetAccountStrategy);
|
|
114
|
+
adminRouter.post('/settings/account-strategy', handleSetAccountStrategy);
|
|
115
|
+
adminRouter.get('/settings/model-map', handleGetModelMap);
|
|
116
|
+
adminRouter.post('/settings/model-map', handleSetModelMap);
|
|
117
|
+
adminRouter.get('/settings/raw-proxy-logs', handleGetRawProxyLogs);
|
|
118
|
+
adminRouter.post('/settings/raw-proxy-logs', handleSetRawProxyLogs);
|
|
119
|
+
adminRouter.get('/settings/client-api-keys', handleListClientApiKeys);
|
|
120
|
+
adminRouter.post('/settings/client-api-keys', handleCreateClientApiKey);
|
|
121
|
+
adminRouter.put('/settings/client-api-keys/:id', handleUpdateClientApiKey);
|
|
122
|
+
adminRouter.delete('/settings/client-api-keys/:id', handleDeleteClientApiKey);
|
|
114
123
|
|
|
115
124
|
// ─── Account Management ───────────────────────────────────────────────────
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
125
|
+
adminRouter.get('/accounts', handleListAccounts);
|
|
126
|
+
adminRouter.get('/accounts/status', handleAccountStatus);
|
|
127
|
+
adminRouter.get('/accounts/quota', handleGetQuota);
|
|
128
|
+
adminRouter.get('/accounts/quota/all', handleGetAllQuotas);
|
|
129
|
+
adminRouter.get('/accounts/rate-limit-reset-credits', handleGetRateLimitResetCredits);
|
|
130
|
+
adminRouter.post('/accounts/rate-limit-reset-credits/consume', handleConsumeRateLimitResetCredit);
|
|
131
|
+
|
|
132
|
+
adminRouter.post('/accounts/add', handleAddAccount);
|
|
133
|
+
adminRouter.post('/accounts/add/manual', handleAddAccountManual);
|
|
134
|
+
adminRouter.post('/accounts/switch', handleSwitchAccount);
|
|
135
|
+
adminRouter.post('/accounts/import', handleImportAccount);
|
|
136
|
+
adminRouter.post('/accounts/refresh', handleRefreshActiveAccount);
|
|
137
|
+
adminRouter.post('/accounts/refresh/all', handleRefreshAllAccounts);
|
|
138
|
+
adminRouter.post('/accounts/oauth/cleanup', handleOAuthCleanup);
|
|
139
|
+
adminRouter.post('/accounts/:email/refresh', handleRefreshAccount);
|
|
140
|
+
|
|
141
|
+
adminRouter.delete('/accounts/:email', handleRemoveAccount);
|
|
133
142
|
|
|
134
143
|
// ─── Claude CLI Configuration ──────────────────────────────────────────────
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
144
|
+
adminRouter.get('/claude/config', handleGetClaudeConfig);
|
|
145
|
+
adminRouter.post('/claude/config/direct', handleSetDirectMode);
|
|
146
|
+
adminRouter.post('/claude/config/set', handleSetClaudeApiEndpoint);
|
|
138
147
|
|
|
139
148
|
// ─── Logs ──────────────────────────────────────────────────────────────────
|
|
140
|
-
|
|
141
|
-
|
|
149
|
+
adminRouter.get('/api/logs', handleGetLogs);
|
|
150
|
+
adminRouter.get('/api/logs/stream', handleStreamLogs);
|
|
142
151
|
}
|
|
143
152
|
|
|
144
153
|
export default { registerApiRoutes };
|