A full-featured download manager.
feat(logging): centralize structured log redaction (#1908)
Dr_rOot6b48e855a83b
diff --git a/src/core/log-redact.test.ts b/src/core/log-redact.test.tsnew file mode 100644index 00000000..5c774627--- /dev/null+++ b/src/core/log-redact.test.ts@@ -0,0 +1,603 @@+import { describe, expect, it } from 'vitest'+import { redactApplicationLogArguments, redactLogFields } from './log-redact'++describe('redactLogFields', () => {+ describe('application profile', () => {+ it('retains safe create diagnostics while removing request credentials', () => {+ const out = redactLogFields(+ {+ method: 'createDownload',+ params: {+ gid: '0123456789abcdef',+ uris: [+ 'https://user:[email protected]/file.zip?token=url-secret#part',+ ],+ saveDir: '/Users/alice/Downloads',+ filename: 'file.zip.motrix',+ connections: 16,+ headers: {+ Authorization: 'Bearer auth-secret',+ Cookie: 'session=cookie-secret',+ },+ proxy: 'http://user:[email protected]:8080/private',+ extraEngineOptions: {+ referer: 'https://origin.example/watch?token=referer-secret',+ 'load-cookies': '/tmp/cookie-jar-secret.txt',+ 'select-file': '1,3',+ 'unknown-option': 'unknown-secret',+ },+ },+ },+ { profile: 'application' }+ )++ expect(out).toEqual({+ method: 'createDownload',+ params: {+ gid: '0123456789abcdef',+ uris: ['https://example.com/file.zip'],+ saveDir: '/Users/alice/Downloads',+ filename: 'file.zip.motrix',+ connections: 16,+ headers: ['Authorization', 'Cookie'],+ proxy: 'http://proxy.example:8080',+ extraEngineOptions: {+ referer: 'https://origin.example/watch',+ 'load-cookies': '[redacted-path]',+ 'select-file': '1,3',+ 'unknown-option': '[redacted]',+ },+ },+ })+ const serialized = JSON.stringify(out)+ for (const secret of [+ 'url-secret',+ 'auth-secret',+ 'cookie-secret',+ 'proxy-secret',+ 'referer-secret',+ 'cookie-jar-secret',+ 'unknown-secret',+ ]) {+ expect(serialized).not.toContain(secret)+ }+ })++ it('sanitizes URL collections and opaque URIs', () => {+ const out = redactLogFields(+ {+ rewrittenUris: [+ 'https://cdn.example/file?signature=secret',+ 'magnet:?xt=urn:btih:secret-info-hash&dn=private-name',+ ],+ },+ { profile: 'application' }+ )+ expect(out.rewrittenUris).toEqual([+ 'https://cdn.example/file',+ 'magnet:<redacted>',+ ])+ })++ it('preserves short collection provenance but bounds locations', () => {+ const out = redactLogFields(+ {+ uris: 'plugin-rewriter',+ urls: 3,+ sourceUrl: `https://example.com/${'x'.repeat(70_000)}`,+ proxy: `http://${'y'.repeat(70_000)}.example`,+ },+ { profile: 'application' }+ )++ expect(out).toEqual({+ uris: 'plugin-rewriter',+ urls: 3,+ sourceUrl: '[unparseable-url]',+ proxy: '[unparseable-proxy]',+ })+ expect(redactLogFields(out, { profile: 'application' })).toEqual(out)+ })++ it('fails closed for object values in URL collections and storage keys', () => {+ const out = redactLogFields(+ {+ uris: { token: 'uri-object-secret' },+ storageKey: { token: 'storage-object-secret' },+ },+ { profile: 'application' }+ )++ expect(out).toEqual({+ uris: '[unparseable-url]',+ storageKey: '[redacted]',+ })+ expect(JSON.stringify(out)).not.toContain('object-secret')+ })++ it('redacts exact credential keys without hiding diagnostic metadata', () => {+ const out = redactLogFields(+ {+ token: 'secret',+ api_key: 'secret',+ authToken: 'secret',+ clientSecret: 'secret',+ credentials: { password: 'secret' },+ privateKey: 'secret',+ tokenCount: 2,+ hasCookie: true,+ secretFields: ['apiKey'],+ },+ { profile: 'application' }+ )+ expect(out).toEqual({+ token: '[redacted]',+ api_key: '[redacted]',+ authToken: '[redacted]',+ clientSecret: '[redacted]',+ credentials: '[redacted]',+ privateKey: '[redacted]',+ tokenCount: 2,+ hasCookie: true,+ secretFields: ['apiKey'],+ })+ })++ it('omits body and storage values even when they are nullish', () => {+ const out = redactLogFields(+ { body: null, storageValue: undefined, status: 'ready' },+ { profile: 'application' }+ )+ expect(out).toEqual({ status: 'ready' })+ })++ it('keeps only syntactically valid header names', () => {+ const out = redactLogFields(+ {+ headers: [+ 'Bearer malformed-header-secret',+ 'Authorization: Bearer auth-secret',+ { name: 'Cookie', value: 'cookie-secret' },+ { name: 'invalid header', value: 'other-secret' },+ ],+ },+ { profile: 'application' }+ )++ expect(out.headers).toEqual(['Authorization', 'Cookie'])+ expect(JSON.stringify(out)).not.toContain('secret')+ })++ it('preserves proxy presence metadata', () => {+ const out = redactLogFields(+ {+ proxy: true,+ nested: { proxy: false },+ unset: { proxy: undefined },+ extraEngineOptions: undefined,+ },+ { profile: 'application' }+ )+ expect(out).toEqual({+ proxy: true,+ nested: { proxy: false },+ unset: { proxy: undefined },+ extraEngineOptions: undefined,+ })+ })++ it('fails closed when a safe engine option has an unexpected object', () => {+ const out = redactLogFields(+ {+ extraEngineOptions: {+ 'select-file': { token: 'option-object-secret' },+ 'seed-ratio': 1.5,+ },+ },+ { profile: 'application' }+ )++ expect(out.extraEngineOptions).toEqual({+ 'select-file': '[redacted]',+ 'seed-ratio': 1.5,+ })+ expect(JSON.stringify(out)).not.toContain('option-object-secret')+ })++ it('summarizes binary values instead of expanding their contents', () => {+ const out = redactLogFields(+ { bytes: new Uint8Array([1, 2, 3]) },+ { profile: 'application' }+ )+ expect(out.bytes).toBe('[binary:3 bytes]')+ })++ it('keeps error diagnostics while redacting structured error fields', () => {+ const cause = Object.assign(new Error('upstream failed'), {+ token: 'cause-secret',+ })+ const error = Object.assign(new Error('connection failed', { cause }), {+ code: 'ECONNRESET',+ token: 'error-secret',+ })+ const out = redactLogFields({ err: error }, { profile: 'application' })+ const redactedError = out.err as Error & Record<string, unknown>++ expect(redactedError).toBeInstanceOf(Error)+ expect(redactedError.name).toBe('Error')+ expect(redactedError.message).toBe('connection failed')+ expect(redactedError.stack).toContain('connection failed')+ expect(redactedError.code).toBe('ECONNRESET')+ expect(redactedError.token).toBe('[redacted]')+ const redactedCause = redactedError.cause as Error &+ Record<string, unknown>+ expect(redactedCause).toBeInstanceOf(Error)+ expect(redactedCause.message).toBe('upstream failed')+ expect(redactedCause.token).toBe('[redacted]')+ const serialized = JSON.stringify(redactedError)+ expect(serialized).toContain('connection failed')+ expect(serialized).toContain('ECONNRESET')+ expect(serialized).not.toContain('error-secret')+ expect(serialized).not.toContain('cause-secret')+ })++ it('retains a late enumerable Error cause beyond the width budget', () => {+ const error = new Error('wide failure') as Error & Record<string, unknown>+ for (let index = 0; index < 300; index += 1) {+ error[`field${index}`] = index+ }+ error.cause = Object.assign(new Error('root failure'), {+ token: 'late-cause-secret',+ })++ const out = redactLogFields({ err: error }, { profile: 'application' })+ const redactedError = out.err as Error & Record<string, unknown>+ const redactedCause = redactedError.cause as Error &+ Record<string, unknown>++ expect(redactedError.redactionTruncatedFields).toBe(46)+ expect(redactedCause.message).toBe('root failure')+ expect(redactedCause.token).toBe('[redacted]')+ expect(JSON.stringify(redactedError)).not.toContain('late-cause-secret')+ })++ it('handles circular values and hostile getters without throwing', () => {+ const circular: Record<string, unknown> = {}+ circular.self = circular+ Object.defineProperty(circular, 'hostile', {+ enumerable: true,+ get() {+ throw new Error('getter secret')+ },+ })++ const out = redactLogFields(circular, { profile: 'application' })+ expect(out.self).toBe('[circular]')+ expect(out.hostile).toBe('[unreadable]')+ })++ it('fails closed when a structured log object cannot be inspected', () => {+ const hostile = new Proxy(+ {},+ {+ getPrototypeOf() {+ throw new Error('proxy secret')+ },+ }+ )+ expect(redactApplicationLogArguments([hostile, 'message'])).toEqual([+ { redactionFailed: true },+ 'message',+ ])+ })++ it('blocks custom serialization and unknown object instances', () => {+ class SecretBox {+ password = 'class-secret'+ }+ const out = redactLogFields(+ {+ customSerializer: {+ visible: 'safe',+ toJSON: () => ({ token: 'serializer-secret' }),+ },+ secretBox: new SecretBox(),+ },+ { profile: 'application' }+ )++ expect(out).toEqual({+ customSerializer: {+ visible: 'safe',+ toJSON: '[function]',+ },+ secretBox: '[redacted-object]',+ })+ expect(JSON.stringify(out)).not.toContain('serializer-secret')+ expect(JSON.stringify(out)).not.toContain('class-secret')+ })++ it('renames root logger control fields without changing nested fields', () => {+ const out = redactLogFields(+ {+ level: 99,+ time: 0,+ msg: 'forged message',+ pid: 1,+ hostname: 'attacker',+ module: 'forged-module',+ name: 'resolved-file',+ timestamp: 123,+ ts: 2,+ nested: { level: 10, msg: 'nested diagnostic' },+ },+ { profile: 'application' }+ )++ expect(out).toEqual({+ fieldLevel: 99,+ fieldTime: 0,+ fieldMsg: 'forged message',+ fieldPid: 1,+ fieldHostname: 'attacker',+ fieldModule: 'forged-module',+ name: 'resolved-file',+ timestamp: 123,+ ts: 2,+ nested: { level: 10, msg: 'nested diagnostic' },+ })+ })++ it('preserves colliding diagnostic fields under deterministic suffixes', () => {+ const out = redactLogFields(+ {+ level: 99,+ fieldLevel: 'existing diagnostic',+ fieldLevel2: 'second diagnostic',+ },+ { profile: 'application' }+ )++ expect(out).toEqual({+ fieldLevel: 99,+ fieldLevel2: 'existing diagnostic',+ fieldLevel22: 'second diagnostic',+ })+ expect(redactLogFields(out, { profile: 'application' })).toEqual(out)+ })++ it('treats __proto__ as data instead of mutating the output prototype', () => {+ const input: Record<string, unknown> = { status: 'safe' }+ Object.defineProperty(input, '__proto__', {+ enumerable: true,+ value: { token: 'prototype-secret' },+ })++ const out = redactLogFields(input, { profile: 'application' })++ expect(Object.getPrototypeOf(out)).toBe(Object.prototype)+ expect(Object.hasOwn(out, '__proto__')).toBe(true)+ expect(Object.getOwnPropertyDescriptor(out, '__proto__')?.value).toEqual({+ token: '[redacted]',+ })+ expect(JSON.stringify(out)).not.toContain('prototype-secret')+ })++ it('bounds structured strings, arrays, and record width idempotently', () => {+ const wide = Object.fromEntries(+ Array.from({ length: 300 }, (_, index) => [`field${index}`, index])+ )+ const out = redactLogFields(+ {+ detail: 'x'.repeat(20_000),+ items: Array.from({ length: 300 }, (_, index) => index),+ wide,+ },+ { profile: 'application' }+ )++ expect((out.detail as string).length).toBeLessThanOrEqual(16 * 1024)+ expect(out.detail).toContain('[truncated:')+ expect(out.items).toHaveLength(256)+ expect((out.items as unknown[]).at(-1)).toBe('[truncated:45 items]')+ expect(Object.keys(out.wide as Record<string, unknown>)).toHaveLength(256)+ expect(+ (out.wide as Record<string, unknown>).redactionTruncatedFields+ ).toBe(45)+ expect(redactLogFields(out, { profile: 'application' })).toEqual(out)+ })++ it('replaces oversized field names without reading their values', () => {+ const oversizedKey = `credential-${'secret'.repeat(100)}`+ const input: Record<string, unknown> = { status: 'safe' }+ Object.defineProperty(input, oversizedKey, {+ enumerable: true,+ get() {+ throw new Error('oversized-value-secret')+ },+ })++ const out = redactLogFields(input, { profile: 'application' })++ expect(out).toEqual({+ status: 'safe',+ fieldKeyTruncated1: '[redacted]',+ })+ const serialized = JSON.stringify(out)+ expect(serialized).not.toContain(oversizedKey)+ expect(serialized).not.toContain('oversized-value-secret')+ })++ it('normalizes non-JSON bigint and symbol values', () => {+ const out = redactLogFields(+ { bytesRead: 42n, marker: Symbol('diagnostic') },+ { profile: 'application' }+ )+ expect(out).toEqual({+ bytesRead: '42n',+ marker: '[symbol:diagnostic]',+ })+ expect(() => JSON.stringify(out)).not.toThrow()+ })++ it('normalizes unusual primitive and function formatting arguments', () => {+ const out = redactApplicationLogArguments([+ 'values %s %s %s',+ 42n,+ Symbol('diagnostic'),+ () => 'function-secret',+ ])++ expect(out).toEqual([+ 'values %s %s %s',+ '42n',+ '[symbol:diagnostic]',+ '[function]',+ ])+ expect(JSON.stringify(out)).not.toContain('function-secret')+ })++ it('does not invoke an overridden Date serializer', () => {+ const date = new Date('2026-08-21T00:00:00.000Z')+ Object.defineProperty(date, 'toJSON', {+ value: () => ({ token: 'date-serializer-secret' }),+ })++ const out = redactApplicationLogArguments(['date %j', date])++ expect(out).toEqual(['date %j', '2026-08-21T00:00:00.000Z'])+ expect(JSON.stringify(out)).not.toContain('date-serializer-secret')+ })++ it('is immutable and idempotent', () => {+ const input = {+ url: 'https://a.example/file?q=secret',+ headers: { Cookie: 'secret' },+ nested: { password: 'secret' },+ }+ const snapshot = structuredClone(input)+ const once = redactLogFields(input, { profile: 'application' })+ const twice = redactLogFields(once, { profile: 'application' })++ expect(input).toEqual(snapshot)+ expect(twice).toEqual(once)+ })+ })++ describe('plugin profile', () => {+ const redactPlugin = (fields: Record<string, unknown>, verbose = false) =>+ redactLogFields(fields, { profile: 'plugin', verbose })++ it('strips query strings and fragments from URLs', () => {+ const out = redactPlugin({+ url: 'https://api.example.com/v1/data?token=abc123&user=42#frag',+ })+ expect(out.url).toBe('https://api.example.com/v1/data')+ })++ it('preserves URL origin and pathname without query data', () => {+ const out = redactPlugin({ url: 'https://api.example.com/v1/data' })+ expect(out.url).toBe('https://api.example.com/v1/data')+ })++ it('uses a safe sentinel when a URL is not parseable', () => {+ const out = redactPlugin({ url: 'not-a-url' })+ expect(out.url).toBe('[unparseable-url]')+ })++ it('redacts nested URLs', () => {+ const out = redactPlugin({+ request: { url: 'https://api.example.com/?secret=xyz' },+ })+ expect((out.request as { url: string }).url).toBe(+ 'https://api.example.com/'+ )+ })++ it('drops top-level and nested headers', () => {+ const out = redactPlugin({+ headers: { authorization: 'Bearer xxx' },+ request: { headers: { x: 1 }, url: 'https://a/b' },+ otherKey: 'kept',+ })+ expect('headers' in out).toBe(false)+ expect(out.otherKey).toBe('kept')+ const request = out.request as { headers?: unknown; url: string }+ expect(request.headers).toBeUndefined()+ expect(request.url).toBe('https://a/b')+ })++ it('drops body and storage values', () => {+ const out = redactPlugin({+ body: 'username=alice&password=hunter2',+ storageValue: 'secret',+ })+ expect('body' in out).toBe(false)+ expect('storageValue' in out).toBe(false)+ })++ it('reduces plugin paths to basenames on Unix and Windows', () => {+ const out = redactPlugin({+ path: '/Users/alice/Downloads/secret-document.pdf',+ filePath: 'C:\\Users\\alice\\data\\foo.txt',+ nested: { path: '/var/x/y/z.mp4' },+ })+ expect(out.path).toBe('secret-document.pdf')+ expect(out.filePath).toBe('foo.txt')+ expect((out.nested as { path: string }).path).toBe('z.mp4')+ })++ it('truncates long storage keys', () => {+ const out = redactPlugin({ storageKey: 'a'.repeat(50) })+ expect(out.storageKey).toBe(`${'a'.repeat(32)}…`)+ })++ it('keeps verbose values while protecting root logger control fields', () => {+ const input = {+ url: 'https://api.example.com/v1/data?token=abc',+ headers: { authorization: 'Bearer xxx' },+ body: 'payload',+ path: '/etc/passwd',+ storageKey: 'k'.repeat(50),+ storageValue: 'v',+ level: 99,+ msg: 'forged',+ }+ expect(redactPlugin(input, true)).toEqual({+ url: input.url,+ headers: input.headers,+ body: input.body,+ path: input.path,+ storageKey: input.storageKey,+ storageValue: input.storageValue,+ fieldLevel: 99,+ fieldMsg: 'forged',+ })+ })++ it('keeps verbose secrets but still blocks structural attacks', () => {+ const circular: Record<string, unknown> = { token: 'raw-secret' }+ circular.self = circular+ const out = redactPlugin(+ {+ nested: {+ token: 'raw-secret',+ toJSON: () => ({ token: 'serializer-secret' }),+ },+ circular,+ items: Array.from({ length: 300 }, (_, index) => index),+ },+ true+ )++ expect(out.nested).toEqual({+ token: 'raw-secret',+ toJSON: '[function]',+ })+ expect((out.circular as Record<string, unknown>).self).toBe('[circular]')+ expect(out.items).toHaveLength(256)+ expect(JSON.stringify(out)).toContain('raw-secret')+ expect(JSON.stringify(out)).not.toContain('serializer-secret')+ })+ })+})diff --git a/src/core/log-redact.ts b/src/core/log-redact.tsnew file mode 100644index 00000000..4a7be19f--- /dev/null+++ b/src/core/log-redact.ts@@ -0,0 +1,944 @@+import { basename } from 'node:path'++export type LogRedactionContext =+ | { profile: 'application' }+ | { profile: 'plugin'; verbose: boolean }++const REDACTED = '[redacted]'+const REDACTED_PATH = '[redacted-path]'+const UNREADABLE = '[unreadable]'+const CIRCULAR = '[circular]'+const MAX_DEPTH_REACHED = '[max-depth]'+const FUNCTION_VALUE = '[function]'+const UNKNOWN_OBJECT = '[redacted-object]'+const MAX_DEPTH = 8+const MAX_RECORD_FIELDS = 256+const MAX_ARRAY_ITEMS = 256+const MAX_STRUCTURED_STRING_CHARS = 16 * 1024+const MAX_ERROR_NAME_CHARS = 256+const MAX_ERROR_STACK_CHARS = 64 * 1024+const MAX_FIELD_NAME_CHARS = 256+const MAX_PARSEABLE_LOCATION_CHARS = 64 * 1024+const STORAGE_KEY_MAX_CHARS = 32+const HEADER_NAME_MAX_CHARS = 128+const TRUNCATED_FIELDS_KEY = 'redactionTruncatedFields'+const OMIT = Symbol('omit-log-field')++const ROOT_LOG_FIELD_RENAMES = new Map([+ ['level', 'fieldLevel'],+ ['time', 'fieldTime'],+ ['msg', 'fieldMsg'],+ ['pid', 'fieldPid'],+ ['hostname', 'fieldHostname'],+ ['module', 'fieldModule'],+])++const HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/++const LOG_URL_KEYS = new Set([+ 'url',+ 'uri',+ 'sourceurl',+ 'videourl',+ 'audiourl',+])++const LOG_URL_COLLECTION_KEYS = new Set(['urls', 'uris', 'rewrittenuris'])++const PROXY_KEYS = new Set([+ 'proxy',+ 'proxyurl',+ 'allproxy',+ 'httpproxy',+ 'httpsproxy',+])++const SENSITIVE_VALUE_KEYS = new Set([+ 'authorization',+ 'proxyauthorization',+ 'cookie',+ 'cookies',+ 'setcookie',+ 'setcookies',+ 'password',+ 'passwd',+ 'passphrase',+ 'userpassword',+ 'secret',+ 'clientsecret',+ 'apisecret',+ 'secretkey',+ 'secretaccesskey',+ 'privatekey',+ 'credential',+ 'credentials',+ 'rpcsecret',+ 'token',+ 'authtoken',+ 'accesstoken',+ 'refreshtoken',+ 'sessiontoken',+ 'idtoken',+ 'csrftoken',+ 'bearertoken',+ 'localtoken',+ 'apikey',+ 'proxyauth',+ 'mutualkey',+ 'ticketkey',+ 'nmticket',+ 'proxyusername',+ 'proxypassword',+ 'allproxyuser',+ 'allproxypasswd',+ 'httpuser',+ 'httppasswd',+ 'ftpuser',+ 'ftppasswd',+])++const COMMON_DROP_KEYS = new Set(['body', 'storagevalue'])+const PLUGIN_PATH_KEYS = new Set(['path', 'filepath'])+const SENSITIVE_PATH_KEYS = new Set([+ 'cookiejar',+ 'cookiejarpath',+ 'loadcookies',+])++const SAFE_ENGINE_OPTION_KEYS = new Set([+ 'selectfile',+ 'maxdownloadlimit',+ 'maxuploadlimit',+ 'seedratio',+])++interface RedactionState {+ readonly context: LogRedactionContext+ readonly seen: WeakSet<object>+}++function normalizeKey(key: string): string {+ return key.toLowerCase().replace(/[^a-z0-9]/g, '')+}++function outputKey(+ key: string,+ depth: number,+ profile: LogRedactionContext['profile']+): string {+ if (depth !== 0) return key+ if (profile === 'plugin' && key === 'ts') return 'fieldTs'+ return ROOT_LOG_FIELD_RENAMES.get(key) ?? key+}++function boundedOutputKey(+ key: string,+ depth: number,+ index: number,+ profile: LogRedactionContext['profile']+): string {+ return key.length > MAX_FIELD_NAME_CHARS+ ? `fieldKeyTruncated${index}`+ : outputKey(key, depth, profile)+}++function uniqueOutputKey(+ target: Record<string, unknown>,+ desiredKey: string+): string {+ if (!Object.hasOwn(target, desiredKey)) return desiredKey+ for (let suffix = 2; suffix <= MAX_RECORD_FIELDS + 2; suffix += 1) {+ const suffixText = `${suffix}`+ const candidate = `${desiredKey.slice(+ 0,+ MAX_FIELD_NAME_CHARS - suffixText.length+ )}${suffixText}`+ if (!Object.hasOwn(target, candidate)) return candidate+ }+ return 'fieldNameCollision'+}++function setOwnField(+ target: Record<string, unknown>,+ key: string,+ value: unknown+): void {+ Object.defineProperty(target, key, {+ value,+ enumerable: true,+ configurable: true,+ writable: true,+ })+}++function truncateText(value: string, maxChars: number): string {+ if (value.length <= maxChars) return value+ let suffix = ''+ let prefixChars = maxChars+ for (let attempt = 0; attempt < 3; attempt += 1) {+ prefixChars = Math.max(0, maxChars - suffix.length)+ suffix = `…[truncated:${value.length - prefixChars} chars]`+ }+ prefixChars = Math.max(0, maxChars - suffix.length)+ return `${value.slice(0, prefixChars)}${suffix}`+}++export function truncateLogText(value: string): string {+ return truncateText(value, MAX_STRUCTURED_STRING_CHARS)+}++function truncationMarker(count: number, unit: string): string {+ return `[truncated:${count} ${unit}]`+}++function headerTruncationMarker(count: number): string {+ return `Motrix-Redaction-Truncated-${count}-Headers`+}++function boundedArrayItems<T>(values: readonly T[]): readonly T[] {+ const limit =+ values.length > MAX_ARRAY_ITEMS ? MAX_ARRAY_ITEMS - 1 : values.length+ return values.slice(0, limit)+}++function boundedRecordKeys(keys: readonly string[]): readonly string[] {+ const limit =+ keys.length > MAX_RECORD_FIELDS ? MAX_RECORD_FIELDS - 1 : keys.length+ return keys.slice(0, limit)+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ if (value === null || typeof value !== 'object') return false+ try {+ const proto = Object.getPrototypeOf(value)+ return proto === Object.prototype || proto === null+ } catch {+ return false+ }+}++function safeBasename(raw: unknown): string {+ if (typeof raw !== 'string') return '[unparseable-path]'+ if (raw.length > MAX_PARSEABLE_LOCATION_CHARS) return '[unparseable-path]'+ return truncateText(+ basename(raw.replaceAll('\\', '/')),+ MAX_STRUCTURED_STRING_CHARS+ )+}++function redactUrl(raw: unknown): string {+ if (typeof raw !== 'string') return '[unparseable-url]'+ if (raw.length > MAX_PARSEABLE_LOCATION_CHARS) return '[unparseable-url]'+ try {+ const url = new URL(raw)+ const protocol = url.protocol.toLowerCase()+ if (+ protocol === 'http:' ||+ protocol === 'https:' ||+ protocol === 'ftp:' ||+ protocol === 'sftp:' ||+ protocol === 'ws:' ||+ protocol === 'wss:'+ ) {+ return truncateText(+ `${protocol}//${url.host}${url.pathname}`,+ MAX_STRUCTURED_STRING_CHARS+ )+ }+ if (protocol === 'file:') {+ return truncateText(+ `file:${safeBasename(url.pathname)}`,+ MAX_STRUCTURED_STRING_CHARS+ )+ }+ return truncateText(`${protocol}<redacted>`, MAX_STRUCTURED_STRING_CHARS)+ } catch {+ return '[unparseable-url]'+ }+}++function redactCollectionValue(raw: unknown): unknown {+ if (Array.isArray(raw)) {+ const selected = boundedArrayItems(raw)+ const out = selected.map(redactUrl)+ if (raw.length > MAX_ARRAY_ITEMS) {+ out.push(truncationMarker(raw.length - selected.length, 'items'))+ }+ return out+ }+ if (typeof raw === 'boolean' || typeof raw === 'number') return raw+ if (typeof raw !== 'string') return '[unparseable-url]'+ if (raw.length > MAX_PARSEABLE_LOCATION_CHARS) return '[unparseable-url]'+ try {+ new URL(raw)+ return redactUrl(raw)+ } catch {+ // A scalar under a collection-shaped key can be provenance metadata,+ // for example contributors.uris = "plugin-rewriter". Preserve that+ // diagnostic instead of treating the key name alone as proof of a URL.+ return truncateText(raw, MAX_STRUCTURED_STRING_CHARS)+ }+}++function redactProxy(raw: unknown): string {+ if (typeof raw !== 'string') return '[unparseable-proxy]'+ if (raw.length > MAX_PARSEABLE_LOCATION_CHARS) return '[unparseable-proxy]'+ try {+ const url = new URL(raw)+ return truncateText(+ `${url.protocol}//${url.host}`,+ MAX_STRUCTURED_STRING_CHARS+ )+ } catch {+ return '[unparseable-proxy]'+ }+}++function redactStorageKey(raw: unknown): unknown {+ if (typeof raw !== 'string') return REDACTED+ if (raw.length <= STORAGE_KEY_MAX_CHARS) return raw+ return `${raw.slice(0, STORAGE_KEY_MAX_CHARS)}…`+}++function validHeaderName(raw: unknown): string | undefined {+ if (typeof raw !== 'string') return undefined+ if (raw.length > HEADER_NAME_MAX_CHARS) return undefined+ const name = raw.trim()+ if (+ name.length === 0 ||+ name.length > HEADER_NAME_MAX_CHARS ||+ !HEADER_NAME_PATTERN.test(name)+ ) {+ return undefined+ }+ return name+}++function headerNames(raw: unknown): string[] {+ if (isPlainObject(raw)) {+ try {+ const keys = Object.keys(raw)+ const selected = boundedArrayItems(keys)+ const names = selected.flatMap((key) => {+ const name = validHeaderName(key)+ return name ? [name] : []+ })+ if (keys.length > MAX_ARRAY_ITEMS) {+ names.push(headerTruncationMarker(keys.length - selected.length))+ }+ return names+ } catch {+ return []+ }+ }+ const allValues = Array.isArray(raw) ? raw : [raw]+ const values = boundedArrayItems(allValues)+ const names: string[] = []+ for (const value of values) {+ if (typeof value === 'string') {+ const separator = value.indexOf(':')+ const name =+ separator > 0+ ? validHeaderName(value.slice(0, separator))+ : validHeaderName(value)+ if (name) names.push(name)+ continue+ }+ if (isPlainObject(value)) {+ try {+ const name = validHeaderName(value.name)+ if (name) names.push(name)+ } catch {+ // Ignore a hostile getter rather than leaking the original value.+ }+ }+ }+ if (allValues.length > MAX_ARRAY_ITEMS) {+ names.push(headerTruncationMarker(allValues.length - values.length))+ }+ return names+}++function binarySummary(value: ArrayBuffer | ArrayBufferView): string {+ return `[binary:${value.byteLength} bytes]`+}++function redactError(+ error: Error,+ state: RedactionState,+ depth: number+): Error | string {+ if (state.seen.has(error)) return CIRCULAR+ state.seen.add(error)+ try {+ let name: string+ let message: string+ let stack: string | undefined+ try {+ name = truncateText(error.name, MAX_ERROR_NAME_CHARS)+ } catch {+ name = UNREADABLE+ }+ try {+ message = truncateText(error.message, MAX_STRUCTURED_STRING_CHARS)+ } catch {+ message = UNREADABLE+ }++ try {+ stack = error.stack+ ? truncateText(error.stack, MAX_ERROR_STACK_CHARS)+ : undefined+ } catch {+ stack = UNREADABLE+ }++ const out = new Error(message)+ Object.defineProperties(out, {+ name: {+ value: name,+ enumerable: true,+ configurable: true,+ writable: true,+ },+ message: {+ value: message,+ enumerable: true,+ configurable: true,+ writable: true,+ },+ })+ if (stack === undefined) {+ delete out.stack+ } else {+ Object.defineProperty(out, 'stack', {+ value: stack,+ enumerable: true,+ configurable: true,+ writable: true,+ })+ }++ let keys: string[]+ try {+ keys = Object.keys(error)+ } catch {+ return out+ }+ const outFields = out as unknown as Record<string, unknown>+ const selectedKeys = boundedRecordKeys(keys)+ for (const [index, key] of selectedKeys.entries()) {+ if (key === 'name' || key === 'message' || key === 'stack') continue+ const safeKey = uniqueOutputKey(+ outFields,+ boundedOutputKey(key, depth, index, state.context.profile)+ )+ if (key.length > MAX_FIELD_NAME_CHARS) {+ setOwnField(outFields, safeKey, REDACTED)+ continue+ }+ let value: unknown+ try {+ value = (error as unknown as Record<string, unknown>)[key]+ } catch {+ setOwnField(outFields, safeKey, UNREADABLE)+ continue+ }+ const redacted = redactValue(value, key, state, depth + 1)+ if (redacted !== OMIT) setOwnField(outFields, safeKey, redacted)+ }+ if (keys.length > MAX_RECORD_FIELDS) {+ setOwnField(+ outFields,+ TRUNCATED_FIELDS_KEY,+ keys.length - selectedKeys.length+ )+ }++ if (!selectedKeys.includes('cause')) {+ try {+ if (Object.hasOwn(error, 'cause')) {+ const cause = (error as Error & { cause?: unknown }).cause+ const redacted = redactValue(cause, 'cause', state, depth + 1)+ if (redacted !== OMIT) setOwnField(outFields, 'cause', redacted)+ }+ } catch {+ setOwnField(outFields, 'cause', UNREADABLE)+ }+ }+ return out+ } finally {+ state.seen.delete(error)+ }+}++function redactExtraEngineOptions(value: unknown): unknown {+ if (!isPlainObject(value)) return REDACTED+ const out: Record<string, unknown> = {}+ let keys: string[]+ try {+ keys = Object.keys(value)+ } catch {+ return REDACTED+ }+ const selectedKeys = boundedRecordKeys(keys)+ for (const [index, key] of selectedKeys.entries()) {+ const safeKey = uniqueOutputKey(+ out,+ boundedOutputKey(key, 1, index, 'application')+ )+ if (key.length > MAX_FIELD_NAME_CHARS) {+ setOwnField(out, safeKey, REDACTED)+ continue+ }+ const normalized = normalizeKey(key)+ let optionValue: unknown+ try {+ optionValue = value[key]+ } catch {+ setOwnField(out, safeKey, UNREADABLE)+ continue+ }+ if (normalized === 'referer') {+ setOwnField(out, safeKey, redactUrl(optionValue))+ } else if (SENSITIVE_PATH_KEYS.has(normalized)) {+ setOwnField(out, safeKey, REDACTED_PATH)+ } else if (SENSITIVE_VALUE_KEYS.has(normalized)) {+ setOwnField(out, safeKey, REDACTED)+ } else if (SAFE_ENGINE_OPTION_KEYS.has(normalized)) {+ const safe =+ optionValue === null ||+ optionValue === undefined ||+ typeof optionValue === 'string' ||+ typeof optionValue === 'number' ||+ typeof optionValue === 'boolean'+ ? optionValue+ : REDACTED+ setOwnField(+ out,+ safeKey,+ typeof safe === 'string'+ ? truncateText(safe, MAX_STRUCTURED_STRING_CHARS)+ : safe+ )+ } else {+ setOwnField(out, safeKey, REDACTED)+ }+ }+ if (keys.length > MAX_RECORD_FIELDS) {+ setOwnField(out, TRUNCATED_FIELDS_KEY, keys.length - selectedKeys.length)+ }+ return out+}++function redactArray(+ values: readonly unknown[],+ key: string,+ state: RedactionState,+ depth: number+): unknown[] | string {+ if (state.seen.has(values)) return CIRCULAR+ state.seen.add(values)+ try {+ const selected = boundedArrayItems(values)+ const out = selected.map((value) => {+ const redacted = redactValue(value, key, state, depth + 1)+ return redacted === OMIT ? REDACTED : redacted+ })+ if (values.length > MAX_ARRAY_ITEMS) {+ out.push(truncationMarker(values.length - selected.length, 'items'))+ }+ return out+ } finally {+ state.seen.delete(values)+ }+}++function redactRecord(+ fields: Record<string, unknown>,+ state: RedactionState,+ depth: number+): Record<string, unknown> | string {+ if (state.seen.has(fields)) return CIRCULAR+ state.seen.add(fields)+ try {+ const out: Record<string, unknown> = {}+ let keys: string[]+ try {+ keys = Object.keys(fields)+ } catch {+ return { redactionFailed: true }+ }+ const selectedKeys = boundedRecordKeys(keys)+ for (const [index, key] of selectedKeys.entries()) {+ const safeKey = uniqueOutputKey(+ out,+ boundedOutputKey(key, depth, index, state.context.profile)+ )+ if (key.length > MAX_FIELD_NAME_CHARS) {+ setOwnField(out, safeKey, REDACTED)+ continue+ }+ let value: unknown+ try {+ value = fields[key]+ } catch {+ setOwnField(out, safeKey, UNREADABLE)+ continue+ }+ const redacted = redactValue(value, key, state, depth + 1)+ if (redacted !== OMIT) setOwnField(out, safeKey, redacted)+ }+ if (keys.length > MAX_RECORD_FIELDS) {+ setOwnField(out, TRUNCATED_FIELDS_KEY, keys.length - selectedKeys.length)+ }+ return out+ } finally {+ state.seen.delete(fields)+ }+}++function redactValue(+ value: unknown,+ key: string,+ state: RedactionState,+ depth: number+): unknown | typeof OMIT {+ if (depth > MAX_DEPTH) return MAX_DEPTH_REACHED++ const normalized = normalizeKey(key)+ if (COMMON_DROP_KEYS.has(normalized)) return OMIT+ if (value === null || value === undefined) return value+ if (normalized === 'headers') {+ if (typeof value === 'boolean' || typeof value === 'number') return value+ return state.context.profile === 'plugin' ? OMIT : headerNames(value)+ }+ if (normalized === 'extraengineoptions') {+ return redactExtraEngineOptions(value)+ }+ if (SENSITIVE_VALUE_KEYS.has(normalized)) return REDACTED+ if (SENSITIVE_PATH_KEYS.has(normalized)) return REDACTED_PATH+ if (LOG_URL_KEYS.has(normalized)) return redactUrl(value)+ if (LOG_URL_COLLECTION_KEYS.has(normalized)) {+ return redactCollectionValue(value)+ }+ if (PROXY_KEYS.has(normalized)) {+ if (typeof value === 'boolean' || typeof value === 'number') return value+ return redactProxy(value)+ }+ if (normalized === 'storagekey') return redactStorageKey(value)+ if (state.context.profile === 'plugin' && PLUGIN_PATH_KEYS.has(normalized)) {+ return safeBasename(value)+ }++ if (typeof value === 'function') return FUNCTION_VALUE+ if (value instanceof Error) return redactError(value, state, depth)+ if (value instanceof Date) {+ try {+ return Date.prototype.toISOString.call(value)+ } catch {+ return UNKNOWN_OBJECT+ }+ }+ if (value instanceof URL) {+ try {+ return redactUrl(URL.prototype.toString.call(value))+ } catch {+ return UNKNOWN_OBJECT+ }+ }+ if (value instanceof ArrayBuffer) return binarySummary(value)+ if (ArrayBuffer.isView(value)) return binarySummary(value)+ if (Array.isArray(value)) return redactArray(value, '', state, depth)+ if (isPlainObject(value)) return redactRecord(value, state, depth)+ if (value !== null && typeof value === 'object') return UNKNOWN_OBJECT+ if (typeof value === 'string') {+ return truncateText(value, MAX_STRUCTURED_STRING_CHARS)+ }+ if (typeof value === 'bigint') return `${value}n`+ if (typeof value === 'symbol') {+ return value.description+ ? `[symbol:${truncateText(value.description, MAX_ERROR_NAME_CHARS)}]`+ : '[symbol]'+ }+ return value+}++function limitVerboseArray(+ values: readonly unknown[],+ seen: WeakSet<object>,+ depth: number+): unknown[] | string {+ if (seen.has(values)) return CIRCULAR+ seen.add(values)+ try {+ const selected = boundedArrayItems(values)+ const out = selected.map((value) =>+ limitVerboseValue(value, seen, depth + 1)+ )+ if (values.length > MAX_ARRAY_ITEMS) {+ out.push(truncationMarker(values.length - selected.length, 'items'))+ }+ return out+ } finally {+ seen.delete(values)+ }+}++function limitVerboseError(+ error: Error,+ seen: WeakSet<object>,+ depth: number+): Error | string {+ if (seen.has(error)) return CIRCULAR+ seen.add(error)+ try {+ let name = UNREADABLE+ let message = UNREADABLE+ let stack: string | undefined+ try {+ name = truncateText(error.name, MAX_ERROR_NAME_CHARS)+ } catch {+ // Keep the sentinel.+ }+ try {+ message = truncateText(error.message, MAX_STRUCTURED_STRING_CHARS)+ } catch {+ // Keep the sentinel.+ }+ try {+ stack = error.stack+ ? truncateText(error.stack, MAX_ERROR_STACK_CHARS)+ : undefined+ } catch {+ stack = UNREADABLE+ }++ const out = new Error(message)+ Object.defineProperties(out, {+ name: {+ value: name,+ enumerable: true,+ configurable: true,+ writable: true,+ },+ message: {+ value: message,+ enumerable: true,+ configurable: true,+ writable: true,+ },+ })+ if (stack === undefined) {+ delete out.stack+ } else {+ Object.defineProperty(out, 'stack', {+ value: stack,+ enumerable: true,+ configurable: true,+ writable: true,+ })+ }++ let keys: string[]+ try {+ keys = Object.keys(error)+ } catch {+ return out+ }+ const outFields = out as unknown as Record<string, unknown>+ const selectedKeys = boundedRecordKeys(keys)+ for (const [index, key] of selectedKeys.entries()) {+ if (key === 'name' || key === 'message' || key === 'stack') continue+ const safeKey = uniqueOutputKey(+ outFields,+ boundedOutputKey(key, depth, index, 'plugin')+ )+ if (key.length > MAX_FIELD_NAME_CHARS) {+ setOwnField(outFields, safeKey, REDACTED)+ continue+ }+ let value: unknown+ try {+ value = (error as unknown as Record<string, unknown>)[key]+ } catch {+ value = UNREADABLE+ }+ setOwnField(outFields, safeKey, limitVerboseValue(value, seen, depth + 1))+ }+ if (keys.length > MAX_RECORD_FIELDS) {+ setOwnField(+ outFields,+ TRUNCATED_FIELDS_KEY,+ keys.length - selectedKeys.length+ )+ }+ if (!selectedKeys.includes('cause')) {+ try {+ if (Object.hasOwn(error, 'cause')) {+ setOwnField(+ outFields,+ 'cause',+ limitVerboseValue(+ (error as Error & { cause?: unknown }).cause,+ seen,+ depth + 1+ )+ )+ }+ } catch {+ setOwnField(outFields, 'cause', UNREADABLE)+ }+ }+ return out+ } finally {+ seen.delete(error)+ }+}++function limitVerboseRecord(+ fields: Record<string, unknown>,+ seen: WeakSet<object>,+ depth: number+): Record<string, unknown> | string {+ if (seen.has(fields)) return CIRCULAR+ seen.add(fields)+ try {+ const out: Record<string, unknown> = {}+ let keys: string[]+ try {+ keys = Object.keys(fields)+ } catch {+ return { redactionFailed: true }+ }+ const selectedKeys = boundedRecordKeys(keys)+ for (const [index, key] of selectedKeys.entries()) {+ const safeKey = uniqueOutputKey(+ out,+ boundedOutputKey(key, depth, index, 'plugin')+ )+ if (key.length > MAX_FIELD_NAME_CHARS) {+ setOwnField(out, safeKey, REDACTED)+ continue+ }+ let value: unknown+ try {+ value = fields[key]+ } catch {+ value = UNREADABLE+ }+ setOwnField(out, safeKey, limitVerboseValue(value, seen, depth + 1))+ }+ if (keys.length > MAX_RECORD_FIELDS) {+ setOwnField(out, TRUNCATED_FIELDS_KEY, keys.length - selectedKeys.length)+ }+ return out+ } finally {+ seen.delete(fields)+ }+}++function limitVerboseValue(+ value: unknown,+ seen: WeakSet<object>,+ depth: number+): unknown {+ if (depth > MAX_DEPTH) return MAX_DEPTH_REACHED+ if (value === null || value === undefined) return value+ if (typeof value === 'string') {+ return truncateText(value, MAX_STRUCTURED_STRING_CHARS)+ }+ if (typeof value === 'bigint') return `${value}n`+ if (typeof value === 'symbol') {+ return value.description+ ? `[symbol:${truncateText(value.description, MAX_ERROR_NAME_CHARS)}]`+ : '[symbol]'+ }+ if (typeof value === 'function') return FUNCTION_VALUE+ if (value instanceof Error) return limitVerboseError(value, seen, depth)+ if (value instanceof Date) {+ try {+ return Date.prototype.toISOString.call(value)+ } catch {+ return UNKNOWN_OBJECT+ }+ }+ if (value instanceof URL) {+ try {+ return truncateText(+ URL.prototype.toString.call(value),+ MAX_STRUCTURED_STRING_CHARS+ )+ } catch {+ return UNKNOWN_OBJECT+ }+ }+ if (value instanceof ArrayBuffer) return binarySummary(value)+ if (ArrayBuffer.isView(value)) return binarySummary(value)+ if (Array.isArray(value)) return limitVerboseArray(value, seen, depth)+ if (isPlainObject(value)) return limitVerboseRecord(value, seen, depth)+ if (typeof value === 'object') return UNKNOWN_OBJECT+ return value+}++function protectVerboseRootFields(+ fields: Record<string, unknown>+): Record<string, unknown> {+ try {+ const limited = limitVerboseRecord(fields, new WeakSet(), 0)+ return typeof limited === 'string' ? { redactionFailed: true } : limited+ } catch {+ return { redactionFailed: true }+ }+}++/**+ * Redacts structured log fields without mutating the input. Application logs+ * retain safe diagnostics; plugin logs keep their existing stricter privacy+ * boundary and may opt into the already-visible per-plugin verbose mode.+ */+export function redactLogFields(+ fields: Record<string, unknown>,+ context: LogRedactionContext+): Record<string, unknown> {+ try {+ if (context.profile === 'plugin' && context.verbose) {+ return protectVerboseRootFields(fields)+ }+ const redacted = redactRecord(fields, { context, seen: new WeakSet() }, 0)+ return typeof redacted === 'string' ? { redactionFailed: true } : redacted+ } catch {+ return { redactionFailed: true }+ }+}++function redactApplicationArgument(value: unknown): unknown {+ if (+ value === null ||+ value === undefined ||+ typeof value === 'string' ||+ typeof value === 'number' ||+ typeof value === 'boolean'+ ) {+ return value+ }+ try {+ const redacted = redactValue(+ value,+ '',+ { context: { profile: 'application' }, seen: new WeakSet() },+ 0+ )+ return redacted === OMIT ? REDACTED : redacted+ } catch {+ return { redactionFailed: true }+ }+}++/** Preserve Pino string overloads and primitive formatting values while+ * sanitizing every object argument, including direct Errors and `%j` data. */+export function redactApplicationLogArguments(+ args: readonly unknown[]+): unknown[] {+ return args.map(redactApplicationArgument)+}diff --git a/src/core/logger.test.ts b/src/core/logger.test.tsindex 7ecf4eeb..76a298e9 100644--- a/src/core/logger.test.ts+++ b/src/core/logger.test.ts@@ -1,7 +1,12 @@-import { describe, expect, it, vi } from 'vitest'+import pino from 'pino'+import { beforeEach, describe, expect, it, vi } from 'vitest'import { getLogger, initLogger } from './logger'describe('logger', () => {+ beforeEach(() => {+ initLogger(pino({ level: 'silent' }))+ })+it('getLogger returns a pino child logger with module field', () => {const log = getLogger('engine')expect(log).toBeDefined()@@ -25,4 +30,183 @@ describe('logger', () => {expect(mockChild).toHaveBeenCalledWith({ module: 'test-module' })expect(mockInfo).toHaveBeenCalledWith('hello')})++ it('redacts structured fields before forwarding to the root logger', () => {+ const mockInfo = vi.fn()+ const mockChild = vi.fn().mockReturnValue({ info: mockInfo })+ initLogger({ child: mockChild } as never)++ getLogger('downloads').info(+ {+ url: 'https://example.com/file?token=secret',+ headers: { Authorization: 'Bearer secret' },+ proxy: 'http://user:[email protected]:8080',+ connections: 16,+ },+ 'dispatching'+ )++ expect(mockInfo).toHaveBeenCalledWith(+ {+ url: 'https://example.com/file',+ headers: ['Authorization'],+ proxy: 'http://proxy.example:8080',+ connections: 16,+ },+ 'dispatching'+ )+ })++ it('preserves Pino string and formatting overloads', () => {+ const mockInfo = vi.fn()+ initLogger({ child: vi.fn().mockReturnValue({ info: mockInfo }) } as never)++ getLogger('format').info('created %s', 'task-1')++ expect(mockInfo).toHaveBeenCalledWith('created %s', 'task-1')+ })++ it('redacts objects used by Pino formatting overloads', () => {+ const mockInfo = vi.fn()+ initLogger({ child: vi.fn().mockReturnValue({ info: mockInfo }) } as never)++ getLogger('format').info('request %j', {+ token: 'format-secret',+ url: 'https://example.com/file?signature=format-url-secret',+ count: 1,+ })++ expect(mockInfo).toHaveBeenCalledWith('request %j', {+ token: '[redacted]',+ url: 'https://example.com/file',+ count: 1,+ })+ })++ it('redacts direct Error properties while retaining Error diagnostics', () => {+ const mockError = vi.fn()+ initLogger({+ child: vi.fn().mockReturnValue({ error: mockError }),+ } as never)+ const error = Object.assign(new Error('request failed'), {+ code: 'ECONNRESET',+ token: 'direct-error-secret',+ })++ getLogger('requests').error(error, 'direct error')++ const forwarded = mockError.mock.calls[0]?.[0] as Error &+ Record<string, unknown>+ expect(forwarded).toBeInstanceOf(Error)+ expect(forwarded.message).toBe('request failed')+ expect(forwarded.stack).toContain('request failed')+ expect(forwarded.code).toBe('ECONNRESET')+ expect(forwarded.token).toBe('[redacted]')+ expect(mockError.mock.calls[0]?.[1]).toBe('direct error')+ })++ it('protects custom Pino level methods', () => {+ const mockNotice = vi.fn()+ const rootChild = {+ levels: { values: { notice: 35 } },+ notice: mockNotice,+ }+ initLogger({ child: vi.fn().mockReturnValue(rootChild) } as never)++ const log = getLogger('custom-level') as unknown as {+ notice(fields: Record<string, unknown>, message: string): void+ }+ log.notice({ authorization: 'Bearer secret', count: 1 }, 'notice')++ expect(mockNotice).toHaveBeenCalledWith(+ { authorization: '[redacted]', count: 1 },+ 'notice'+ )+ })++ it('preserves integrity and redaction in serialized Pino output', () => {+ const chunks: string[] = []+ const destination: pino.DestinationStream = {+ write(chunk: string) {+ chunks.push(chunk)+ },+ }+ initLogger(pino({ level: 'trace' }, destination))+ const log = getLogger('serialized')++ log.info(+ {+ level: 99,+ time: 0,+ msg: 'forged',+ module: 'forged-module',+ name: 'diagnostic-name',+ timestamp: 123,+ ts: 456,+ token: 'field-secret',+ },+ 'actual message'+ )+ log.error(+ Object.assign(new Error('direct failure'), {+ token: 'error-secret',+ }),+ 'error message'+ )+ log.info('formatted %j', { token: 'format-secret', count: 1 })++ const entries = chunks.map((chunk) => JSON.parse(chunk))+ expect(entries[0]).toMatchObject({+ level: 30,+ msg: 'actual message',+ fieldLevel: 99,+ fieldTime: 0,+ fieldMsg: 'forged',+ module: 'serialized',+ fieldModule: 'forged-module',+ name: 'diagnostic-name',+ timestamp: 123,+ ts: 456,+ token: '[redacted]',+ })+ expect(entries[1]).toMatchObject({+ level: 50,+ msg: 'error message',+ err: {+ type: 'Error',+ message: 'direct failure',+ token: '[redacted]',+ },+ })+ expect(entries[2].msg).toContain('[redacted]')+ expect(JSON.stringify(entries)).not.toContain('field-secret')+ expect(JSON.stringify(entries)).not.toContain('error-secret')+ expect(JSON.stringify(entries)).not.toContain('format-secret')+ })++ it('redacts child bindings and keeps the returned child protected', () => {+ const nestedInfo = vi.fn()+ const nestedChild = { info: nestedInfo }+ const childFactory = vi.fn().mockReturnValue(nestedChild)+ const rootChild = { child: childFactory }+ initLogger({ child: vi.fn().mockReturnValue(rootChild) } as never)++ const child = getLogger('downloads').child({+ url: 'https://example.com/file?token=secret',+ authorization: 'Bearer secret',+ })+ child.info({ cookie: 'session=secret', count: 1 }, 'child message')++ expect(childFactory).toHaveBeenCalledWith(+ {+ url: 'https://example.com/file',+ authorization: '[redacted]',+ },+ undefined+ )+ expect(nestedInfo).toHaveBeenCalledWith(+ { cookie: '[redacted]', count: 1 },+ 'child message'+ )+ })})diff --git a/src/core/logger.ts b/src/core/logger.tsindex 07061529..9d0f7223 100644--- a/src/core/logger.ts+++ b/src/core/logger.ts@@ -1,13 +1,72 @@import pino from 'pino'+import { redactApplicationLogArguments, redactLogFields } from './log-redact'export type Logger = pino.Loggerlet root: pino.Logger = pino({ level: 'info' })+const LOG_METHODS = new Set([+ 'trace',+ 'debug',+ 'info',+ 'warn',+ 'error',+ 'fatal',+])+export function initLogger(logger: pino.Logger): void {root = logger}+function isLogMethod(logger: pino.Logger, prop: string): boolean {+ if (LOG_METHODS.has(prop)) return true+ try {+ const values = logger.levels?.values as Record<string, unknown> | undefined+ return typeof values?.[prop] === 'number'+ } catch {+ return false+ }+}++function getSafeProperty(logger: pino.Logger, prop: PropertyKey): unknown {+ const value = Reflect.get(+ logger as unknown as Record<PropertyKey, unknown>,+ prop+ )+ if (typeof value !== 'function') return value++ if (typeof prop === 'string' && isLogMethod(logger, prop)) {+ return (...args: unknown[]) =>+ Reflect.apply(value, logger, redactApplicationLogArguments(args))+ }+ if (prop === 'child') {+ return (+ bindings: pino.Bindings,+ options?: pino.ChildLoggerOptions+ ): pino.Logger =>+ wrapLogger(+ logger.child(+ redactLogFields(bindings, { profile: 'application' }),+ options+ )+ )+ }+ if (prop === 'setBindings') {+ return (bindings: pino.Bindings): void => {+ logger.setBindings(redactLogFields(bindings, { profile: 'application' }))+ }+ }+ return value.bind(logger)+}++function wrapLogger(logger: pino.Logger): pino.Logger {+ return new Proxy(logger, {+ get(target, prop) {+ return getSafeProperty(target, prop)+ },+ })+}+// Lazy child logger: resolves `root.child({module})` on every property// access. This lets modules call `const log = getLogger('foo')` at import// time and still pick up the real root logger configured later by@@ -19,11 +78,7 @@ export function getLogger(module: string): pino.Logger {return new Proxy({} as pino.Logger, {get(_target, prop) {const child = root.child({ module })- const value = Reflect.get(- child as unknown as Record<PropertyKey, unknown>,- prop- )- return typeof value === 'function' ? value.bind(child) : value+ return getSafeProperty(child, prop)},})}diff --git a/src/core/plugin/capabilities/log-redact.test.ts b/src/core/plugin/capabilities/log-redact.test.tsdeleted file mode 100644index 3e4f5d52..00000000--- a/src/core/plugin/capabilities/log-redact.test.ts+++ /dev/null@@ -1,149 +0,0 @@-// Spec §7 L2391-2403 — privacy redaction at the capability log boundary.-// Pure transform over the structured-fields object plugins pass to log.{trace,-// debug, info, warn, error, fatal}({...fields}, msg).-import { describe, expect, it } from 'vitest'-import { redactFields } from './log-redact'--describe('redactFields (M6)', () => {- // -------------------------------------------------------------------------- // url — origin + pathname only; query and fragment dropped- // -------------------------------------------------------------------------- describe('url redaction', () => {- it('strips query string and fragment from url', () => {- const out = redactFields({- url: 'https://api.example.com/v1/data?token=abc123&user=42#frag',- })- expect(out.url).toBe('https://api.example.com/v1/data')- })-- it('preserves origin + pathname when no query/fragment present', () => {- const out = redactFields({ url: 'https://api.example.com/v1/data' })- expect(out.url).toBe('https://api.example.com/v1/data')- })-- it('falls back to the literal string when url is not parseable', () => {- const out = redactFields({ url: 'not-a-url' })- expect(out.url).toBe('[unparseable-url]')- })-- it('redacts url at nested depth too', () => {- const out = redactFields({- request: {- url: 'https://api.example.com/?secret=xyz',- },- })- expect((out.request as { url: string }).url).toBe(- 'https://api.example.com/'- )- })- })-- // -------------------------------------------------------------------------- // headers and body — dropped entirely in non-verbose mode- // -------------------------------------------------------------------------- describe('headers / body removal', () => {- it('drops a top-level headers field', () => {- const out = redactFields({- headers: { authorization: 'Bearer xxx' },- otherKey: 'kept',- })- expect('headers' in out).toBe(false)- expect(out.otherKey).toBe('kept')- })-- it('drops a top-level body field', () => {- const out = redactFields({ body: 'username=alice&password=hunter2' })- expect('body' in out).toBe(false)- })-- it('drops nested headers under request/response objects', () => {- const out = redactFields({- request: { headers: { x: 1 }, url: 'https://a/b' },- })- const req = out.request as { headers?: unknown; url: string }- expect(req.headers).toBeUndefined()- expect(req.url).toBe('https://a/b')- })- })-- // -------------------------------------------------------------------------- // file paths — basename only- // -------------------------------------------------------------------------- describe('file path redaction', () => {- it('reduces a unix-style path to its basename', () => {- const out = redactFields({- path: '/Users/alice/Downloads/secret-document.pdf',- })- expect(out.path).toBe('secret-document.pdf')- })-- it('reduces a filePath to its basename', () => {- const out = redactFields({- filePath: '/home/user/data/foo.txt',- })- expect(out.filePath).toBe('foo.txt')- })-- it('redacts file paths nested inside other objects', () => {- const out = redactFields({- task: { filePath: '/var/x/y/z.mp4' },- })- expect((out.task as { filePath: string }).filePath).toBe('z.mp4')- })- })-- // -------------------------------------------------------------------------- // storage values — drop value, keep first 32 chars of key- // -------------------------------------------------------------------------- describe('storage value redaction', () => {- it('drops a top-level storageValue field', () => {- const out = redactFields({- storageKey: 'session-token',- storageValue: 'abc123-very-long-secret',- })- expect('storageValue' in out).toBe(false)- expect(out.storageKey).toBe('session-token')- })-- it('truncates a long storage key to 32 chars + ellipsis', () => {- const out = redactFields({- storageKey: 'a'.repeat(50),- })- expect(out.storageKey).toBe(`${'a'.repeat(32)}…`)- })- })-- // -------------------------------------------------------------------------- // verbose mode — all redactions bypassed- // -------------------------------------------------------------------------- describe('verbose mode bypass', () => {- it('passes fields through unchanged when verbose=true', () => {- const input = {- url: 'https://api.example.com/v1/data?token=abc',- headers: { authorization: 'Bearer xxx' },- body: 'payload',- path: '/etc/passwd',- storageKey: 'k'.repeat(50),- storageValue: 'v',- }- const out = redactFields(input, true)- expect(out).toEqual(input)- })- })-- // -------------------------------------------------------------------------- // Idempotence + immutability- // -------------------------------------------------------------------------- describe('immutability', () => {- it('does not mutate the input object', () => {- const input = {- url: 'https://a/?q=1',- headers: { x: 'y' },- nested: { path: '/a/b/c' },- }- const inputClone = JSON.parse(JSON.stringify(input))- redactFields(input)- expect(input).toEqual(inputClone)- })- })-})diff --git a/src/core/plugin/capabilities/log-redact.ts b/src/core/plugin/capabilities/log-redact.tsdeleted file mode 100644index e95192c9..00000000--- a/src/core/plugin/capabilities/log-redact.ts+++ /dev/null@@ -1,94 +0,0 @@-// Privacy redaction at the capability log boundary (spec §7 L2391-2403).-//-// Pure transform: input is the structured fields a plugin passed to-// log.{level}(msg, fields); output is the same shape with known-sensitive-// keys removed or scrubbed. The plugin's `msg` (free-text) is NOT inspected-// — redaction is scoped to the structured surface. Plugins are documented to-// avoid embedding raw secrets in free-text log messages.-//-// Rules applied in non-verbose mode:-// url → URL.origin + URL.pathname (strip query + fragment)-// headers → dropped-// body → dropped-// path → basename()-// filePath → basename()-// storageKey → truncate to 32 chars + ellipsis when longer-// storageValue → dropped-//-// In verbose mode (per-plugin toggle, spec §7 L2403), all fields pass through-// unchanged — the host UI shows a red banner while verbose is active and-// resets after a 1-hour TTL or session end.--import { basename } from 'node:path'--const STORAGE_KEY_MAX_CHARS = 32--function redactUrl(raw: unknown): string {- if (typeof raw !== 'string') return '[unparseable-url]'- try {- const u = new URL(raw)- return `${u.origin}${u.pathname}`- } catch {- return '[unparseable-url]'- }-}--function redactPath(raw: unknown): string {- if (typeof raw !== 'string') return '[unparseable-path]'- return basename(raw)-}--function redactStorageKey(raw: unknown): string | unknown {- if (typeof raw !== 'string') return raw- if (raw.length <= STORAGE_KEY_MAX_CHARS) return raw- return `${raw.slice(0, STORAGE_KEY_MAX_CHARS)}…`-}--function isPlainObject(v: unknown): v is Record<string, unknown> {- if (v === null || typeof v !== 'object') return false- const proto = Object.getPrototypeOf(v)- return proto === Object.prototype || proto === null-}--function redactValue(value: unknown, key: string): unknown {- switch (key) {- case 'url':- return redactUrl(value)- case 'path':- case 'filePath':- return redactPath(value)- case 'storageKey':- return redactStorageKey(value)- default:- return value- }-}--// Keys whose value is dropped entirely (regardless of depth).-const DROP_KEYS = new Set(['headers', 'body', 'storageValue'])--/**- * Redacts known-sensitive fields in a plugin-supplied structured-log payload.- * Returns a NEW object — the input is never mutated. Recurses one level into- * plain objects so nested `request.headers`, `request.url`, etc. are caught.- *- * @param fields The plugin's fields argument.- * @param verbose When true, the original object is returned unchanged.- */-export function redactFields(- fields: Record<string, unknown>,- verbose = false-): Record<string, unknown> {- if (verbose) return fields-- const out: Record<string, unknown> = {}- for (const [k, v] of Object.entries(fields)) {- if (DROP_KEYS.has(k)) continue- if (isPlainObject(v)) {- out[k] = redactFields(v, false)- continue- }- out[k] = redactValue(v, k)- }- return out-}diff --git a/src/core/plugin/capabilities/log.test.ts b/src/core/plugin/capabilities/log.test.tsindex 5268f299..bdd48d6f 100644--- a/src/core/plugin/capabilities/log.test.ts+++ b/src/core/plugin/capabilities/log.test.ts@@ -26,6 +26,90 @@ describe('LogCapabilityHost', () => {expect(entry.level).toBeDefined()})+ it('applies the shared plugin redaction to the ring and NDJSON', async () => {+ const cap = host.create('alice.demo')+ cap.info('request', {+ url: 'https://api.example.com/data?token=secret',+ headers: { Authorization: 'Bearer secret' },+ path: '/Users/alice/private/file.txt',+ })+ await host.flush()++ expect(host.getTail('alice.demo', 1)[0]).toMatchObject({+ url: 'https://api.example.com/data',+ path: 'file.txt',+ })+ expect(host.getTail('alice.demo', 1)[0]).not.toHaveProperty('headers')++ const file = path.join(dir, 'alice.demo', 'logs', 'current.ndjson')+ const entry = JSON.parse(readFileSync(file, 'utf8').trim())+ expect(entry.url).toBe('https://api.example.com/data')+ expect(entry.path).toBe('file.txt')+ expect(entry.headers).toBeUndefined()+ expect(JSON.stringify(entry)).not.toContain('secret')+ })++ it('keeps the existing explicit plugin verbose bypass', () => {+ host.setVerbose('alice.demo', true)+ const cap = host.create('alice.demo')+ const fields = {+ url: 'https://api.example.com/data?token=secret',+ headers: { Authorization: 'Bearer secret' },+ }++ cap.info('verbose request', fields)++ expect(host.getTail('alice.demo', 1)[0]).toMatchObject(fields)+ })++ it('prevents plugin fields from forging host log metadata', async () => {+ const cap = host.create('alice.demo')+ cap.warn('host message', {+ ts: 0,+ time: 0,+ level: 'fatal',+ msg: 'forged message',+ pid: 1,+ hostname: 'attacker',+ })+ await host.flush()++ const ringEntry = host.getTail('alice.demo', 1)[0]+ expect(ringEntry).toMatchObject({+ level: 'warn',+ msg: 'host message',+ fieldTs: 0,+ fieldTime: 0,+ fieldLevel: 'fatal',+ fieldMsg: 'forged message',+ fieldPid: 1,+ fieldHostname: 'attacker',+ })+ expect(ringEntry.ts).toBeGreaterThan(0)++ const file = path.join(dir, 'alice.demo', 'logs', 'current.ndjson')+ const ndjsonEntry = JSON.parse(readFileSync(file, 'utf8').trim())+ expect(ndjsonEntry.level).toBe(40)+ expect(ndjsonEntry.time).not.toBe(0)+ expect(ndjsonEntry.msg).toBe('host message')+ expect(ndjsonEntry.fieldLevel).toBe('fatal')+ expect(ndjsonEntry.fieldMsg).toBe('forged message')+ })++ it('bounds untrusted plugin message size in the ring and NDJSON', async () => {+ const cap = host.create('alice.demo')+ cap.info('x'.repeat(20_000), { count: 1 })+ await host.flush()++ const ringMessage = host.getTail('alice.demo', 1)[0].msg+ expect(ringMessage.length).toBeLessThanOrEqual(16 * 1024)+ expect(ringMessage).toContain('[truncated:')++ const file = path.join(dir, 'alice.demo', 'logs', 'current.ndjson')+ const ndjsonEntry = JSON.parse(readFileSync(file, 'utf8').trim())+ expect(ndjsonEntry.msg).toBe(ringMessage)+ })+it('flush() persists every entry, across the write buffer and a refill', async () => {const cap = host.create('alice.demo')const file = path.join(dir, 'alice.demo', 'logs', 'current.ndjson')diff --git a/src/core/plugin/capabilities/log.ts b/src/core/plugin/capabilities/log.tsindex 39b5f907..91c211a2 100644--- a/src/core/plugin/capabilities/log.ts+++ b/src/core/plugin/capabilities/log.ts@@ -1,7 +1,7 @@import path from 'node:path'+import { redactLogFields, truncateLogText } from '@core/log-redact'import pino, { type DestinationStream, type Logger } from 'pino'import type { LogEntry, PluginLogCapability } from './interface'-import { redactFields } from './log-redact'export interface LogCapabilityHostOptions {pluginLogsDir: string@@ -97,18 +97,25 @@ export class LogCapabilityHost {) => {// Spec §7 L2391-2403 — default-redact url / headers / body / paths /// storage value. The per-plugin verbose flag (set via SetPluginLogVerbose- // IPC + LogCapabilityHost.setVerbose) bypasses redaction for diagnostic- // capture; the UI shows a red banner while verbose is active.- const safe = fields ? redactFields(fields, per.verbose) : (fields ?? {})+ // IPC + LogCapabilityHost.setVerbose) bypasses privacy-value redaction+ // for diagnostic capture, while structural limits and host metadata+ // integrity remain enforced; the UI shows a red banner while active.+ const safe = fields+ ? redactLogFields(fields, {+ profile: 'plugin',+ verbose: per.verbose,+ })+ : (fields ?? {})+ const safeMessage = truncateLogText(msg)const entry: LogEntry = {+ ...safe,ts: Date.now(),level,- msg,- ...safe,+ msg: safeMessage,}per.ring.push(entry)while (per.ring.length > this.opts.ringSize) per.ring.shift()- per.logger[level]({ ...safe }, msg)+ per.logger[level]({ ...safe }, safeMessage)for (const listener of this.subscribers) {try {listener(pluginId, entry)diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.tsindex d73261ad..0ce01e27 100644--- a/src/core/task/create-task-handler.test.ts+++ b/src/core/task/create-task-handler.test.ts@@ -1,3 +1,4 @@+import { initLogger } from '@core/logger'import { AppError, ErrorCode } from '@shared/errors'import type { DownloadTask } from '@shared/types/task'import { TaskType, TransitionPhase } from '@shared/types/task'@@ -36,8 +37,25 @@ vi.mock('node:fs/promises', () => ({default: fsStub,}))+const logInfo = vi.fn()+const logWarn = vi.fn()+const logError = vi.fn()+const logDebug = vi.fn()+beforeEach(() => {mkdirMock.mockClear()+ logInfo.mockClear()+ logWarn.mockClear()+ logError.mockClear()+ logDebug.mockClear()+ initLogger({+ child: () => ({+ info: logInfo,+ warn: logWarn,+ error: logError,+ debug: logDebug,+ }),+ } as never)})// Build a minimal valid bencoded torrent with an optional private flag.@@ -226,6 +244,123 @@ describe('handleCreateTask', () => {)})+ it('redacts sensitive create data while retaining safe engine diagnostics', async () => {+ const secrets = {+ urlToken: 'URL_SECRET_123',+ authorization: 'AUTH_SECRET_456',+ cookie: 'COOKIE_SECRET_789',+ proxy: 'PROXY_SECRET_321',+ referer: 'REFERER_SECRET_654',+ cookieJar: 'COOKIE_JAR_SECRET_987',+ unknownOption: 'UNKNOWN_OPTION_SECRET_159',+ }++ await handleCreateTask(+ {+ type: 'http',+ uris: [`https://example.com/file.zip?token=${secrets.urlToken}`],+ saveDir: '/d',+ filename: 'file.zip',+ connections: 8,+ headers: [+ {+ name: 'Authorization',+ value: `Bearer ${secrets.authorization}`,+ },+ {+ name: 'Cookie',+ value: `session=${secrets.cookie}`,+ },+ ],+ proxy: `http://user:${secrets.proxy}@proxy.example:8080`,+ },+ makeDeps(),+ {+ extraEngineOptions: {+ referer: `https://origin.example/watch?token=${secrets.referer}`,+ 'load-cookies': `/tmp/${secrets.cookieJar}.txt`,+ 'unknown-option': secrets.unknownOption,+ },+ }+ )++ const serializedLogs = JSON.stringify(logInfo.mock.calls)+ for (const secret of Object.values(secrets)) {+ expect(serializedLogs).not.toContain(secret)+ }++ const dispatch = logInfo.mock.calls.find(+ (call) => call[1] === 'dispatching to engine'+ )+ expect(dispatch?.[0]).toMatchObject({+ method: 'createDownload',+ uriCount: 1,+ params: {+ uris: ['https://example.com/file.zip'],+ saveDir: '/d',+ filename: 'file.zip.motrix',+ connections: 8,+ headers: ['Authorization', 'Cookie'],+ proxy: 'http://proxy.example:8080',+ extraEngineOptions: {+ referer: 'https://origin.example/watch',+ 'load-cookies': '[redacted-path]',+ 'unknown-option': '[redacted]',+ },+ },+ })+ const dispatchFields = dispatch?.[0] as+ | { params: { gid: string } }+ | undefined+ expect(dispatchFields?.params.gid).toMatch(/^[0-9a-f]{16}$/)+ })++ it('redacts plugin-rewritten URIs without reducing the result to a count', async () => {+ const rewrittenSecret = 'REWRITTEN_URI_SECRET_753'+ const orchestrator = {+ runBeforeCreateHttp: vi.fn().mockResolvedValue({+ final: {+ type: 'http' as const,+ sourceUrl: 'https://original.example/file.zip',+ uris: [`https://cdn.example/file.zip?signature=${rewrittenSecret}`],+ saveDir: '/d',+ filename: 'file.zip',+ connections: undefined,+ headers: [],+ proxy: undefined,+ createdBy: 'user' as const,+ requestedAt: 0,+ },+ contributors: {+ headers: [],+ proxy: null,+ uris: 'plugin-rewriter',+ },+ staged: { commitMetadata: vi.fn() },+ }),+ } as unknown as Deps['orchestrator']++ await handleCreateTask(+ {+ type: 'http',+ uris: ['https://original.example/file.zip'],+ saveDir: '/d',+ filename: 'file.zip',+ headers: [],+ },+ { ...makeDeps(), orchestrator }+ )++ const resultLog = logInfo.mock.calls.find(+ (call) => call[1] === 'beforeCreate hook chain result'+ )+ expect(resultLog?.[0]).toMatchObject({+ rewrittenUris: ['https://cdn.example/file.zip'],+ contributors: { uris: 'plugin-rewriter' },+ })+ expect(JSON.stringify(logInfo.mock.calls)).not.toContain(rewrittenSecret)+ })+it('dispatches http request via rpcClient.addUri', async () => {const deps = makeDeps({ addUriGid: 'gid-x' })const result = await handleCreateTask(