diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index f2b0ad29..c3879331 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,6 +2,7 @@ import { HookManager } from '@snowluma/bridge'; import { closeLogger, createLogger } from '@snowluma/common/logger'; import { loadRuntimeConfig } from '@snowluma/common/runtime'; import { OneBotManager } from '@snowluma/onebot/manager'; +import { migrateGlobalSettings } from '@snowluma/onebot/global-config'; import { BridgeManager } from './bridge/manager'; import { createNotificationManager } from './notifications/manager'; import { createStateWiring } from './webui/state-wiring'; @@ -28,6 +29,10 @@ process.on('uncaughtException', (error) => { async function main() { log.info('SnowLuma starting'); + // One-shot: lift a legacy per-UIN musicSignUrl into the global store before + // any session (and thus any per-UIN config rewrite) can drop it. + migrateGlobalSettings(); + const bridgeManager = new BridgeManager(); const oneBotManager = new OneBotManager(); const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 2e6c9ea7..f9227895 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -40,6 +40,10 @@ "types": "./src/config.ts", "default": "./src/config.ts" }, + "./global-config": { + "types": "./src/global-config.ts", + "default": "./src/global-config.ts" + }, "./types": { "types": "./src/types.ts", "default": "./src/types.ts" diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index 4bf2e4b1..daf088b3 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -61,7 +61,6 @@ export function makeDefaultOneBotConfig(): OneBotConfig { }], wsClients: [], }, - musicSignUrl: '', statusCommand: makeDefaultStatusCommand(), notifications: { channelIds: [] }, }; @@ -115,7 +114,6 @@ function toJsonObject(config: OneBotConfig): JsonObject { wsServers: nets.wsServers.map(wsServerToJson), wsClients: nets.wsClients.map(wsClientToJson), }, - musicSignUrl: config.musicSignUrl ?? '', statusCommand: { enabled: config.statusCommand.enabled, swallow: config.statusCommand.swallow, @@ -179,12 +177,10 @@ function wsClientToJson(n: WsClientNetwork): JsonObject { function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { let legacyFormat: MessageFormat | undefined; let legacyReport: boolean | undefined; - let musicSignUrl = ''; for (const src of sources) { const mf = parseMessageFormat(src.messageFormat); if (mf) legacyFormat = mf; if (typeof src.reportSelfMessage === 'boolean') legacyReport = src.reportSelfMessage; - if (typeof src.musicSignUrl === 'string') musicSignUrl = src.musicSignUrl; } const inheritedFormat: MessageFormat = legacyFormat ?? 'array'; const inheritedReport: boolean = legacyReport ?? false; @@ -208,7 +204,6 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients }; return { networks, - musicSignUrl, statusCommand: parseStatusCommand(sources), notifications: parseNotifications(sources), }; diff --git a/packages/onebot/src/global-config.ts b/packages/onebot/src/global-config.ts index e8c23f05..760be2f9 100644 --- a/packages/onebot/src/global-config.ts +++ b/packages/onebot/src/global-config.ts @@ -17,10 +17,13 @@ const GLOBAL_CONFIG_PATH = path.join(CONFIG_DIR, 'snowluma.json'); export interface GlobalSettings { /** Opt-in remote rkey fallback (see RKeyConfig). Default: servers empty = off. */ rkey: RKeyConfig; + /** Music-card signing service URL. Deployment-wide (same service for every + * account), so global rather than per-UIN. Empty = use the built-in default. */ + musicSignUrl: string; } export function defaultGlobalSettings(): GlobalSettings { - return { rkey: { fallbackServers: [] } }; + return { rkey: { fallbackServers: [] }, musicSignUrl: '' }; } /** Keep only well-formed, deduped http(s) URLs (must parse + have a host). */ @@ -59,6 +62,11 @@ export function normalizeGlobalSettings(value: unknown): GlobalSettings { if (isObject(rkey)) { out.rkey.fallbackServers = normalizeRkeyServers(rkey.fallbackServers); } + if (typeof value.musicSignUrl === 'string') { + const v = value.musicSignUrl.trim(); + // Empty = "use built-in default"; otherwise must be a real http(s) endpoint. + out.musicSignUrl = v && isHttpUrl(v) ? v : ''; + } return out; } @@ -85,6 +93,10 @@ export function saveGlobalSettings(incoming: unknown): GlobalSettings { if (isObject(incoming.rkey)) { merged.rkey.fallbackServers = normalizeRkeyServers(incoming.rkey.fallbackServers); } + if (typeof incoming.musicSignUrl === 'string') { + const v = incoming.musicSignUrl.trim(); + merged.musicSignUrl = v && isHttpUrl(v) ? v : ''; + } } fs.mkdirSync(CONFIG_DIR, { recursive: true }); const tmp = GLOBAL_CONFIG_PATH + '.tmp'; @@ -94,9 +106,86 @@ export function saveGlobalSettings(incoming: unknown): GlobalSettings { } function toJson(settings: GlobalSettings): JsonObject { - return { rkey: { fallbackServers: settings.rkey.fallbackServers } }; + return { + rkey: { fallbackServers: settings.rkey.fallbackServers }, + musicSignUrl: settings.musicSignUrl, + }; } function isObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } + +/** + * One-shot copy-up: `musicSignUrl` used to live in per-UIN config. If the global + * store has none yet, lift the first non-empty value found in any legacy + * `config/onebot*.json` into `config/snowluma.json`. Idempotent — skips once the + * global value is set. (If an operator later clears the global value while a + * stale per-UIN value lingers, a restart would re-copy it; benign and rare.) + */ +export function migrateGlobalSettings(): void { + // One-shot guard keyed on PRESENCE (not truthiness): once snowluma.json carries + // a musicSignUrl key — written by this migration or any global-config save — + // never re-scan. This is what stops an operator's intentional clear-to-'' from + // being reverted by a stale legacy value on the next boot. + if (globalConfigHasMusicSignUrlKey()) return; + + const found = scanLegacyMusicSignUrl(); + if (!found) return; + + saveGlobalSettings({ musicSignUrl: found.value }); + const extra = found.others.length ? `; ignored differing value(s) in ${found.others.join(', ')}` : ''; + log.info('migrated musicSignUrl to global config from %s: %s%s', found.source, found.value, extra); +} + +function globalConfigHasMusicSignUrlKey(): boolean { + if (!fs.existsSync(GLOBAL_CONFIG_PATH)) return false; + try { + const raw = JSON.parse(fs.readFileSync(GLOBAL_CONFIG_PATH, 'utf8')) as unknown; + return isObject(raw) && 'musicSignUrl' in raw; + } catch { + return false; + } +} + +interface LegacyMusicSignUrl { + value: string; + source: string; + others: string[]; +} + +/** Scan config/onebot.json + config/onebot_.json for a non-empty + * musicSignUrl. Returns the first found plus any other files that carried a + * (differing) value, for logging. */ +function scanLegacyMusicSignUrl(): LegacyMusicSignUrl | null { + let dir: string[]; + try { + dir = fs.readdirSync(CONFIG_DIR); + } catch { + return null; + } + const files = dir + .filter((f) => f === 'onebot.json' || /^onebot_\d+\.json$/.test(f)) + .sort(); + + let first: { value: string; source: string } | null = null; + const others: string[] = []; + for (const file of files) { + let value: unknown; + try { + const raw = JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, file), 'utf8')) as unknown; + value = isObject(raw) ? raw.musicSignUrl : undefined; + } catch { + continue; + } + if (typeof value !== 'string') continue; + const v = value.trim(); + // Skip empty AND invalid here, so "first found" means "first usable" — a + // garbage value in an earlier-sorting file can't shadow a real URL in a + // later one (it would be dropped to '' on save and then locked by the guard). + if (!v || !isHttpUrl(v)) continue; + if (!first) first = { value: v, source: file }; + else if (v !== first.value) others.push(file); + } + return first ? { ...first, others } : null; +} diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 800e1579..35f9b7fc 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -108,7 +108,7 @@ export class OneBotInstance { reactionStore: this.reactionStore, converterCtx: this.converterCtx, config, - musicSignUrl: config.musicSignUrl, + musicSignUrl: globalSettings.musicSignUrl, cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta), dispatchEvent: (event) => this.dispatchEvent(event), }; @@ -139,6 +139,7 @@ export class OneBotInstance { * the manager when config/snowluma.json is saved from the WebUI. */ applyGlobalSettings(globalSettings: GlobalSettings): void { this.rkeyCache.setFallbackServers(globalSettings.rkey.fallbackServers); + this.ctx.musicSignUrl = globalSettings.musicSignUrl; } dispose(): void { diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index c73ad8a3..2859ef5f 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -103,8 +103,6 @@ export interface RKeyConfig { /** Per-UIN OneBot configuration. */ export interface OneBotConfig { networks: OneBotNetworks; - /** Music card signing service URL (optional). */ - musicSignUrl?: string; /** Built-in `#sl` status command settings. Always present after normalization. */ statusCommand: StatusCommandConfig; /** Which GLOBAL notification channels this account opts into (channel ids are diff --git a/packages/onebot/tests/config.test.ts b/packages/onebot/tests/config.test.ts index bda0a22e..9c0b39b9 100644 --- a/packages/onebot/tests/config.test.ts +++ b/packages/onebot/tests/config.test.ts @@ -24,7 +24,6 @@ describe('makeDefaultOneBotConfig', () => { expect(config.networks.wsServers[0].messageFormat).toBe('array'); expect(config.networks.wsServers[0].reportSelfMessage).toBe(false); expect(config.networks.wsClients).toEqual([]); - expect(config.musicSignUrl).toBe(''); expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' }); expect(config.notifications).toEqual({ channelIds: [] }); }); @@ -119,8 +118,6 @@ describe('loadOneBotConfig', () => { expect(config.networks.wsClients[0].messageFormat).toBe('string'); expect(config.networks.wsClients[0].reportSelfMessage).toBe(true); - expect(config.musicSignUrl).toBe('https://example.com/sign'); - // File should now be in unified format on disk. const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8')); expect(onDisk.networks).toBeDefined(); diff --git a/packages/onebot/tests/global-config.test.ts b/packages/onebot/tests/global-config.test.ts index 8a889acc..14b188d6 100644 --- a/packages/onebot/tests/global-config.test.ts +++ b/packages/onebot/tests/global-config.test.ts @@ -5,6 +5,7 @@ import path from 'path'; import { defaultGlobalSettings, loadGlobalSettings, + migrateGlobalSettings, normalizeGlobalSettings, saveGlobalSettings, } from '../src/global-config'; @@ -25,8 +26,8 @@ describe('global-config (config/snowluma.json)', () => { }); it('defaults to an empty fallback list (feature off)', () => { - expect(defaultGlobalSettings()).toEqual({ rkey: { fallbackServers: [] } }); - expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] } }); + expect(defaultGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' }); + expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' }); }); it('keeps only well-formed http(s) URLs, trims, and dedupes', () => { @@ -38,8 +39,8 @@ describe('global-config (config/snowluma.json)', () => { }); it('ignores a malformed rkey block', () => { - expect(normalizeGlobalSettings({ rkey: 'nope' })).toEqual({ rkey: { fallbackServers: [] } }); - expect(normalizeGlobalSettings(null)).toEqual({ rkey: { fallbackServers: [] } }); + expect(normalizeGlobalSettings({ rkey: 'nope' })).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' }); + expect(normalizeGlobalSettings(null)).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' }); }); it('round-trips through save → disk → load', () => { @@ -47,23 +48,95 @@ describe('global-config (config/snowluma.json)', () => { 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(onDisk).toEqual({ rkey: { fallbackServers: ['https://r.example/rkey'] }, musicSignUrl: '' }); 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({}); + // A save touching only musicSignUrl must preserve the rkey servers, and + // vice-versa. + const after = saveGlobalSettings({ musicSignUrl: 'https://sign.example/card' }); expect(after.rkey.fallbackServers).toEqual(['https://r.example/rkey']); - expect(loadGlobalSettings().rkey.fallbackServers).toEqual(['https://r.example/rkey']); + expect(after.musicSignUrl).toBe('https://sign.example/card'); + expect(saveGlobalSettings({ rkey: { fallbackServers: [] } }).musicSignUrl).toBe('https://sign.example/card'); + }); + + it('normalizes + round-trips musicSignUrl (trimmed)', () => { + expect(normalizeGlobalSettings({ musicSignUrl: ' https://s.example/c ' }).musicSignUrl).toBe('https://s.example/c'); + const saved = saveGlobalSettings({ musicSignUrl: 'https://s.example/c' }); + expect(saved.musicSignUrl).toBe('https://s.example/c'); + expect(loadGlobalSettings().musicSignUrl).toBe('https://s.example/c'); + }); + + describe('migrateGlobalSettings (musicSignUrl copy-up)', () => { + function writeOnebot(file: string, body: unknown) { + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, file), JSON.stringify(body), 'utf8'); + } + + it('lifts a legacy per-UIN musicSignUrl into the global store', () => { + writeOnebot('onebot_123.json', { musicSignUrl: 'https://legacy.example/sign' }); + migrateGlobalSettings(); + expect(loadGlobalSettings().musicSignUrl).toBe('https://legacy.example/sign'); + }); + + it('is a no-op when the global value is already set', () => { + saveGlobalSettings({ musicSignUrl: 'https://kept.example/sign' }); + writeOnebot('onebot_123.json', { musicSignUrl: 'https://legacy.example/sign' }); + migrateGlobalSettings(); + expect(loadGlobalSettings().musicSignUrl).toBe('https://kept.example/sign'); + }); + + it('takes the first file and tolerates differing/empty values across files', () => { + writeOnebot('onebot.json', { musicSignUrl: '' }); // empty → skipped + writeOnebot('onebot_111.json', { musicSignUrl: 'https://a.example/s' }); + writeOnebot('onebot_222.json', { musicSignUrl: 'https://b.example/s' }); + migrateGlobalSettings(); + // onebot.json sorts first but is empty; onebot_111 is the first non-empty. + expect(loadGlobalSettings().musicSignUrl).toBe('https://a.example/s'); + }); + + it('does nothing when no legacy value exists', () => { + writeOnebot('onebot_123.json', { networks: {} }); + migrateGlobalSettings(); + expect(loadGlobalSettings().musicSignUrl).toBe(''); + }); + + it('migrates a value carried by the base onebot.json', () => { + writeOnebot('onebot.json', { musicSignUrl: 'https://base.example/s' }); + migrateGlobalSettings(); + expect(loadGlobalSettings().musicSignUrl).toBe('https://base.example/s'); + }); + + it('skips an invalid earlier value and migrates the first VALID one', () => { + writeOnebot('onebot.json', { musicSignUrl: 'not-a-url' }); // earlier-sorting garbage + writeOnebot('onebot_111.json', { musicSignUrl: 'https://real.example/s' }); + migrateGlobalSettings(); + expect(loadGlobalSettings().musicSignUrl).toBe('https://real.example/s'); + }); + + it('does NOT re-copy after an intentional clear-to-empty (presence guard)', () => { + // Operator cleared the global value to '' (the key is present in the file)… + saveGlobalSettings({ musicSignUrl: '' }); + // …while a stale legacy value still lingers. + writeOnebot('onebot_123.json', { musicSignUrl: 'https://legacy.example/sign' }); + migrateGlobalSettings(); + expect(loadGlobalSettings().musicSignUrl).toBe(''); // stays cleared, not reverted + }); + + it('is a safe no-op when config/ does not exist', () => { + // fresh cwd, no config dir at all + expect(() => migrateGlobalSettings()).not.toThrow(); + expect(loadGlobalSettings().musicSignUrl).toBe(''); + }); }); 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: [] } }); + expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' }); }); });