refactor(onebot): move rkey fallback from per-UIN to a global config store

The rkey fallback endpoint is deployment infra (one self-hosted server serves
all accounts; fallback rkeys are fungible), so it doesn't belong in per-UIN
onebot_<uin>.json. Introduce config/snowluma.json — a generic home for small
all-accounts SnowLuma settings — and move rkey.fallbackServers there.

- New onebot/global-config.ts: load/save/normalize with section-merge + atomic
  write; http(s)+host URL validation; default [] (off). Lives in onebot (not
  core) because the onebot manager constructs instances and must not depend on
  core.
- OneBotInstance takes globalSettings; manager loads it on session start and
  exposes reloadGlobalSettings() to hot-push edits to every live instance via
  applyGlobalSettings → RKeyCache.setFallbackServers.
- Remove rkey from per-UIN OneBotConfig + the WebUI per-UIN round-trip (never
  released, so no migration). Register snowluma.json in the backup allowlist.

Reworks the per-UIN rkey from 12b0190. Phase 1 of the global-settings split.
This commit is contained in:
DrSmoothl committed 2026-06-28 20:52:07 +08:00
1 parent 5d39cf5782
commit 659970077a
12 files changed
+227 -78

No files matched your search

-24
View File
@@ -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');
@@ -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: [] } });
});
});
@@ -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();
}
});
});