diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 56ca2157..78c80431 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -3,6 +3,7 @@ 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 { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config'; import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types'; import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; @@ -1247,6 +1248,32 @@ export async function initWebUI( }); }); + // ─── Global deployment config (config/snowluma.json) ───────────────────── + // All-accounts SnowLuma knobs (rkey fallback servers + musicSignUrl). Saving + // section-merges + normalizes server-side, then hot-reloads every instance. + app.get('/api/global-config', (c) => c.json({ config: loadGlobalSettings() })); + + app.post('/api/global-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 = saveGlobalSettings(body); + oneBotManager.reloadGlobalSettings(); + return c.json({ success: true, config }); + } catch (err) { + log.warn('save global config failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500); + } + }); + // ─── 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. diff --git a/packages/webui/src/components/config/general-settings-tab.tsx b/packages/webui/src/components/config/general-settings-tab.tsx index 144852f1..6ac71168 100644 --- a/packages/webui/src/components/config/general-settings-tab.tsx +++ b/packages/webui/src/components/config/general-settings-tab.tsx @@ -1,7 +1,8 @@ -// "通用设置" tab — fields that apply to the whole OneBotInstance rather -// than any specific adapter: the music-sign service URL and the built-in -// `#sl` status command. Edits here mark the config dirty and are -// auto-saved with debounce by the parent ConfigPage. +// "通用设置" tab — per-account fields that apply to the whole OneBotInstance +// rather than any specific adapter: the built-in `#sl` status command and the +// notification opt-in. Edits here mark the config dirty and are auto-saved with +// debounce by the parent ConfigPage. (Deployment-wide knobs like the music-sign +// URL live in Settings → 全局配置, not here.) import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; @@ -21,19 +22,6 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps return (
-
- - onChange({ ...config, musicSignUrl: e.target.value || undefined })} - /> -

- 用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。 -

-
-
diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index 8b8c86e0..fd5da6d9 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -3,7 +3,7 @@ import { motion } from 'motion/react'; import { Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon, Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, Server, ShieldCheck, - Sparkles, Star, Sun, Tag, Upload, Trash2, + SlidersHorizontal, Sparkles, Star, Sun, Tag, Upload, Trash2, } from 'lucide-react'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; @@ -42,6 +42,7 @@ import { useAppState } from '@/contexts/AppStateContext'; import { cn } from '@/lib/utils'; import { settingsRoute, type SettingsTab } from '@/router'; import { NotificationsPanel } from '@/components/settings/notifications-panel'; +import { GlobalConfigPanel } from '@/components/settings/global-config-panel'; import { SystemPanel } from '@/components/settings/system-panel'; const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ @@ -51,6 +52,7 @@ const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ { key: 'account', label: '账号安全', icon: ShieldCheck }, { key: 'system', label: '服务', icon: Server }, { key: 'notifications', label: '通知', icon: Bell }, + { key: 'globalConfig', label: '全局配置', icon: SlidersHorizontal }, { key: 'about', label: '关于', icon: Info }, ]; @@ -83,6 +85,7 @@ export function SettingsPage() { {tab === 'account' && } {tab === 'system' && } {tab === 'notifications' && } + {tab === 'globalConfig' && } {tab === 'about' && }
diff --git a/packages/webui/src/components/settings/global-config-panel.tsx b/packages/webui/src/components/settings/global-config-panel.tsx new file mode 100644 index 00000000..19ba66f0 --- /dev/null +++ b/packages/webui/src/components/settings/global-config-panel.tsx @@ -0,0 +1,210 @@ +// Settings → 全局配置 tab. Deployment-wide SnowLuma knobs (config/snowluma.json): +// rkey fallback servers + the music-card signing URL. Same UX as the other +// settings panels — debounced auto-save, no explicit save button. Unlike the +// channel editor these are typed inline, so the server's normalized result is +// NOT written back onto the inputs while editing (that would erase a half-typed +// URL); the store reconciles on the next load. Invalid entries are flagged +// client-side and simply dropped by the server on save. +import { useCallback, useEffect, useRef, useState } from 'react'; +import { AlertTriangle, KeyRound, Loader2, Music, Plus, RefreshCw, Trash2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useApi } from '@/lib/api'; +import { cn } from '@/lib/utils'; +import type { GlobalSettings } from '@/types'; + +const MUSIC_SIGN_DEFAULT = 'https://ss.xingzhige.com/music_card/card'; + +function isHttpUrl(value: string): boolean { + try { + const u = new URL(value); + return (u.protocol === 'http:' || u.protocol === 'https:') && u.host.length > 0; + } catch { + return false; + } +} + +export function GlobalConfigPanel() { + const api = useApi(); + const [config, setConfig] = useState(null); + const [loading, setLoading] = useState(true); + const [loadFailed, setLoadFailed] = useState(false); + const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null); + const saveTimer = useRef(null); + const msgTimer = useRef(null); + const saveGen = useRef(0); + + const load = useCallback(async () => { + setLoading(true); + setLoadFailed(false); + try { + setConfig(await api.globalConfig.get()); + } catch { + setLoadFailed(true); + } finally { + setLoading(false); + } + }, [api]); + + useEffect(() => { + void load(); + }, [load]); + + useEffect( + () => () => { + if (saveTimer.current) clearTimeout(saveTimer.current); + if (msgTimer.current) clearTimeout(msgTimer.current); + }, + [], + ); + + const flash = (kind: 'ok' | 'err', text: string) => { + setMsg({ kind, text }); + if (msgTimer.current) clearTimeout(msgTimer.current); + msgTimer.current = window.setTimeout(() => setMsg(null), 2400); + }; + + /** Apply locally + debounced auto-save. Deliberately does NOT reconcile the + * inputs from the server's normalized response (it would wipe a half-typed + * URL); a generation guard just confirms the latest save. */ + const commit = (next: GlobalSettings) => { + setConfig(next); + const gen = ++saveGen.current; + if (saveTimer.current) clearTimeout(saveTimer.current); + saveTimer.current = window.setTimeout(() => { + void api.globalConfig + .save(next) + .then(() => { + if (saveGen.current !== gen) return; + // The server drops invalid (non-http) entries; say so rather than a + // bare "已保存" next to a still-visible rejected value. + const dropped = next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim())) + || (next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim())); + flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存'); + }) + .catch(() => { + if (saveGen.current !== gen) return; + flash('err', '保存失败,请检查服务器日志'); + }); + }, 500); + }; + + if (loading) { + return ( +
+ 加载中… +
+ ); + } + + if (loadFailed || !config) { + return ( +
+ +

加载全局配置失败

+ +
+ ); + } + + const servers = config.rkey.fallbackServers; + const setServers = (next: string[]) => commit({ ...config, rkey: { fallbackServers: next } }); + + return ( +
+ {/* rkey fallback servers */} +
+
+ +

+ 图片 / 文件下载链接需要服务器签发的 rkey。SnowLuma 默认走内核获取; + 当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。 + 默认留空=关闭,不配置就不会联系任何第三方。 + 建议填你自建的端点。 +

+
+ +
+
+ + +
+ + {servers.length === 0 ? ( +

+ 未配置回退服务器(rkey 回退已关闭) +

+ ) : ( +
+ {servers.map((url, i) => { + const invalid = url.trim().length > 0 && !isHttpUrl(url.trim()); + return ( +
+ setServers(servers.map((s, idx) => (idx === i ? e.target.value : s)))} + /> + +
+ ); + })} +

+ 端点需返回 {'{ group_rkey, private_rkey, expired_time }'} + (兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。 +

+
+ )} +
+
+ + {/* music sign URL */} +
+
+ +

音乐分享卡片的签名服务,对所有账号统一生效。留空则使用内置默认服务。

+
+
+ + 0 && !isHttpUrl(config.musicSignUrl.trim())} + className={cn( + 'font-mono text-xs', + config.musicSignUrl.trim().length > 0 && !isHttpUrl(config.musicSignUrl.trim()) + && 'border-destructive focus-visible:ring-destructive', + )} + onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })} + /> +

+ 内置默认:{MUSIC_SIGN_DEFAULT} +

+
+
+ + {msg &&

{msg.text}

} +
+ ); +} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index e2d919c4..980d3c43 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -1,4 +1,4 @@ -import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types'; +import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, GlobalSettings, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-page'; import { normalizeOneBotConfig } from '@/lib/onebot-config'; import { @@ -48,6 +48,7 @@ class HttpApiClient implements ApiClient { readonly update: ApiClient['update']; readonly ui: ApiClient['ui']; readonly notifications: ApiClient['notifications']; + readonly globalConfig: ApiClient['globalConfig']; readonly systemSettings: ApiClient['systemSettings']; readonly debug: ApiClient['debug']; readonly agreements: ApiClient['agreements']; @@ -190,6 +191,18 @@ class HttpApiClient implements ApiClient { }), }; + this.globalConfig = { + get: () => + this.getJson<{ config: GlobalSettings }>('/api/global-config').then((d) => d.config), + save: async (config) => { + const data = await this.postJson<{ success: boolean; config: GlobalSettings }>( + '/api/global-config', + config, + ); + return data.config; + }, + }; + this.agreements = { get: () => this.getJson('/api/agreements'), recordConsent: async (version) => { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 51dd22ae..699fd53f 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -5,6 +5,7 @@ import type { DebugActionDoc, DebugInvokeResult, DebugStreamMessage, + GlobalSettings, HookProcessInfo, LogEntry, LogLevel, @@ -167,6 +168,14 @@ export interface ApiClient { test(channelId: string): Promise<{ success: boolean; message?: string; status?: number }>; }; + // ---- global deployment config (rkey fallback servers + musicSignUrl) ---- + globalConfig: { + /** Fetch the all-accounts global settings (config/snowluma.json). Bearer-gated. */ + get(): Promise; + /** Persist global settings (section-merged + normalized server-side). */ + save(config: Partial): Promise; + }; + // ---- update check ---- update: { /** Advisory check for a newer stable release. Read-only — never downloads. */ diff --git a/packages/webui/src/lib/onebot-config.ts b/packages/webui/src/lib/onebot-config.ts index 6cf87f12..90e15e6a 100644 --- a/packages/webui/src/lib/onebot-config.ts +++ b/packages/webui/src/lib/onebot-config.ts @@ -62,7 +62,6 @@ export function normalizeOneBotConfig(raw: unknown): OneBotConfig { wsServers: list(nets.wsServers) as unknown as OneBotConfig['networks']['wsServers'], wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'], }, - musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined, statusCommand: normalizeStatusCommand(cfg.statusCommand), notifications: normalizeNotifications(cfg.notifications), }; diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx index 49367cc6..3742e9d4 100644 --- a/packages/webui/src/router/index.tsx +++ b/packages/webui/src/router/index.tsx @@ -74,7 +74,7 @@ const debugRoute = createRoute({ }); /** Settings sub-tabs — also the contract for the `?tab=` deep link. */ -export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'about'] as const; +export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'globalConfig', 'about'] as const; export type SettingsTab = (typeof SETTINGS_TABS)[number]; export const settingsRoute = createRoute({ diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index fb2b3b5c..45dc202c 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -107,12 +107,24 @@ export interface StatusCommandConfig { export interface OneBotConfig { networks: OneBotNetworks; - musicSignUrl?: string; statusCommand: StatusCommandConfig; /** Per-account opt-in to global notification channels (by channel id). */ notifications?: { channelIds: string[] }; } +// ─── Global deployment settings (config/snowluma.json) ────────────────────── +// All-accounts SnowLuma knobs that aren't per-UIN: rkey fallback servers and +// the music-card signing endpoint. Mirrors @snowluma/onebot/global-config. +export interface RKeyConfig { + fallbackServers: string[]; +} + +export interface GlobalSettings { + rkey: RKeyConfig; + /** Music-card signing service URL. Empty = built-in default. */ + musicSignUrl: string; +} + // ─── Notifications (account up/down webhooks) ─────────────────────────────── export type NotificationEventKind = 'offline' | 'online';