fix: auth bypass, SPA serving, and provider improvements (#97)
* feat(chat): polish syntax highlighting and tool payload rendering (#94) * [verified] feat(chat): polish syntax highlighting and tool payload rendering * [verified] fix(chat): tighten large tool payload rendering * docs: update data volume path in Docker docs Align documentation with docker-compose.yml change: hermes-web-ui-data -> hermes-web-ui, /app/dist/data -> /root/.hermes-web-ui Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: bundle server build and restructure service modules - Add build-server.mjs script for standalone server compilation - Add logger service with structured output - Restructure auth, gateway-manager, hermes-cli, hermes services - Update docker-compose volume mount path - Update tsconfig and entry point for bundled server Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: separate controllers from routes and centralize route registration - Extract business logic from route handlers into controllers/ - Add centralized route registry in routes/index.ts with public/auth/protected layers - Replace global auth whitelist with sequential middleware registration - Extract shared helpers to services/config-helpers.ts - Allow custom provider name to be user-editable in ProviderFormModal - Deduplicate custom providers by poolKey instead of base_url in getAvailable Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: auth bypass via path case, SPA serving, and provider improvements - Fix auth bypass: path case-insensitive check for /api, /v1, /upload - Fix SPA returning 401: skip auth for non-API paths (static files) - Fix profile switch: use local loading state instead of shared store ref - Auto-append /v1 to base_url when fetching models (frontend + backend) - Guard .env writing to built-in providers only - Add builtin field to provider presets, enable base_url input in form - Print auth token to console on startup (pino only writes to file) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Zhicheng Han <43314240+hanzckernel@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
import { readFile, writeFile } from 'fs/promises'
|
||||
import { readFile, writeFile, mkdir } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { config } from '../config'
|
||||
import { homedir } from 'os'
|
||||
|
||||
// Token stored in project data directory
|
||||
const TOKEN_FILE = join(config.dataDir, '.token')
|
||||
const APP_HOME = join(homedir(), '.hermes-web-ui')
|
||||
const TOKEN_FILE = join(APP_HOME, '.token')
|
||||
|
||||
function generateToken(): string {
|
||||
return randomBytes(32).toString('hex')
|
||||
@@ -14,12 +14,10 @@ function generateToken(): string {
|
||||
* Get or create the auth token. Returns null if auth is disabled.
|
||||
*/
|
||||
export async function getToken(): Promise<string | null> {
|
||||
// Auth can be disabled via env var
|
||||
if (process.env.AUTH_DISABLED === '1' || process.env.AUTH_DISABLED === 'true') {
|
||||
return null
|
||||
}
|
||||
|
||||
// Custom token via env var
|
||||
if (process.env.AUTH_TOKEN) {
|
||||
return process.env.AUTH_TOKEN
|
||||
}
|
||||
@@ -28,41 +26,36 @@ export async function getToken(): Promise<string | null> {
|
||||
const token = await readFile(TOKEN_FILE, 'utf-8')
|
||||
return token.trim()
|
||||
} catch {
|
||||
// Generate a new token
|
||||
const token = generateToken()
|
||||
await mkdir(APP_HOME, { recursive: true })
|
||||
await writeFile(TOKEN_FILE, token + '\n', { mode: 0o600 })
|
||||
return token
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Koa middleware: check Authorization header for API routes.
|
||||
* Skips /health, /webhook, and static file requests.
|
||||
* Koa middleware: check Authorization header or query token.
|
||||
* No path whitelisting — applied globally after public routes.
|
||||
*/
|
||||
export async function authMiddleware(token: string | null) {
|
||||
export function requireAuth(token: string | null) {
|
||||
return async (ctx: any, next: () => Promise<void>) => {
|
||||
// If auth is disabled, skip
|
||||
if (!token) {
|
||||
await next()
|
||||
return
|
||||
}
|
||||
|
||||
// Skip non-API paths (static files, health check, SPA)
|
||||
const path = ctx.path.toLowerCase()
|
||||
if (
|
||||
path === '/health' ||
|
||||
(!path.startsWith('/api') && !path.startsWith('/v1') && path !== '/webhook' && path !== '/upload')
|
||||
) {
|
||||
await next()
|
||||
return
|
||||
}
|
||||
|
||||
const auth = ctx.headers.authorization || ''
|
||||
const provided = auth.startsWith('Bearer ')
|
||||
? auth.slice(7)
|
||||
: (ctx.query.token as string) || ''
|
||||
|
||||
if (!provided || provided !== token) {
|
||||
// Skip auth for non-API paths (SPA static files)
|
||||
const lowerPath = ctx.path.toLowerCase()
|
||||
if (!lowerPath.startsWith('/api') && !lowerPath.startsWith('/v1') && !lowerPath.startsWith('/upload')) {
|
||||
await next()
|
||||
return
|
||||
}
|
||||
ctx.status = 401
|
||||
ctx.set('Content-Type', 'application/json')
|
||||
ctx.body = { error: 'Unauthorized' }
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import { readFile, writeFile, copyFile, chmod } from 'fs/promises'
|
||||
import { readdir, stat } from 'fs/promises'
|
||||
import { existsSync, readFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import YAML from 'js-yaml'
|
||||
import { getActiveProfileDir, getActiveConfigPath, getActiveEnvPath, getActiveAuthPath } from './hermes/hermes-profile'
|
||||
import { logger } from './logger'
|
||||
|
||||
// --- Provider env var mapping (from hermes providers.py HERMES_OVERLAYS + config.py) ---
|
||||
export const PROVIDER_ENV_MAP: Record<string, { api_key_env: string; base_url_env: string }> = {
|
||||
openrouter: { api_key_env: 'OPENROUTER_API_KEY', base_url_env: '' },
|
||||
zai: { api_key_env: 'GLM_API_KEY', base_url_env: '' },
|
||||
'kimi-coding-cn': { api_key_env: 'KIMI_CN_API_KEY', base_url_env: '' },
|
||||
moonshot: { api_key_env: 'MOONSHOT_API_KEY', base_url_env: '' },
|
||||
minimax: { api_key_env: 'MINIMAX_API_KEY', base_url_env: '' },
|
||||
'minimax-cn': { api_key_env: 'MINIMAX_CN_API_KEY', base_url_env: '' },
|
||||
deepseek: { api_key_env: 'DEEPSEEK_API_KEY', base_url_env: '' },
|
||||
alibaba: { api_key_env: 'DASHSCOPE_API_KEY', base_url_env: '' },
|
||||
anthropic: { api_key_env: 'ANTHROPIC_API_KEY', base_url_env: '' },
|
||||
xai: { api_key_env: 'XAI_API_KEY', base_url_env: '' },
|
||||
xiaomi: { api_key_env: 'XIAOMI_API_KEY', base_url_env: '' },
|
||||
gemini: { api_key_env: 'GEMINI_API_KEY', base_url_env: '' },
|
||||
kilocode: { api_key_env: 'KILO_API_KEY', base_url_env: '' },
|
||||
'ai-gateway': { api_key_env: 'AI_GATEWAY_API_KEY', base_url_env: '' },
|
||||
'opencode-zen': { api_key_env: 'OPENCODE_API_KEY', base_url_env: '' },
|
||||
'opencode-go': { api_key_env: 'OPENCODE_API_KEY', base_url_env: '' },
|
||||
huggingface: { api_key_env: 'HF_TOKEN', base_url_env: '' },
|
||||
arcee: { api_key_env: 'ARCEE_API_KEY', base_url_env: '' },
|
||||
'openai-codex': { api_key_env: '', base_url_env: '' },
|
||||
}
|
||||
|
||||
// --- Types ---
|
||||
|
||||
export interface SkillInfo {
|
||||
name: string
|
||||
description: string
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export interface SkillCategory {
|
||||
name: string
|
||||
description: string
|
||||
skills: SkillInfo[]
|
||||
}
|
||||
|
||||
export interface ModelInfo {
|
||||
id: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface ModelGroup {
|
||||
provider: string
|
||||
models: ModelInfo[]
|
||||
}
|
||||
|
||||
// --- Config YAML helpers ---
|
||||
|
||||
const configPath = () => getActiveConfigPath()
|
||||
|
||||
export async function readConfigYaml(): Promise<Record<string, any>> {
|
||||
const raw = await safeReadFile(configPath())
|
||||
if (!raw) return {}
|
||||
return (YAML.load(raw) as Record<string, any>) || {}
|
||||
}
|
||||
|
||||
export async function writeConfigYaml(config: Record<string, any>): Promise<void> {
|
||||
const cp = configPath()
|
||||
await copyFile(cp, cp + '.bak')
|
||||
const yamlStr = YAML.dump(config, {
|
||||
lineWidth: -1,
|
||||
noRefs: true,
|
||||
quotingType: '"',
|
||||
})
|
||||
await writeFile(cp, yamlStr, 'utf-8')
|
||||
}
|
||||
|
||||
// --- .env helpers ---
|
||||
|
||||
export async function saveEnvValue(key: string, value: string): Promise<void> {
|
||||
const envPath = getActiveEnvPath()
|
||||
let raw: string
|
||||
try {
|
||||
raw = await readFile(envPath, 'utf-8')
|
||||
} catch {
|
||||
raw = ''
|
||||
}
|
||||
const remove = !value
|
||||
const lines = raw.split('\n')
|
||||
let found = false
|
||||
const result: string[] = []
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (trimmed.startsWith('#') && trimmed.startsWith(`# ${key}=`)) {
|
||||
if (!remove) result.push(`${key}=${value}`)
|
||||
found = true
|
||||
} else {
|
||||
const eqIdx = trimmed.indexOf('=')
|
||||
if (eqIdx !== -1 && trimmed.slice(0, eqIdx).trim() === key) {
|
||||
if (!remove) result.push(`${key}=${value}`)
|
||||
found = true
|
||||
} else {
|
||||
result.push(line)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found && !remove) {
|
||||
result.push(`${key}=${value}`)
|
||||
}
|
||||
let output = result.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\n+$/, '') + '\n'
|
||||
await writeFile(envPath, output, 'utf-8')
|
||||
try { await chmod(envPath, 0o600) } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// --- File helpers ---
|
||||
|
||||
export async function safeReadFile(filePath: string): Promise<string | null> {
|
||||
try {
|
||||
return await readFile(filePath, 'utf-8')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function safeStat(filePath: string): Promise<{ mtime: number } | null> {
|
||||
try {
|
||||
const s = await stat(filePath)
|
||||
return { mtime: Math.round(s.mtimeMs) }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// --- Skill helpers ---
|
||||
|
||||
export function extractDescription(content: string): string {
|
||||
const lines = content.split('\n')
|
||||
let inFrontmatter = false
|
||||
let bodyStarted = false
|
||||
|
||||
for (const line of lines) {
|
||||
if (!bodyStarted && line.trim() === '---') {
|
||||
if (!inFrontmatter) {
|
||||
inFrontmatter = true
|
||||
continue
|
||||
} else {
|
||||
inFrontmatter = false
|
||||
bodyStarted = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (inFrontmatter) continue
|
||||
if (line.trim() === '') continue
|
||||
if (line.startsWith('#')) continue
|
||||
return line.trim().slice(0, 80)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export async function listFilesRecursive(dir: string, prefix: string): Promise<{ path: string; name: string }[]> {
|
||||
const result: { path: string; name: string }[] = []
|
||||
let entries
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true })
|
||||
} catch {
|
||||
return result
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const relPath = prefix ? `${prefix}/${entry.name}` : entry.name
|
||||
if (entry.isDirectory()) {
|
||||
result.push(...await listFilesRecursive(join(dir, entry.name), relPath))
|
||||
} else {
|
||||
result.push({ path: relPath, name: entry.name })
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// --- Provider model helpers ---
|
||||
|
||||
export async function fetchProviderModels(baseUrl: string, apiKey: string): Promise<string[]> {
|
||||
const base = baseUrl.replace(/\/+$/, '')
|
||||
const modelsUrl = base.endsWith('/v1') ? `${base}/models` : `${base}/v1/models`
|
||||
try {
|
||||
const res = await fetch(modelsUrl, {
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
signal: AbortSignal.timeout(8000),
|
||||
})
|
||||
if (!res.ok) {
|
||||
logger.warn('available-models %s returned %d', modelsUrl, res.status)
|
||||
return []
|
||||
}
|
||||
const data = await res.json() as { data?: Array<{ id: string }> }
|
||||
if (!Array.isArray(data.data)) {
|
||||
logger.warn('available-models %s returned unexpected format', modelsUrl)
|
||||
return []
|
||||
}
|
||||
return data.data.map(m => m.id).sort()
|
||||
} catch (err: any) {
|
||||
logger.error(err, 'available-models %s failed', modelsUrl)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function buildModelGroups(config: Record<string, any>): { default: string; groups: ModelGroup[] } {
|
||||
let defaultModel = ''
|
||||
const groups: ModelGroup[] = []
|
||||
|
||||
// 1. Extract current model
|
||||
const modelSection = config.model
|
||||
if (typeof modelSection === 'object' && modelSection !== null) {
|
||||
defaultModel = String(modelSection.default || '').trim()
|
||||
} else if (typeof modelSection === 'string') {
|
||||
defaultModel = modelSection.trim()
|
||||
}
|
||||
|
||||
// 2. Extract custom_providers section
|
||||
const customProviders = config.custom_providers
|
||||
if (Array.isArray(customProviders)) {
|
||||
const customModels: ModelInfo[] = []
|
||||
for (const entry of customProviders) {
|
||||
if (entry && typeof entry === 'object') {
|
||||
const cName = String(entry.name || '').trim()
|
||||
const cModel = String(entry.model || '').trim()
|
||||
if (cName && cModel) {
|
||||
customModels.push({ id: cModel, label: `${cName}: ${cModel}` })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (customModels.length > 0) {
|
||||
groups.push({ provider: 'Custom', models: customModels })
|
||||
}
|
||||
}
|
||||
|
||||
return { default: defaultModel, groups }
|
||||
}
|
||||
|
||||
// --- Profile directory helper ---
|
||||
|
||||
export const getHermesDir = () => getActiveProfileDir()
|
||||
@@ -7,12 +7,10 @@ export function getGatewayManagerInstance(): any {
|
||||
export async function initGatewayManager(): Promise<void> {
|
||||
const { GatewayManager } = await import('./hermes/gateway-manager')
|
||||
const { getActiveProfileName } = await import('./hermes/hermes-profile')
|
||||
const { setGatewayManager } = await import('../routes/hermes/gateways')
|
||||
|
||||
const activeProfile = getActiveProfileName()
|
||||
gatewayManager = new GatewayManager(activeProfile)
|
||||
setGatewayManager(gatewayManager)
|
||||
|
||||
await gatewayManager.detectAllOnStartup()
|
||||
await gatewayManager.startAll()
|
||||
console.log("startall")
|
||||
}
|
||||
|
||||
@@ -33,10 +33,12 @@
|
||||
import { spawn, type ChildProcess } from 'child_process'
|
||||
import { resolve, join } from 'path'
|
||||
import { homedir } from 'os'
|
||||
import { readFileSync, writeFileSync, existsSync } from 'fs'
|
||||
import { readFileSync, writeFileSync, existsSync, readdirSync } from 'fs'
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { createServer } from 'net'
|
||||
import yaml from 'js-yaml'
|
||||
import { logger } from '../logger'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -48,7 +50,7 @@ const HERMES_BASE = resolve(homedir(), '.hermes')
|
||||
const HERMES_BIN = process.env.HERMES_BIN?.trim() || 'hermes'
|
||||
|
||||
// WSL / Docker 没有 systemd 或 launchd,需要用 "gateway run" 代替 "gateway start"
|
||||
const isWsl = existsSync('/proc/version') && require('fs').readFileSync('/proc/version', 'utf-8').toLowerCase().includes('microsoft')
|
||||
const isWsl = existsSync('/proc/version') && readFileSync('/proc/version', 'utf-8').toLowerCase().includes('microsoft')
|
||||
const isDocker = existsSync('/.dockerenv')
|
||||
const needsRunMode = isWsl || isDocker
|
||||
|
||||
@@ -110,7 +112,6 @@ export class GatewayManager {
|
||||
if (!existsSync(configPath)) return { port: 8642, host: '127.0.0.1' }
|
||||
|
||||
try {
|
||||
const yaml = require('js-yaml')
|
||||
const content = readFileSync(configPath, 'utf-8')
|
||||
const cfg = yaml.load(content) as any || {}
|
||||
|
||||
@@ -225,7 +226,6 @@ export class GatewayManager {
|
||||
private writeProfilePort(name: string, port: number, host: string): void {
|
||||
const configPath = join(this.profileDir(name), 'config.yaml')
|
||||
try {
|
||||
const yaml = require('js-yaml')
|
||||
const content = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : ''
|
||||
const cfg = (yaml.load(content) as any) || {}
|
||||
|
||||
@@ -248,9 +248,9 @@ export class GatewayManager {
|
||||
}
|
||||
|
||||
writeFileSync(configPath, yaml.dump(cfg, { lineWidth: -1 }), 'utf-8')
|
||||
console.log(`[GatewayManager] Updated ${configPath}: api_server.extra.port = ${port}`)
|
||||
logger.debug('Updated %s: api_server.extra.port = %d', configPath, port)
|
||||
} catch (err) {
|
||||
console.error(`[GatewayManager] Failed to write config for profile "${name}":`, err)
|
||||
logger.error(err, 'Failed to write config for profile "%s"', name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,7 +280,7 @@ export class GatewayManager {
|
||||
if (usedPorts.has(port)) {
|
||||
// 已管理端口冲突 → 找空闲端口
|
||||
const newPort = await this.findFreePort(port, host)
|
||||
console.log(`[GatewayManager] Port ${port} is in use for profile "${name}", reassigning to ${newPort}`)
|
||||
logger.info('Port %d is in use for profile "%s", reassigning to %d', port, name, newPort)
|
||||
this.writeProfilePort(name, newPort, host)
|
||||
port = newPort
|
||||
} else {
|
||||
@@ -288,7 +288,7 @@ export class GatewayManager {
|
||||
const available = await this.checkPortAvailable(port, host)
|
||||
if (!available) {
|
||||
const newPort = await this.findFreePort(port, host)
|
||||
console.log(`[GatewayManager] Port ${port} is occupied by another process for profile "${name}", reassigning to ${newPort}`)
|
||||
logger.info('Port %d is occupied by another process for profile "%s", reassigning to %d', port, name, newPort)
|
||||
this.writeProfilePort(name, newPort, host)
|
||||
port = newPort
|
||||
} else {
|
||||
@@ -354,7 +354,6 @@ export class GatewayManager {
|
||||
// CLI 不可用时回退到文件系统扫描
|
||||
const profiles = ['default']
|
||||
const profilesDir = join(HERMES_BASE, 'profiles')
|
||||
const { existsSync, readdirSync } = require('fs')
|
||||
if (existsSync(profilesDir)) {
|
||||
for (const entry of readdirSync(profilesDir, { withFileTypes: true })) {
|
||||
if (entry.isDirectory() && existsSync(join(profilesDir, entry.name, 'config.yaml'))) {
|
||||
@@ -423,7 +422,7 @@ export class GatewayManager {
|
||||
child.unref()
|
||||
|
||||
const pid = child.pid ?? 0
|
||||
console.log(`[GatewayManager] Starting gateway for profile "${name}" (run mode, PID: ${pid}, port: ${port})`)
|
||||
logger.info('Starting gateway for profile "%s" (run mode, PID: %d, port: %d)', name, pid, port)
|
||||
|
||||
this.waitForReady(name, pid, port, host, url)
|
||||
.then(resolve)
|
||||
@@ -432,7 +431,7 @@ export class GatewayManager {
|
||||
}
|
||||
|
||||
// 正常系统:先 start,失败则 restart(处理服务已运行的情况)
|
||||
console.log(`[GatewayManager] Starting gateway for profile "${name}" (start mode, port: ${port})`)
|
||||
logger.info('Starting gateway for profile "%s" (start mode, port: %d)', name, port)
|
||||
const env = { ...process.env, HERMES_HOME: hermesHome }
|
||||
try {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, ['gateway', 'start'], {
|
||||
@@ -440,7 +439,7 @@ export class GatewayManager {
|
||||
env,
|
||||
windowsHide: true,
|
||||
})
|
||||
console.log(`[GatewayManager] gateway start output: ${stdout?.trim()}`)
|
||||
logger.debug('gateway start output: %s', stdout?.trim())
|
||||
} catch {
|
||||
// start 失败(可能服务已运行),用 restart
|
||||
try {
|
||||
@@ -449,9 +448,9 @@ export class GatewayManager {
|
||||
env,
|
||||
windowsHide: true,
|
||||
})
|
||||
console.log(`[GatewayManager] gateway restart output: ${stdout?.trim()}`)
|
||||
logger.debug('gateway restart output: %s', stdout?.trim())
|
||||
} catch (err: any) {
|
||||
console.log(`[GatewayManager] gateway start/restart (non-fatal): ${err.stderr?.trim() || err.message}`)
|
||||
logger.warn(err, 'gateway start/restart (non-fatal)')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,14 +517,14 @@ export class GatewayManager {
|
||||
while (Date.now() < deadline) {
|
||||
if (!(await this.checkHealth(url, 1000))) {
|
||||
this.gateways.delete(name)
|
||||
console.log(`[GatewayManager] Stopped gateway for profile "${name}"`)
|
||||
logger.info('Stopped gateway for profile "%s"', name)
|
||||
return
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 300))
|
||||
}
|
||||
// 超时也清理
|
||||
this.gateways.delete(name)
|
||||
console.log(`[GatewayManager] Stopped gateway for profile "${name}" (timeout)`)
|
||||
logger.warn('Stopped gateway for profile "%s" (timeout)', name)
|
||||
}
|
||||
|
||||
/** 停止所有已管理的网关(并行执行) */
|
||||
@@ -540,15 +539,15 @@ export class GatewayManager {
|
||||
|
||||
/** 扫描所有 profile,检测网关运行状态并注册 */
|
||||
async detectAllOnStartup(): Promise<void> {
|
||||
console.log('[GatewayManager] Scanning profiles for running gateways...')
|
||||
logger.info('Scanning profiles for running gateways...')
|
||||
const profiles = await this.listProfiles()
|
||||
|
||||
for (const name of profiles) {
|
||||
const status = await this.detectStatus(name)
|
||||
if (status.running) {
|
||||
console.log(`[GatewayManager] ✓ ${name}: running (PID: ${status.pid}, port: ${status.port})`)
|
||||
logger.info('%s: running (PID: %s, port: %d)', name, status.pid, status.port)
|
||||
} else {
|
||||
console.log(`[GatewayManager] ○ ${name}: stopped`)
|
||||
logger.debug('%s: stopped', name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -568,14 +567,14 @@ export class GatewayManager {
|
||||
for (const name of profiles) {
|
||||
const existing = this.gateways.get(name)
|
||||
if (existing && this.isProcessAlive(existing.pid)) {
|
||||
console.log(`[GatewayManager] ${name}: already running (PID: ${existing.pid})`)
|
||||
logger.info('%s: already running (PID: %d)', name, existing.pid)
|
||||
continue
|
||||
}
|
||||
|
||||
// 有 PID 文件但进程未在正确端口运行 → 旧进程,先停掉
|
||||
const pid = this.readPidFile(name)
|
||||
if (pid && this.isProcessAlive(pid)) {
|
||||
console.log(`[GatewayManager] ${name}: stale process (PID: ${pid}), stopping`)
|
||||
logger.info('%s: stale process (PID: %d), stopping', name, pid)
|
||||
try { await this.stop(name) } catch { }
|
||||
}
|
||||
|
||||
@@ -588,7 +587,7 @@ export class GatewayManager {
|
||||
try {
|
||||
await this.start(name)
|
||||
} catch (err: any) {
|
||||
console.error(`[GatewayManager] ✗ ${name}: failed to start — ${err.message}`)
|
||||
logger.error(err, '%s: failed to start', name)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { execFile, spawn } from 'child_process'
|
||||
import { existsSync } from 'fs'
|
||||
import { promisify } from 'util'
|
||||
import { logger } from '../logger'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -126,7 +127,7 @@ export async function listSessions(source?: string, limit?: number): Promise<Her
|
||||
}
|
||||
return sessions
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] sessions export failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: sessions export failed')
|
||||
throw new Error(`Failed to list sessions: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -174,7 +175,7 @@ export async function getSession(id: string): Promise<HermesSession | null> {
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (err.code === 1 || err.status === 1) return null
|
||||
console.error('[Hermes CLI] session export failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: session export failed')
|
||||
throw new Error(`Failed to get session: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -190,7 +191,7 @@ export async function deleteSession(id: string): Promise<boolean> {
|
||||
})
|
||||
return true
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] session delete failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: session delete failed')
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -206,7 +207,7 @@ export async function renameSession(id: string, title: string): Promise<boolean>
|
||||
})
|
||||
return true
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] session rename failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: session rename failed')
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -250,7 +251,6 @@ export async function startGateway(): Promise<string> {
|
||||
* Uses "hermes gateway run" as a detached background process
|
||||
*/
|
||||
export async function startGatewayBackground(): Promise<number | null> {
|
||||
const { spawn } = require('child_process') as typeof import('child_process')
|
||||
const child = spawn(HERMES_BIN, ['gateway', 'run'], {
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
@@ -311,7 +311,7 @@ export async function listLogFiles(): Promise<LogFileInfo[]> {
|
||||
}
|
||||
return files
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] logs list failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: logs list failed')
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -339,7 +339,7 @@ export async function readLogs(
|
||||
})
|
||||
return stdout
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] logs read failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: logs read failed')
|
||||
throw new Error(`Failed to read logs: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -396,7 +396,7 @@ export async function listProfiles(): Promise<HermesProfile[]> {
|
||||
|
||||
return profiles
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] profile list failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile list failed')
|
||||
throw new Error(`Failed to list profiles: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -437,7 +437,7 @@ export async function getProfile(name: string): Promise<HermesProfileDetail> {
|
||||
if (err.code === 1 || err.status === 1) {
|
||||
throw new Error(`Profile "${name}" not found`)
|
||||
}
|
||||
console.error('[Hermes CLI] profile show failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile show failed')
|
||||
throw new Error(`Failed to get profile: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -456,7 +456,7 @@ export async function createProfile(name: string, clone?: boolean): Promise<stri
|
||||
})
|
||||
return stdout || stderr
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] profile create failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile create failed')
|
||||
throw new Error(`Failed to create profile: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -472,7 +472,7 @@ export async function deleteProfile(name: string): Promise<boolean> {
|
||||
})
|
||||
return true
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] profile delete failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile delete failed')
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -488,7 +488,7 @@ export async function renameProfile(oldName: string, newName: string): Promise<b
|
||||
})
|
||||
return true
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] profile rename failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile rename failed')
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -504,7 +504,7 @@ export async function useProfile(name: string): Promise<string> {
|
||||
})
|
||||
return stdout || stderr
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] profile use failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile use failed')
|
||||
throw new Error(`Failed to switch profile: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -523,7 +523,7 @@ export async function exportProfile(name: string, outputPath?: string): Promise<
|
||||
})
|
||||
return stdout || stderr
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] profile export failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile export failed')
|
||||
throw new Error(`Failed to export profile: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -539,7 +539,7 @@ export async function setupReset(): Promise<string> {
|
||||
})
|
||||
return stdout || stderr
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] setup reset failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: setup reset failed')
|
||||
throw new Error(`Failed to reset config: ${err.message}`)
|
||||
}
|
||||
}
|
||||
@@ -558,7 +558,7 @@ export async function importProfile(archivePath: string, name?: string): Promise
|
||||
})
|
||||
return stdout || stderr
|
||||
} catch (err: any) {
|
||||
console.error('[Hermes CLI] profile import failed:', err.message)
|
||||
logger.error(err, 'Hermes CLI: profile import failed')
|
||||
throw new Error(`Failed to import profile: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { config } from '../../config'
|
||||
import { logger } from '../logger'
|
||||
|
||||
const UPSTREAM = config.upstream.replace(/\/$/, '')
|
||||
|
||||
@@ -121,7 +122,7 @@ export function emitWebhook(payload: any) {
|
||||
for (const cb of webhookCallbacks) {
|
||||
const result = cb(payload)
|
||||
if (result && typeof result.catch === 'function') {
|
||||
result.catch((err: Error) => console.error('Webhook callback error:', err))
|
||||
result.catch((err: Error) => logger.error(err, 'Webhook callback error'))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import pino from 'pino'
|
||||
import { resolve } from 'path'
|
||||
import { mkdirSync, statSync, truncateSync, openSync, readSync, closeSync, writeFileSync } from 'fs'
|
||||
import { homedir } from 'os'
|
||||
|
||||
const MAX_LOG_SIZE = 3 * 1024 * 1024 // 3MB
|
||||
|
||||
const logDir = resolve(homedir(), '.hermes-web-ui', 'logs')
|
||||
mkdirSync(logDir, { recursive: true })
|
||||
|
||||
const logFile = resolve(logDir, 'server.log')
|
||||
|
||||
// Rotate log if it exceeds MAX_LOG_SIZE — truncate to keep the last half
|
||||
try {
|
||||
const stat = statSync(logFile)
|
||||
if (stat.size > MAX_LOG_SIZE) {
|
||||
const keepSize = Math.floor(MAX_LOG_SIZE / 2)
|
||||
const fd = openSync(logFile, 'r')
|
||||
const buf = Buffer.alloc(keepSize)
|
||||
readSync(fd, buf, 0, keepSize, stat.size - keepSize)
|
||||
closeSync(fd)
|
||||
truncateSync(logFile, 0)
|
||||
writeFileSync(logFile, buf)
|
||||
}
|
||||
} catch {}
|
||||
|
||||
export const logger = pino({
|
||||
level: process.env.LOG_LEVEL || 'info',
|
||||
}, pino.destination({
|
||||
dest: logFile,
|
||||
sync: false,
|
||||
}))
|
||||
@@ -1,3 +1,5 @@
|
||||
import { logger } from './logger'
|
||||
|
||||
export function bindShutdown(server: any): void {
|
||||
let isShuttingDown = false
|
||||
|
||||
@@ -5,19 +7,19 @@ export function bindShutdown(server: any): void {
|
||||
if (isShuttingDown) return
|
||||
isShuttingDown = true
|
||||
|
||||
console.log(`\n[${signal}] shutting down...`)
|
||||
logger.info('Shutting down (%s)...', signal)
|
||||
|
||||
try {
|
||||
if (server) {
|
||||
await new Promise<void>((resolve) => {
|
||||
server.close(() => {
|
||||
console.log('✓ http server closed')
|
||||
logger.info('HTTP server closed')
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('shutdown error:', err)
|
||||
logger.error(err, 'Shutdown error')
|
||||
}
|
||||
|
||||
process.exit(0)
|
||||
@@ -26,14 +28,4 @@ export function bindShutdown(server: any): void {
|
||||
process.once('SIGUSR2', shutdown)
|
||||
process.on('SIGINT', shutdown)
|
||||
process.on('SIGTERM', shutdown)
|
||||
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('uncaughtException:', err)
|
||||
shutdown('uncaughtException')
|
||||
})
|
||||
|
||||
process.on('unhandledRejection', (err) => {
|
||||
console.error('unhandledRejection:', err)
|
||||
shutdown('unhandledRejection')
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user