diff --git a/packages/common/src/logger.ts b/packages/common/src/logger.ts index ceeb0910..73f0f301 100644 --- a/packages/common/src/logger.ts +++ b/packages/common/src/logger.ts @@ -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(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 diff --git a/packages/common/tests/logger.test.ts b/packages/common/tests/logger.test.ts index a9b3330b..db08e896 100644 --- a/packages/common/tests/logger.test.ts +++ b/packages/common/tests/logger.test.ts @@ -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(); + } }); }); diff --git a/packages/core/src/notifications/config.ts b/packages/core/src/notifications/config.ts index 20380a02..7fe91419 100644 --- a/packages/core/src/notifications/config.ts +++ b/packages/core/src/notifications/config.ts @@ -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; diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 2feb1c4b..0c1041a1 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -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_.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_.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 }, diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index d7acaecf..08f97b41 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -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('════════════════════════════════════════════════════════════════'); diff --git a/packages/core/tests/notifications-config.test.ts b/packages/core/tests/notifications-config.test.ts index 29bde880..e3a75b9f 100644 --- a/packages/core/tests/notifications-config.test.ts +++ b/packages/core/tests/notifications-config.test.ts @@ -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' }] }); diff --git a/packages/core/tests/webui-backup.test.ts b/packages/core/tests/webui-backup.test.ts index 5524f0a9..a4bc0d69 100644 --- a/packages/core/tests/webui-backup.test.ts +++ b/packages/core/tests/webui-backup.test.ts @@ -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', () => { diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index b4e02678..77f62cb2 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -606,7 +606,7 @@ export function LogsPage() {
服务端日志级别 - · 普通日志仅影响控制台 / 实时流;首次登录凭据始终可见;文件等级由环境变量决定,默认为 debug + · 普通日志仅影响控制台 / 实时流;首次登录凭据仅输出到启动终端;文件等级由环境变量决定,默认为 debug
配置备份 / 恢复 - 备份外观、通知、系统设置和证书等配置;敏感开关还会包含 OneBot 配置。不含消息数据库。 + 备份外观、系统设置和证书等配置;通知渠道与 OneBot 配置仅在包含敏感配置时导出。不含消息数据库。
@@ -388,7 +388,7 @@ export function SystemPanel() {
{exportCreds && ( -

⚠ 将额外包含 WebUI 登录状态、TLS 私钥,以及带访问令牌的 OneBot 配置,请妥善保管。

+

⚠ 将额外包含 WebUI 登录状态、TLS 私钥、通知渠道地址与 OneBot 访问令牌,请妥善保管。

)}
{restoreCreds && ( -

⚠ 将覆盖当前 WebUI 登录状态、TLS 私钥与 OneBot 配置(含访问令牌);若备份口令未知可能登不进。

+

⚠ 将覆盖当前 WebUI 登录状态、TLS 私钥、通知渠道地址与 OneBot 访问令牌;若备份口令未知可能登不进。

)}