fix(config): protect operator credentials

Keep first-run access details confined to the active process console and remove development credentials from managed application logs.

Treat notification delivery settings as sensitive during backup and restore, preserve private file access across creation and updates, and align the WebUI guidance with the new boundary.
This commit is contained in:
DrSmoothl committed 2026-08-01 17:02:39 +08:00
1 parent ea841d929e
commit 8940f8864b
9 files changed
+123 -43

No files matched your search

+11 -7
View File
@@ -214,13 +214,12 @@ function emit(
level: LogLevel,
options: LogOptions,
args: unknown[],
forceInitialCredentials = false,
): void {
// Console / subscriber and file filters are independent. If no destination
// accepts the record, stop before formatting or building a LogEntry.
const passesConsole = forceInitialCredentials || shouldLog(level);
const passesConsole = shouldLog(level);
const passesFile = level !== 'trace'
&& (forceInitialCredentials || shouldLogToFile(level));
&& shouldLogToFile(level);
if (!passesConsole && !passesFile) return;
// `trace` is the high-volume full-chain diagnostic stream, intentionally
@@ -239,7 +238,7 @@ function emit(
const reqId = currentRequestId();
const formattedMessage = format(...realArgs);
const message = level === 'trace' || forceInitialCredentials
const message = level === 'trace'
? formattedMessage
: redactLogMessage(formattedMessage);
const line = render(level, options, message, reqId);
@@ -364,12 +363,17 @@ export function runWithTraceRequest<T>(fn: () => T): T {
}
export function logInitialWebuiCredentials(password: string): void {
emit(
// This is deliberately not a LogEntry: application logs can be retained on
// disk, exported through WebUI, and delivered to subscribers. First-run
// credentials must only cross the process terminal boundary.
const line = render(
'info',
{ scope: 'WebUI' },
['initial credentials: user=admin password=%s', password],
true,
format('initial credentials: user=admin password=%s', password),
);
// Keep the same terminal control-character policy as regular console logs.
// eslint-disable-next-line no-control-regex
process.stdout.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n');
}
// Request-correlation primitives remain available for callers that already own
+15 -14
View File
@@ -289,25 +289,26 @@ describe('file output gating', () => {
]);
});
it('keeps bootstrap notices visible and persisted above configured thresholds', async () => {
it('prints bootstrap credentials only to the current process terminal', async () => {
const fresh = await loadLoggerForFileLevel('error');
fresh.setLogLevel('error');
const entries: LogEntry[] = [];
const unsubscribe = fresh.subscribeLogs((entry) => entries.push(entry));
const snapshotBefore = fresh.getLogSnapshot();
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
fresh.logInitialWebuiCredentials('secret');
unsubscribe();
try {
fresh.logInitialWebuiCredentials('secret');
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
level: 'info',
scope: 'WebUI',
message: 'initial credentials: user=admin password=secret',
});
expect(fileWriteSpy).toHaveBeenCalledTimes(1);
expect(fileWriteSpy).toHaveBeenCalledWith(
expect.stringContaining('initial credentials: user=admin password=secret'),
undefined,
);
expect(stdout).toHaveBeenCalledWith(
expect.stringContaining('initial credentials: user=admin password=secret'),
);
expect(entries).toEqual([]);
expect(fresh.getLogSnapshot()).toEqual(snapshotBefore);
expect(fileWriteSpy).not.toHaveBeenCalled();
} finally {
unsubscribe();
stdout.mockRestore();
}
});
});
+18 -3
View File
@@ -170,11 +170,22 @@ function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function enforceSensitiveFileMode(file: string): void {
// POSIX mode bits do not model Windows ACLs; on Windows the inherited ACL
// remains authoritative. Avoid pretending chmod provides equivalent policy.
if (process.platform !== 'win32') fs.chmodSync(file, 0o600);
}
function atomicWrite(config: NotificationsConfig): void {
ensureConfigDir();
const tmp = NOTIFICATIONS_CONFIG_PATH + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
fs.writeFileSync(tmp, JSON.stringify(config, null, 2), {
encoding: 'utf8',
mode: 0o600,
});
enforceSensitiveFileMode(tmp);
fs.renameSync(tmp, NOTIFICATIONS_CONFIG_PATH);
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
}
let cached: NotificationsConfig | null = null;
@@ -195,6 +206,10 @@ export function loadNotificationsConfig(): NotificationsConfig {
return fresh;
}
// Webhook URLs commonly embed credentials. Repair older permissive files
// before reading them into memory so upgrades close the exposure promptly.
enforceSensitiveFileMode(NOTIFICATIONS_CONFIG_PATH);
try {
const raw = fs.readFileSync(NOTIFICATIONS_CONFIG_PATH, 'utf8');
const parsed = JSON.parse(raw) as unknown;
@@ -203,8 +218,8 @@ export function loadNotificationsConfig(): NotificationsConfig {
if (JSON.stringify(parsed) !== JSON.stringify(normalized)) {
try {
atomicWrite(normalized);
} catch {
/* best-effort self-heal */
} catch (err) {
log.warn('failed to normalize notifications.json on disk: %s', err instanceof Error ? err.message : String(err));
}
}
cached = normalized;
+6 -6
View File
@@ -4,9 +4,10 @@
// can't leak and an import can't path-traverse.
//
// Credentials are gated by a toggle on both export and import. The credential
// set is: webui.json (password hash), key.pem (TLS private key), AND every
// OneBot config (onebot.json + per-account onebot_<uin>.json) — those carry the
// OneBot access token, so a no-credentials backup must NOT include them.
// set is: webui.json (password hash), key.pem (TLS private key),
// notifications.json (webhook URLs may embed secrets), AND every OneBot config
// (onebot.json + per-account onebot_<uin>.json) — those carry access tokens, so
// a no-credentials backup must NOT include them.
// cert.pem is public so it always travels.
//
// Pure functions here own bundle validation and semantic preflight. Filesystem
@@ -39,9 +40,8 @@ export interface BackupFileSpec {
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: 'notifications.json', binary: false, credential: true },
// Global all-accounts SnowLuma settings (rkey fallback servers, …).
{ name: 'snowluma.json', binary: false, credential: false },
{ name: 'cert.pem', binary: false, credential: false },
{ name: 'ui-assets/background', binary: true, credential: false },
+1 -1
View File
@@ -484,7 +484,7 @@ export async function initWebUI(
const auth = WebuiAuth.load();
const initialPassword = auth.takeInitialPassword();
if (auth.isDevMode()) {
log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword);
log.warn('dev mode enabled with the configured development credential');
log.warn('dev mode skips config/webui.json and password rotation');
} else if (initialPassword) {
log.info('════════════════════════════════════════════════════════════════');
@@ -160,7 +160,11 @@ describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () =>
const mod = await import('../src/notifications/config');
const cfg = mod.loadNotificationsConfig();
expect(cfg).toEqual(mod.defaultNotificationsConfig());
expect(fs.existsSync(path.join('config', 'notifications.json'))).toBe(true);
const file = path.join('config', 'notifications.json');
expect(fs.existsSync(file)).toBe(true);
if (process.platform !== 'win32') {
expect(fs.statSync(file).mode & 0o777).toBe(0o600);
}
});
it('round-trips a saved config across a fresh module load', async () => {
@@ -177,6 +181,42 @@ describe('loadNotificationsConfig / saveNotificationsConfig (fs-backed)', () =>
expect(mod2.loadNotificationsConfig()).toEqual(saved);
});
it('repairs permissive permissions on an existing sensitive config', async () => {
const file = path.join('config', 'notifications.json');
fs.mkdirSync('config', { recursive: true });
fs.writeFileSync(file, JSON.stringify({
version: 1,
debounceSeconds: 30,
channels: [{ id: 'ops', url: 'https://example.com/private-hook' }],
}), { encoding: 'utf8', mode: 0o644 });
if (process.platform !== 'win32') fs.chmodSync(file, 0o644);
const mod = await import('../src/notifications/config');
expect(mod.loadNotificationsConfig().channels).toHaveLength(1);
if (process.platform !== 'win32') {
expect(fs.statSync(file).mode & 0o777).toBe(0o600);
}
});
it('keeps restrictive permissions after replacing an existing config', async () => {
const file = path.join('config', 'notifications.json');
fs.mkdirSync('config', { recursive: true });
fs.writeFileSync(file, JSON.stringify({ version: 1, debounceSeconds: 30, channels: [] }), {
encoding: 'utf8',
mode: 0o644,
});
if (process.platform !== 'win32') fs.chmodSync(file, 0o644);
const mod = await import('../src/notifications/config');
mod.saveNotificationsConfig({
channels: [{ id: 'ops', url: 'https://example.com/private-hook' }],
});
if (process.platform !== 'win32') {
expect(fs.statSync(file).mode & 0o777).toBe(0o600);
}
});
it('section-merges partial saves (debounce-only keeps channels)', async () => {
const mod = await import('../src/notifications/config');
mod.saveNotificationsConfig({ channels: [{ id: 'c1', url: 'https://a.com' }] });
+27 -7
View File
@@ -27,9 +27,10 @@ describe('buildBackup', () => {
expect(b.files['runtime.json']).toEqual({ encoding: 'utf8', data: '{"webuiPort":5099}' });
});
it('treats all OneBot config (global + per-uin), webui.json, key.pem as credentials', () => {
it('treats notification endpoints and all authentication material as credentials', () => {
const map = {
'runtime.json': Buffer.from('{}'),
'notifications.json': Buffer.from('{"channels":[]}'),
'webui.json': Buffer.from('{"hash":"x"}'),
'key.pem': Buffer.from('KEY'),
'cert.pem': Buffer.from('CERT'),
@@ -42,7 +43,7 @@ describe('buildBackup', () => {
expect(Object.keys(without.files).sort()).toEqual(['cert.pem', 'runtime.json']);
const withCreds = buildBackup(reader(map), perUin, { includeCredentials: true }, TS);
expect(Object.keys(withCreds.files).sort()).toEqual(
['cert.pem', 'key.pem', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'],
['cert.pem', 'key.pem', 'notifications.json', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'],
);
});
@@ -61,6 +62,7 @@ describe('buildBackup', () => {
describe('specFor', () => {
it('resolves static names and per-uin onebot pattern; rejects others', () => {
expect(specFor('runtime.json')?.credential).toBe(false);
expect(specFor('notifications.json')?.credential).toBe(true);
expect(specFor('onebot.json')?.credential).toBe(true);
expect(specFor('onebot_98765.json')).toEqual({ name: 'onebot_98765.json', binary: false, credential: true });
expect(specFor('onebot_.json')).toBeNull();
@@ -71,9 +73,9 @@ describe('specFor', () => {
});
});
it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.pem public', () => {
it('BACKUP_FILES marks notification endpoints and authentication material as credentials', () => {
const creds = BACKUP_FILES.filter((f) => f.credential).map((f) => f.name).sort();
expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']);
expect(creds).toEqual(['key.pem', 'notifications.json', 'onebot.json', 'webui.json']);
expect(specFor('cert.pem')?.credential).toBe(false);
});
@@ -156,10 +158,23 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
}),
},
}),
{ restoreCredentials: false, readCurrent: () => null },
{ restoreCredentials: true, readCurrent: () => null },
)).toThrow(/notifications\.json.*channels/i);
});
it('skips notification endpoints when credential restore is disabled', () => {
const prepared = prepareRestorePlan(
backupWith({
'notifications.json': { encoding: 'utf8', data: '{private malformed value' },
'runtime.json': { encoding: 'utf8', data: '{}' },
}),
{ restoreCredentials: false, readCurrent: () => null },
);
expect(prepared.skipped).toEqual(['notifications.json']);
expect(prepared.restore.map((entry) => entry.name)).toEqual(['runtime.json']);
});
it('does not validate credential files that the operator chose to skip', () => {
const prepared = prepareRestorePlan(
backupWith({
@@ -278,13 +293,18 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
const prepared = prepareRestorePlan(
backupWith({
'webui.json': { encoding: 'utf8', data: JSON.stringify(validAuth) },
'notifications.json': {
encoding: 'utf8',
data: JSON.stringify({ version: 1, debounceSeconds: 30, channels: [] }),
},
}),
{ restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] },
);
expect(prepared.restore).toEqual([
expect(prepared.restore).toEqual(expect.arrayContaining([
expect.objectContaining({ name: 'webui.json', mode: 0o600 }),
]);
expect.objectContaining({ name: 'notifications.json', mode: 0o600 }),
]));
});
it('rejects an encoding that does not match the allowlisted file kind', () => {
@@ -606,7 +606,7 @@ export function LogsPage() {
<div>
<div className="mb-2 flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
<span className="text-xs font-medium text-foreground">服务端日志级别</span>
<span className="text-xs text-muted-foreground">· 普通日志仅影响控制台 / 实时流;首次登录凭据始终可见;文件等级由环境变量决定,默认为 debug</span>
<span className="text-xs text-muted-foreground">· 普通日志仅影响控制台 / 实时流;首次登录凭据仅输出到启动终端;文件等级由环境变量决定,默认为 debug</span>
</div>
<SkeletonSwap
ready={serverLevelReady}
@@ -379,7 +379,7 @@ export function SystemPanel() {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm"><Database className="h-4 w-4" /> 配置备份 / 恢复</CardTitle>
<CardDescription>备份外观、通知、系统设置和证书等配置;敏感开关还会包含 OneBot 配置。不含消息数据库。</CardDescription>
<CardDescription>备份外观、系统设置和证书等配置;通知渠道与 OneBot 配置仅在包含敏感配置时导出。不含消息数据库。</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
@@ -388,7 +388,7 @@ export function SystemPanel() {
<ToggleSwitch value={exportCreds} onChange={setExportCreds} ariaLabel="导出包含敏感配置" />
</div>
{exportCreds && (
<p className="text-sm leading-relaxed text-red-600 dark:text-red-400">⚠ 将额外包含 WebUI 登录状态、TLS 私钥,以及带访问令牌的 OneBot 配置,请妥善保管。</p>
<p className="text-sm leading-relaxed text-red-600 dark:text-red-400">⚠ 将额外包含 WebUI 登录状态、TLS 私钥、通知渠道地址与 OneBot 访问令牌,请妥善保管。</p>
)}
<div>
<Button onClick={exportBackup} disabled={saving} className="gap-1.5">
@@ -405,7 +405,7 @@ export function SystemPanel() {
<ToggleSwitch value={restoreCreds} onChange={setRestoreCreds} ariaLabel="恢复包含敏感配置" />
</div>
{restoreCreds && (
<p className="text-sm leading-relaxed text-red-600 dark:text-red-400">⚠ 将覆盖当前 WebUI 登录状态、TLS 私钥与 OneBot 配置(含访问令牌);若备份口令未知可能登不进。</p>
<p className="text-sm leading-relaxed text-red-600 dark:text-red-400">⚠ 将覆盖当前 WebUI 登录状态、TLS 私钥、通知渠道地址与 OneBot 访问令牌;若备份口令未知可能登不进。</p>
)}
<input
ref={fileRef}