diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 32a645ae..7a97a913 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -28,6 +28,9 @@ export const BACKUP_FILES: readonly BackupFileSpec[] = [ { name: 'runtime.json', binary: false, credential: false }, { name: 'ui.json', binary: false, credential: false }, { name: 'notifications.json', binary: false, credential: false }, + // Global all-accounts SnowLuma settings (rkey fallback servers, …). Same + // class as notifications.json: global, opt-in, non-credential. + { name: 'snowluma.json', binary: false, credential: false }, { name: 'cert.pem', binary: false, credential: false }, { name: 'ui-assets/background', binary: true, credential: false }, { name: 'webui.json', binary: false, credential: true }, diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index c9cbddd0..4bf2e4b1 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -9,7 +9,6 @@ import type { MessageFormat, OneBotConfig, OneBotNetworks, - RKeyConfig, StatusCommandConfig, WsClientNetwork, WsRole, @@ -65,7 +64,6 @@ export function makeDefaultOneBotConfig(): OneBotConfig { musicSignUrl: '', statusCommand: makeDefaultStatusCommand(), notifications: { channelIds: [] }, - rkey: { fallbackServers: [] }, }; } @@ -125,7 +123,6 @@ function toJsonObject(config: OneBotConfig): JsonObject { trigger: config.statusCommand.trigger, }, notifications: { channelIds: config.notifications?.channelIds ?? [] }, - rkey: { fallbackServers: config.rkey?.fallbackServers ?? [] }, }; } @@ -214,39 +211,9 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { musicSignUrl, statusCommand: parseStatusCommand(sources), notifications: parseNotifications(sources), - rkey: parseRKeyConfig(sources), }; } -/** Last-write-wins merge of `rkey.fallbackServers` across config sources. Only - * http(s) URLs are kept; the list is deduped. Default empty (feature off). */ -function parseRKeyConfig(sources: JsonObject[]): RKeyConfig { - let fallbackServers: string[] = []; - for (const src of sources) { - const raw = src.rkey; - if (!isObject(raw)) continue; - if (Array.isArray(raw.fallbackServers)) { - fallbackServers = normalizeRkeyServers(raw.fallbackServers); - } - } - return { fallbackServers }; -} - -function normalizeRkeyServers(value: unknown): string[] { - if (!Array.isArray(value)) return []; - const seen = new Set(); - const out: string[] = []; - for (const item of value) { - if (typeof item !== 'string') continue; - const v = item.trim(); - if (!v || !/^https?:\/\//i.test(v)) continue; - if (seen.has(v)) continue; - seen.add(v); - out.push(v); - } - return out; -} - /** Last-write-wins merge of `notifications.channelIds` across config sources, * each id validated as a slug + deduped. Mirrors the channel-id rule in * packages/core/src/notifications/config.ts (CHANNEL_ID_RE) — duplicated diff --git a/packages/onebot/src/global-config.ts b/packages/onebot/src/global-config.ts new file mode 100644 index 00000000..e8c23f05 --- /dev/null +++ b/packages/onebot/src/global-config.ts @@ -0,0 +1,102 @@ +import { createLogger } from '@snowluma/common/logger'; +import fs from 'fs'; +import path from 'path'; +import type { JsonObject, RKeyConfig } from './types'; + +const log = createLogger('OneBot.GlobalConfig'); + +const CONFIG_DIR = 'config'; +const GLOBAL_CONFIG_PATH = path.join(CONFIG_DIR, 'snowluma.json'); + +/** + * Global, all-accounts SnowLuma protocol settings — the home for small + * deployment-wide knobs that are NOT per-UIN (so they don't belong in + * `onebot_.json`). Persisted as `config/snowluma.json`. New small global + * settings should be added here rather than spawning a file/page per feature. + */ +export interface GlobalSettings { + /** Opt-in remote rkey fallback (see RKeyConfig). Default: servers empty = off. */ + rkey: RKeyConfig; +} + +export function defaultGlobalSettings(): GlobalSettings { + return { rkey: { fallbackServers: [] } }; +} + +/** Keep only well-formed, deduped http(s) URLs (must parse + have a host). */ +export function normalizeRkeyServers(value: unknown): string[] { + if (!Array.isArray(value)) return []; + const seen = new Set(); + const out: string[] = []; + for (const item of value) { + if (typeof item !== 'string') continue; + const v = item.trim(); + if (!v || !isHttpUrl(v) || seen.has(v)) continue; + seen.add(v); + out.push(v); + } + return out; +} + +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; + } +} + +// NOTE: when adding a new section, extend normalizeGlobalSettings, toJson AND +// saveGlobalSettings in lockstep. normalize/toJson only copy known sections, so +// an un-handled on-disk section is silently dropped on the next load+save — the +// section-merge in saveGlobalSettings only guards against a request OMITTING a +// section, not against this load/serialize pipeline discarding an unknown one. +export function normalizeGlobalSettings(value: unknown): GlobalSettings { + const out = defaultGlobalSettings(); + if (!isObject(value)) return out; + const rkey = value.rkey; + if (isObject(rkey)) { + out.rkey.fallbackServers = normalizeRkeyServers(rkey.fallbackServers); + } + return out; +} + +export function loadGlobalSettings(): GlobalSettings { + if (!fs.existsSync(GLOBAL_CONFIG_PATH)) return defaultGlobalSettings(); + try { + const raw = fs.readFileSync(GLOBAL_CONFIG_PATH, 'utf8'); + return normalizeGlobalSettings(JSON.parse(raw) as unknown); + } catch (err) { + log.warn('config/snowluma.json is corrupt and will be ignored: %s', err instanceof Error ? err.message : String(err)); + return defaultGlobalSettings(); + } +} + +/** + * Persist global settings, SECTION-MERGING over what's on disk: only the + * top-level sections actually present in `incoming` are overwritten, so a + * partial save (e.g. just `rkey`) never wipes a sibling knob. Mirrors + * saveNotificationsConfig's merge discipline. + */ +export function saveGlobalSettings(incoming: unknown): GlobalSettings { + const merged = loadGlobalSettings(); + if (isObject(incoming)) { + if (isObject(incoming.rkey)) { + merged.rkey.fallbackServers = normalizeRkeyServers(incoming.rkey.fallbackServers); + } + } + fs.mkdirSync(CONFIG_DIR, { recursive: true }); + const tmp = GLOBAL_CONFIG_PATH + '.tmp'; + fs.writeFileSync(tmp, JSON.stringify(toJson(merged), null, 2), 'utf8'); + fs.renameSync(tmp, GLOBAL_CONFIG_PATH); + return merged; +} + +function toJson(settings: GlobalSettings): JsonObject { + return { rkey: { fallbackServers: settings.rkey.fallbackServers } }; +} + +function isObject(value: unknown): value is JsonObject { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/packages/onebot/src/instance-rkey.ts b/packages/onebot/src/instance-rkey.ts index d8340b5f..f74f88f0 100644 --- a/packages/onebot/src/instance-rkey.ts +++ b/packages/onebot/src/instance-rkey.ts @@ -38,12 +38,17 @@ export class RKeyCache { private lastRefreshAttempt = 0; private refreshInflight: Promise | null = null; /** Opt-in remote rkey endpoints; empty = feature off (the default). */ - private readonly fallbackServers: string[]; + private fallbackServers: string[]; constructor(config?: RKeyConfig) { this.fallbackServers = config?.fallbackServers ?? []; } + /** Replace the fallback endpoint list (global-config hot-reload). */ + setFallbackServers(servers: string[]): void { + this.fallbackServers = servers; + } + warmUp(bridge: BridgeInterface, uin: string): void { this.ensureFresh(bridge).then( () => log.info('rkeys loaded: UIN=%s count=%d', uin, this.cache.size), diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 5f0ec60d..800e1579 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -7,6 +7,7 @@ import type { ConverterContext } from './event-converter'; import { registerEventPipeline } from './event-pipeline'; import { buildApiContext, type OneBotInstanceContext } from './instance-context'; import { RKeyCache } from './instance-rkey'; +import type { GlobalSettings } from './global-config'; import { MediaIndexer } from './media-indexer'; import { MediaStore } from './media-store'; import { MediaUrlResolver } from './media-url-resolver'; @@ -73,7 +74,7 @@ export class OneBotInstance { return this.apiHandler.handle(action, params); } - constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) { + constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) { this.uin = uin; this.bridge = bridge; const uinNum = Number.parseInt(uin, 10); @@ -81,7 +82,7 @@ export class OneBotInstance { ? moduleLog.child({ uin: uinNum }) : moduleLog; - this.rkeyCache = new RKeyCache(config.rkey); + this.rkeyCache = new RKeyCache(globalSettings.rkey); this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db')); this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json')); this.reactionStore = new ReactionStore(path.join('data', this.uin, 'reactions.db')); @@ -134,6 +135,12 @@ export class OneBotInstance { }); } + /** Apply edited global (all-accounts) settings without a restart. Called by + * the manager when config/snowluma.json is saved from the WebUI. */ + applyGlobalSettings(globalSettings: GlobalSettings): void { + this.rkeyCache.setFallbackServers(globalSettings.rkey.fallbackServers); + } + dispose(): void { this.online = false; this.stopHeartbeat(); diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index 1822428a..7618489d 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -2,6 +2,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { BridgeManager } from '@snowluma/core/manager'; import { loadOneBotConfig } from './config'; +import { loadGlobalSettings } from './global-config'; import { OneBotInstance } from './instance'; import type { AdapterStatus } from './network'; @@ -55,6 +56,16 @@ export class OneBotManager { return true; } + /** Re-read global (all-accounts) settings from config/snowluma.json and push + * them to every live instance. Called after the WebUI saves global config. */ + reloadGlobalSettings(): void { + const globalSettings = loadGlobalSettings(); + for (const instance of this.instances.values()) { + instance.applyGlobalSettings(globalSettings); + } + log.info('global settings reloaded for %d instance(s)', this.instances.size); + } + dispose(): void { for (const instance of this.instances.values()) { instance.dispose(); @@ -66,7 +77,7 @@ export class OneBotManager { if (this.instances.has(uin)) return; const config = loadOneBotConfig(uin, { persistDefaults: true }); - const instance = new OneBotInstance(uin, bridge, config); + const instance = new OneBotInstance(uin, bridge, config, loadGlobalSettings()); const activePid = bridge.activePid; if (activePid !== null) { diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index caf2a48c..c73ad8a3 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -111,9 +111,6 @@ export interface OneBotConfig { * validated slugs; channels themselves live in config/notifications.json). * Always present after normalization. */ notifications?: { channelIds: string[] }; - /** Remote rkey fallback servers (opt-in, default off). Always present after - * normalization. */ - rkey: RKeyConfig; } export interface MessageMeta { diff --git a/packages/onebot/tests/config.test.ts b/packages/onebot/tests/config.test.ts index 9b241622..bda0a22e 100644 --- a/packages/onebot/tests/config.test.ts +++ b/packages/onebot/tests/config.test.ts @@ -63,30 +63,6 @@ describe('loadOneBotConfig', () => { expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' }); }); - it('defaults rkey.fallbackServers to empty (feature off)', () => { - const config = loadOneBotConfig('10055'); - expect(config.rkey).toEqual({ fallbackServers: [] }); - }); - - it('parses, validates (http only), dedupes and round-trips rkey.fallbackServers', () => { - const uin = '10056'; - const dir = path.join(tempDir, 'config'); - fs.mkdirSync(dir, { recursive: true }); - fs.writeFileSync( - path.join(dir, `onebot_${uin}.json`), - JSON.stringify({ rkey: { fallbackServers: ['https://a.example/r', 'not-a-url', 'https://a.example/r', 'http://b.example/r', 42] } }), - 'utf8', - ); - - const config = loadOneBotConfig(uin); - expect(config.rkey.fallbackServers).toEqual(['https://a.example/r', 'http://b.example/r']); - - saveOneBotConfig(uin, config); - const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8')); - expect(onDisk.rkey).toEqual({ fallbackServers: ['https://a.example/r', 'http://b.example/r'] }); - expect(loadOneBotConfig(uin).rkey.fallbackServers).toEqual(['https://a.example/r', 'http://b.example/r']); - }); - it('fills statusCommand defaults and clamps a negative cooldown', () => { const uin = '10042'; const dir = path.join(tempDir, 'config'); diff --git a/packages/onebot/tests/global-config.test.ts b/packages/onebot/tests/global-config.test.ts new file mode 100644 index 00000000..8a889acc --- /dev/null +++ b/packages/onebot/tests/global-config.test.ts @@ -0,0 +1,69 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { + defaultGlobalSettings, + loadGlobalSettings, + normalizeGlobalSettings, + saveGlobalSettings, +} from '../src/global-config'; + +describe('global-config (config/snowluma.json)', () => { + let tempDir: string; + let prevCwd: string; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-global-config-')); + prevCwd = process.cwd(); + process.chdir(tempDir); + }); + + afterEach(() => { + process.chdir(prevCwd); + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it('defaults to an empty fallback list (feature off)', () => { + expect(defaultGlobalSettings()).toEqual({ rkey: { fallbackServers: [] } }); + expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] } }); + }); + + it('keeps only well-formed http(s) URLs, trims, and dedupes', () => { + const out = normalizeGlobalSettings({ + rkey: { fallbackServers: [' https://a.example/r ', 'ftp://x', 'not-a-url', 'https://', 'https://a.example/r', 'http://b.example/r', 42] }, + }); + // 'https://' (no host) and non-http schemes are dropped. + expect(out.rkey.fallbackServers).toEqual(['https://a.example/r', 'http://b.example/r']); + }); + + it('ignores a malformed rkey block', () => { + expect(normalizeGlobalSettings({ rkey: 'nope' })).toEqual({ rkey: { fallbackServers: [] } }); + expect(normalizeGlobalSettings(null)).toEqual({ rkey: { fallbackServers: [] } }); + }); + + it('round-trips through save → disk → load', () => { + const saved = saveGlobalSettings({ rkey: { fallbackServers: ['https://r.example/rkey', 'bogus'] } }); + expect(saved.rkey.fallbackServers).toEqual(['https://r.example/rkey']); + + const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', 'snowluma.json'), 'utf8')); + expect(onDisk).toEqual({ rkey: { fallbackServers: ['https://r.example/rkey'] } }); + + expect(loadGlobalSettings().rkey.fallbackServers).toEqual(['https://r.example/rkey']); + }); + + it('section-merges on save: a partial write never wipes a sibling section', () => { + saveGlobalSettings({ rkey: { fallbackServers: ['https://r.example/rkey'] } }); + // A save that omits `rkey` (e.g. a future tenant saving only its own block) + // must preserve the existing rkey servers. + const after = saveGlobalSettings({}); + expect(after.rkey.fallbackServers).toEqual(['https://r.example/rkey']); + expect(loadGlobalSettings().rkey.fallbackServers).toEqual(['https://r.example/rkey']); + }); + + it('falls back to defaults when the file is corrupt', () => { + fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true }); + fs.writeFileSync(path.join(tempDir, 'config', 'snowluma.json'), '{ not json', 'utf8'); + expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] } }); + }); +}); diff --git a/packages/onebot/tests/instance-rkey.test.ts b/packages/onebot/tests/instance-rkey.test.ts index 15a95371..0ba8def2 100644 --- a/packages/onebot/tests/instance-rkey.test.ts +++ b/packages/onebot/tests/instance-rkey.test.ts @@ -269,4 +269,30 @@ describe('RKeyCache remote fallback (#156)', () => { expect(url).toBe(NT_IMAGE_URL); }); + + // Hot-reload wire: manager.reloadGlobalSettings → instance.applyGlobalSettings + // → rkeyCache.setFallbackServers. Verify the new list actually takes effect. + // (Fake Date so the 2nd lookup clears the empty-cache refresh cooldown.) + it('setFallbackServers turns the fallback on for a cache that started with none', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + try { + vi.setSystemTime(new Date(1_700_000_000_000)); + const fetchSpy = stubFetch({ group_rkey: '&rkey=HOTGROUP', expired_time: 1_700_000_000 + 3600 }); + const { bridge } = makeBridge(async () => []); + const cache = new RKeyCache(); // starts OFF (no servers) + + const before = await cache.resolveImageUrl(bridge as never, imageEl(), true); + expect(before).toBe(NT_IMAGE_URL); // bare — fallback off + expect(fetchSpy).not.toHaveBeenCalled(); + + cache.setFallbackServers([SERVER]); // hot-reload pushes a new endpoint + vi.setSystemTime(new Date(1_700_000_000_000 + 11_000)); // clear the 10s empty-cooldown + + const after = await cache.resolveImageUrl(bridge as never, imageEl(), true); + expect(after).toBe(`${NT_IMAGE_URL}&rkey=HOTGROUP`); + expect(fetchSpy).toHaveBeenCalledWith(SERVER, expect.anything()); + } finally { + vi.useRealTimers(); + } + }); }); diff --git a/packages/webui/src/lib/onebot-config.ts b/packages/webui/src/lib/onebot-config.ts index bec68543..6cf87f12 100644 --- a/packages/webui/src/lib/onebot-config.ts +++ b/packages/webui/src/lib/onebot-config.ts @@ -65,16 +65,5 @@ export function normalizeOneBotConfig(raw: unknown): OneBotConfig { musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined, statusCommand: normalizeStatusCommand(cfg.statusCommand), notifications: normalizeNotifications(cfg.notifications), - rkey: normalizeRkey(cfg.rkey), }; } - -/** Preserve `rkey.fallbackServers` verbatim so a hand-edited value isn't wiped - * when the operator saves an unrelated change from the WebUI (no form yet). */ -function normalizeRkey(raw: unknown): { fallbackServers: string[] } { - const obj = (raw ?? {}) as Record; - const servers = Array.isArray(obj.fallbackServers) - ? obj.fallbackServers.filter((s): s is string => typeof s === 'string') - : []; - return { fallbackServers: servers }; -} diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 951240df..fb2b3b5c 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -111,9 +111,6 @@ export interface OneBotConfig { statusCommand: StatusCommandConfig; /** Per-account opt-in to global notification channels (by channel id). */ notifications?: { channelIds: string[] }; - /** Opt-in remote rkey fallback servers. No dedicated form yet — preserved - * verbatim across load/save so a hand-edited value survives WebUI writes. */ - rkey?: { fallbackServers: string[] }; } // ─── Notifications (account up/down webhooks) ───────────────────────────────