Skip to content

A full-featured download manager.

fix(plugins): preserve url queries in diagnostic logs (#2340)

Dr_rOoteacdcab31f66
diff --git a/docs/plugin-hook-runtime.md b/docs/plugin-hook-runtime.md
index 460db1e4..580a19da 100644
--- a/docs/plugin-hook-runtime.md
+++ b/docs/plugin-hook-runtime.md
@@ -839,6 +839,35 @@ dead-letter counts, attempt latency, retries, and oldest pending age.
Electron and Server use the same event names and field meanings. Tests assert
both assembly paths, not merely the core factory.
+### HTTP URL diagnostics
+
+For each participating HTTP `beforeCreate` plugin, its log includes host
+records for `beforeCreate.input`, `beforeCreate.output`, and `engine.dispatch`,
+correlated by `taskId`. The dispatch record describes the parameters handed to
+the engine adapter, not a successful network request. Failed Hooks also record
+`beforeCreate.error` when the chain handles the failure.
+
+Normal application and plugin logs preserve ordinary query parameters such as
+`id`, `export`, and `confirm`. A provider-independent credential-name policy masks
+values such as `token`, `sig`, `signature`, and `X-Amz-Credential` with
+`[redacted]`; URL credentials and fragments are removed. Query ordering,
+duplicate parameters, empty values, and percent encoding are preserved for
+unmasked parameters. These transformations affect log copies only: the Hook
+context and engine request retain the original URL bytes.
+
+The plugin log tab's **Verbose mode** enables raw diagnostic capture for that
+plugin for one hour. The host enforces expiry on every log write, even with the
+tab closed; reopening the tab retrieves the existing expiry without renewing
+it. Disabling the mode affects future entries. **Clear** empties the displayed
+buffer; previously captured entries remain in the local log file.
+
+**Copy redacted logs** sanitizes the selected entries again, including entries
+captured in verbose mode: all URL query values are masked, URL credentials and
+fragments are removed, and structured headers and bodies are omitted. This
+generic policy cannot identify every secret in arbitrary plugin text or URL
+paths; review the result before publishing it. No per-site rules or plugin SDK
+API changes are required.
+
## 16. Electron and Server assembly
Each shell performs this order:
diff --git a/docs/plugin-hook-runtime.zh-CN.md b/docs/plugin-hook-runtime.zh-CN.md
index b84acab4..827ec87a 100644
--- a/docs/plugin-hook-runtime.zh-CN.md
+++ b/docs/plugin-hook-runtime.zh-CN.md
@@ -740,6 +740,29 @@ pending/delivering/delivered/dead-letter 数量、attempt latency、retry 次数
Electron 与 Server 使用相同事件名和字段含义。测试必须断言两套装配,而不
只是测试 core factory。
+### HTTP URL 诊断
+
+每个参与 HTTP `beforeCreate` 的插件都会收到宿主记录的 `beforeCreate.input`、
+`beforeCreate.output` 和 `engine.dispatch` 日志,通过 `taskId` 关联。
+dispatch 记录表示参数已经交给引擎适配器,不代表网络请求成功。Hook 失败且由
+调用链处理时,还会记录 `beforeCreate.error`。
+
+日常应用日志和插件日志保留 `id`、`export`、`confirm` 等普通查询参数。
+统一的凭据名称规则会将 `token`、`sig`、`signature`、`X-Amz-Credential` 等
+参数值替换为 `[redacted]`,并移除 URL 中的用户名、密码和 fragment。
+未遮蔽参数的顺序、重复项、空值和百分号编码保持原样。这些转换只作用于日志
+副本,Hook 上下文与引擎请求中的原始 URL 字节保持不变。
+
+插件日志页的**详细模式**为该插件开启一小时的原始诊断记录。宿主在每次写入
+时检查有效期,关闭页面也会到期;重新打开页面只读取已有状态,不会续期。
+关闭模式仅影响后续记录。**清空**只清除界面缓冲区,之前捕获的内容仍保留
+在本地日志文件中。
+
+**复制脱敏日志**会再次处理所选记录,包括详细模式产生的记录:隐藏全部 URL
+查询参数值,移除 URL 用户名、密码和 fragment,省略结构化 header 与 body。
+通用规则无法识别插件任意文本或 URL 路径中的所有秘密,公开前仍应检查内容。
+这套机制无需维护站点规则,也不需要修改插件 SDK API。
+
## 16. Electron 与 Server 装配
每个外壳按以下顺序执行:
diff --git a/src/core/log-redact.test.ts b/src/core/log-redact.test.ts
index a1568601..03d601d5 100644
--- a/src/core/log-redact.test.ts
+++ b/src/core/log-redact.test.ts
@@ -35,14 +35,14 @@ describe('redactLogFields', () => {
method: 'createDownload',
params: {
gid: '0123456789abcdef',
- uris: ['https://example.com/file.zip'],
+ uris: ['https://example.com/file.zip?token=[redacted]'],
saveDir: '/Users/alice/Downloads',
filename: 'file.zip.motrix',
connections: 16,
headers: ['Authorization', 'Cookie'],
proxy: 'http://proxy.example:8080',
extraEngineOptions: {
- referer: 'https://origin.example/watch',
+ referer: 'https://origin.example/watch?token=[redacted]',
'load-cookies': '[redacted-path]',
'select-file': '1,3',
'unknown-option': '[redacted]',
@@ -74,7 +74,7 @@ describe('redactLogFields', () => {
{ profile: 'application' }
)
expect(out.rewrittenUris).toEqual([
- 'https://cdn.example/file',
+ 'https://cdn.example/file?signature=[redacted]',
'magnet:<redacted>',
])
})
@@ -512,11 +512,13 @@ describe('redactLogFields', () => {
const redactPlugin = (fields: Record<string, unknown>, verbose = false) =>
redactLogFields(fields, { profile: 'plugin', verbose })
- it('strips query strings and fragments from URLs', () => {
+ it('masks credential query values and strips fragments', () => {
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')
+ expect(out.url).toBe(
+ 'https://api.example.com/v1/data?token=[redacted]&user=42'
+ )
})
it('preserves URL origin and pathname without query data', () => {
@@ -534,7 +536,7 @@ describe('redactLogFields', () => {
request: { url: 'https://api.example.com/?secret=xyz' },
})
expect((out.request as { url: string }).url).toBe(
- 'https://api.example.com/'
+ 'https://api.example.com/?secret=[redacted]'
)
})
@@ -625,3 +627,58 @@ describe('redactLogFields', () => {
})
})
})
+
+describe('URL query diagnostics', () => {
+ it('preserves ordinary parameters, duplicate keys, empty values and exact encoding', () => {
+ const url =
+ 'https://drive.usercontent.google.com/download?id=a%2fb+X&export=download&confirm=t&item=1&item=2&empty=&flag&&token=secret%26value&x=%252F'
+ const fields = { url, rewrittenUris: [url], params: { uris: [url] } }
+ const original = structuredClone(fields)
+ const expected = url.replace('token=secret%26value', 'token=[redacted]')
+ expect(redactLogFields(fields, { profile: 'application' })).toEqual({
+ url: expected,
+ rewrittenUris: [expected],
+ params: { uris: [expected] },
+ })
+ expect(fields).toEqual(original)
+ })
+
+ it.each([
+ 'token',
+ 'access_token',
+ 'ToKeN',
+ '%74oken',
+ 'api-key',
+ 'sig',
+ 'signature',
+ 'X-Amz-Signature',
+ 'X-Amz-Credential',
+ 'X-Amz-Security-Token',
+ 'X-Goog-Signature',
+ 'X-Goog-Credential',
+ '%invalid',
+ ])('masks credential parameter %s independently of host', (key) => {
+ const url = `https://anything.example/file?id=42&${key}=private&${key}=second&export=download`
+ const out = redactLogFields({ url }, { profile: 'application' })
+ expect(out.url).toBe(
+ `https://anything.example/file?id=42&${key}=[redacted]&${key}=[redacted]&export=download`
+ )
+ expect(redactLogFields(out, { profile: 'application' })).toEqual(out)
+ })
+
+ it('also sanitizes URL credentials embedded in text and errors', () => {
+ const out = redactLogFields(
+ {
+ detail:
+ 'GET https://user:[email protected]/a?id=1&token=secret#fragment',
+ err: new Error('GET https://example.com/a?id=1&sig=secret'),
+ },
+ { profile: 'application' }
+ )
+ expect(out.detail).toBe('GET https://example.com/a?id=1&token=[redacted]')
+ expect((out.err as Error).message).toBe(
+ 'GET https://example.com/a?id=1&sig=[redacted]'
+ )
+ expect((out.err as Error).stack).not.toContain('sig=secret')
+ })
+})
diff --git a/src/core/log-redact.ts b/src/core/log-redact.ts
index 4483aced..07cb1f96 100644
--- a/src/core/log-redact.ts
+++ b/src/core/log-redact.ts
@@ -1,946 +1,7 @@
-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',
- 'mutualkeyb64',
- 'ticketkey',
- 'nmticket',
- 'pairnonce',
- '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)
-}
+export {
+ type LogRedactionContext,
+ redactApplicationLogArguments,
+ redactLogFields,
+ redactLogText,
+ truncateLogText,
+} from '@shared/lib/log-redact'
diff --git a/src/core/logger.test.ts b/src/core/logger.test.ts
index 8e2e7423..7dee43d7 100644
--- a/src/core/logger.test.ts
+++ b/src/core/logger.test.ts
@@ -38,7 +38,7 @@ describe('logger', () => {
expect(mockInfo).toHaveBeenCalledWith(
{
- url: 'https://example.com/file',
+ url: 'https://example.com/file?token=[redacted]',
headers: ['Authorization'],
proxy: 'http://proxy.example:8080',
connections: 16,
@@ -68,7 +68,7 @@ describe('logger', () => {
expect(mockInfo).toHaveBeenCalledWith('request %j', {
token: '[redacted]',
- url: 'https://example.com/file',
+ url: 'https://example.com/file?signature=[redacted]',
count: 1,
})
})
@@ -189,7 +189,7 @@ describe('logger', () => {
expect(childFactory).toHaveBeenCalledWith(
{
- url: 'https://example.com/file',
+ url: 'https://example.com/file?token=[redacted]',
authorization: '[redacted]',
},
undefined
diff --git a/src/core/plugin/capabilities/interface.ts b/src/core/plugin/capabilities/interface.ts
index 6fd73bc2..36156ca4 100644
--- a/src/core/plugin/capabilities/interface.ts
+++ b/src/core/plugin/capabilities/interface.ts
@@ -1,6 +1,7 @@
// src/core/plugin/capabilities/interface.ts
import type { SupportedLocale } from '@shared/constants/locales'
+import type { PluginLogState } from '@shared/schemas/plugin-logs'
import type { PluginLogEntry } from '@shared/types/plugin'
import type { ManifestLocaleDict } from '../manifest/i18n-resolve'
import type { CommandsCapabilityHost } from './commands'
@@ -56,6 +57,7 @@ export interface CapabilityHost {
clearLog(pluginId: string): void
setLogVerbose(pluginId: string, verbose: boolean): void
isLogVerbose(pluginId: string): boolean
+ getLogState(pluginId: string): PluginLogState
subscribeLog(listener: LogStreamListener): () => void
appSnapshot(): AppCapabilitySnapshot
i18nSnapshot(pluginId: string): I18nSnapshot
diff --git a/src/core/plugin/capabilities/log.test.ts b/src/core/plugin/capabilities/log.test.ts
index bdd48d6f..1bbbec43 100644
--- a/src/core/plugin/capabilities/log.test.ts
+++ b/src/core/plugin/capabilities/log.test.ts
@@ -1,11 +1,12 @@
import { mkdtempSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { LogEntry } from './interface'
import { LogCapabilityHost } from './log'
describe('LogCapabilityHost', () => {
+ afterEach(() => vi.useRealTimers())
let dir: string
let host: LogCapabilityHost
@@ -36,14 +37,14 @@ describe('LogCapabilityHost', () => {
await host.flush()
expect(host.getTail('alice.demo', 1)[0]).toMatchObject({
- url: 'https://api.example.com/data',
+ url: 'https://api.example.com/data?token=[redacted]',
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.url).toBe('https://api.example.com/data?token=[redacted]')
expect(entry.path).toBe('file.txt')
expect(entry.headers).toBeUndefined()
expect(JSON.stringify(entry)).not.toContain('secret')
@@ -206,3 +207,37 @@ describe('LogCapabilityHost', () => {
expect(good).toHaveBeenCalledTimes(1)
})
})
+
+describe('verbose diagnostic lifetime', () => {
+ afterEach(() => vi.useRealTimers())
+ it('expires at one hour for previously created loggers without a UI timer', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'mlog-expiry-'))
+ const host = new LogCapabilityHost({ pluginLogsDir: dir })
+ const cap = host.create('alice.demo')
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(10_000)
+ host.setVerbose('alice.demo', true)
+ expect(host.getState('alice.demo')).toEqual({
+ verbose: true,
+ expiresAt: 3_610_000,
+ })
+ cap.info('raw', { url: 'https://example.com/?token=secret' })
+ expect(host.getTail('alice.demo', 1)[0].url).toContain('token=secret')
+ vi.setSystemTime(3_610_000)
+ cap.info('expired', { url: 'https://example.com/?id=public&token=secret' })
+ expect(host.getState('alice.demo')).toEqual({
+ verbose: false,
+ expiresAt: null,
+ })
+ expect(host.getTail('alice.demo', 1)[0].url).toBe(
+ 'https://example.com/?id=public&token=[redacted]'
+ )
+ expect(host.isVerbose('bob.other')).toBe(false)
+ host.setVerbose('alice.demo', true)
+ host.setVerbose('alice.demo', false)
+ expect(host.getState('alice.demo')).toEqual({
+ verbose: false,
+ expiresAt: null,
+ })
+ })
+})
diff --git a/src/core/plugin/capabilities/log.ts b/src/core/plugin/capabilities/log.ts
index 91c211a2..d9142225 100644
--- a/src/core/plugin/capabilities/log.ts
+++ b/src/core/plugin/capabilities/log.ts
@@ -1,5 +1,13 @@
import path from 'node:path'
-import { redactLogFields, truncateLogText } from '@core/log-redact'
+import {
+ redactLogFields,
+ redactLogText,
+ truncateLogText,
+} from '@core/log-redact'
+import {
+ PLUGIN_LOG_VERBOSE_TTL_MS,
+ type PluginLogState,
+} from '@shared/schemas/plugin-logs'
import pino, { type DestinationStream, type Logger } from 'pino'
import type { LogEntry, PluginLogCapability } from './interface'
@@ -23,7 +31,7 @@ interface Per {
*/
opened: Promise<boolean>
ring: LogEntry[]
- verbose: boolean
+ verboseUntil: number | null
}
/**
@@ -83,7 +91,7 @@ export class LogCapabilityHost {
dest.once('ready', () => resolve(true))
dest.once('error', () => resolve(false))
})
- entry = { logger, dest, opened, ring: [], verbose: false }
+ entry = { logger, dest, opened, ring: [], verboseUntil: null }
this.per.set(pluginId, entry)
return entry
}
@@ -99,14 +107,15 @@ export class LogCapabilityHost {
// storage value. The per-plugin verbose flag (set via SetPluginLogVerbose
// 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.
+ // integrity remain enforced; the UI shows a warning while active.
+ const verbose = this.isVerbose(pluginId)
const safe = fields
? redactLogFields(fields, {
profile: 'plugin',
- verbose: per.verbose,
+ verbose,
})
: (fields ?? {})
- const safeMessage = truncateLogText(msg)
+ const safeMessage = verbose ? truncateLogText(msg) : redactLogText(msg)
const entry: LogEntry = {
...safe,
ts: Date.now(),
@@ -147,11 +156,23 @@ export class LogCapabilityHost {
}
setVerbose(pluginId: string, verbose: boolean): void {
- this.getOrCreate(pluginId).verbose = verbose
+ this.getOrCreate(pluginId).verboseUntil = verbose
+ ? Date.now() + PLUGIN_LOG_VERBOSE_TTL_MS
+ : null
}
isVerbose(pluginId: string): boolean {
- return this.per.get(pluginId)?.verbose ?? false
+ return this.getState(pluginId).verbose
+ }
+
+ getState(pluginId: string): PluginLogState {
+ const per = this.per.get(pluginId)
+ const expiresAt = per?.verboseUntil ?? null
+ if (expiresAt === null || expiresAt <= Date.now()) {
+ if (per) per.verboseUntil = null
+ return { verbose: false, expiresAt: null }
+ }
+ return { verbose: true, expiresAt }
}
subscribe(listener: LogStreamListener): () => void {
diff --git a/src/core/plugin/hooks/hook-orchestrator.test.ts b/src/core/plugin/hooks/hook-orchestrator.test.ts
index 1cbdda6b..b13d6f18 100644
--- a/src/core/plugin/hooks/hook-orchestrator.test.ts
+++ b/src/core/plugin/hooks/hook-orchestrator.test.ts
@@ -396,6 +396,31 @@ describe('HookOrchestrator', () => {
expect(result.contributors.headers).toContain('plugin-enrich')
})
+ it('keeps hook results and engine dispatch usable when diagnostic logging fails', async () => {
+ const createLog = vi.fn(() => {
+ throw new Error('log destination unavailable')
+ })
+ const orch = new HookOrchestrator({
+ host,
+ createLog,
+ hookTimeoutMs: TIMEOUTS,
+ ...ORCH_OPTS_BASE,
+ })
+ const result = await orch.runBeforeCreateHttp(
+ makeBeforeCreateDto(),
+ 'task-1'
+ )
+ if (result.aborted) throw new Error('expected non-aborted result')
+ expect(result.final.uris).toEqual(['https://cdn.example.com/file.zip'])
+ expect(() =>
+ result.recordEngineDispatch?.({
+ uris: result.final.uris,
+ saveDir: '/downloads',
+ })
+ ).not.toThrow()
+ expect(createLog).toHaveBeenCalled()
+ })
+
it('passes each accepted patch into the next plugin working context', async () => {
let laterPayload: Record<string, unknown> | undefined
const { host } = makeMockHost([
diff --git a/src/core/plugin/hooks/hook-orchestrator.ts b/src/core/plugin/hooks/hook-orchestrator.ts
index 4270260e..685c94b1 100644
--- a/src/core/plugin/hooks/hook-orchestrator.ts
+++ b/src/core/plugin/hooks/hook-orchestrator.ts
@@ -1,3 +1,4 @@
+import type { CreateDownloadParams } from '@core/engine/engine-adapter'
import {
admitDownloadSources,
DownloadSourceError,
@@ -73,6 +74,7 @@ export interface OrchestratorOptions {
pluginStorageRootFor: (pluginId: string) => string
/** Production task-filesystem and metadata context for every Hook. */
capabilityHost?: Pick<CapabilityHost, 'fsTaskFor' | 'metadata'>
+ createLog?: CapabilityHost['createLog']
/** ffmpeg per-(plugin, task) staging quota in bytes. */
ffmpegStagingQuotaBytes?: number
/** Optional NDJSON audit log; T15 wires the real instance. */
@@ -91,6 +93,8 @@ export interface BeforeCreateHttpResult {
aborted?: false
/** Merged DTO ready for engine handoff. */
final: BeforeCreateHttpContextDTO
+ /** Bound to this invocation's participants; no task-global diagnostic state. */
+ recordEngineDispatch?: (params: CreateDownloadParams) => void
/** Plugin attribution for the final headers / proxy / uris choices. */
contributors: MergedHttp['contributors']
/** Caller (TaskManager) commits this store inside its DB transaction. */
@@ -154,6 +158,24 @@ export class HookOrchestrator {
this.breaker = opts.breaker ?? new RealCircuitBreaker()
}
+ private recordHttpDiagnostic(
+ pluginId: string,
+ taskId: string,
+ stage: string,
+ fields: Record<string, unknown>
+ ): void {
+ try {
+ this.opts.createLog?.(pluginId).info(`HTTP task: ${stage}`, {
+ ...fields,
+ taskId,
+ stage,
+ source: 'host',
+ })
+ } catch {
+ // Diagnostic capture must never change hook or download behavior.
+ }
+ }
+
// -------------------------------------------------------------------------
// beforeCreate (HTTP)
// -------------------------------------------------------------------------
@@ -187,6 +209,7 @@ export class HookOrchestrator {
const staged = new StagedEffectStore()
const timeout = this.opts.hookTimeoutMs.series
let working = cloneBeforeCreate(initial)
+ const diagnosticPluginIds: string[] = []
for (const entry of chain) {
if (this.breaker.isOpen(entry.id, 'beforeCreate')) {
@@ -204,6 +227,13 @@ export class HookOrchestrator {
}
const abort = newHookAbort(timeout)
+ diagnosticPluginIds.push(entry.id)
+ this.recordHttpDiagnostic(entry.id, taskId, 'beforeCreate.input', {
+ sourceUrl: working.sourceUrl,
+ uris: working.uris,
+ headers: working.headers,
+ proxy: working.proxy,
+ })
try {
const check = this.opts.host.capturePolicyCheck?.(entry.id)
@@ -230,11 +260,19 @@ export class HookOrchestrator {
'http',
'https',
]).map((source) => source.sourceUrl)
+ this.recordHttpDiagnostic(entry.id, taskId, 'beforeCreate.output', {
+ uris: working.uris,
+ headers: working.headers,
+ proxy: working.proxy,
+ })
this.breaker.success(entry.id, 'beforeCreate')
} catch (e) {
if (e instanceof DownloadSourceError) throw e
await this.recordPluginFailure(entry.id, 'beforeCreate')
const message = (e as Error).message
+ this.recordHttpDiagnostic(entry.id, taskId, 'beforeCreate.error', {
+ error: message,
+ })
await this.opts.auditLog?.log({
type: 'chain.plugin_error',
hook: 'beforeCreate',
@@ -295,7 +333,21 @@ export class HookOrchestrator {
})
staged.assertPolicyCurrent()
- return { final, contributors: merged.contributors, staged }
+ return {
+ final,
+ contributors: merged.contributors,
+ staged,
+ recordEngineDispatch: (params) => {
+ for (const pluginId of diagnosticPluginIds) {
+ this.recordHttpDiagnostic(pluginId, taskId, 'engine.dispatch', {
+ uris: params.uris,
+ headers: params.headers,
+ proxy: params.proxy,
+ gid: params.gid,
+ })
+ }
+ },
+ }
}
// -------------------------------------------------------------------------
diff --git a/src/core/plugin/host/capability-bridge.dispatch.test.ts b/src/core/plugin/host/capability-bridge.dispatch.test.ts
index bd9ace71..56afabdd 100644
--- a/src/core/plugin/host/capability-bridge.dispatch.test.ts
+++ b/src/core/plugin/host/capability-bridge.dispatch.test.ts
@@ -119,6 +119,7 @@ function buildCapabilityHost(): BuiltHost {
clearLog: () => {},
setLogVerbose: () => {},
isLogVerbose: () => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => () => {},
appSnapshot: () => ({
version: '2.5.0',
diff --git a/src/core/plugin/host/capability-bridge.ffmpeg-gate.test.ts b/src/core/plugin/host/capability-bridge.ffmpeg-gate.test.ts
index c2799b56..e5c3801d 100644
--- a/src/core/plugin/host/capability-bridge.ffmpeg-gate.test.ts
+++ b/src/core/plugin/host/capability-bridge.ffmpeg-gate.test.ts
@@ -269,6 +269,7 @@ function buildMinimalCapabilityHost(
clearLog: () => {},
setLogVerbose: () => {},
isLogVerbose: () => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => () => {},
appSnapshot: () => ({
version: '2.5.0',
diff --git a/src/core/plugin/host/capability-bridge.permission.test.ts b/src/core/plugin/host/capability-bridge.permission.test.ts
index 60d19f1d..102d3d62 100644
--- a/src/core/plugin/host/capability-bridge.permission.test.ts
+++ b/src/core/plugin/host/capability-bridge.permission.test.ts
@@ -62,6 +62,7 @@ function nullCapabilityHost(): CapabilityHost {
clearLog: noop,
setLogVerbose: noop,
isLogVerbose: () => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => () => {},
appSnapshot: () => ({
version: '2.0.0',
diff --git a/src/core/plugin/host/capability-bridge.phase.test.ts b/src/core/plugin/host/capability-bridge.phase.test.ts
index 16b5c0df..0e50e358 100644
--- a/src/core/plugin/host/capability-bridge.phase.test.ts
+++ b/src/core/plugin/host/capability-bridge.phase.test.ts
@@ -140,6 +140,7 @@ function buildCapabilityHost(): CapabilityHost {
clearLog: () => {},
setLogVerbose: () => {},
isLogVerbose: () => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => () => {},
appSnapshot: () => ({
version: '2.5.0',
diff --git a/src/core/plugin/host/e2e-capabilities.test.ts b/src/core/plugin/host/e2e-capabilities.test.ts
index b328239a..15587e89 100644
--- a/src/core/plugin/host/e2e-capabilities.test.ts
+++ b/src/core/plugin/host/e2e-capabilities.test.ts
@@ -71,6 +71,7 @@ function buildAllcapsHost(): CapabilityHost {
clearLog: (_pluginId: string) => {},
setLogVerbose: (_pluginId: string, _verbose: boolean) => {},
isLogVerbose: (_pluginId: string) => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => () => {},
appSnapshot: () => ({
version: '2.5.0',
diff --git a/src/core/plugin/host/test-helpers.ts b/src/core/plugin/host/test-helpers.ts
index e595750b..697cbb42 100644
--- a/src/core/plugin/host/test-helpers.ts
+++ b/src/core/plugin/host/test-helpers.ts
@@ -45,6 +45,7 @@ export function makeStubCapabilityHost(): CapabilityHost {
clearLog: (_pluginId: string) => {},
setLogVerbose: (_pluginId: string, _verbose: boolean) => {},
isLogVerbose: (_pluginId: string) => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => noop,
appSnapshot: () => ({
version: '2.5.0',
diff --git a/src/core/plugin/install/e2e-install.test.ts b/src/core/plugin/install/e2e-install.test.ts
index 7659c15b..ab20783a 100644
--- a/src/core/plugin/install/e2e-install.test.ts
+++ b/src/core/plugin/install/e2e-install.test.ts
@@ -156,6 +156,7 @@ function makeHost(calls: CascadeCalls): CapabilityHost {
clearLog: () => {},
setLogVerbose: () => {},
isLogVerbose: () => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => noop,
appSnapshot: () => ({
version: '2.5.0',
diff --git a/src/core/plugin/runtime/runtime-factory.ts b/src/core/plugin/runtime/runtime-factory.ts
index 19d0dad2..8cf09b48 100644
--- a/src/core/plugin/runtime/runtime-factory.ts
+++ b/src/core/plugin/runtime/runtime-factory.ts
@@ -99,6 +99,7 @@ export async function createPluginRuntime(
},
})
const orchestrator = new HookOrchestrator({
+ createLog: (pluginId) => options.capabilityHost.createLog(pluginId),
host: options.host,
activationDispatcher: options.activation,
breaker,
diff --git a/src/core/task/create-task-handler.plugin-hook-e2e.test.ts b/src/core/task/create-task-handler.plugin-hook-e2e.test.ts
index e7ebe530..52f44435 100644
--- a/src/core/task/create-task-handler.plugin-hook-e2e.test.ts
+++ b/src/core/task/create-task-handler.plugin-hook-e2e.test.ts
@@ -16,10 +16,11 @@
// user-supplied URL. After the wiring fix in commands.ts, that scenario
// cannot occur in production.
-import { cpSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'
+import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import type { CapabilityHost } from '@core/plugin/capabilities/interface'
+import { LogCapabilityHost } from '@core/plugin/capabilities/log'
import { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'
import { PluginHost } from '@core/plugin/host/plugin-host'
import { PluginRegistry } from '@core/plugin/plugin-registry'
@@ -57,6 +58,7 @@ function buildCapHost(_rootDir: string): CapabilityHost {
clearLog: () => {},
setLogVerbose: () => {},
isLogVerbose: () => false,
+ getLogState: () => ({ verbose: false, expiresAt: null }),
subscribeLog: () => noop,
appSnapshot: () => ({
version: '2.5.0',
@@ -106,13 +108,17 @@ vi.mock('node:fs/promises', async () => {
interface BootedStack {
host: PluginHost
+ logs: LogCapabilityHost
orchestrator: HookOrchestrator
rootDir: string
pluginsDir: string
shutdown(): Promise<void>
}
-async function bootStack(fixtureId: string): Promise<BootedStack> {
+async function bootStack(
+ fixtureId: string,
+ rewrittenUri?: string
+): Promise<BootedStack> {
const rootDir = mkdtempSync(path.join(tmpdir(), 'mhe-hook-e2e-'))
const pluginsDir = path.join(rootDir, 'plugins')
mkdirSync(pluginsDir, { recursive: true })
@@ -120,6 +126,23 @@ async function bootStack(fixtureId: string): Promise<BootedStack> {
recursive: true,
})
+ if (rewrittenUri) {
+ writeFileSync(
+ path.join(pluginsDir, fixtureId, 'dist/plugin.js'),
+ `
+ import { hooks } from 'motrix:plugin-api';
+ hooks.beforeCreate(async (ctx) => {
+ if (ctx.sourceUrl !== ${JSON.stringify(SOURCE_URL)} || ctx.uris[0] !== ${JSON.stringify(SOURCE_URL)}) {
+ throw new Error('source query changed before hook');
+ }
+ ctx.update({ uris: [${JSON.stringify(rewrittenUri)}] });
+ });
+ `
+ )
+ }
+ const logs = new LogCapabilityHost({
+ pluginLogsDir: path.join(rootDir, 'logs'),
+ })
const db = new Database(':memory:')
migrate(db)
const stateStore = new PluginStateStore(db)
@@ -146,6 +169,7 @@ async function bootStack(fixtureId: string): Promise<BootedStack> {
const orchestrator = new HookOrchestrator({
host,
+ createLog: (id) => logs.create(id),
hookTimeoutMs: { series: 10_000, parallel: 30_000 },
pluginsDir,
pluginStorageRootFor: (id) => path.join(pluginsDir, id, 'storage'),
@@ -153,11 +177,13 @@ async function bootStack(fixtureId: string): Promise<BootedStack> {
return {
host,
+ logs,
orchestrator,
rootDir,
pluginsDir,
async shutdown() {
await host.shutdown()
+ await logs.flush()
db.close()
rmSync(rootDir, { recursive: true, force: true })
},
@@ -259,6 +285,51 @@ describe('handleCreateTask + beforeCreate hook wiring', () => {
}
})
+ it.each([
+ ['https://httpbin.org/get?a=1', false],
+ [
+ 'https://drive.usercontent.google.com/download?id=test-ID&export=download&confirm=t',
+ false,
+ ],
+ [
+ 'https://cdn.example.com/download?item=a%2fb+X&item=2&empty=&sig=private-signature',
+ false,
+ ],
+ [
+ 'https://cdn.example.com/download?item=a%2fb+X&item=2&empty=&sig=private-signature',
+ true,
+ ],
+ ])(
+ 'preserves %s through QuickJS and aria2 while recording scoped diagnostics (verbose=%s)',
+ async (uri, verbose) => {
+ stack = await bootStack('test.resolve-band', uri as string)
+ stack.logs.setVerbose('test.resolve-band', verbose as boolean)
+ const saveDir = path.join(stack.rootDir, 'save')
+ const deps = makeBaseDeps(saveDir)
+ await handleCreateTask(
+ { type: 'http', uris: [SOURCE_URL], saveDir, headers: [] },
+ { ...deps, orchestrator: stack.orchestrator }
+ )
+ expect(deps.addUri.mock.calls[0][0]).toEqual([uri])
+ const records = stack.logs.getTail('test.resolve-band', 10)
+ expect(records.map((record) => record.stage)).toEqual([
+ 'beforeCreate.input',
+ 'beforeCreate.output',
+ 'engine.dispatch',
+ ])
+ expect(records[0].uris).toEqual([SOURCE_URL])
+ const logged = verbose
+ ? uri
+ : (uri as string).replace('sig=private-signature', 'sig=[redacted]')
+ expect(records[1].uris).toEqual([logged])
+ expect(records[2].uris).toEqual([logged])
+ expect(records[2].gid).toBe(deps.addUri.mock.calls[0][1].gid)
+ expect(new Set(records.map((record) => record.taskId)).size).toBe(1)
+ expect(stack.logs.getTail('other.plugin', 10)).toEqual([])
+ },
+ 30_000
+ )
+
it('rewrites the source URL when the orchestrator is wired', async () => {
stack = await bootStack('test.resolve-band')
const saveDir = path.join(stack.rootDir, 'save')
diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.ts
index 52a9556d..145c73b1 100644
--- a/src/core/task/create-task-handler.test.ts
+++ b/src/core/task/create-task-handler.test.ts
@@ -765,7 +765,9 @@ describe('handleCreateTask', () => {
| undefined
expect(dispatchFields?.gid).toMatch(/^[0-9a-f]{16}$/)
expect(dispatchFields).not.toHaveProperty('params')
- expect(dispatchFields).not.toHaveProperty('uris')
+ expect(dispatchFields).toHaveProperty('uris', [
+ 'https://example.com/file.zip?token=[redacted]',
+ ])
expect(dispatchFields).not.toHaveProperty('headers')
expect(dispatchFields).not.toHaveProperty('proxy')
expect(dispatchFields).not.toHaveProperty('extraEngineOptions')
diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.ts
index 95b2b4fc..66934650 100644
--- a/src/core/task/create-task-handler.ts
+++ b/src/core/task/create-task-handler.ts
@@ -580,6 +580,9 @@ async function handleCreateTaskUnderAdmission(
// incomplete suffix. BT uses its final output directory and no `out`;
// parsed torrents additionally carry per-file output mappings. The adapter
// is responsible for the aria2 wire shape.
+ let recordPluginEngineDispatch:
+ | ((params: CreateDownloadParams) => void)
+ | undefined
let pluginMetadataOps: readonly StagedMetadataOp[] = []
let assertPluginPolicyCurrent: (() => void) | undefined
let dispatchEngine: (reservedGid: string) => Promise<string>
@@ -600,6 +603,7 @@ async function handleCreateTaskUnderAdmission(
{
method: 'createDownload',
uriCount: params.uris.length,
+ uris: params.uris,
gid: reservedGid,
saveDir: params.saveDir,
filename: params.filename,
@@ -607,6 +611,7 @@ async function handleCreateTaskUnderAdmission(
},
'dispatching to engine'
)
+ recordPluginEngineDispatch?.(params)
return deps.adapter.createDownload(params)
}
@@ -767,6 +772,7 @@ async function handleCreateTaskUnderAdmission(
{
taskId,
aborted: result.aborted === true,
+ rewrittenUris: result.aborted ? undefined : result.final.uris,
rewrittenUriCount: result.aborted
? undefined
: result.final.uris.length,
@@ -786,6 +792,7 @@ async function handleCreateTaskUnderAdmission(
`plugin chain aborted: ${result.reason}`
)
}
+ recordPluginEngineDispatch = result.recordEngineDispatch
if (result.staged.hasPolicyChecks) {
assertPluginPolicyCurrent = () => result.staged.assertPolicyCurrent()
assertPluginPolicyCurrent()
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index 6adb09d4..727ba91b 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -3014,3 +3014,37 @@ describe('manual media merge logging', () => {
)
})
})
+
+describe('plugin diagnostic mode command', () => {
+ it.each([true, false])(
+ 'returns authoritative state after setting verbose=%s',
+ async (verbose) => {
+ const state = { verbose, expiresAt: verbose ? 3_610_000 : null }
+ const setLogVerbose = vi.fn()
+ const getLogState = vi.fn(() => state)
+ const handlers = buildCommandHandlers({
+ ...fakeCtx(),
+ capabilityHost: { setLogVerbose, getLogState },
+ } as unknown as CommandContext)
+ await expect(
+ handlers[Commands.SetPluginLogVerbose]?.({
+ pluginId: 'alice.demo',
+ verbose,
+ })
+ ).resolves.toEqual(state)
+ expect(setLogVerbose).toHaveBeenCalledWith('alice.demo', verbose)
+ expect(getLogState).toHaveBeenCalledWith('alice.demo')
+ setLogVerbose.mockClear()
+ for (const payload of [
+ null,
+ {},
+ { pluginId: 'alice.demo', verbose: 'true' },
+ ]) {
+ await expect(
+ handlers[Commands.SetPluginLogVerbose]?.(payload)
+ ).rejects.toThrow()
+ }
+ expect(setLogVerbose).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index c85ab09b..9cd30683 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -113,6 +113,7 @@ import {
import { closeCurrentWindowSchema } from '@shared/schemas/close-current-window'
import { filePickerOptionsSchema } from '@shared/schemas/file-picker'
import { moveTasksPayloadSchema } from '@shared/schemas/move-tasks'
+import { PluginLogVerboseRequestSchema } from '@shared/schemas/plugin-logs'
import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'
import { REGISTRY_PLUGIN_ID_RE } from '@shared/schemas/registry'
import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'
@@ -1918,11 +1919,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
},
[Commands.SetPluginLogVerbose]: async (payload: unknown) => {
- const parsed = z
- .object({ pluginId: z.string().min(1), verbose: z.boolean() })
- .parse(payload)
+ const parsed = PluginLogVerboseRequestSchema.parse(payload)
capabilityHost.setLogVerbose(parsed.pluginId, parsed.verbose)
- return { ok: true }
+ return capabilityHost.getLogState(parsed.pluginId)
},
}
}
diff --git a/src/main/ipc/queries.test.ts b/src/main/ipc/queries.test.ts
index 9e15d1f0..b5edaf76 100644
--- a/src/main/ipc/queries.test.ts
+++ b/src/main/ipc/queries.test.ts
@@ -855,3 +855,24 @@ describe('GetFfmpegDetection handler', () => {
expect(handlers[Queries.GetFfmpegDetection]).toBeInstanceOf(Function)
})
})
+
+describe('plugin diagnostic state query', () => {
+ it('returns host expiry and rejects invalid plugin requests', async () => {
+ const state = { verbose: true, expiresAt: 3_610_000 }
+ const getLogState = vi.fn(() => state)
+ const handlers = buildQueryHandlers({
+ capabilityHost: { getLogState },
+ } as unknown as QueryContext)
+ await expect(
+ handlers[Queries.GetPluginLogState]?.({ pluginId: 'alice.demo' })
+ ).resolves.toEqual(state)
+ expect(getLogState).toHaveBeenCalledWith('alice.demo')
+ getLogState.mockClear()
+ for (const payload of [null, {}, { pluginId: '' }]) {
+ await expect(
+ handlers[Queries.GetPluginLogState]?.(payload)
+ ).rejects.toThrow()
+ }
+ expect(getLogState).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/ipc/queries.ts b/src/main/ipc/queries.ts
index 7d3b59b5..59268689 100644
--- a/src/main/ipc/queries.ts
+++ b/src/main/ipc/queries.ts
@@ -45,6 +45,7 @@ import {
} from '@shared/protocol/errors'
import type { QueryHandlerMap } from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
+import { PluginLogRequestSchema } from '@shared/schemas/plugin-logs'
import { parseTaskInspectorActivitySnapshot } from '@shared/schemas/task-inspector-activity'
import { taskTrackerRequestSchema } from '@shared/schemas/task-tracker'
import type { GetTransferStatsParams } from '@shared/types/stats'
@@ -305,6 +306,11 @@ export function buildQueryHandlers(ctx: QueryContext): QueryHandlerMap {
path.join(pluginsDir, '_audit', 'command-invokes.ndjson')
),
+ [Queries.GetPluginLogState]: async (payload: unknown) => {
+ const { pluginId } = PluginLogRequestSchema.parse(payload)
+ return capabilityHost.getLogState(pluginId)
+ },
+
[Queries.GetPluginLogs]: async (params: {
pluginId: string
limit?: number
diff --git a/src/main/plugin/capability-host.ts b/src/main/plugin/capability-host.ts
index da904776..6a34c9ed 100644
--- a/src/main/plugin/capability-host.ts
+++ b/src/main/plugin/capability-host.ts
@@ -135,6 +135,7 @@ export async function createElectronCapabilityHost(
clearLog: (id) => log.clear(id),
setLogVerbose: (id, v) => log.setVerbose(id, v),
isLogVerbose: (id) => log.isVerbose(id),
+ getLogState: (id) => log.getState(id),
subscribeLog: (listener) => log.subscribe(listener),
appSnapshot: () => ({
...appCap.snapshot(),
diff --git a/src/renderer/routes/plugins/components/plugin-log-tab.test.tsx b/src/renderer/routes/plugins/components/plugin-log-tab.test.tsx
new file mode 100644
index 00000000..9f294e16
--- /dev/null
+++ b/src/renderer/routes/plugins/components/plugin-log-tab.test.tsx
@@ -0,0 +1,56 @@
+import '@testing-library/jest-dom/vitest'
+import '@renderer/lib/i18n'
+import { Queries } from '@shared/protocol/queries'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeAll, describe, expect, it, vi } from 'vitest'
+import { PluginLogTab } from './plugin-log-tab'
+
+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
+vi.mock('@renderer/lib/transport', () => ({
+ transport: { invoke, on: vi.fn(), off: vi.fn() },
+}))
+
+beforeAll(() => {
+ Element.prototype.getAnimations = vi.fn(() => [])
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ )
+})
+
+describe('PluginLogTab', () => {
+ it('copies sanitized entries while keeping verbose local output intact', async () => {
+ const raw = 'https://example.com/file?id=private-id&sig=private-signature'
+ const entry = { ts: 1000, level: 'info', msg: `GET ${raw}`, uris: [raw] }
+ invoke.mockImplementation(async (channel) =>
+ channel === Queries.GetPluginLogState
+ ? { verbose: true, expiresAt: Date.now() + 60_000 }
+ : [entry]
+ )
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText },
+ })
+ const { unmount } = render(<PluginLogTab pluginId="alice.demo" />)
+ await screen.findByText(`GET ${raw}`)
+ expect(screen.getByRole('switch')).toBeChecked()
+ fireEvent.click(screen.getByRole('button', { name: 'Copy redacted logs' }))
+ await waitFor(() => expect(writeText).toHaveBeenCalledOnce())
+ const copied = writeText.mock.calls[0][0] as string
+ expect(JSON.parse(copied)[0]).toMatchObject({
+ ts: 1000,
+ level: 'info',
+ uris: ['https://example.com/file?id=[redacted]&sig=[redacted]'],
+ })
+ expect(copied).not.toContain('private-id')
+ expect(copied).not.toContain('private-signature')
+ expect(screen.getByText(`GET ${raw}`)).toBeInTheDocument()
+ expect(entry.uris).toEqual([raw])
+ unmount()
+ })
+})
diff --git a/src/renderer/routes/plugins/components/plugin-log-tab.tsx b/src/renderer/routes/plugins/components/plugin-log-tab.tsx
index c2c3ad18..d63708a5 100644
--- a/src/renderer/routes/plugins/components/plugin-log-tab.tsx
+++ b/src/renderer/routes/plugins/components/plugin-log-tab.tsx
@@ -23,9 +23,11 @@ import {
import { Separator } from '@renderer/components/ui/separator'
import { Switch } from '@renderer/components/ui/switch'
import { transport } from '@renderer/lib/transport'
+import { serializePluginLogsForExport } from '@shared/lib/plugin-log-export'
import { Commands } from '@shared/protocol/commands'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { usePluginLogState } from '../hooks/use-plugin-log-state'
import { usePluginLogStream } from '../hooks/use-plugin-log-stream'
import { PluginLogRow } from './plugin-log-row'
@@ -42,7 +44,7 @@ const LEVELS = [
export function PluginLogTab({ pluginId }: { pluginId: string }) {
const { t } = useTranslation()
const [level, setLevel] = useState<(typeof LEVELS)[number]>('all')
- const [verbose, setVerbose] = useState(false)
+ const { verbose, pending, setVerbose } = usePluginLogState(pluginId)
const { entries, setEntries } = usePluginLogStream(pluginId)
const levelOptions = LEVELS.map((value) => ({
value,
@@ -52,14 +54,6 @@ export function PluginLogTab({ pluginId }: { pluginId: string }) {
const filtered =
level === 'all' ? entries : entries.filter((e) => e.level === level)
- async function onVerboseChange(v: boolean) {
- setVerbose(v)
- await transport.invoke(Commands.SetPluginLogVerbose, {
- pluginId,
- verbose: v,
- })
- }
-
async function onClear() {
await transport.invoke(Commands.ClearPluginLogs, { pluginId })
setEntries([])
@@ -102,7 +96,8 @@ export function PluginLogTab({ pluginId }: { pluginId: string }) {
id="plugin-log-verbose"
size="sm"
checked={verbose}
- onCheckedChange={onVerboseChange}
+ onCheckedChange={setVerbose}
+ disabled={pending}
/>
<span>{t('plugins.logs.verbose')}</span>
</label>
@@ -114,7 +109,7 @@ export function PluginLogTab({ pluginId }: { pluginId: string }) {
size="xs"
variant="ghost"
disabled={filtered.length === 0}
- content={JSON.stringify(filtered, null, 2)}
+ content={() => serializePluginLogsForExport(filtered)}
className="active:scale-[0.97] motion-reduce:transform-none"
>
{t('plugins.logs.copy')}
diff --git a/src/renderer/routes/plugins/hooks/use-plugin-log-state.test.ts b/src/renderer/routes/plugins/hooks/use-plugin-log-state.test.ts
new file mode 100644
index 00000000..4303cc59
--- /dev/null
+++ b/src/renderer/routes/plugins/hooks/use-plugin-log-state.test.ts
@@ -0,0 +1,110 @@
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { usePluginLogState } from './use-plugin-log-state'
+
+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
+vi.mock('@renderer/lib/transport', () => ({ transport: { invoke } }))
+
+async function flush() {
+ await act(async () => {
+ await Promise.resolve()
+ })
+}
+
+describe('plugin diagnostic state', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(10_000)
+ invoke.mockReset()
+ })
+ afterEach(() => vi.useRealTimers())
+
+ it('restores the host state on remount and stops displaying verbose at expiry', async () => {
+ invoke.mockResolvedValue({ verbose: true, expiresAt: 11_000 })
+ const first = renderHook(() => usePluginLogState('alice.demo'))
+ await flush()
+ expect(first.result.current.verbose).toBe(true)
+ first.unmount()
+ const second = renderHook(() => usePluginLogState('alice.demo'))
+ await flush()
+ expect(second.result.current.verbose).toBe(true)
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+ expect(second.result.current.verbose).toBe(false)
+ expect(invoke).not.toHaveBeenCalledWith(
+ Commands.SetPluginLogVerbose,
+ expect.anything()
+ )
+ second.unmount()
+ })
+
+ it('keeps the switch off on a failed enable and allows a retry', async () => {
+ invoke.mockImplementation((channel) =>
+ channel === Queries.GetPluginLogState
+ ? Promise.resolve({ verbose: false, expiresAt: null })
+ : Promise.reject(new Error('offline'))
+ )
+ const { result, unmount } = renderHook(() =>
+ usePluginLogState('alice.demo')
+ )
+ await flush()
+ await act(async () => {
+ await result.current.setVerbose(true)
+ })
+ expect(result.current.verbose).toBe(false)
+ expect(result.current.pending).toBe(false)
+ invoke.mockResolvedValue({ verbose: true, expiresAt: 3_610_000 })
+ await act(async () => {
+ await result.current.setVerbose(true)
+ })
+ expect(result.current.verbose).toBe(true)
+ unmount()
+ })
+
+ it('ignores a stale snapshot after a successful toggle', async () => {
+ let resolve!: (value: unknown) => void
+ invoke.mockImplementation((channel) =>
+ channel === Queries.GetPluginLogState
+ ? new Promise((done) => {
+ resolve = done
+ })
+ : Promise.resolve({ verbose: true, expiresAt: 3_610_000 })
+ )
+ const { result, unmount } = renderHook(() =>
+ usePluginLogState('alice.demo')
+ )
+ await act(async () => {
+ await result.current.setVerbose(true)
+ })
+ await act(async () => {
+ resolve({ verbose: false, expiresAt: null })
+ })
+ expect(result.current.verbose).toBe(true)
+ unmount()
+ })
+
+ it('does not show another plugin’s state after navigation', async () => {
+ let resolve!: (value: unknown) => void
+ invoke.mockImplementation((_channel, { pluginId }) =>
+ pluginId === 'alice.demo'
+ ? new Promise((done) => {
+ resolve = done
+ })
+ : Promise.resolve({ verbose: false, expiresAt: null })
+ )
+ const { result, rerender, unmount } = renderHook(
+ ({ pluginId }) => usePluginLogState(pluginId),
+ { initialProps: { pluginId: 'alice.demo' } }
+ )
+ rerender({ pluginId: 'bob.demo' })
+ await flush()
+ await act(async () => {
+ resolve({ verbose: true, expiresAt: 3_610_000 })
+ })
+ expect(result.current.verbose).toBe(false)
+ unmount()
+ })
+})
diff --git a/src/renderer/routes/plugins/hooks/use-plugin-log-state.ts b/src/renderer/routes/plugins/hooks/use-plugin-log-state.ts
new file mode 100644
index 00000000..d1a6c55c
--- /dev/null
+++ b/src/renderer/routes/plugins/hooks/use-plugin-log-state.ts
@@ -0,0 +1,97 @@
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import {
+ type PluginLogState,
+ PluginLogStateSchema,
+} from '@shared/schemas/plugin-logs'
+import { useEffect, useRef, useState } from 'react'
+
+const OFF: PluginLogState = { verbose: false, expiresAt: null }
+
+/** Host-owned expiry survives tab remounts and cannot be extended by rendering. */
+export function usePluginLogState(pluginId: string) {
+ const [snapshot, setSnapshot] = useState({ pluginId, state: OFF })
+ const [pending, setPending] = useState(false)
+ const generation = useRef(0)
+ const mutation = useRef(false)
+ const activePlugin = useRef(pluginId)
+ activePlugin.current = pluginId
+ const state = snapshot.pluginId === pluginId ? snapshot.state : OFF
+
+ useEffect(() => {
+ let cancelled = false
+ setPending(false)
+ mutation.current = false
+ const refresh = async () => {
+ if (mutation.current) return
+ const request = ++generation.current
+ try {
+ const result = PluginLogStateSchema.parse(
+ await transport.invoke(Queries.GetPluginLogState, { pluginId })
+ )
+ if (!cancelled && request === generation.current)
+ setSnapshot({ pluginId, state: result })
+ } catch {
+ // Keep the last host snapshot; reconnect/focus or the next poll retries.
+ }
+ }
+ void refresh()
+ // Synchronize toggles made in another client, including a disabled -> enabled change.
+ const poll = setInterval(() => void refresh(), 10_000)
+ const onFocus = () => void refresh()
+ window.addEventListener('focus', onFocus)
+ const unsubscribe = transport.onConnectionChange?.(({ state }) => {
+ if (state === 'connected') void refresh()
+ })
+ return () => {
+ cancelled = true
+ generation.current += 1
+ clearInterval(poll)
+ window.removeEventListener('focus', onFocus)
+ unsubscribe?.()
+ }
+ }, [pluginId])
+
+ useEffect(() => {
+ if (state.expiresAt === null) return
+ const timer = setTimeout(
+ () => {
+ setSnapshot((current) =>
+ current.pluginId === pluginId &&
+ current.state.expiresAt === state.expiresAt
+ ? { pluginId, state: OFF }
+ : current
+ )
+ },
+ Math.max(0, state.expiresAt - Date.now())
+ )
+ return () => clearTimeout(timer)
+ }, [pluginId, state.expiresAt])
+
+ async function setVerbose(verbose: boolean) {
+ if (mutation.current) return
+ mutation.current = true
+ const request = ++generation.current
+ setPending(true)
+ try {
+ const result = PluginLogStateSchema.parse(
+ await transport.invoke(Commands.SetPluginLogVerbose, {
+ pluginId,
+ verbose,
+ })
+ )
+ if (request === generation.current && activePlugin.current === pluginId)
+ setSnapshot({ pluginId, state: result })
+ } catch {
+ // A failed command must not make the switch claim capture is enabled.
+ } finally {
+ if (request === generation.current && activePlugin.current === pluginId) {
+ mutation.current = false
+ setPending(false)
+ }
+ }
+ }
+
+ return { verbose: state.verbose, pending, setVerbose }
+}
diff --git a/src/renderer/routes/plugins/plugin-detail-page.test.tsx b/src/renderer/routes/plugins/plugin-detail-page.test.tsx
index 07b6eac5..6b5022ee 100644
--- a/src/renderer/routes/plugins/plugin-detail-page.test.tsx
+++ b/src/renderer/routes/plugins/plugin-detail-page.test.tsx
@@ -285,7 +285,9 @@ describe('PluginDetailPage', () => {
).toBeInTheDocument()
expect(screen.getByText('Live output')).toBeInTheDocument()
expect(screen.getByText('0 entries')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Copy' })).toBeDisabled()
+ expect(
+ screen.getByRole('button', { name: 'Copy redacted logs' })
+ ).toBeDisabled()
expect(screen.getByRole('button', { name: 'Clear' })).toBeDisabled()
})
diff --git a/src/server/ipc/commands.test.ts b/src/server/ipc/commands.test.ts
index f896eb47..dc5dd1bc 100644
--- a/src/server/ipc/commands.test.ts
+++ b/src/server/ipc/commands.test.ts
@@ -2063,3 +2063,37 @@ describe('manual media merge logging', () => {
)
})
})
+
+describe('plugin diagnostic mode command', () => {
+ it.each([true, false])(
+ 'returns authoritative state after setting verbose=%s',
+ async (verbose) => {
+ const state = { verbose, expiresAt: verbose ? 3_610_000 : null }
+ const setLogVerbose = vi.fn()
+ const getLogState = vi.fn(() => state)
+ const handlers = buildServerCommandHandlers({
+ ...makeFakeCtx(),
+ capabilityHost: { setLogVerbose, getLogState },
+ } as unknown as ServerCommandContext)
+ await expect(
+ handlers[Commands.SetPluginLogVerbose]?.({
+ pluginId: 'alice.demo',
+ verbose,
+ })
+ ).resolves.toEqual(state)
+ expect(setLogVerbose).toHaveBeenCalledWith('alice.demo', verbose)
+ expect(getLogState).toHaveBeenCalledWith('alice.demo')
+ setLogVerbose.mockClear()
+ for (const payload of [
+ null,
+ {},
+ { pluginId: 'alice.demo', verbose: 'true' },
+ ]) {
+ await expect(
+ handlers[Commands.SetPluginLogVerbose]?.(payload)
+ ).rejects.toThrow()
+ }
+ expect(setLogVerbose).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 216cd9e8..dbd51c5c 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -90,6 +90,7 @@ import {
} from '@shared/schemas/bulk-task-command'
import { languagePreferenceSchema } from '@shared/schemas/locale'
import { moveTasksPayloadSchema } from '@shared/schemas/move-tasks'
+import { PluginLogVerboseRequestSchema } from '@shared/schemas/plugin-logs'
import { checkPluginUpdatesPayloadSchema } from '@shared/schemas/plugin-update'
import { removeTaskPayloadSchema } from '@shared/schemas/remove-task'
import {
@@ -1127,11 +1128,9 @@ export function buildServerCommandHandlers(
},
[Commands.SetPluginLogVerbose]: async (payload: unknown) => {
- const parsed = z
- .object({ pluginId: z.string().min(1), verbose: z.boolean() })
- .parse(payload)
+ const parsed = PluginLogVerboseRequestSchema.parse(payload)
capabilityHost.setLogVerbose(parsed.pluginId, parsed.verbose)
- return { ok: true }
+ return capabilityHost.getLogState(parsed.pluginId)
},
[Commands.MarkNotificationRead]: async (id: string) =>
diff --git a/src/server/ipc/queries.test.ts b/src/server/ipc/queries.test.ts
index e932054b..b9a06d9f 100644
--- a/src/server/ipc/queries.test.ts
+++ b/src/server/ipc/queries.test.ts
@@ -760,3 +760,24 @@ describe('directory location query validation', () => {
expect(locations).not.toHaveBeenCalled()
})
})
+
+describe('plugin diagnostic state query', () => {
+ it('returns host expiry and rejects invalid plugin requests', async () => {
+ const state = { verbose: true, expiresAt: 3_610_000 }
+ const getLogState = vi.fn(() => state)
+ const handlers = buildServerQueryHandlers({
+ capabilityHost: { getLogState },
+ } as unknown as ServerQueryContext)
+ await expect(
+ handlers[Queries.GetPluginLogState]?.({ pluginId: 'alice.demo' })
+ ).resolves.toEqual(state)
+ expect(getLogState).toHaveBeenCalledWith('alice.demo')
+ getLogState.mockClear()
+ for (const payload of [null, {}, { pluginId: '' }]) {
+ await expect(
+ handlers[Queries.GetPluginLogState]?.(payload)
+ ).rejects.toThrow()
+ }
+ expect(getLogState).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/server/ipc/queries.ts b/src/server/ipc/queries.ts
index 58cc7d07..c9aa9778 100644
--- a/src/server/ipc/queries.ts
+++ b/src/server/ipc/queries.ts
@@ -41,6 +41,7 @@ import type { TrackerManager } from '@core/tracker'
import type { SupportedLocale } from '@shared/constants/locales'
import type { QueryHandlerMap } from '@shared/protocol/handler-types'
import { Queries } from '@shared/protocol/queries'
+import { PluginLogRequestSchema } from '@shared/schemas/plugin-logs'
import { ListServerDirectoryLocationsRequestSchema } from '@shared/schemas/server-directory'
import { taskTrackerRequestSchema } from '@shared/schemas/task-tracker'
import type { AppUpdateState } from '@shared/types/app-update'
@@ -353,6 +354,11 @@ export function buildServerQueryHandlers(
path.join(pluginsDir, '_audit', 'command-invokes.ndjson')
),
+ [Queries.GetPluginLogState]: async (payload: unknown) => {
+ const { pluginId } = PluginLogRequestSchema.parse(payload)
+ return capabilityHost.getLogState(pluginId)
+ },
+
[Queries.GetPluginLogs]: async (params: {
pluginId: string
limit?: number
diff --git a/src/server/plugin/capability-host.ts b/src/server/plugin/capability-host.ts
index d3f7733e..1e63ba0d 100644
--- a/src/server/plugin/capability-host.ts
+++ b/src/server/plugin/capability-host.ts
@@ -124,6 +124,7 @@ export async function createServerCapabilityHost(
clearLog: (id) => log.clear(id),
setLogVerbose: (id, v) => log.setVerbose(id, v),
isLogVerbose: (id) => log.isVerbose(id),
+ getLogState: (id) => log.getState(id),
subscribeLog: (listener) => log.subscribe(listener),
appSnapshot: () => ({
...appCap.snapshot(),
diff --git a/src/shared/lib/log-redact.ts b/src/shared/lib/log-redact.ts
new file mode 100644
index 00000000..f56638fa
--- /dev/null
+++ b/src/shared/lib/log-redact.ts
@@ -0,0 +1,1011 @@
+export type LogRedactionContext =
+ | { profile: 'application' }
+ | { profile: 'plugin'; verbose: boolean }
+ | { profile: 'export' }
+
+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',
+ 'mutualkeyb64',
+ 'ticketkey',
+ 'nmticket',
+ 'pairnonce',
+ 'proxyusername',
+ 'proxypassword',
+ 'allproxyuser',
+ 'allproxypasswd',
+ 'httpuser',
+ 'httppasswd',
+ 'ftpuser',
+ 'ftppasswd',
+ 'authkey',
+ 'accesskey',
+ 'signature',
+ 'sig',
+ 'jwt',
+ 'xamzsignature',
+ 'xamzcredential',
+ 'xamzsecuritytoken',
+ 'xgoogsignature',
+ 'xgoogcredential',
+])
+
+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 || profile === 'export') 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(
+ raw.replaceAll('\\', '/').replace(/\/+$/, '').split('/').at(-1) ?? '',
+ MAX_STRUCTURED_STRING_CHARS
+ )
+}
+
+// Generic credential names, independent of download providers. Normalization also
+// catches case, separators, and percent-encoded query keys. Unknown names are
+// preserved in local logs; exported diagnostics hide every query value.
+const SENSITIVE_QUERY_KEYS = new Set([
+ ...SENSITIVE_VALUE_KEYS,
+ 'auth',
+ 'key',
+ 'session',
+ 'sessionid',
+ 'sid',
+ 'code',
+])
+
+function redactQuery(query: string, strict: boolean): string {
+ // Do not serialize URLSearchParams: doing so changes ordering/encoding and
+ // hides precisely the differences a signed-URL diagnostic needs to show.
+ return query
+ .split('&')
+ .map((part) => {
+ const separator = part.indexOf('=')
+ const key = separator < 0 ? part : part.slice(0, separator)
+ if (!part) return part
+ let sensitive = strict
+ try {
+ sensitive ||= SENSITIVE_QUERY_KEYS.has(
+ normalizeKey(decodeURIComponent(key.replaceAll('+', ' ')))
+ )
+ } catch {
+ sensitive = true
+ }
+ if (separator < 0) return strict ? REDACTED : part
+ if (!sensitive) return part
+ return `${key}=${REDACTED}`
+ })
+ .join('&')
+}
+
+function redactUrl(raw: unknown, strict = false): 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 (
+ ['http:', 'https:', 'ftp:', 'sftp:', 'ws:', 'wss:'].includes(protocol)
+ ) {
+ // URL parses/validates the authority, while the raw suffix preserves the
+ // query's byte representation (including duplicate and empty values).
+ const parts =
+ /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*([^?#]*)(\?[^#]*)?(#.*)?$/i.exec(raw)
+ if (!parts) return '[unparseable-url]'
+ const query = parts[2]
+ return truncateText(
+ `${protocol}//${url.host}${parts[1] || '/'}${query === undefined ? '' : `?${redactQuery(query.slice(1), strict)}`}`,
+ 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]'
+ }
+}
+
+/** Sanitize URLs embedded in messages, error text, or arbitrary string fields. */
+export function redactLogText(value: string, strict = false): string {
+ return truncateLogText(
+ value
+ .replace(/\b(?:https?|ftp|sftp|wss?):\/\/[^\s<>"`]+/gi, (url) =>
+ redactUrl(url, strict)
+ )
+ .replace(/\bBearer\s+[^\s,;]+/gi, `Bearer ${REDACTED}`)
+ )
+}
+
+function redactCollectionValue(raw: unknown, strict: boolean): unknown {
+ if (Array.isArray(raw)) {
+ const selected = boundedArrayItems(raw)
+ const out = selected.map((url) => redactUrl(url, strict))
+ 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, strict)
+ } 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 redactLogText(raw, strict)
+ }
+}
+
+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 = redactLogText(error.message, state.context.profile === 'export')
+ } catch {
+ message = UNREADABLE
+ }
+
+ try {
+ stack = error.stack
+ ? redactLogText(
+ truncateText(error.stack, MAX_ERROR_STACK_CHARS),
+ state.context.profile === 'export'
+ )
+ : 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, strict: boolean): 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, strict))
+ } 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 strict = state.context.profile === 'export'
+ 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 !== 'application' ? OMIT : headerNames(value)
+ }
+ if (normalized === 'extraengineoptions') {
+ return redactExtraEngineOptions(value, strict)
+ }
+ 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, strict)
+ if (LOG_URL_COLLECTION_KEYS.has(normalized)) {
+ return redactCollectionValue(value, strict)
+ }
+ 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 !== 'application' &&
+ 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), strict)
+ } 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 redactLogText(value, strict)
+ }
+ 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 (typeof value === 'string') return redactLogText(value)
+ if (
+ value === null ||
+ value === undefined ||
+ 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/shared/lib/plugin-log-export.test.ts b/src/shared/lib/plugin-log-export.test.ts
new file mode 100644
index 00000000..069f863d
--- /dev/null
+++ b/src/shared/lib/plugin-log-export.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest'
+import { serializePluginLogsForExport } from './plugin-log-export'
+
+describe('plugin log export', () => {
+ it('redacts verbose structured fields and embedded URLs without changing the live entries', () => {
+ const entries = [
+ {
+ ts: 123,
+ level: 'info' as const,
+ msg: 'GET https://example.com/download?id=private-id&token=secret',
+ uris: [
+ 'https://user:[email protected]/download?id=private-id&sig=secret#private',
+ ],
+ nested: {
+ detail: 'redirect https://example.com/?unknown=opaque&flag&empty=',
+ token: 'nested-secret',
+ signature: 'nested-signature',
+ code: 'ETIMEDOUT',
+ },
+ headers: {
+ Cookie: 'session=cookie-secret',
+ Authorization: 'Bearer auth-secret',
+ },
+ body: 'private-body',
+ filepath: '/Users/alice/private/file.txt',
+ stage: 'engine.dispatch',
+ taskId: 'task-1',
+ },
+ ]
+ const original = structuredClone(entries)
+ const output = serializePluginLogsForExport(entries)
+ const [entry] = JSON.parse(output)
+ expect(entry).toMatchObject({
+ ts: 123,
+ level: 'info',
+ taskId: 'task-1',
+ stage: 'engine.dispatch',
+ })
+ expect(entry.msg).toBe(
+ 'GET https://example.com/download?id=[redacted]&token=[redacted]'
+ )
+ expect(entry.uris).toEqual([
+ 'https://example.com/download?id=[redacted]&sig=[redacted]',
+ ])
+ expect(entry.nested.detail).toBe(
+ 'redirect https://example.com/?unknown=[redacted]&[redacted]&empty=[redacted]'
+ )
+ expect(entry.nested.signature).toBe('[redacted]')
+ expect(entry.nested.code).toBe('ETIMEDOUT')
+ expect(entry).not.toHaveProperty('headers')
+ expect(entry).not.toHaveProperty('body')
+ for (const secret of [
+ 'private-id',
+ 'secret',
+ 'opaque',
+ 'user:pass',
+ '/Users/alice',
+ ])
+ expect(output).not.toContain(secret)
+ expect(entries).toEqual(original)
+ })
+})
diff --git a/src/shared/lib/plugin-log-export.ts b/src/shared/lib/plugin-log-export.ts
new file mode 100644
index 00000000..063c8d23
--- /dev/null
+++ b/src/shared/lib/plugin-log-export.ts
@@ -0,0 +1,13 @@
+import type { PluginLogEntry } from '@shared/types/plugin'
+import { redactLogFields } from './log-redact'
+
+/** Apply export policy even when entries were captured in verbose mode. */
+export function serializePluginLogsForExport(
+ entries: readonly PluginLogEntry[]
+): string {
+ return JSON.stringify(
+ entries.map((entry) => redactLogFields(entry, { profile: 'export' })),
+ null,
+ 2
+ )
+}
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index a3f77907..621e4be7 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -1606,7 +1606,7 @@
"lead": "أضف ميزات صغيرة إلى Motrix. احتفظ بالإضافات التي تثق بها، وعطّل الباقي.",
"logs": {
"clear": "مسح",
- "copy": "نسخ",
+ "copy": "نسخ السجلات بعد حجب البيانات الحساسة",
"empty": "لا توجد إدخالات في السجل بعد",
"emptyFiltered": "لا توجد إدخالات تطابق هذا المستوى.",
"emptyHint": "سيظهر نشاط الإضافة الجديد هنا تلقائيًا.",
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index f9ea0d63..dc38307b 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -1538,7 +1538,7 @@
"lead": "Добавяйте малки функции към Motrix. Оставете включени приставките, на които имате доверие, и изключете останалите.",
"logs": {
"clear": "Изчистване",
- "copy": "Копиране",
+ "copy": "Копиране на обезличени логове",
"empty": "Все още няма записи в журнала",
"emptyFiltered": "Няма записи с това ниво.",
"emptyHint": "Новата активност на приставката ще се появява тук автоматично.",
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index f284aa55..cf5ee226 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -1555,7 +1555,7 @@
"lead": "Afegiu petites funcions al Motrix. Manteniu els connectors de confiança i desactiveu la resta.",
"logs": {
"clear": "Esborrar",
- "copy": "Copiar",
+ "copy": "Copia els registres amb dades ocultes",
"empty": "Encara no hi ha entrades al registre",
"emptyFiltered": "No hi ha entrades d'aquest nivell.",
"emptyHint": "L'activitat nova del connector apareixerà aquí automàticament.",
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index 07b668fc..e855149d 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -2446,7 +2446,7 @@
"error": "Fehler",
"fatal": "Schwerwiegend"
},
- "copy": "Kopieren",
+ "copy": "Bereinigte Protokolle kopieren",
"clear": "Leeren",
"output": "Live-Ausgabe",
"entryCount_one": "{{count}} Eintrag",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index ef0efbe3..61e6b71d 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -1538,7 +1538,7 @@
"lead": "Προσθέστε μικρές λειτουργίες στο Motrix. Κρατήστε όσες εμπιστεύεστε και απενεργοποιήστε τις υπόλοιπες.",
"logs": {
"clear": "Εκκαθάριση",
- "copy": "Αντιγραφή",
+ "copy": "Αντιγραφή αρχείων καταγραφής με απόκρυψη στοιχείων",
"empty": "Δεν υπάρχουν ακόμη εγγραφές καταγραφής",
"emptyFiltered": "Δεν υπάρχουν εγγραφές που να αντιστοιχούν σε αυτό το επίπεδο.",
"emptyHint": "Η νέα δραστηριότητα του πρόσθετου θα εμφανίζεται εδώ αυτόματα.",
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 2bf74425..c62bac9e 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -2446,7 +2446,7 @@
"error": "Error",
"fatal": "Fatal"
},
- "copy": "Copy",
+ "copy": "Copy redacted logs",
"clear": "Clear",
"output": "Live output",
"entryCount_one": "{{count}} entry",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 7bc01125..39f57ace 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -2463,7 +2463,7 @@
"error": "Error",
"fatal": "Crítico"
},
- "copy": "Copiar",
+ "copy": "Copiar registros censurados",
"clear": "Borrar",
"output": "Salida en tiempo real",
"entryCount_one": "{{count}} entrada",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index 90748ea4..945eafb8 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -1538,7 +1538,7 @@
"lead": "قابلیت‌های کوچکی به Motrix اضافه کنید. افزونه‌های مورد اعتماد را نگه دارید و بقیه را خاموش کنید.",
"logs": {
"clear": "پاک کردن",
- "copy": "کپی",
+ "copy": "کپی گزارش‌های پالایش‌شده",
"empty": "هنوز گزارشی ثبت نشده",
"emptyFiltered": "موردی با این سطح مطابقت ندارد.",
"emptyHint": "فعالیت جدید افزونه خودکار اینجا نمایش داده می‌شود.",
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index 5649735c..d05283e8 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -1555,7 +1555,7 @@
"lead": "Ajoutez des fonctionnalités à Motrix. Gardez les extensions de confiance et désactivez les autres.",
"logs": {
"clear": "Effacer",
- "copy": "Copier",
+ "copy": "Copier les journaux expurgés",
"empty": "Aucune entrée dans le journal pour le moment",
"emptyFiltered": "Aucune entrée ne correspond à ce niveau.",
"emptyHint": "Les nouvelles activités de l’extension apparaîtront ici automatiquement.",
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 624a5f24..6cf22372 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -2446,7 +2446,7 @@
"error": "Hiba",
"fatal": "Végzetes hiba"
},
- "copy": "Másolás",
+ "copy": "Kitakart naplók másolása",
"clear": "Törlés",
"output": "Élő napló",
"entryCount_one": "{{count}} bejegyzés",
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index d6e80639..2f5a32ac 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -2428,7 +2428,7 @@
"error": "Kesalahan",
"fatal": "Fatal"
},
- "copy": "Salin",
+ "copy": "Salin log tersamarkan",
"clear": "Hapus",
"output": "Keluaran langsung",
"entryCount_other": "{{count}} entri",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index fec075a7..ea7d03de 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -2464,7 +2464,7 @@
"error": "Errore",
"fatal": "Critico"
},
- "copy": "Copia",
+ "copy": "Copia log oscurati",
"clear": "Cancella",
"output": "Output in tempo reale",
"entryCount_one": "{{count}} voce",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 92ad677f..f8d28019 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -2428,7 +2428,7 @@
"error": "エラー",
"fatal": "致命的"
},
- "copy": "コピー",
+ "copy": "機密情報を除いてログをコピー",
"clear": "クリア",
"output": "リアルタイム出力",
"entryCount_other": "{{count}} 件",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index 7e1316cb..bb368570 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -2428,7 +2428,7 @@
"error": "오류",
"fatal": "치명적 오류"
},
- "copy": "복사",
+ "copy": "민감 정보를 가린 로그 복사",
"clear": "지우기",
"output": "실시간 출력",
"entryCount_other": "항목 {{count}}개",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 144ddb3f..1ffc45c7 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -1538,7 +1538,7 @@
"lead": "Legg til små funksjoner i Motrix. Behold dem du stoler på, og slå av resten.",
"logs": {
"clear": "Tøm",
- "copy": "Kopier",
+ "copy": "Kopier sladdede logger",
"empty": "Ingen loggoppføringer ennå",
"emptyFiltered": "Ingen oppføringer samsvarer med dette nivået.",
"emptyHint": "Ny aktivitet fra programtillegget vises automatisk her.",
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 4624125e..f2ef61f1 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -1538,7 +1538,7 @@
"lead": "Voeg kleine functies toe aan Motrix. Laat de plug-ins die je vertrouwt ingeschakeld en schakel de rest uit.",
"logs": {
"clear": "Wissen",
- "copy": "Kopiëren",
+ "copy": "Geredigeerde logboeken kopiëren",
"empty": "Nog geen logboekvermeldingen",
"emptyFiltered": "Geen vermeldingen op dit niveau.",
"emptyHint": "Nieuwe plug-inactiviteit verschijnt hier automatisch.",
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 7087590b..f13a8124 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -2482,7 +2482,7 @@
"error": "Błąd",
"fatal": "Błąd krytyczny"
},
- "copy": "Kopiuj",
+ "copy": "Kopiuj logi z ukrytymi danymi",
"clear": "Wyczyść",
"output": "Bieżące wpisy",
"entryCount_one": "{{count}} wpis",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 27eafdef..c82203e8 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -2464,7 +2464,7 @@
"error": "Erro",
"fatal": "Fatal"
},
- "copy": "Copiar",
+ "copy": "Copiar logs com dados ocultos",
"clear": "Limpar",
"output": "Saída em tempo real",
"entryCount_one": "{{count}} registro",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index 80e65b98..2fc95efe 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -1555,7 +1555,7 @@
"lead": "Adaugă funcții mici în Motrix. Păstrează active modulele în care ai încredere și dezactivează-le pe celelalte.",
"logs": {
"clear": "Șterge",
- "copy": "Copiază",
+ "copy": "Copiază jurnalele cu date mascate",
"empty": "Încă nu există înregistrări în jurnal",
"emptyFiltered": "Nicio înregistrare nu corespunde acestui nivel.",
"emptyHint": "Activitatea nouă a modulului va apărea aici automat.",
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index b0fbd548..6d973fa6 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -2482,7 +2482,7 @@
"error": "Ошибка",
"fatal": "Критическая ошибка"
},
- "copy": "Копировать",
+ "copy": "Копировать логи со скрытыми данными",
"clear": "Очистить",
"output": "Вывод в реальном времени",
"entryCount_one": "{{count}} запись",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index c6b5e80c..a89c77e3 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -1521,7 +1521,7 @@
"lead": "เพิ่มความสามารถเล็กๆ ให้ Motrix เปิดใช้เฉพาะปลั๊กอินที่เชื่อถือและปิดที่เหลือ",
"logs": {
"clear": "ล้าง",
- "copy": "คัดลอก",
+ "copy": "คัดลอกบันทึกที่ปกปิดข้อมูลแล้ว",
"empty": "ยังไม่มีรายการบันทึก",
"emptyFiltered": "ไม่มีรายการตรงกับระดับนี้",
"emptyHint": "กิจกรรมใหม่ของปลั๊กอินจะแสดงที่นี่โดยอัตโนมัติ",
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 49f62db5..1899ea47 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -2446,7 +2446,7 @@
"error": "Hata",
"fatal": "Kritik"
},
- "copy": "Kopyala",
+ "copy": "Hassas verileri gizlenmiş günlükleri kopyala",
"clear": "Temizle",
"output": "Canlı çıktı",
"entryCount_one": "{{count}} kayıt",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 39a54a7e..b1c2a382 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -1572,7 +1572,7 @@
"lead": "Додавайте невеликі можливості до Motrix. Залишайте довірені плагіни, решту вимикайте.",
"logs": {
"clear": "Очистити",
- "copy": "Копіювати",
+ "copy": "Копіювати журнали з прихованими даними",
"empty": "У журналі ще немає записів",
"emptyFiltered": "Немає записів цього рівня.",
"emptyHint": "Нова активність плагіна з'являтиметься тут автоматично.",
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index 86762147..55933325 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -2428,7 +2428,7 @@
"error": "Lỗi",
"fatal": "Lỗi nghiêm trọng"
},
- "copy": "Sao chép",
+ "copy": "Sao chép nhật ký đã che dữ liệu",
"clear": "Xóa",
"output": "Đầu ra trực tiếp",
"entryCount_other": "{{count}} mục",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index fb399117..ffbb1d07 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -2428,7 +2428,7 @@
"error": "错误",
"fatal": "严重"
},
- "copy": "复制",
+ "copy": "复制脱敏日志",
"clear": "清空",
"output": "实时输出",
"entryCount_other": "{{count}} 条日志",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 98093dee..c57ec6a6 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -2528,7 +2528,7 @@
"error": "錯誤",
"fatal": "嚴重錯誤"
},
- "copy": "複製",
+ "copy": "複製已遮蔽的日誌",
"clear": "清除",
"output": "即時輸出",
"entryCount_other": "{{count}} 筆項目",
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index 59a65809..53c2197a 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -33,6 +33,7 @@ export const Queries = {
ListPluginGrants: 'query:listPluginGrants',
GetPluginCommandGraph: 'query:getPluginCommandGraph',
GetPluginLogs: 'query:getPluginLogs',
+ GetPluginLogState: 'query:getPluginLogState',
// Remote plugin registry (dl.motrix.app) — read-side directory queries.
// Entries come back annotated with a `compatible` host-version flag.
// Contract: .claude/rules/plugin-registry.md.
diff --git a/src/shared/schemas/plugin-logs.ts b/src/shared/schemas/plugin-logs.ts
new file mode 100644
index 00000000..e12257f5
--- /dev/null
+++ b/src/shared/schemas/plugin-logs.ts
@@ -0,0 +1,15 @@
+import { z } from 'zod'
+
+export const PLUGIN_LOG_VERBOSE_TTL_MS = 60 * 60 * 1000
+
+export const PluginLogRequestSchema = z.object({
+ pluginId: z.string().min(1),
+})
+export const PluginLogVerboseRequestSchema = PluginLogRequestSchema.extend({
+ verbose: z.boolean(),
+})
+export const PluginLogStateSchema = z.object({
+ verbose: z.boolean(),
+ expiresAt: z.number().nullable(),
+})
+export type PluginLogState = z.infer<typeof PluginLogStateSchema>