refactor(onebot): make loadOneBotConfig read-only by default

GET on a load helper used to mint a fresh access_token and write it to
disk whenever the per-UIN file was missing or in legacy format. Reading
should not have side effects, and the WebUI's read-only GET handler in
particular was racing on concurrent requests and surprising operators
with materialized config files.

Introduce a `{ persistDefaults?: boolean }` option (default false). The
two boot-time call sites in `OneBotManager` (onSessionStarted, reloadConfig)
opt in explicitly; WebUI's GET path will rely on the new default once
that side of the patch lands.

Also stop reviving default 0.0.0.0 listeners when the operator has
explicitly emptied every adapter — only seed defaults on a true fresh
install (no per-uin and no global config on disk).

Drop the unused deepClone / deepMerge helpers; tryLoadJson now logs a
warning instead of silently swallowing JSON parse errors.
This commit is contained in:
时瑾 authored and DrSmoothl committed 2026-05-16 21:31:28 +08:00
1 parent 655af833dc
commit 2c80e1a267
3 files changed
+58 -27

No files matched your search

+26 -23
View File
@@ -1,6 +1,7 @@
import fs from 'fs';
import path from 'path';
import { randomBytes } from 'crypto';
import { createLogger } from '../utils/logger';
import type {
HttpClientNetwork,
HttpServerNetwork,
@@ -13,6 +14,8 @@ import type {
WsServerNetwork,
} from './types';
const log = createLogger('OneBot.Config');
const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
@@ -50,7 +53,18 @@ function generateAccessToken(): string {
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
}
export function loadOneBotConfig(uin: string): OneBotConfig {
export interface LoadOneBotConfigOptions {
/**
* Persist the normalized config to disk when the file is missing or was
* in legacy format. Default `false` so accidental call sites (read-only
* GETs in particular) don't generate fresh access tokens, race on
* concurrent writes, or surprise the operator with materialized files.
* Pass `true` from boot / explicit POST handlers.
*/
persistDefaults?: boolean;
}
export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig {
ensureConfigDir();
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
@@ -65,12 +79,11 @@ export function loadOneBotConfig(uin: string): OneBotConfig {
if (globalRaw) sources.push(globalRaw);
if (perUinRaw) sources.push(perUinRaw);
const config = fromJson(sources);
const config = fromJson(sources, !perUinRaw && !globalRaw);
// Persist normalized form whenever the file is missing OR was in legacy
// format, so downstream code can rely on the unified shape on disk.
const shouldSave = !perUinRaw || legacy;
if (shouldSave) saveOneBotConfig(uin, config);
if (options.persistDefaults && (!perUinRaw || legacy)) {
saveOneBotConfig(uin, config);
}
return config;
}
@@ -148,7 +161,7 @@ function wsClientToJson(n: WsClientNetwork): JsonObject {
return out;
}
function fromJson(sources: JsonObject[]): OneBotConfig {
function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
// Legacy top-level scalars are pulled DOWN into each adapter on the first
// load: the on-disk schema has no globals anymore, every adapter is
// self-describing. We compute the legacy fallbacks here so that adapters
@@ -175,8 +188,11 @@ function fromJson(sources: JsonObject[]): OneBotConfig {
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
// Seed defaults if all four arrays are empty (brand-new install).
// Seed defaults ONLY for a brand-new install (no source files at all).
// If the operator deliberately emptied every adapter, respect that and
// do NOT silently revive default 0.0.0.0 listeners.
if (
freshInstall &&
httpServers.length === 0 &&
httpClients.length === 0 &&
wsServers.length === 0 &&
@@ -354,7 +370,8 @@ function tryLoadJson(filePath: string): JsonObject | null {
const raw = fs.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(raw) as unknown;
return isObject(parsed) ? parsed : null;
} catch {
} catch (err) {
log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err));
return null;
}
}
@@ -364,20 +381,6 @@ function saveJson(filePath: string, json: JsonObject): void {
fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8');
}
function deepClone(obj: JsonObject): JsonObject {
return JSON.parse(JSON.stringify(obj)) as JsonObject;
}
function deepMerge(base: JsonObject, override: JsonObject): void {
for (const [key, value] of Object.entries(override)) {
if (isObject(base[key]) && isObject(value)) {
deepMerge(base[key] as JsonObject, value);
} else {
base[key] = value as never;
}
}
}
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+2 -2
View File
@@ -35,7 +35,7 @@ export class OneBotManager {
const instance = this.instances.get(uin);
if (!instance) return false;
const config = loadOneBotConfig(uin);
const config = loadOneBotConfig(uin, { persistDefaults: true });
instance.reloadConfig(config);
log.info('configuration reloaded: UIN=%s', uin);
return true;
@@ -51,7 +51,7 @@ export class OneBotManager {
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin);
const config = loadOneBotConfig(uin, { persistDefaults: true });
const instance = new OneBotInstance(uin, bridge, config);
const activePid = bridge.activePid;
+30 -2
View File
@@ -45,7 +45,7 @@ describe('loadOneBotConfig', () => {
it('creates and persists default config when none exists', () => {
const uin = '10001';
const config = loadOneBotConfig(uin);
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toHaveLength(1);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
@@ -74,7 +74,7 @@ describe('loadOneBotConfig', () => {
};
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8');
const config = loadOneBotConfig(uin);
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toHaveLength(1);
expect(config.networks.httpServers[0].port).toBe(3100);
expect(config.networks.httpServers[0].accessToken).toBe('tok');
@@ -128,6 +128,34 @@ describe('loadOneBotConfig', () => {
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
});
it('does not write to disk by default (read-only contract)', () => {
const uin = '10006';
const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`);
// Default call must not materialize the file or mint a fresh access token.
const config = loadOneBotConfig(uin);
expect(config.networks.httpServers).toHaveLength(1);
expect(fs.existsSync(cfgPath)).toBe(false);
// Explicit opt-in still writes.
loadOneBotConfig(uin, { persistDefaults: true });
expect(fs.existsSync(cfgPath)).toBe(true);
});
it('respects an operator-emptied adapter list instead of seeding defaults back', () => {
const uin = '10007';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
musicSignUrl: '',
}), 'utf8');
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toEqual([]);
expect(config.networks.wsServers).toEqual([]);
});
it('migrates legacy lowercase WsRole values into canonical uppercase form', () => {
const uin = '10005';
const dir = path.join(tempDir, 'config');