From 0503af2fccd47c947a0c8fde422ad915b35f783c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 16 Jul 2026 19:20:48 +0800 Subject: [PATCH] fix(webui): export logs without terminal control codes Keep terminal styling confined to interactive console output while storing plain structured log lines for subscribers and file persistence. Sanitize downloads again at the WebUI boundary so cached legacy entries and fallback-formatted records cannot leak CSI, OSC, DCS, or C1 control sequences. Add regression coverage for colored output, hyperlinks, control strings, malformed sequences, and preserved multiline text. --- packages/common/package.json | 4 + packages/common/src/log-file-transport.ts | 14 +--- packages/common/src/log-sanitize.ts | 81 +++++++++++++++++++ packages/common/src/logger.ts | 3 +- packages/common/tests/log-sanitize.test.ts | 26 ++++++ packages/common/tests/logger.test.ts | 14 +++- packages/webui/package.json | 1 + .../webui/src/components/pages/logs-page.tsx | 7 +- pnpm-lock.yaml | 3 + 9 files changed, 136 insertions(+), 17 deletions(-) create mode 100644 packages/common/src/log-sanitize.ts create mode 100644 packages/common/tests/log-sanitize.test.ts diff --git a/packages/common/package.json b/packages/common/package.json index a159cec7..1400237d 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -40,6 +40,10 @@ "types": "./src/log-file-transport.ts", "default": "./src/log-file-transport.ts" }, + "./log-sanitize": { + "types": "./src/log-sanitize.ts", + "default": "./src/log-sanitize.ts" + }, "./log-summary": { "types": "./src/log-summary.ts", "default": "./src/log-summary.ts" diff --git a/packages/common/src/log-file-transport.ts b/packages/common/src/log-file-transport.ts index d028d6c4..8bc96a69 100644 --- a/packages/common/src/log-file-transport.ts +++ b/packages/common/src/log-file-transport.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; +import { sanitizeLogLine } from './log-sanitize'; const DEFAULT_DIR = 'logs'; const DEFAULT_MAX_MB = 50; @@ -8,13 +9,6 @@ const FILE_PREFIX = 'snowluma-'; const FILE_SUFFIX = '.log'; const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/; -// eslint-disable-next-line no-control-regex -const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g; -// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit -// multi-line records (stack traces), ESC is stripped through ANSI_RE. -// eslint-disable-next-line no-control-regex -const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g; - function parsePositiveInt(v: string | undefined, dflt: number): number { if (!v) return dflt; const n = Number.parseInt(v, 10); @@ -33,10 +27,6 @@ function dateOf(s: string): Date { return new Date(y!, m! - 1, d!); } -function stripAnsi(line: string): string { - return line.replace(ANSI_RE, '').replace(CTRL_RE, ''); -} - interface OpenFile { stream: fs.WriteStream; bytes: number; @@ -234,7 +224,7 @@ export class FileTransport { write(line: string, uin?: number): void { if (!this.shared) return; - const data = stripAnsi(line) + '\n'; + const data = sanitizeLogLine(line) + '\n'; const bytes = Buffer.byteLength(data, 'utf8'); this.shared.write(data, bytes); diff --git a/packages/common/src/log-sanitize.ts b/packages/common/src/log-sanitize.ts new file mode 100644 index 00000000..34f773ff --- /dev/null +++ b/packages/common/src/log-sanitize.ts @@ -0,0 +1,81 @@ +const ESC = 0x1b; +const BEL = 0x07; +const C1_CSI = 0x9b; +const C1_ST = 0x9c; +const C1_OSC = 0x9d; +const C1_STRING_STARTERS = new Set([0x90, 0x98, 0x9e, 0x9f]); + +function skipCsi(line: string, start: number): number { + for (let i = start; i < line.length; i += 1) { + const code = line.charCodeAt(i); + if (code >= 0x40 && code <= 0x7e) return i + 1; + } + return line.length; +} + +function skipControlString(line: string, start: number, allowBell: boolean): number { + for (let i = start; i < line.length; i += 1) { + const code = line.charCodeAt(i); + if (allowBell && code === BEL) return i + 1; + if (code === C1_ST) return i + 1; + if (code === ESC && line.charCodeAt(i + 1) === 0x5c) return i + 2; + } + return line.length; +} + +function skipEscSequence(line: string, start: number): number { + if (start >= line.length) return line.length; + + const first = line.charCodeAt(start); + if (first === 0x5b) return skipCsi(line, start + 1); + if (first === 0x5d) return skipControlString(line, start + 1, true); + if (first === 0x50 || first === 0x58 || first === 0x5e || first === 0x5f) { + return skipControlString(line, start + 1, false); + } + + let i = start; + while (i < line.length) { + const code = line.charCodeAt(i); + if (code < 0x20 || code > 0x2f) break; + i += 1; + } + const final = line.charCodeAt(i); + return final >= 0x30 && final <= 0x7e ? i + 1 : start; +} + +/** + * Remove terminal presentation and control sequences from a log line. + * + * The parser handles both seven-bit ESC forms and eight-bit C1 forms, + * including CSI styling, OSC hyperlinks, and DCS/SOS/PM/APC control strings. + * TAB and LF remain available for formatted records such as stack traces. + * Unterminated terminal strings consume the remainder instead of leaking their + * invisible payload into persisted or downloaded logs. + */ +export function sanitizeLogLine(line: string): string { + let plain = ''; + for (let i = 0; i < line.length;) { + const code = line.charCodeAt(i); + + if (code === ESC) { + i = skipEscSequence(line, i + 1); + continue; + } + if (code === C1_CSI) { + i = skipCsi(line, i + 1); + continue; + } + if (code === C1_OSC || C1_STRING_STARTERS.has(code)) { + i = skipControlString(line, i + 1, code === C1_OSC); + continue; + } + if ((code < 0x20 && code !== 0x09 && code !== 0x0a) || (code >= 0x7f && code <= 0x9f)) { + i += 1; + continue; + } + + plain += line[i]; + i += 1; + } + return plain; +} diff --git a/packages/common/src/logger.ts b/packages/common/src/logger.ts index 6ff80ff1..6e2f83c0 100644 --- a/packages/common/src/logger.ts +++ b/packages/common/src/logger.ts @@ -1,5 +1,6 @@ import { format } from 'util'; import { getFileTransport } from './log-file-transport'; +import { sanitizeLogLine } from './log-sanitize'; import { currentRequestId } from './request-context'; type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error'; @@ -212,7 +213,7 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { ...(options.uin !== undefined ? { uin: options.uin } : {}), ...(reqId !== undefined ? { req: reqId } : {}), message, - line, + line: sanitizeLogLine(line), }; if (passesConsole) { diff --git a/packages/common/tests/log-sanitize.test.ts b/packages/common/tests/log-sanitize.test.ts new file mode 100644 index 00000000..bee296d6 --- /dev/null +++ b/packages/common/tests/log-sanitize.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest'; +import { sanitizeLogLine } from '../src/log-sanitize'; + +describe('sanitizeLogLine', () => { + it('removes SGR styling in seven-bit and eight-bit forms', () => { + expect(sanitizeLogLine('\x1b[31mred\x1b[0m / \u009b32mgreen\u009b0m')).toBe('red / green'); + }); + + it('removes OSC hyperlinks without removing their visible label', () => { + expect( + sanitizeLogLine('\x1b]8;;https://example.com\x07visible\x1b]8;;\x07'), + ).toBe('visible'); + }); + + it('removes terminal control-string payloads', () => { + expect(sanitizeLogLine('before\x1bPprivate payload\x1b\\after')).toBe('beforeafter'); + }); + + it('preserves tabs and newlines while removing other controls', () => { + expect(sanitizeLogLine('one\ttwo\nthree\r\x00')).toBe('one\ttwo\nthree'); + }); + + it('does not leak unterminated terminal strings', () => { + expect(sanitizeLogLine('visible\x1b]8;;https://example.com')).toBe('visible'); + }); +}); diff --git a/packages/common/tests/logger.test.ts b/packages/common/tests/logger.test.ts index 66020f11..5c0cf87a 100644 --- a/packages/common/tests/logger.test.ts +++ b/packages/common/tests/logger.test.ts @@ -5,7 +5,7 @@ vi.mock('../src/log-file-transport', () => ({ getFileTransport: () => ({ write: () => {} }), })); -import { createLogger } from '../src/logger'; +import { createLogger, subscribeLogs, type LogEntry } from '../src/logger'; // Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp // shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored @@ -42,4 +42,16 @@ describe('logger UIN slot padding', () => { expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow(); expect(() => createLogger('Test').info('no uin')).not.toThrow(); }); + + it('keeps structured subscriber lines plain while terminal output stays colored', () => { + const captured: LogEntry[] = []; + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + + createLogger('WebUI.Export').info('download me'); + unsubscribe(); + + expect(captured).toHaveLength(1); + expect(captured[0]!.line).toMatch(/INFO\s+\[WebUI\.Export\] download me$/); + expect(process.stdout.write).toHaveBeenCalledWith(expect.stringContaining('\x1b[')); + }); }); diff --git a/packages/webui/package.json b/packages/webui/package.json index 522a76f0..e0a49ae4 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -19,6 +19,7 @@ "@radix-ui/react-separator": "^1.1.3", "@radix-ui/react-slot": "^1.1.3", "@radix-ui/react-tooltip": "^1.1.9", + "@snowluma/common": "workspace:*", "@tanstack/react-router": "^1.169.2", "@tanstack/react-virtual": "^3.14.5", "class-variance-authority": "^0.7.1", diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index 52b9a6d6..7000aa14 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { sanitizeLogLine } from '@snowluma/common/log-sanitize'; import { useVirtualizer } from '@tanstack/react-virtual'; import { motion, AnimatePresence } from 'motion/react'; import { ArrowDownToLine, Download, Filter, Highlighter, Inbox, Pause, Plus, RefreshCw, Search, SearchX, SlidersHorizontal, Trash2, WrapText, X } from 'lucide-react'; @@ -317,9 +318,9 @@ export function LogsPage() { // Dump the current (filtered) view to a .log text file — purely client-side. const exportLogs = useCallback(() => { if (filtered.length === 0) return; - const lines = filtered.map( - (l) => l.line || `${l.time} ${l.level.toUpperCase().padEnd(7)} [${l.scope}] ${l.message}`, - ); + const lines = filtered.map((l) => sanitizeLogLine( + l.line || `${l.time} ${l.level.toUpperCase().padEnd(7)} [${l.scope}] ${l.message}`, + )); const blob = new Blob([lines.join('\n') + '\n'], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fd84492e..959bb539 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -376,6 +376,9 @@ importers: '@radix-ui/react-tooltip': specifier: ^1.1.9 version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@snowluma/common': + specifier: workspace:* + version: link:../common '@tanstack/react-router': specifier: ^1.169.2 version: 1.169.2(react-dom@19.2.5(react@19.2.5))(react@19.2.5)