import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; import type { HookManager, HookProcessInfo } from '@snowluma/bridge'; import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig } from '@snowluma/onebot/types'; import { randomBytes } from 'crypto'; import { existsSync, readFileSync } from 'fs'; import { createServer as createHttpsServer } from 'https'; import { Hono, type Context } from 'hono'; import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; import { resolveTlsContext } from './tls'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; import { clearBackgroundImage, loadUiConfig, MAX_BACKGROUND_BYTES, publicAppearance, readBackgroundImage, saveUiConfig, sniffImageMime, writeBackgroundImage, } from './ui-config'; import { getUpdateInfo } from './update-check'; import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config'; import type { NotificationManager } from '../notifications/manager'; const log = createLogger('WebUI'); const __dirname = path.dirname(fileURLToPath(import.meta.url)); interface SessionInfo { expiresAt: number; mustChangePassword: boolean; } const sessionTokens = new Map(); const loginAttempts = new Map(); const LOGIN_MAX_ATTEMPTS = 5; const LOGIN_LOCKOUT_MS = 15 * 60 * 1000; const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60; // Endpoints that an auth-required-but-must-change-password session can still hit. const MUST_CHANGE_ALLOWLIST = new Set([ '/api/status', '/api/auth/state', '/api/auth/check-strength', '/api/auth/change-password', '/api/logout', ]); // Endpoints that may authenticate via `?token=` query parameter. Only the // SSE log stream is here because EventSource cannot set custom headers; all // other endpoints MUST use the Authorization header so tokens never leak // into access logs / Referer / browser history. const TOKEN_QUERY_ALLOWLIST = new Set([ '/api/logs/stream', ]); // uin = QQ number; 5–12 digits. Used to construct config file paths, // so we MUST refuse anything else (path traversal, NUL bytes, etc.). const UIN_REGEX = /^\d{5,12}$/; const avatarCache = new Map(); function purgeExpiredTokens() { const now = Date.now(); for (const [token, info] of sessionTokens) { if (now > info.expiresAt) sessionTokens.delete(token); } for (const [ip, attempt] of loginAttempts) { if (now > attempt.resetAt) loginAttempts.delete(ip); } } async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> { const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, { headers: { 'User-Agent': 'SnowLuma WebUI', Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8', }, }); if (!response.ok) throw new Error(`avatar upstream responded with ${response.status}`); const contentType = response.headers.get('content-type') || 'image/jpeg'; const body = new Uint8Array(await response.arrayBuffer()); return { body, contentType }; } export async function initWebUI( desiredPort: number = 5099, oneBotManager: OneBotManager, hookManager?: HookManager, notificationManager?: NotificationManager, listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {}, ): Promise<{ port: number }> { // Resolve the client IP for per-IP rate limiting from the configured // trust-proxy directive (runtime.json `trustProxy`, env-overridable via // SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in). // Default ('') = trust the TCP socket peer only (cannot be spoofed). const trustProxyMode = parseTrustProxy(listener.trustProxy); const getClientIp = makeClientIpResolver(trustProxyMode); const auth = WebuiAuth.load(); const initialPassword = auth.takeInitialPassword(); if (auth.isDevMode()) { log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword); log.warn('dev mode skips config/webui.json and password rotation'); } else if (initialPassword) { log.info('════════════════════════════════════════════════════════════════'); log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★'); log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。'); log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。'); log.info(' Log in and change the password now; it will not be shown again.'); log.info('────────────────────────────────────────────────────────────────'); log.info('initial credentials: user=admin password=%s', initialPassword); log.info('════════════════════════════════════════════════════════════════'); } else if (auth.mustChangePassword()) { log.warn('password change is still required'); } log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode)); if (trustProxyMode.kind === 'all') { log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For'); } const app = new Hono(); // ─── Anti-indexing ─────────────────────────────────────────────────────── // The WebUI is an admin surface that has no business showing up in // search results — even the login page leaks the existence of a // SnowLuma instance to anyone scanning the IP. Three overlapping // signals: a hard X-Robots-Tag on every response, a robots.txt for // crawlers that read it before pages, and a in the // SPA shell for the case where a proxy strips headers. app.use('*', async (c, next) => { await next(); c.res.headers.set( 'X-Robots-Tag', 'noindex, nofollow, noarchive, nosnippet, noimageindex', ); }); app.get('/robots.txt', (c) => { c.res.headers.set('Content-Type', 'text/plain; charset=utf-8'); return c.body('User-agent: *\nDisallow: /\n'); }); // ─── Auth middleware ───────────────────────────────────────────────────── app.use('/api/*', async (c, next) => { const reqPath = c.req.path; // `/api/ui/public` serves the cosmetic appearance subset to the // pre-auth login page, so it must skip the bearer check. It exposes // nothing sensitive (no layout, no secrets) — see ui-config.ts. if (reqPath === '/api/login' || reqPath === '/api/ui/public') return next(); const authHeader = c.req.header('Authorization'); const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''; const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : ''; const token = bearerToken || queryToken; if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401); const info = sessionTokens.get(token); if (!info || Date.now() > info.expiresAt) { return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401); } if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) { return c.json({ status: 'failed', message: '请先修改密码', mustChangePassword: true }, 403); } c.set('sessionToken' as never, token); await next(); }); // Periodic janitor — keeps sessionTokens / loginAttempts from growing // unbounded and replaces the per-request O(n) sweep we used to do. const tokenJanitor = setInterval(purgeExpiredTokens, 60_000); tokenJanitor.unref?.(); // ─── Login ─────────────────────────────────────────────────────────────── app.post('/api/login', async (c) => { const ip = getClientIp(c); const now = Date.now(); const attempt = loginAttempts.get(ip); if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) { const waitSec = Math.ceil((attempt.resetAt - now) / 1000); return c.json({ success: false, message: `登录尝试过多,请 ${waitSec} 秒后重试` }, 429); } let body: { password?: unknown }; try { body = await c.req.json(); } catch { return c.json({ success: false, message: '请求格式错误' }, 400); } const password = typeof body.password === 'string' ? body.password : ''; if (!auth.verify(password)) { const current = loginAttempts.get(ip) ?? { count: 0, resetAt: now + LOGIN_LOCKOUT_MS }; current.count += 1; if (current.count === 1) current.resetAt = now + LOGIN_LOCKOUT_MS; loginAttempts.set(ip, current); return c.json({ success: false, message: '密码错误' }, 401); } loginAttempts.delete(ip); const token = randomBytes(32).toString('hex'); const mustChange = auth.mustChangePassword(); sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange }); return c.json({ success: true, token, mustChangePassword: mustChange }); }); app.post('/api/logout', (c) => { const token = c.get('sessionToken' as never) as string | undefined; if (token) sessionTokens.delete(token); return c.json({ success: true }); }); app.get('/api/auth/state', (c) => { const token = c.get('sessionToken' as never) as string | undefined; const info = token ? sessionTokens.get(token) : undefined; return c.json({ mustChangePassword: info?.mustChangePassword ?? auth.mustChangePassword(), }); }); app.post('/api/auth/check-strength', async (c) => { let body: { password?: unknown }; try { body = await c.req.json(); } catch { return c.json({ rules: evaluatePasswordRules(''), valid: false }); } const pwd = typeof body.password === 'string' ? body.password : ''; return c.json({ rules: evaluatePasswordRules(pwd), valid: isStrongPassword(pwd) }); }); app.post('/api/auth/change-password', async (c) => { let body: { oldPassword?: unknown; newPassword?: unknown }; try { body = await c.req.json(); } catch { return c.json({ success: false, message: '请求格式错误' }, 400); } const oldPassword = typeof body.oldPassword === 'string' ? body.oldPassword : ''; const newPassword = typeof body.newPassword === 'string' ? body.newPassword : ''; if (!auth.verify(oldPassword)) { return c.json({ success: false, message: '当前密码不正确' }, 401); } if (!isStrongPassword(newPassword)) { return c.json( { success: false, message: '新密码不符合强度要求', rules: evaluatePasswordRules(newPassword) }, 400, ); } if (oldPassword === newPassword) { return c.json({ success: false, message: '新密码不得与旧密码相同' }, 400); } try { auth.setPassword(newPassword); } catch (err) { log.warn('change password failed: %s', err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '密码修改失败' }, 400); } // Invalidate every session, including the current one. If the old // password was compromised, the attacker may already hold the current // token; rotating credentials must rotate sessions too. sessionTokens.clear(); log.info('password updated; all sessions invalidated'); return c.json({ success: true, requireRelogin: true }); }); // ─── Avatar proxy (uin validated) ──────────────────────────────────────── app.get('/avatar/:uin', async (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.text('invalid uin', 400); const now = Date.now(); let cached = avatarCache.get(uin); if (!cached || cached.expiresAt <= now) { try { const avatar = await fetchQqAvatar(uin); cached = { ...avatar, expiresAt: now + AVATAR_CACHE_TTL_MS }; avatarCache.set(uin, cached); } catch (err) { log.warn('failed to proxy avatar for UIN %s: %s', uin, err instanceof Error ? err.message : String(err)); if (!cached) return c.text('avatar unavailable', 502); } } return new Response(cached.body, { headers: { 'Content-Type': cached.contentType, 'Cache-Control': `public, max-age=${AVATAR_BROWSER_CACHE_SECONDS}, immutable`, }, }); }); // ─── Background image (unauth, like /avatar) ───────────────────────────── // The login page needs to render the operator's background before auth, so // this route is intentionally public. It only serves a file the operator // themselves uploaded. Cache-busting is via the `?v=` version the client // appends; the bytes for a given version are immutable. app.get('/ui-asset/background', (c) => { const asset = readBackgroundImage(); if (!asset) return c.text('no background', 404); return new Response(new Uint8Array(asset.bytes), { headers: { 'Content-Type': asset.mime, 'Cache-Control': 'public, max-age=31536000, immutable', // Defence-in-depth: never let an uploaded blob be interpreted as // anything but the sniffed image type. 'X-Content-Type-Options': 'nosniff', }, }); }); // ─── Read-only API ─────────────────────────────────────────────────────── app.get('/api/status', (c) => c.json({ status: 'running' })); // Advisory update check — compares the running build against the latest // GitHub stable release and links the user to it. Read-only: SnowLuma // never downloads or applies the update itself. `?force=1` bypasses the // server-side cache (the "立即检查" button). Never errors out — a failed // check returns `{ hasUpdate: false, error }` and the UI degrades quietly. app.get('/api/update/check', async (c) => { const force = c.req.query('force') === 'true' || c.req.query('force') === '1'; return c.json(await getUpdateInfo(force)); }); // Host system info let lastCpuTimes: { idle: number; total: number }[] | null = null; function sampleCpuLoad(): number[] { const cpus = os.cpus(); const current = cpus.map((cpu) => { const t = cpu.times; const total = t.user + t.nice + t.sys + t.idle + t.irq; return { idle: t.idle, total }; }); if (!lastCpuTimes || lastCpuTimes.length !== current.length) { lastCpuTimes = current; return current.map(() => 0); } const usage = current.map((cur, i) => { const prev = lastCpuTimes![i]; const totalDiff = cur.total - prev.total; const idleDiff = cur.idle - prev.idle; if (totalDiff <= 0) return 0; return Math.max(0, Math.min(100, ((totalDiff - idleDiff) / totalDiff) * 100)); }); lastCpuTimes = current; return usage; } app.get('/api/system', (c) => { const cpus = os.cpus(); const usage = sampleCpuLoad(); const totalMem = os.totalmem(); const freeMem = os.freemem(); const usedMem = totalMem - freeMem; const runtimeMemory = process.memoryUsage(); return c.json({ hostname: os.hostname(), platform: os.platform(), arch: os.arch(), release: os.release(), uptime: os.uptime(), processUptime: process.uptime(), nodeVersion: process.version, cpu: { model: cpus[0]?.model ?? 'unknown', cores: cpus.length, speedMHz: cpus[0]?.speed ?? 0, loadAvg: os.loadavg(), perCore: usage, average: usage.length ? usage.reduce((s, v) => s + v, 0) / usage.length : 0, }, memory: { total: totalMem, free: freeMem, used: usedMem, usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0, }, runtime: { pid: process.pid, rss: runtimeMemory.rss, heapTotal: runtimeMemory.heapTotal, heapUsed: runtimeMemory.heapUsed, external: runtimeMemory.external, arrayBuffers: runtimeMemory.arrayBuffers, }, }); }); app.get('/api/qq-list', (c) => { const instances = oneBotManager.getInstances(); const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); return c.json({ list }); }); // Live OneBot adapter health per account (listening / connected / client // counts / last-delivery), powering the dashboard's connection card. app.get('/api/connections', (c) => { return c.json({ list: oneBotManager.getConnectionStatuses() }); }); app.get('/api/logs', (c) => { const limit = Number(c.req.query('limit') ?? 300); return c.json({ list: getRecentLogs(limit) }); }); app.get('/api/logs/level', (c) => { return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); }); app.post('/api/logs/level', async (c) => { const body = await c.req.json().catch(() => null) as { level?: unknown } | null; const next = typeof body?.level === 'string' ? body.level : ''; if (!setLogLevel(next)) { return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400); } log.info('console log level set to %s via WebUI', getLogLevel()); return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); }); app.get('/api/logs/stream', (c) => { const stream = new ReadableStream({ start(controller) { const encoder = new TextEncoder(); let closed = false; let unsubscribe: (() => void) | undefined; let heartbeat: NodeJS.Timeout | undefined; const teardown = () => { if (closed) return; closed = true; if (heartbeat) clearInterval(heartbeat); unsubscribe?.(); try { controller.close(); } catch { /* ignore */ } }; const safeEnqueue = (chunk: Uint8Array) => { if (closed) return; try { controller.enqueue(chunk); } catch { // The peer dropped between abort and the next enqueue — // treat as end-of-stream so we don't leak listeners. teardown(); } }; const send = (event: unknown) => { safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); }; send({ type: 'ready' }); unsubscribe = subscribeLogs((entry) => send(entry)); heartbeat = setInterval(() => { safeEnqueue(encoder.encode(': heartbeat\n\n')); }, 15000); c.req.raw.signal.addEventListener('abort', teardown); }, }); return new Response(stream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', }, }); }); app.get('/api/processes', async (c) => { if (!hookManager) return c.json({ list: [] }); try { return c.json({ list: await hookManager.listProcesses() }); } catch (err) { return c.json({ list: [], message: err instanceof Error ? err.message : String(err) }, 500); } }); // Per-process action handler. The three routes below differ only in // which HookManager method they call. const MAX_PID = 4_194_304; function processAction(label: string, action: (pid: number) => Promise) { return async (c: Context) => { if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); const pid = Number(c.req.param('pid')); if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { return c.json({ success: false, message: 'invalid pid' }, 400); } try { const processInfo = await action(pid); return c.json({ success: processInfo.status !== 'error', process: processInfo }); } catch (err) { log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500); } }; } app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid))); app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid))); app.get('/api/processes/:pid/probe-login', async (c) => { if (!hookManager) return c.json({ info: null, message: 'hook manager is not available' }, 503); const pid = Number(c.req.param('pid')); if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { return c.json({ info: null, message: 'invalid pid' }, 400); } try { const info = await hookManager.probeProcessLoginInfo(pid); return c.json({ info }); } catch (err) { log.warn('probe-login pid=%d failed: %s', pid, err instanceof Error ? err.message : String(err)); return c.json({ info: null, message: '探测失败' }, 500); } }); app.get('/api/config/:uin', (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); // Read-only: never write defaults to disk on a GET. The persisted // file is created when manager.onSessionStarted boots an instance // or when the operator POSTs from this very endpoint. const config = loadOneBotConfig(uin); return c.json({ config }); }); app.post('/api/config/:uin', async (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400); try { const body = (await c.req.json()) as OneBotConfig; saveOneBotConfig(uin, body); const reloaded = oneBotManager.reloadConfig(uin); log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : ''); return c.json({ success: true, reloaded, message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。', }); } catch (err) { log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400); } }); // ─── Notifications (account up/down → webhook) ─────────────────────────── // Global channel store (config/notifications.json); per-UIN opt-in lives in // OneBotConfig.notifications.channelIds. All bearer-gated — channel URLs can // embed secrets, so none of this is exposed unauthenticated. app.get('/api/notifications/config', (c) => c.json({ config: loadNotificationsConfig() })); app.post('/api/notifications/config', async (c) => { const declaredLen = Number(c.req.header('content-length')); if (Number.isFinite(declaredLen) && declaredLen > 512 * 1024) { return c.json({ success: false, message: '配置过大' }, 413); } let body: unknown; try { body = await c.req.json(); } catch { return c.json({ success: false, message: '请求格式错误' }, 400); } try { const config = saveNotificationsConfig(body); return c.json({ success: true, config }); } catch (err) { log.warn('save notifications config failed: %s', err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); } }); app.get('/api/notifications/recent', (c) => { if (!notificationManager) return c.json({ recent: [] }); const limitRaw = Number(c.req.query('limit')); const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.trunc(limitRaw), 100) : 100; return c.json({ recent: notificationManager.getRecent(limit) }); }); app.post('/api/notifications/test', async (c) => { if (!notificationManager) return c.json({ success: false, message: '通知子系统不可用' }, 503); let body: { channelId?: unknown }; try { body = await c.req.json(); } catch { return c.json({ success: false, message: '请求格式错误' }, 400); } const channelId = typeof body.channelId === 'string' ? body.channelId : ''; if (!channelId) return c.json({ success: false, message: '缺少 channelId' }, 400); const result = await notificationManager.testSend(channelId); if (!result.found) return c.json({ success: false, message: '渠道不存在' }, 404); return c.json({ success: result.ok, status: result.status, message: result.ok ? '测试发送成功' : `测试发送失败:${result.error ?? (result.status ? `HTTP ${result.status}` : '未知错误')}`, }); }); // ─── WebUI customization config (config/ui.json) ───────────────────────── // Appearance (A) + layout (C). The full config is bearer-gated; only the // cosmetic appearance subset is exposed unauthenticated for the login page. app.get('/api/ui', (c) => c.json({ config: loadUiConfig() })); app.get('/api/ui/public', (c) => c.json({ appearance: publicAppearance() })); app.post('/api/ui', async (c) => { // Reject oversized bodies before buffering — the normalizer caps individual // fields (customCss 50KB, per-widget config 4KB) but not the whole payload. const declaredLen = Number(c.req.header('content-length')); if (Number.isFinite(declaredLen) && declaredLen > 256 * 1024) { return c.json({ success: false, message: '配置过大' }, 413); } let body: unknown; try { body = await c.req.json(); } catch { return c.json({ success: false, message: '请求格式错误' }, 400); } try { const config = saveUiConfig(body); return c.json({ success: true, config }); } catch (err) { log.warn('save ui.json failed: %s', err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 400); } }); app.post('/api/ui/background', async (c) => { // Early reject by Content-Length BEFORE parseBody() buffers the whole // multipart body into memory — otherwise a multi-GB upload is fully // materialized before the post-parse size check fires. The slack covers // the multipart envelope (boundary + part headers); the exact decoded // size is still enforced below. A chunked request with no Content-Length // skips this coarse guard, but the endpoint is bearer-gated to the single // admin, so that residual is acceptable. const declaredLen = Number(c.req.header('content-length')); if (Number.isFinite(declaredLen) && declaredLen > MAX_BACKGROUND_BYTES + 1024 * 1024) { return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413); } let file: unknown; try { const form = await c.req.parseBody(); file = form['file']; } catch { return c.json({ success: false, message: '上传解析失败' }, 400); } if (!(file instanceof File)) { return c.json({ success: false, message: '缺少图片文件' }, 400); } if (file.size > MAX_BACKGROUND_BYTES) { return c.json({ success: false, message: '图片过大(上限 5MB)' }, 413); } const bytes = new Uint8Array(await file.arrayBuffer()); const mime = sniffImageMime(bytes); if (!mime) { return c.json({ success: false, message: '仅支持 PNG / JPEG / WebP 图片' }, 415); } try { const config = writeBackgroundImage(bytes, mime); return c.json({ success: true, config }); } catch (err) { log.warn('write background image failed: %s', err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '保存图片失败,请检查服务器日志' }, 500); } }); app.delete('/api/ui/background', (c) => { try { const config = clearBackgroundImage(); return c.json({ success: true, config }); } catch (err) { log.warn('clear background image failed: %s', err instanceof Error ? err.message : String(err)); return c.json({ success: false, message: '删除图片失败' }, 500); } }); // ─── Static frontend ───────────────────────────────────────────────────── // Build path is relative to the bundled / dev __dirname. SPA fallback to // index.html so client-side routes (if any) keep working. const staticRoot = path.resolve(__dirname, 'client'); app.use('/*', serveStatic({ root: staticRoot })); const indexHtmlPath = path.join(staticRoot, 'index.html'); app.get('*', (c) => { // SPA fallback: only for navigations that didn't hit a static asset. if ( c.req.path.startsWith('/api/') || c.req.path.startsWith('/avatar/') || c.req.path.startsWith('/ui-asset/') ) { return c.text('not found', 404); } if (existsSync(indexHtmlPath)) { const html = readFileSync(indexHtmlPath, 'utf8'); return c.html(html); } return c.text( 'WebUI client bundle not found. Run `pnpm --filter webui build` (or use the dev server on :5178).', 404, ); }); const finalPort = await findAvailablePort(desiredPort); if (finalPort !== desiredPort) { log.warn('port %d is in use, using %d instead', desiredPort, finalPort); } const host = listener.host || '0.0.0.0'; // TLS: only when explicitly enabled AND the on-disk cert/key load. A bad // or missing cert must never brick the WebUI — fall back to HTTP + warn. let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined; let scheme = 'http'; if (listener.tlsEnabled) { const tls = resolveTlsContext('config'); if (tls.ok && tls.cert && tls.key) { tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } }; scheme = 'https'; } else { log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason); } } await new Promise((resolve) => { serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => { log.info(`listening ${scheme}://${host}:${info.port}`); resolve(); }); }); return { port: finalPort }; }