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
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user