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:
12 files changed
+227
-78
No files matched your search
@@ -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 },
|
||||
|
||||
@@ -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<string>();
|
||||
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
|
||||
|
||||
@@ -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_<uin>.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<string>();
|
||||
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);
|
||||
}
|
||||
@@ -38,12 +38,17 @@ export class RKeyCache {
|
||||
private lastRefreshAttempt = 0;
|
||||
private refreshInflight: Promise<void> | 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),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>;
|
||||
const servers = Array.isArray(obj.fallbackServers)
|
||||
? obj.fallbackServers.filter((s): s is string => typeof s === 'string')
|
||||
: [];
|
||||
return { fallbackServers: servers };
|
||||
}
|
||||
@@ -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) ───────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user