From 7faef1b7c043bb00891dceab086a9a2eb9231050 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 18 Jun 2026 14:32:24 +0800 Subject: [PATCH] feat(webui): system settings + TLS cert API (Wave A1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET/POST /api/system/settings (port/host/tlsEnabled/trustProxy) persisted via updateRuntimeConfig — listener-level, restart-to-apply; response carries restartRequiredToApply + the env-overridden field names so the panel can flag edits that won't take effect. Enabling TLS is blocked unless a usable cert is present. POST/DELETE /api/system/tls/cert validates a pasted PEM pair (validateTlsPair) before writing config/cert.pem + key.pem. Adds read-only readRuntimeConfig() and a tested pure coerceSettingsPatch validator. All routes sit behind the existing /api/* auth middleware. --- packages/common/src/runtime.ts | 8 ++ packages/core/src/webui/server.ts | 99 ++++++++++++++++++- packages/core/src/webui/system-settings.ts | 52 ++++++++++ .../core/tests/webui-system-settings.test.ts | 39 ++++++++ 4 files changed, 196 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/webui/system-settings.ts create mode 100644 packages/core/tests/webui-system-settings.test.ts diff --git a/packages/common/src/runtime.ts b/packages/common/src/runtime.ts index 18cbd1b5..e6eca30b 100644 --- a/packages/common/src/runtime.ts +++ b/packages/common/src/runtime.ts @@ -77,6 +77,14 @@ export function loadRuntimeConfig(): RuntimeConfig { return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) }; } +/** + * Read the persisted config (normalized, no env overrides, no write). For the + * settings panel's GET — shows what's actually saved/editable on disk. + */ +export function readRuntimeConfig(): RuntimeConfig { + return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {}); +} + /** * Persist a partial update. Merges onto the ON-DISK config (not the env-merged * runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 7b8b29c5..5034e344 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -5,15 +5,17 @@ import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subs import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig } from '@snowluma/onebot/types'; +import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; import { randomBytes } from 'crypto'; -import { existsSync, readFileSync } from 'fs'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } 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 { resolveTlsContext, validateTlsPair } from './tls'; +import { coerceSettingsPatch } from './system-settings'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; import { @@ -108,6 +110,10 @@ export async function initWebUI( const trustProxyMode = parseTrustProxy(listener.trustProxy); const getClientIp = makeClientIpResolver(trustProxyMode); + // Actual bound port (set just before serve; findAvailablePort may bump it). + // Read by GET /api/system/settings so the panel shows what's really live. + let boundPort = desiredPort; + const auth = WebuiAuth.load(); const initialPassword = auth.takeInitialPassword(); if (auth.isDevMode()) { @@ -397,6 +403,94 @@ export async function initWebUI( }); }); + // ── System settings (WebUI listener) — Wave A1 ── + // Listener-level changes (port/host/TLS) are persisted but apply only on the + // next restart (no supervisor → no self-restart). The panel surfaces which + // fields are currently overridden by env so edits that won't take effect are + // visible. + const SYSTEM_CERT_PATH = path.join('config', 'cert.pem'); + const SYSTEM_KEY_PATH = path.join('config', 'key.pem'); + const hasCert = (): boolean => existsSync(SYSTEM_CERT_PATH) && existsSync(SYSTEM_KEY_PATH); + + app.get('/api/system/settings', (c) => { + const disk = readRuntimeConfig(); + const envOverrides = Object.keys(resolveRuntimeEnvOverrides(process.env)); + return c.json({ + settings: { + webuiPort: disk.webuiPort, + webuiHost: disk.webuiHost, + tlsEnabled: disk.webuiTls?.enabled ?? false, + trustProxy: disk.trustProxy ?? '', + }, + hasCert: hasCert(), + envOverrides, // field names currently pinned by SNOWLUMA_* env vars + listeningPort: boundPort, + restartRequiredToApply: true, + }); + }); + + app.post('/api/system/settings', async (c) => { + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const coerced = coerceSettingsPatch(body); + if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400); + // Enabling TLS without a usable cert would brick HTTPS on restart — block it. + if (coerced.patch.webuiTls?.enabled && !resolveTlsContext('config').ok) { + return c.json({ success: false, message: '启用 TLS 前请先上传有效的证书与私钥' }, 400); + } + const saved = updateRuntimeConfig(coerced.patch); + return c.json({ + success: true, + settings: { + webuiPort: saved.webuiPort, + webuiHost: saved.webuiHost, + tlsEnabled: saved.webuiTls?.enabled ?? false, + trustProxy: saved.trustProxy ?? '', + }, + restartRequiredToApply: true, + }); + }); + + app.post('/api/system/tls/cert', async (c) => { + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ success: false, message: '请求格式错误' }, 400); + } + const cert = (body as { cert?: unknown }).cert; + const key = (body as { key?: unknown }).key; + if (typeof cert !== 'string' || typeof key !== 'string') { + return c.json({ success: false, message: 'cert 和 key 必须为 PEM 字符串' }, 400); + } + const valid = validateTlsPair(cert, key); + if (!valid.ok) return c.json({ success: false, message: valid.reason }, 400); + try { + mkdirSync('config', { recursive: true }); + writeFileSync(SYSTEM_CERT_PATH, cert.endsWith('\n') ? cert : cert + '\n', 'utf8'); + writeFileSync(SYSTEM_KEY_PATH, key.endsWith('\n') ? key : key + '\n', 'utf8'); + } catch (err) { + log.warn('write cert/key failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '写入证书失败,请检查服务器日志' }, 500); + } + return c.json({ success: true, restartRequiredToApply: true }); + }); + + app.delete('/api/system/tls/cert', (c) => { + try { + rmSync(SYSTEM_CERT_PATH, { force: true }); + rmSync(SYSTEM_KEY_PATH, { force: true }); + } catch (err) { + log.warn('remove cert/key failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '删除证书失败' }, 500); + } + return c.json({ success: true }); + }); + app.get('/api/qq-list', (c) => { const instances = oneBotManager.getInstances(); const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); @@ -710,6 +804,7 @@ export async function initWebUI( if (finalPort !== desiredPort) { log.warn('port %d is in use, using %d instead', desiredPort, finalPort); } + boundPort = finalPort; const host = listener.host || '0.0.0.0'; diff --git a/packages/core/src/webui/system-settings.ts b/packages/core/src/webui/system-settings.ts new file mode 100644 index 00000000..fcecf80e --- /dev/null +++ b/packages/core/src/webui/system-settings.ts @@ -0,0 +1,52 @@ +// Pure validator for the POST /api/system/settings body. Rejects clearly-bad +// input with a message (→ 400) rather than silently normalizing it, then hands +// a clean patch to updateRuntimeConfig. Wire field `tlsEnabled` maps to the +// nested `webuiTls.enabled`. + +import type { RuntimeConfig } from '@snowluma/common/runtime'; + +export type SettingsPatch = Partial>; + +export type CoerceResult = + | { ok: true; patch: SettingsPatch } + | { ok: false; error: string }; + +function isObject(v: unknown): v is Record { + return typeof v === 'object' && v !== null && !Array.isArray(v); +} + +export function coerceSettingsPatch(body: unknown): CoerceResult { + if (!isObject(body)) return { ok: false, error: 'body must be an object' }; + const patch: SettingsPatch = {}; + + if ('webuiPort' in body) { + const p = body.webuiPort; + if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) { + return { ok: false, error: 'webuiPort must be an integer in 1..65535' }; + } + patch.webuiPort = p; + } + + if ('webuiHost' in body) { + if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) { + return { ok: false, error: 'webuiHost must be a non-empty string' }; + } + patch.webuiHost = body.webuiHost.trim(); + } + + if ('tlsEnabled' in body) { + if (typeof body.tlsEnabled !== 'boolean') { + return { ok: false, error: 'tlsEnabled must be a boolean' }; + } + patch.webuiTls = { enabled: body.tlsEnabled }; + } + + if ('trustProxy' in body) { + if (typeof body.trustProxy !== 'string') { + return { ok: false, error: 'trustProxy must be a string' }; + } + patch.trustProxy = body.trustProxy; + } + + return { ok: true, patch }; +} diff --git a/packages/core/tests/webui-system-settings.test.ts b/packages/core/tests/webui-system-settings.test.ts new file mode 100644 index 00000000..d79b6607 --- /dev/null +++ b/packages/core/tests/webui-system-settings.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect } from 'vitest'; +import { coerceSettingsPatch } from '../src/webui/system-settings'; + +describe('coerceSettingsPatch', () => { + it('accepts a full valid body and maps tlsEnabled → webuiTls.enabled', () => { + const r = coerceSettingsPatch({ webuiPort: 8080, webuiHost: '127.0.0.1', tlsEnabled: true, trustProxy: '1' }); + expect(r).toEqual({ ok: true, patch: { webuiPort: 8080, webuiHost: '127.0.0.1', webuiTls: { enabled: true }, trustProxy: '1' } }); + }); + + it('only includes provided keys (partial patch)', () => { + const r = coerceSettingsPatch({ webuiHost: '0.0.0.0' }); + expect(r).toEqual({ ok: true, patch: { webuiHost: '0.0.0.0' } }); + }); + + it('rejects a non-object body', () => { + expect(coerceSettingsPatch(null).ok).toBe(false); + expect(coerceSettingsPatch('x').ok).toBe(false); + }); + + it('rejects an out-of-range or non-integer port', () => { + expect(coerceSettingsPatch({ webuiPort: 0 }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiPort: 70000 }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiPort: 12.5 }).ok).toBe(false); + }); + + it('rejects an empty/blank host', () => { + expect(coerceSettingsPatch({ webuiHost: ' ' }).ok).toBe(false); + expect(coerceSettingsPatch({ webuiHost: 123 }).ok).toBe(false); + }); + + it('rejects a non-boolean tlsEnabled and non-string trustProxy', () => { + expect(coerceSettingsPatch({ tlsEnabled: 'yes' }).ok).toBe(false); + expect(coerceSettingsPatch({ trustProxy: 1 }).ok).toBe(false); + }); + + it('accepts an empty-string trustProxy (trust nobody)', () => { + expect(coerceSettingsPatch({ trustProxy: '' })).toEqual({ ok: true, patch: { trustProxy: '' } }); + }); +});