Skip to content

A full-featured download manager.

fix(engine): preserve production download diagnostics (#2361)

Dr_rOot552f6b50c764
diff --git a/src/core/engine/aria2/aria2-process-manager.test.ts b/src/core/engine/aria2/aria2-process-manager.test.ts
index 5a76217e..afba096a 100644
--- a/src/core/engine/aria2/aria2-process-manager.test.ts
+++ b/src/core/engine/aria2/aria2-process-manager.test.ts
@@ -328,11 +328,96 @@ describe('Aria2ProcessManager', () => {
expect(mockLogInfo).toHaveBeenCalledWith(
{
data: 'RPC-DIAG CUID#7 first WebSocket response queued: bytes=42',
+ stream: 'stdout',
+ cuid: '7',
+ enginePid: 12345,
},
'aria2 RPC diagnostic'
)
})
+ it('retains the actual HTTP error when stdout arrives in separate chunks', async () => {
+ const child = createMockChildProcess()
+ mockSpawnFn.mockReturnValue(child)
+ await manager.spawn('/usr/bin/aria2c', [])
+ const data = child.stdout.on.mock.calls.find(
+ ([event]) => event === 'data'
+ )?.[1]
+ data(
+ Buffer.from(
+ '10/14 00:09:21 [ERROR] CUID#17 - Download aborted. URI=https://cdn.example/?t=priv'
+ )
+ )
+ expect(mockLogError).not.toHaveBeenCalled()
+ data(
+ Buffer.from(
+ 'ate-token\r\nException: [AbstractCommand.cc:351] errorCode=22\r\n'
+ )
+ )
+ data(
+ Buffer.from(
+ ' -> [HttpSkipResponseCommand.cc:240] errorCode=22 The response status is not successful. status=403\r\n'
+ )
+ )
+ expect(mockLogError).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ enginePid: 12345,
+ stream: 'stdout',
+ cuid: '17',
+ aria2ErrorCode: 22,
+ httpStatus: 403,
+ }),
+ 'aria2 engine diagnostic'
+ )
+ expect(JSON.stringify(mockLogError.mock.calls)).not.toContain(
+ 'private-token'
+ )
+ })
+
+ it('drains pipe output after exit and flushes an unterminated line once on close', async () => {
+ const child = createMockChildProcess()
+ mockSpawnFn.mockReturnValue(child)
+ await manager.spawn('/usr/bin/aria2c', [])
+ const data = child.stdout.on.mock.calls.find(
+ ([event]) => event === 'data'
+ )?.[1]
+ const end = child.stdout.on.mock.calls.find(
+ ([event]) => event === 'end'
+ )?.[1]
+ data(Buffer.from('10/14 00:09:21 [ERROR] CUID#17 failed\n'))
+ child._emit('exit', 22, null)
+ data(Buffer.from('Exception: [source:1] errorCode=22 status=429'))
+ end()
+ child._emit('close', 22, null)
+ expect(mockLogError).toHaveBeenCalledTimes(2)
+ expect(mockLogError).toHaveBeenLastCalledWith(
+ expect.objectContaining({ httpStatus: 429, cuid: '17' }),
+ 'aria2 engine diagnostic'
+ )
+ })
+
+ it('does not mix a previous process stderr tail into a restarted engine', async () => {
+ const first = createMockChildProcess()
+ const second = createMockChildProcess()
+ mockSpawnFn.mockReturnValueOnce(first).mockReturnValueOnce(second)
+ await manager.spawn('/usr/bin/aria2c', [])
+ const firstData = first.stderr.on.mock.calls.find(
+ ([event]) => event === 'data'
+ )?.[1]
+ firstData(Buffer.from('old process partial error'))
+ first._emit('exit', 1, null)
+ await manager.spawn('/usr/bin/aria2c', [])
+ first._emit('close', 1, null)
+ expect(manager.getRecentStderr()).toBe('')
+ const secondData = second.stderr.on.mock.calls.find(
+ ([event]) => event === 'data'
+ )?.[1]
+ secondData(Buffer.from('new process error'))
+ second._emit('exit', 1, null)
+ second._emit('close', 1, null)
+ expect(manager.getRecentStderr()).toBe('new process error\n')
+ })
+
it('calls onExit when process exits', async () => {
const mockChild = createMockChildProcess()
mockSpawnFn.mockReturnValue(mockChild)
@@ -422,7 +507,7 @@ describe('Aria2ProcessManager', () => {
const firstStderrHandler = firstChild.stderr.on.mock.calls[0]?.[1]
firstStderrHandler?.(
Buffer.from(
- `database disk image is malformed: ${sensitiveArgs.join(' ')}`
+ `database disk image is malformed: ${sensitiveArgs.join(' ')}\n`
)
)
expect(manager.getRecentStderr()).toContain(
diff --git a/src/core/engine/aria2/aria2-process-manager.ts b/src/core/engine/aria2/aria2-process-manager.ts
index 2fdba809..f7bc4e12 100644
--- a/src/core/engine/aria2/aria2-process-manager.ts
+++ b/src/core/engine/aria2/aria2-process-manager.ts
@@ -15,13 +15,13 @@ import {
Aria2ProcessInspector,
type InspectedProcess,
} from './aria2-process-inspector'
+import { Aria2ProcessOutput } from './aria2-process-output'
import { buildFeatureReport } from './feature-report'
const log = getLogger('aria2')
const OWNER_RECORD_VERSION = 1
const STDERR_TAIL_LIMIT = 32 * 1024
-const RPC_DIAGNOSTIC_MARKER = 'RPC-DIAG'
const OWNER_MARKER_PREFIXES = [
'--conf-path=',
'--save-session=',
@@ -123,6 +123,7 @@ export class Aria2ProcessManager {
private readonly ownershipFilePath: string | null
private readonly inspector: Aria2ProcessInspector
private recentStderr = ''
+ private outputGeneration = 0
onExit: ((code: number | null, signal: string | null) => void) | null = null
onError: ((err: Error) => void) | null = null
@@ -168,6 +169,7 @@ export class Aria2ProcessManager {
env?: NodeJS.ProcessEnv
): Promise<void> {
this.recentStderr = ''
+ const outputGeneration = ++this.outputGeneration
const options: SpawnOptions = {
stdio: ['ignore', 'pipe', 'pipe'],
}
@@ -190,25 +192,28 @@ export class Aria2ProcessManager {
)
}
- child.stdout?.on('data', (data: Buffer) => {
- const text = redactSensitiveText(data.toString().trim(), args)
- if (text.includes(RPC_DIAGNOSTIC_MARKER)) {
- // Native RPC diagnostics are sparse (first queue/send per session and
- // exceptional states). Promote only those lines into production logs;
- // ordinary aria2 stdout remains debug-only.
- log.info({ data: text }, 'aria2 RPC diagnostic')
- } else {
- log.debug({ data: text }, 'aria2 stdout')
- }
- })
-
- child.stderr?.on('data', (data: Buffer) => {
- const text = redactSensitiveText(data.toString(), args)
- this.recentStderr = `${this.recentStderr}${text}`.slice(
- -STDERR_TAIL_LIMIT
+ for (const stream of ['stdout', 'stderr'] as const) {
+ const output = new Aria2ProcessOutput(
+ stream,
+ ({ level, fields, message }) => {
+ if (
+ stream === 'stderr' &&
+ this.outputGeneration === outputGeneration
+ ) {
+ this.recentStderr = `${this.recentStderr}${fields.data}\n`.slice(
+ -STDERR_TAIL_LIMIT
+ )
+ }
+ log[level]({ enginePid: child.pid, ...fields }, message)
+ },
+ (text) => redactSensitiveText(text, args)
)
- log.warn({ data: text.trim() }, 'aria2 stderr')
- })
+ child[stream]?.on('data', (data: Buffer) => output.write(data))
+ child[stream]?.on('end', () => output.end())
+ // Pipes may still deliver output after exit. Close is the fallback for
+ // streams destroyed without end and flushes an unterminated last line.
+ child.on('close', () => output.end())
+ }
child.on('exit', (code, signal) => {
log.info({ code, signal }, 'aria2 process exited')
diff --git a/src/core/engine/aria2/aria2-process-output.integration.test.ts b/src/core/engine/aria2/aria2-process-output.integration.test.ts
new file mode 100644
index 00000000..d6e47593
--- /dev/null
+++ b/src/core/engine/aria2/aria2-process-output.integration.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment node
+import { once } from 'node:events'
+import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { initLogger } from '@core/logger'
+import { bundledAria2Exists, resolveBundledAria2 } from '@test-utils/aria2'
+import pino from 'pino'
+import { afterEach, describe, expect, it } from 'vitest'
+import { Aria2ProcessManager } from './aria2-process-manager'
+
+describe.runIf(bundledAria2Exists())('aria2 production diagnostics', () => {
+ afterEach(() => initLogger(pino({ enabled: false })))
+
+ it.each([403, 416, 429])(
+ 'records the original HTTP %s at the production log level',
+ async (status) => {
+ const records: Record<string, unknown>[] = []
+ initLogger(
+ pino(
+ { level: 'info' },
+ {
+ write(line) {
+ records.push(JSON.parse(line))
+ },
+ }
+ )
+ )
+ const server = createServer((_request, response) => {
+ response.writeHead(status, {
+ 'Content-Length': '0',
+ 'Set-Cookie': 'session=private-server-cookie',
+ })
+ response.end()
+ })
+ const root = await mkdtemp(
+ path.join(tmpdir(), 'motrix-engine-diagnostic-')
+ )
+ const manager = new Aria2ProcessManager()
+ try {
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const address = server.address()
+ if (!address || typeof address === 'string')
+ throw new Error('missing HTTP port')
+ const input = path.join(root, 'input.txt')
+ await writeFile(
+ input,
+ `http://127.0.0.1:${address.port}/payload.bin?newToken=private-query-token\n`
+ )
+ const exited = new Promise<number | null>((resolve, reject) => {
+ manager.onExit = (code) => resolve(code)
+ manager.onError = reject
+ })
+ await manager.spawn(resolveBundledAria2(), [
+ '--no-conf=true',
+ '--max-tries=1',
+ '--split=1',
+ '--connect-timeout=2',
+ '--timeout=2',
+ '--summary-interval=0',
+ '--enable-color=true',
+ `--dir=${root}`,
+ '--out=payload.bin',
+ `--input-file=${input}`,
+ ])
+ expect(await exited).not.toBe(0)
+ // Exit can precede the final pipe data; allow the process reader to drain.
+ await expect
+ .poll(() => records.some((record) => record.httpStatus === status))
+ .toBe(true)
+ expect(records).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ level: 50,
+ module: 'aria2',
+ stream: 'stdout',
+ aria2ErrorCode: 22,
+ httpStatus: status,
+ }),
+ ])
+ )
+ const serialized = JSON.stringify(records)
+ expect(serialized).not.toContain('private-query-token')
+ expect(serialized).not.toContain('private-server-cookie')
+ expect(serialized).not.toContain('\\u001b')
+ } finally {
+ await manager.gracefulStop(1000)
+ server.closeAllConnections()
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ await rm(root, { recursive: true, force: true })
+ }
+ },
+ 10000
+ )
+})
diff --git a/src/core/engine/aria2/aria2-process-output.test.ts b/src/core/engine/aria2/aria2-process-output.test.ts
new file mode 100644
index 00000000..1c05cc59
--- /dev/null
+++ b/src/core/engine/aria2/aria2-process-output.test.ts
@@ -0,0 +1,224 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest'
+import {
+ type Aria2OutputRecord,
+ Aria2ProcessOutput,
+} from './aria2-process-output'
+
+function capture(stream: 'stdout' | 'stderr' = 'stdout') {
+ const records: Aria2OutputRecord[] = []
+ const reader = new Aria2ProcessOutput(
+ stream,
+ (record) => records.push(record),
+ (text) => text.replaceAll('private-rpc-secret', '<redacted>')
+ )
+ return { reader, records }
+}
+
+function failure(status: number, separator = '\n') {
+ return [
+ '10/14 00:09:21 [\u001b[1;31mERROR\u001b[0m] CUID#17 - Download aborted. URI=https://user:[email protected]/private-path?unknown=signed-value#fragment',
+ 'Exception: [AbstractCommand.cc:351] errorCode=22 URI=https://cdn.example/private-path?unknown=signed-value',
+ ` -> [HttpSkipResponseCommand.cc:240] errorCode=22 The response status is not successful. status=${status}`,
+ '',
+ ].join(separator)
+}
+
+describe('Aria2ProcessOutput', () => {
+ it.each([403, 416, 429])(
+ 'retains HTTP %s and its connection at error level',
+ (status) => {
+ const { reader, records } = capture()
+ reader.write(Buffer.from(failure(status)))
+ expect(records).toHaveLength(3)
+ expect(records.every((record) => record.level === 'error')).toBe(true)
+ expect(records[2]).toMatchObject({
+ message: 'aria2 engine diagnostic',
+ fields: {
+ stream: 'stdout',
+ cuid: '17',
+ aria2ErrorCode: 22,
+ httpStatus: status,
+ },
+ })
+ const serialized = JSON.stringify(records)
+ for (const secret of [
+ 'password',
+ 'private-path',
+ 'signed-value',
+ 'fragment',
+ '\\u001b',
+ ]) {
+ expect(serialized).not.toContain(secret)
+ }
+ expect(records[0].fields.data).toContain('https://cdn.example/[redacted]')
+ }
+ )
+
+ it.each(['\n', '\r\n'])(
+ 'handles every byte boundary and %j line endings',
+ (separator) => {
+ const input = Buffer.from(failure(403, separator))
+ const expected = capture()
+ expected.reader.write(input)
+ expected.reader.end()
+ for (let offset = 1; offset < input.length; offset += 1) {
+ const actual = capture()
+ actual.reader.write(input.subarray(0, offset))
+ actual.reader.write(input.subarray(offset))
+ actual.reader.end()
+ expect(actual.records).toEqual(expected.records)
+ }
+ expect(expected.records[2].fields.cuid).toBe('17')
+ }
+ )
+
+ it('decodes UTF-8 across byte boundaries and flushes the last line once', () => {
+ const { reader, records } = capture()
+ for (const byte of Buffer.from('10/14 00:09:21 [WARN] 磁盘写入失败')) {
+ reader.write(Buffer.from([byte]))
+ }
+ expect(records).toHaveLength(0)
+ reader.end()
+ reader.end()
+ reader.write(Buffer.from('ignored'))
+ expect(records).toHaveLength(1)
+ expect(records[0]).toMatchObject({
+ level: 'warn',
+ fields: { data: '10/14 00:09:21 [WARN] 磁盘写入失败' },
+ })
+ })
+
+ it('keeps progress and ordinary notices out of production logs', () => {
+ const { reader, records } = capture()
+ reader.write(
+ Buffer.from(
+ [
+ '[#123456 31MiB/32MiB(99%) CN:1 DL:0B]\r',
+ '10/14 00:09:21 [NOTICE] Download complete\n',
+ '10/14 00:09:21 [INFO] RPC-DIAG CUID#7 queue ready\n',
+ '10/14 00:09:21 [DEBUG] ordinary engine detail\n',
+ ].join('')
+ )
+ )
+ expect(records.map((record) => record.level)).toEqual([
+ 'debug',
+ 'debug',
+ 'info',
+ 'debug',
+ ])
+ expect(records[2].message).toBe('aria2 RPC diagnostic')
+ })
+
+ it('does not attach a previous connection to a later unrelated exception', () => {
+ const { reader, records } = capture()
+ reader.write(
+ Buffer.from(
+ `${failure(403)}\nException: [CreateRequestCommand.cc:108] errorCode=22 No URI available.\n`
+ )
+ )
+ expect(records.at(-1)?.fields).not.toHaveProperty('cuid')
+ expect(records.at(-1)?.fields).not.toHaveProperty('httpStatus')
+ expect(records.at(-1)?.level).toBe('error')
+ })
+
+ it('keeps independently interleaved stdout and stderr contexts separate', () => {
+ const out = capture()
+ const err = capture('stderr')
+ out.reader.write(Buffer.from('10/14 00:09:21 [ERROR] CUID#7 failed\n'))
+ err.reader.write(Buffer.from('10/14 00:09:21 [WARN] CUID#8 failed\n'))
+ out.reader.write(
+ Buffer.from('Exception: [source:1] errorCode=22 status=403\n')
+ )
+ err.reader.write(Buffer.from('Exception: [source:1] errorCode=2 Timeout\n'))
+ expect(out.records[1]).toMatchObject({
+ level: 'error',
+ fields: { cuid: '7', httpStatus: 403 },
+ })
+ expect(err.records[1]).toMatchObject({
+ level: 'warn',
+ fields: { cuid: '8', aria2ErrorCode: 2 },
+ })
+ })
+
+ it('redacts headers, folded credentials, known secrets and signed URL paths', () => {
+ const { reader, records } = capture('stderr')
+ const text = [
+ 'Cookie: session=private-cookie',
+ ' folded-cookie-secret',
+ 'Authorization: Basic private-basic',
+ 'Set-Cookie: private-set-cookie',
+ 'X-Provider-Token: private-header',
+ 'Provider-Credential: custom-private-header',
+ 'Referer: https://example.com/private-referer',
+ 'failure Bearer private-bearer',
+ 'failure --rpc-secret=private-rpc-secret',
+ 'failure https://alice:[email protected]/private-url-path?newKey=private-query',
+ '',
+ ].join('\n')
+ for (const byte of Buffer.from(text)) reader.write(Buffer.from([byte]))
+ const serialized = JSON.stringify(records)
+ expect(serialized).not.toContain('private')
+ expect(serialized).not.toContain('alice')
+ expect(records.every((record) => record.level === 'warn')).toBe(true)
+ })
+
+ it('omits oversized lines entirely and recovers at the next separator', () => {
+ const { reader, records } = capture()
+ reader.write(Buffer.from('https://cdn.example/'))
+ for (let index = 0; index < 100; index += 1) {
+ reader.write(Buffer.from('private-segment'.repeat(100)))
+ }
+ reader.write(Buffer.from('private-suffix\n'))
+ reader.write(Buffer.from(failure(429)))
+ expect(records).toHaveLength(4)
+ expect(records[0].message).toBe('aria2 output truncated')
+ expect(JSON.stringify(records)).not.toContain('private')
+ expect(records.at(-1)?.fields.httpStatus).toBe(429)
+ })
+
+ it('flushes an oversized unterminated line without emitting its contents', () => {
+ const { reader, records } = capture('stderr')
+ reader.write(Buffer.from('secret'.repeat(10_000)))
+ reader.end()
+ expect(records).toHaveLength(1)
+ expect(records[0].fields.data).toContain('omitted')
+ expect(records[0].fields.data).not.toContain('secret')
+ })
+
+ it('retains native startup diagnostics with a colon prefix', () => {
+ const { reader, records } = capture('stderr')
+ reader.write(
+ Buffer.from(
+ 'aria2c: unrecognized option --broken\nSQLite3: database is locked\n'
+ )
+ )
+ expect(records.map((record) => record.fields.data)).toEqual([
+ 'aria2c: unrecognized option --broken',
+ 'SQLite3: database is locked',
+ ])
+ })
+
+ it('redacts raw HTTP targets and arbitrary header blocks without consuming later errors', () => {
+ const { reader, records } = capture()
+ reader.write(
+ Buffer.from(
+ [
+ 'GET /private-path?key=private-query HTTP/1.1',
+ 'Provider-Session: private-session',
+ ' folded-private-value',
+ '',
+ 'HTTP/1.1 403 Forbidden',
+ 'Unusual-Auth-Header: private-auth',
+ '',
+ failure(403),
+ ].join('\r\n')
+ )
+ )
+ expect(JSON.stringify(records)).not.toContain('private')
+ expect(records.at(-1)).toMatchObject({
+ level: 'error',
+ fields: { cuid: '17', httpStatus: 403 },
+ })
+ })
+})
diff --git a/src/core/engine/aria2/aria2-process-output.ts b/src/core/engine/aria2/aria2-process-output.ts
new file mode 100644
index 00000000..a58dc5cc
--- /dev/null
+++ b/src/core/engine/aria2/aria2-process-output.ts
@@ -0,0 +1,201 @@
+import { StringDecoder } from 'node:string_decoder'
+import { stripVTControlCharacters } from 'node:util'
+import { redactLogText } from '@core/log-redact'
+
+const MAX_LINE_LENGTH = 32 * 1024
+const OMITTED_LINE = '[aria2 output line omitted: exceeds 32768 characters]'
+const LOG_HEADER =
+ /^(?:\d{2}\/\d{2} \d{2}:\d{2}:\d{2}|\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)?) \[(DEBUG|INFO|NOTICE|WARN|ERROR)\]/
+const EXCEPTION_LINE = /^\s*(?:Exception:|->)/
+const SENSITIVE_HEADER =
+ /\b((?:Proxy-)?Authorization|(?:Set-)?Cookie|Referer|X-[\w-]+|[\w-]*(?:Token|Secret|Credential|Api-Key))\s*:.*/i
+
+type OutputLevel = 'debug' | 'info' | 'warn' | 'error'
+type OutputStream = 'stdout' | 'stderr'
+
+export interface Aria2OutputRecord {
+ level: OutputLevel
+ message: string
+ fields: {
+ stream: OutputStream
+ data: string
+ cuid?: string
+ aria2ErrorCode?: number
+ httpStatus?: number
+ }
+}
+
+interface ExceptionContext {
+ level: OutputLevel
+ cuid?: string
+ aria2ErrorCode?: number
+}
+
+/** Read complete lines before classification or redaction, including split UTF-8. */
+export class Aria2ProcessOutput {
+ private readonly decoder = new StringDecoder('utf8')
+ private pending = ''
+ private droppingLine = false
+ private previousWasCr = false
+ private ended = false
+ private context: ExceptionContext | undefined
+ private redactedHeader = false
+ private httpHeaders = false
+
+ constructor(
+ private readonly stream: OutputStream,
+ private readonly emit: (record: Aria2OutputRecord) => void,
+ private readonly redactKnownSecrets: (text: string) => string
+ ) {}
+
+ write(chunk: Buffer): void {
+ if (!this.ended) this.consume(this.decoder.write(chunk))
+ }
+
+ end(): void {
+ if (this.ended) return
+ this.ended = true
+ this.consume(this.decoder.end())
+ if (this.droppingLine) this.emitOmittedLine()
+ else if (this.pending) this.emitLine(this.pending)
+ this.pending = ''
+ this.context = undefined
+ }
+
+ private consume(text: string): void {
+ let start = 0
+ for (let index = 0; index < text.length; index += 1) {
+ // Treat CRLF as one separator even across chunks; standalone carriage
+ // returns delimit progress output without growing an unbounded line.
+ if (text[index] === '\n' && this.previousWasCr) {
+ this.previousWasCr = false
+ start = index + 1
+ continue
+ }
+ this.previousWasCr = text[index] === '\r'
+ if (text[index] !== '\n' && text[index] !== '\r') continue
+ this.append(text.slice(start, index))
+ if (this.droppingLine) this.emitOmittedLine()
+ else this.emitLine(this.pending)
+ this.pending = ''
+ this.droppingLine = false
+ start = index + 1
+ }
+ this.append(text.slice(start))
+ }
+
+ private append(text: string): void {
+ if (this.droppingLine) return
+ if (this.pending.length + text.length > MAX_LINE_LENGTH) {
+ // Never emit an arbitrary prefix/suffix: it may split a credential.
+ this.pending = ''
+ this.droppingLine = true
+ return
+ }
+ this.pending += text
+ }
+
+ private emitOmittedLine(): void {
+ this.emit({
+ level: this.context?.level ?? 'warn',
+ message: 'aria2 output truncated',
+ fields: { stream: this.stream, data: OMITTED_LINE },
+ })
+ this.context = undefined
+ this.redactedHeader = false
+ this.httpHeaders = false
+ }
+
+ private emitLine(raw: string): void {
+ const line = stripVTControlCharacters(raw)
+ if (!line.trim()) {
+ this.context = undefined
+ this.redactedHeader = false
+ this.httpHeaders = false
+ return
+ }
+ const data = this.sanitize(line)
+ const header = LOG_HEADER.exec(data)
+ const continuation = EXCEPTION_LINE.test(data)
+ if (!continuation) this.context = undefined
+
+ let level: OutputLevel = this.stream === 'stderr' ? 'warn' : 'debug'
+ if (header?.[1] === 'ERROR') level = 'error'
+ else if (header?.[1] === 'WARN') level = 'warn'
+ else if (continuation) level = this.context?.level ?? 'error'
+
+ const cuid = /\bCUID#(\d{1,20})\b/.exec(data)?.[1] ?? this.context?.cuid
+ const code = continuation
+ ? /\berrorCode=(\d{1,3})\b/.exec(data)?.[1]
+ : undefined
+ const aria2ErrorCode = code ? Number(code) : this.context?.aria2ErrorCode
+ const httpStatus = continuation
+ ? /\bstatus=([1-5]\d{2})\b/.exec(data)?.[1]
+ : undefined
+ if (header || continuation) {
+ this.context = { level, cuid, aria2ErrorCode }
+ }
+
+ const rpcDiagnostic = data.includes('RPC-DIAG')
+ this.emit({
+ level: rpcDiagnostic && level === 'debug' ? 'info' : level,
+ message: rpcDiagnostic
+ ? 'aria2 RPC diagnostic'
+ : level === 'error' || level === 'warn'
+ ? 'aria2 engine diagnostic'
+ : `aria2 ${this.stream}`,
+ fields: {
+ stream: this.stream,
+ data,
+ ...(cuid ? { cuid } : {}),
+ ...(aria2ErrorCode === undefined ? {} : { aria2ErrorCode }),
+ ...(httpStatus ? { httpStatus: Number(httpStatus) } : {}),
+ },
+ })
+ }
+
+ private sanitize(line: string): string {
+ if (
+ this.redactedHeader &&
+ /^\s+\S/.test(line) &&
+ !EXCEPTION_LINE.test(line)
+ ) {
+ return '[redacted header continuation]'
+ }
+ // Debug-enabled engines can print raw HTTP messages. Their request target
+ // and arbitrary header values are not safe diagnostic fields.
+ const request =
+ /^(GET|HEAD|POST|PUT|DELETE|OPTIONS|PATCH|CONNECT) \S+ (HTTP\/\d(?:\.\d)?)$/.exec(
+ line
+ )
+ if (request || /^HTTP\/\d(?:\.\d)? \d{3}\b/.test(line)) {
+ this.httpHeaders = true
+ this.redactedHeader = false
+ return request ? `${request[1]} [redacted] ${request[2]}` : line
+ }
+ const header = /^\s*([!#$%&'*+.^_`|~\w-]+):/.exec(line)
+ if (this.httpHeaders && header) {
+ this.redactedHeader = true
+ return `${header[1]}: [redacted]`
+ }
+ this.httpHeaders = false
+ this.redactedHeader = SENSITIVE_HEADER.test(line)
+ const text = this.redactKnownSecrets(line).replace(
+ SENSITIVE_HEADER,
+ '$1: [redacted]'
+ )
+ // Signed cloud URLs can put credentials in paths or arbitrary query keys.
+ // The origin is sufficient to identify the failing provider in this log.
+ return redactLogText(
+ text.replace(/\b(?:https?|ftp|sftp|wss?):\/\/[^\s<>"`]+/gi, (rawUrl) => {
+ try {
+ const url = new URL(rawUrl)
+ return `${url.protocol}//${url.host}/[redacted]`
+ } catch {
+ return '[redacted-url]'
+ }
+ }),
+ true
+ )
+ }
+}