feat(runtime): override deploy settings from the environment

SNOWLUMA_ variables can set the factory OneBot listen ports, WebUI TLS,
packet and hook timeouts, the stream directory, file download timeout,
and notification HTTP timeout. The values apply in memory and are not
written back to saved config.
This commit is contained in:
DrSmoothl committed 2026-10-06 00:48:34 +08:00
1 parent c989c764e3
commit f95d247e73
19 files changed
+342 -14

No files matched your search

+7 -2
View File
@@ -1,3 +1,4 @@
import { positiveIntEnv } from '@snowluma/common/env';
import { readFile } from 'node:fs/promises';
import { FriendDressError } from '@snowluma/protocol/web/friend-dress';
import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info';
@@ -21,7 +22,11 @@ import { groupInfoReturnsSchema } from './group-info';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
const DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
function downloadFileTimeoutMs(): number {
return positiveIntEnv('SNOWLUMA_DOWNLOAD_FILE_TIMEOUT_MS', DEFAULT_DOWNLOAD_FILE_TIMEOUT_MS);
}
const profileLikeUserSchema = {
type: 'object',
@@ -2592,7 +2597,7 @@ export const actions = [
buf = Buffer.from(base64, 'base64');
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
} else {
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS);
buf = await fetchDownloadFile(url, parseDownloadHeaders(p.headers), DOWNLOAD_FILE_MAX_BYTES, downloadFileTimeoutMs());
}
try {
const safe = await saveDownloadBuffer(buf, name);
+64 -1
View File
@@ -1,3 +1,4 @@
import { positiveIntEnv } from '@snowluma/common/env';
import { createLogger } from '@snowluma/common/logger';
import { isRealUin } from '@snowluma/common/uin';
import { randomBytes } from 'crypto';
@@ -110,7 +111,69 @@ export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions =
saveOneBotConfig(uin, config, { mode: globalRaw ? 'overlay' : 'snapshot' });
}
return config;
// Listen-port overrides stay in memory. Persisting them would bake a
// machine-specific port into onebot_<uin>.json.
return applyOneBotListenPortOverrides(config);
}
const HTTP_DEFAULT_SERVER = 'http-default';
const WS_DEFAULT_SERVER = 'ws-default';
/** Override only the factory listeners. Other adapters keep their saved ports. */
export function applyOneBotListenPortOverrides(
config: OneBotConfig,
env: NodeJS.ProcessEnv = process.env,
): OneBotConfig {
const httpPort = readListenPort('SNOWLUMA_ONEBOT_HTTP_PORT', env);
const wsPort = readListenPort('SNOWLUMA_ONEBOT_WS_PORT', env);
if (httpPort === undefined && wsPort === undefined) return config;
const next = structuredClone(config);
const httpApplied = httpPort !== undefined && assignFactoryPort(
next.networks.httpServers,
HTTP_DEFAULT_SERVER,
httpPort,
'SNOWLUMA_ONEBOT_HTTP_PORT',
);
const wsApplied = wsPort !== undefined && assignFactoryPort(
next.networks.wsServers,
WS_DEFAULT_SERVER,
wsPort,
'SNOWLUMA_ONEBOT_WS_PORT',
);
if (!httpApplied && !wsApplied) return config;
try {
assertValidOneBotConfig(next);
} catch (error) {
log.warn(
'OneBot listen port override ignored: %s',
error instanceof Error ? error.message : String(error),
);
return config;
}
return next;
}
function readListenPort(name: string, env: NodeJS.ProcessEnv): number | undefined {
const raw = env[name];
if (typeof raw !== 'string' || !raw.trim()) return undefined;
const port = positiveIntEnv(name, 0, { max: 65535, env });
return port > 0 ? port : undefined;
}
function assignFactoryPort(
servers: Array<{ name: string; port: number }>,
name: string,
port: number,
envName: string,
): boolean {
const server = servers.find((entry) => entry.name === name);
if (!server) {
log.warn('%s is ignored; no %s listener', envName, name);
return false;
}
server.port = port;
return true;
}
export interface SaveOneBotConfigOptions {
+20 -1
View File
@@ -1,7 +1,10 @@
import { createLogger } from '@snowluma/common/logger';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const log = createLogger('OneBot.Stream');
export interface StreamStorageSnapshot {
totalBytes: number;
fileCount: number;
@@ -273,7 +276,23 @@ function resolveManagedRoot(input: string): string {
return path.join(fs.realpathSync(parent), path.basename(absolute));
}
export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'onebot-stream'));
export function createStreamStorage(env: NodeJS.ProcessEnv = process.env): StreamStorage {
const fallback = path.join(os.tmpdir(), 'onebot-stream');
const raw = env.SNOWLUMA_STREAM_DIR?.trim();
if (!raw) return new StreamStorage(fallback);
try {
return new StreamStorage(raw);
} catch (error) {
log.warn(
'SNOWLUMA_STREAM_DIR=%j is ignored: %s',
raw,
error instanceof Error ? error.message : String(error),
);
return new StreamStorage(fallback);
}
}
export const streamStorage = createStreamStorage();
export const STREAM_ROOT = streamStorage.root;
export const STREAM_UPLOAD_DIR = streamStorage.uploadDir;
export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir;
+58
View File
@@ -640,3 +640,61 @@ describe('OneBotConfig login history sync', () => {
.toThrow(/historySync\.enabled must be a boolean/);
});
});
describe('OneBot listen port environment overrides', () => {
let tempDir = '';
let previous = '';
const saved: Record<string, string | undefined> = {};
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-port-env-'));
previous = process.cwd();
process.chdir(tempDir);
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
saved[name] = process.env[name];
delete process.env[name];
}
});
afterEach(() => {
for (const name of ['SNOWLUMA_ONEBOT_HTTP_PORT', 'SNOWLUMA_ONEBOT_WS_PORT']) {
if (saved[name] === undefined) delete process.env[name];
else process.env[name] = saved[name];
}
process.chdir(previous);
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('overrides only the factory listeners and does not write the port back', () => {
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
process.env.SNOWLUMA_ONEBOT_WS_PORT = '3801';
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
expect(loaded.networks.httpServers[0]?.port).toBe(3800);
expect(loaded.networks.wsServers[0]?.port).toBe(3801);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', 'onebot_10001.json'), 'utf8')) as {
networks: { httpServers: Array<{ port: number }>; wsServers: Array<{ port: number }> };
};
expect(onDisk.networks.httpServers[0]?.port).toBe(3000);
expect(onDisk.networks.wsServers[0]?.port).toBe(3001);
});
it('leaves a custom listener alone', () => {
const config = makeDefaultOneBotConfig();
config.networks.httpServers = [{
...config.networks.httpServers[0]!,
name: 'public-http',
port: 4000,
}];
saveOneBotConfig('10001', config);
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = '3800';
const loaded = loadOneBotConfig('10001');
expect(loaded.networks.httpServers.map((server) => server.port)).toEqual([4000]);
});
it('keeps the saved port when the override is not a port', () => {
process.env.SNOWLUMA_ONEBOT_HTTP_PORT = 'nope';
const loaded = loadOneBotConfig('10001', { persistDefaults: true });
expect(loaded.networks.httpServers[0]?.port).toBe(3000);
});
});
@@ -0,0 +1,36 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { createStreamStorage } from '../src/stream-storage';
describe('SNOWLUMA_STREAM_DIR', () => {
const created: string[] = [];
afterEach(() => {
for (const directory of created.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
it('uses the system temp directory by default', () => {
const storage = createStreamStorage({});
expect(storage.root.endsWith(`${path.sep}onebot-stream`)).toBe(true);
created.push(storage.root);
});
it('uses a caller directory when the variable is set', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-stream-env-'));
created.push(root);
const storage = createStreamStorage({ SNOWLUMA_STREAM_DIR: root });
expect(storage.root).toBe(fs.realpathSync(root));
});
it('falls back when the variable does not name a usable directory', () => {
const file = path.join(os.tmpdir(), `snowluma-stream-not-dir-${process.pid}`);
fs.writeFileSync(file, 'x');
created.push(file);
const storage = createStreamStorage({ SNOWLUMA_STREAM_DIR: file });
expect(storage.root.endsWith(`${path.sep}onebot-stream`)).toBe(true);
});
});