LCOV - code coverage report
Current view: top level - packages/telemetry/src - redactTelemetryUrls.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 32.0 % 181 58
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /** Remove credentials, query strings, and fragments from URL-shaped text. */
       2        94253 : export function redactTelemetryUrls(text: string): string {
       3        94253 :   if (text.length > MAX_REDACTABLE_TEXT_LENGTH) return REDACTION_SENTINEL
       4        94253 :   return text
       5              :     .replace(SPACED_QUERY_URL_PATTERN, redactUrlToken)
       6              :     .replace(URL_TOKEN_PATTERN, redactUrlToken)
       7              : }
       8              : 
       9         2356 : const MAX_REDACTABLE_TEXT_LENGTH = 16_384
      10         2356 : const ABSOLUTE_URL_START = /(?:https?:)?\/\/[^\s"'<>?#]+/.source
      11              : /**
      12              :  * The root-relative alternative starts at a non-digit, or at a digit followed
      13              :  * by a second path character. That keeps `/v?token=…` and `/a/b?token=…`
      14              :  * redacted while leaving a bare fraction such as `1/2?x` as ordinary text, so
      15              :  * non-URL messages keep their Sentry grouping.
      16              :  */
      17         2356 : const ROOT_RELATIVE_URL_START =
      18              :   /(?<!\d)\/(?!\/|https?:\/\/)(?:[A-Za-z._~%-]|\d(?:[A-Za-z0-9._~%/-]|(?=[?#]))|(?=[?#]))[A-Za-z0-9._~%/-]*/
      19              :     .source
      20         2356 : const RELATIVE_URL_START =
      21              :   /(?<![A-Za-z0-9._~%/-])(?!\d+\/\d+[?#])[A-Za-z0-9_~%-]+(?:[./][A-Za-z0-9._~%-]+)*/
      22              :     .source
      23         2356 : const URL_START = `(?:${ABSOLUTE_URL_START}|${ROOT_RELATIVE_URL_START}|${RELATIVE_URL_START})`
      24         2356 : const SPACED_QUERY_URL_PATTERN = new RegExp(
      25              :   `${URL_START}\\?[^\\n"'<>]*\\s[^\\n"'<>]*&[A-Za-z0-9_~%-]+=[^\\n"'<>]*`,
      26              :   'gi'
      27              : )
      28              : 
      29         2356 : const URL_TOKEN_PATTERN = new RegExp(
      30              :   `(?:${ABSOLUTE_URL_START}|${ROOT_RELATIVE_URL_START})[^\\s"'<>]*|${RELATIVE_URL_START}(?:\\?[^\\s"'<>]*=[^\\s"'<>]*|#[^\\s"'<>]+)`,
      31              :   'gi'
      32              : )
      33              : 
      34        47100 : function redactUrlToken(token: string): string {
      35        47100 :   let redacted = ''
      36        47100 :   let tokenStart = 0
      37        47100 :   for (;;) {
      38        47100 :     const boundary = findGluedUrlBoundary(token, tokenStart)
      39        47100 :     if (!boundary) {
      40        47100 :       return redacted + redactSingleUrlToken(token.slice(tokenStart))
      41              :     }
      42            0 :     const { nextUrl, separator } = boundary
      43            0 :     redacted += redactSingleUrlToken(token.slice(tokenStart, separator))
      44            0 :     redacted += token.slice(separator, nextUrl)
      45            0 :     tokenStart = nextUrl
      46              :   }
      47              : }
      48              : 
      49        47100 : function redactSingleUrlToken(token: string): string {
      50        47100 :   const { core, trailing } = peelTrailingPunctuation(token)
      51        47100 :   const stackSuffix = core.match(/:\d+:\d+$/)?.[0] ?? ''
      52              :   const url = stackSuffix ? core.slice(0, -stackSuffix.length) : core
      53        47100 :   const clean = url.split(/[?#]/, 1)[0]
      54        47100 :   const absolute = clean.match(/^((?:https?:)?\/\/)([^/]*)(.*)$/i)
      55        47100 :   if (!absolute) return `${clean}${stackSuffix}${trailing}`
      56              : 
      57            0 :   const [, prefix, authority, path] = absolute
      58            0 :   const userInfoEnd = authority.lastIndexOf('@')
      59            0 :   return `${prefix}${authority.slice(userInfoEnd + 1)}${path}${stackSuffix}${trailing}`
      60              : }
      61              : 
      62        47100 : function findGluedUrlBoundary(
      63              :   token: string,
      64              :   tokenStart: number
      65              : ): { separator: number; nextUrl: number } | undefined {
      66        47100 :   const urlStartPattern = /(?:https?:)?\/\//g
      67        47100 :   urlStartPattern.lastIndex = tokenStart + 1
      68        47100 :   for (const match of token.matchAll(urlStartPattern)) {
      69            0 :     const nextUrl = match.index
      70            0 :     let separator = nextUrl
      71            0 :     while (separator > 0 && /[[\](){};,]/.test(token[separator - 1])) {
      72            0 :       separator--
      73              :     }
      74            0 :     if (separator < nextUrl || token[nextUrl - 1] === '/') {
      75            0 :       return {
      76              :         separator: token[nextUrl - 1] === '/' ? nextUrl - 1 : separator,
      77              :         nextUrl
      78              :       }
      79              :     }
      80              :   }
      81              : }
      82              : 
      83        47100 : function peelTrailingPunctuation(token: string): {
      84              :   core: string
      85              :   trailing: string
      86              : } {
      87        47100 :   let trailing = ''
      88        47100 :   const separatorSuffix = token.match(/[,;]+$/)?.[0] ?? ''
      89        47100 :   if (separatorSuffix) {
      90            0 :     trailing = separatorSuffix
      91            0 :     token = token.slice(0, -separatorSuffix.length)
      92              :   }
      93        47100 :   const bracketSuffix = token.match(/[)\]]+$/)?.[0] ?? ''
      94        47100 :   if (bracketSuffix) {
      95            0 :     const peelCount = countExcessClosingBrackets(token, bracketSuffix)
      96            0 :     if (peelCount) {
      97            0 :       trailing = token.slice(-peelCount) + trailing
      98            0 :       token = token.slice(0, -peelCount)
      99              :     }
     100              :   }
     101        47100 :   return { core: token, trailing }
     102              : }
     103              : 
     104            0 : function countExcessClosingBrackets(token: string, suffix: string): number {
     105            0 :   const counts = {
     106              :     parens: countCharacter(token, ')') - countCharacter(token, '('),
     107              :     brackets: countCharacter(token, ']') - countCharacter(token, '[')
     108              :   }
     109            0 :   let count = 0
     110            0 :   for (let index = suffix.length - 1; index >= 0; index--) {
     111            0 :     if (!consumeExcessClosingBracket(suffix[index], counts)) break
     112            0 :     count++
     113              :   }
     114            0 :   return count
     115              : }
     116              : 
     117            0 : function countCharacter(text: string, target: string): number {
     118            0 :   let count = 0
     119            0 :   for (const character of text) {
     120            0 :     if (character === target) count++
     121              :   }
     122            0 :   return count
     123              : }
     124              : 
     125            0 : function consumeExcessClosingBracket(
     126              :   bracket: string,
     127              :   counts: { parens: number; brackets: number }
     128              : ): boolean {
     129            0 :   if (bracket === ')' && counts.parens > 0) {
     130            0 :     counts.parens--
     131            0 :     return true
     132              :   }
     133            0 :   if (bracket === ']' && counts.brackets > 0) {
     134            0 :     counts.brackets--
     135            0 :     return true
     136              :   }
     137            0 :   return false
     138              : }
     139              : 
     140         2356 : export const REDACTION_SENTINEL = '[Redacted]'
     141         2356 : const MAX_REDACTION_DEPTH = 32
     142         2356 : const MAX_REDACTION_NODES = 1_000
     143              : 
     144              : /**
     145              :  * Copy a telemetry payload with URL metadata removed from every reachable
     146              :  * string.
     147              :  *
     148              :  * Only plain records, arrays, `Error`s, `URL`s and primitives survive the copy.
     149              :  * Every other object — `Date`, `Map`, `Request`, class instances — becomes
     150              :  * `[Redacted]`, because inspecting it safely is not possible for an arbitrary
     151              :  * accessor. Accessor properties are dropped rather than invoked for the same
     152              :  * reason. Traversal is bounded by depth and node count, and anything past
     153              :  * either bound also becomes `[Redacted]`.
     154              :  */
     155        47153 : export function redactTelemetryValues(
     156              :   values: Record<string, unknown> | undefined
     157              : ): Record<string, unknown> | undefined {
     158        47153 :   if (!values) return values
     159        47100 :   return redactPlainObject(
     160              :     values,
     161              :     {
     162              :       ancestors: new WeakSet<object>(),
     163              :       memo: new WeakMap<object, unknown>(),
     164              :       nodesRemaining: MAX_REDACTION_NODES
     165              :     },
     166              :     0
     167              :   )
     168              : }
     169              : 
     170            0 : export function redactTelemetryError(error: unknown): Error {
     171            0 :   let source: Error
     172            0 :   if (error instanceof Error) {
     173            0 :     source = error
     174              :   } else {
     175            0 :     try {
     176            0 :       source = new Error(String(error))
     177              :     } catch {
     178            0 :       source = new Error('[Redacted]')
     179              :     }
     180              :   }
     181            0 :   return redactError(
     182              :     source,
     183              :     {
     184              :       ancestors: new WeakSet<object>(),
     185              :       memo: new WeakMap<object, unknown>(),
     186              :       nodesRemaining: MAX_REDACTION_NODES
     187              :     },
     188              :     0
     189              :   )
     190              : }
     191              : 
     192              : interface RedactionContext {
     193              :   ancestors: WeakSet<object>
     194              :   memo: WeakMap<object, unknown>
     195              :   nodesRemaining: number
     196              : }
     197              : 
     198        47100 : function redactValue(
     199              :   value: unknown,
     200              :   context: RedactionContext,
     201              :   depth = 0
     202              : ): unknown {
     203        47100 :   if (typeof value === 'string') return redactTelemetryUrls(value)
     204        47100 :   if (typeof value === 'function') return REDACTION_SENTINEL
     205        47100 :   if (typeof value !== 'object' || value === null) return value
     206            0 :   const guarded = guardedRedactionValue(value, context, depth)
     207            0 :   if (guarded) return guarded.value
     208            0 :   return redactClassifiedValue(classifyObject(value), value, context, depth)
     209              : }
     210              : 
     211            0 : function redactClassifiedValue(
     212              :   classification: ObjectClassification,
     213              :   value: object,
     214              :   context: RedactionContext,
     215              :   depth: number
     216              : ): unknown {
     217            0 :   switch (classification.kind) {
     218              :     case 'error':
     219            0 :       return redactError(classification.value, context, depth)
     220              :     case 'array':
     221            0 :       return redactArray(classification.value, context, depth)
     222              :     case 'url':
     223            0 :       return redactTelemetryUrls(classification.value.href)
     224              :     case 'plain':
     225            0 :       return redactPlainObject(value, context, depth)
     226              :     case 'other':
     227              :     case 'unsafe':
     228            0 :       return REDACTION_SENTINEL
     229              :   }
     230              : }
     231              : 
     232            0 : function guardedRedactionValue(
     233              :   value: object,
     234              :   context: RedactionContext,
     235              :   depth: number
     236              : ): { value: unknown } | undefined {
     237            0 :   if (context.ancestors.has(value)) return { value: '[Circular]' }
     238            0 :   if (context.memo.has(value)) return { value: context.memo.get(value) }
     239            0 :   if (depth >= MAX_REDACTION_DEPTH || context.nodesRemaining-- <= 0) {
     240            0 :     return { value: REDACTION_SENTINEL }
     241              :   }
     242              : }
     243              : 
     244            0 : function redactArray(
     245              :   value: unknown[],
     246              :   context: RedactionContext,
     247              :   depth: number
     248              : ): unknown[] {
     249            0 :   const output: unknown[] = []
     250            0 :   output.length = value.length
     251            0 :   context.memo.set(value, output)
     252            0 :   context.ancestors.add(value)
     253            0 :   try {
     254            0 :     const entries = ownDataEntries(value)
     255            0 :     if (!entries) return [REDACTION_SENTINEL]
     256            0 :     for (const [key, nested] of entries) {
     257            0 :       if (!isArrayIndex(key, value.length)) continue
     258            0 :       output[Number(key)] = redactValue(nested, context, depth + 1)
     259              :     }
     260            0 :     return output
     261              :   } finally {
     262            0 :     context.ancestors.delete(value)
     263              :   }
     264              : }
     265              : 
     266            0 : function isArrayIndex(key: string, length: number): boolean {
     267            0 :   const index = Number(key)
     268            0 :   return (
     269              :     Number.isInteger(index) &&
     270              :     index >= 0 &&
     271              :     index < length &&
     272              :     `${index}` === key
     273              :   )
     274              : }
     275              : 
     276        47100 : function redactPlainObject(
     277              :   value: object,
     278              :   context: RedactionContext,
     279              :   depth: number
     280              : ): Record<string, unknown> {
     281        47100 :   const entries = ownDataEntries(value)
     282        47100 :   if (!entries) return { redaction: REDACTION_SENTINEL }
     283        47100 :   const output: Record<string, unknown> = Object.create(null)
     284        47100 :   context.memo.set(value, output)
     285        47100 :   context.ancestors.add(value)
     286        47100 :   try {
     287        47100 :     for (const [key, nested] of entries) {
     288        47100 :       Object.defineProperty(output, redactTelemetryUrls(key), {
     289              :         configurable: true,
     290              :         enumerable: true,
     291              :         value: redactValue(nested, context, depth + 1),
     292              :         writable: true
     293              :       })
     294              :     }
     295        47100 :     return output
     296              :   } finally {
     297        47100 :     context.ancestors.delete(value)
     298              :   }
     299              : }
     300              : 
     301              : type ObjectClassification =
     302              :   | { kind: 'error'; value: Error }
     303              :   | { kind: 'array'; value: unknown[] }
     304              :   | { kind: 'url'; value: URL }
     305              :   | { kind: 'plain' | 'other' | 'unsafe' }
     306              : 
     307            0 : function classifyObject(value: object): ObjectClassification {
     308            0 :   try {
     309            0 :     if (value instanceof Error) return { kind: 'error', value }
     310            0 :     if (value instanceof URL) return { kind: 'url', value }
     311            0 :     if (Array.isArray(value)) return { kind: 'array', value }
     312            0 :     const prototype = Object.getPrototypeOf(value)
     313            0 :     return prototype === Object.prototype || prototype === null
     314              :       ? { kind: 'plain' }
     315              :       : { kind: 'other' }
     316              :   } catch {
     317            0 :     return { kind: 'unsafe' }
     318              :   }
     319              : }
     320              : 
     321        47100 : function ownDataEntries(value: object): [string, unknown][] | null {
     322        47100 :   try {
     323        47100 :     return Object.entries(Object.getOwnPropertyDescriptors(value))
     324              :       .filter(
     325              :         ([, descriptor]) => descriptor.enumerable && 'value' in descriptor
     326              :       )
     327              :       .map(([key, descriptor]) => [key, descriptor.value])
     328              :   } catch {
     329            0 :     return null
     330              :   }
     331              : }
     332              : 
     333            0 : function redactError(
     334              :   source: Error,
     335              :   context: RedactionContext,
     336              :   depth: number
     337              : ): Error {
     338            0 :   const properties = ownDataProperties(source)
     339            0 :   if (!properties) return new Error(REDACTION_SENTINEL)
     340            0 :   const message = readErrorString(source, properties, 'message')
     341            0 :   const redactedMessage =
     342              :     message === undefined ? '' : redactTelemetryUrls(message)
     343            0 :   const output = new Error(redactedMessage)
     344            0 :   context.memo.set(source, output)
     345            0 :   context.ancestors.add(source)
     346            0 :   try {
     347            0 :     if ('cause' in properties) {
     348            0 :       output.cause = redactValue(properties.cause, context, depth + 1)
     349              :     }
     350            0 :     const name = readErrorString(source, properties, 'name')
     351            0 :     if (name !== undefined) {
     352            0 :       output.name = redactTelemetryUrls(name)
     353              :     }
     354            0 :     const stack = readErrorString(source, properties, 'stack')
     355            0 :     if (stack !== undefined) {
     356            0 :       output.stack = redactTelemetryUrls(stack)
     357              :     }
     358            0 :     return output
     359              :   } finally {
     360            0 :     context.ancestors.delete(source)
     361              :   }
     362              : }
     363              : 
     364            0 : function readErrorString(
     365              :   source: Error,
     366              :   properties: Record<string, unknown>,
     367              :   key: 'message' | 'name' | 'stack'
     368              : ): string | undefined {
     369            0 :   if (typeof properties[key] === 'string') return properties[key]
     370            0 :   try {
     371            0 :     const ownDescriptor = Object.getOwnPropertyDescriptor(source, key)
     372            0 :     if (ownDescriptor && !('value' in ownDescriptor)) return REDACTION_SENTINEL
     373            0 :     let prototype = Object.getPrototypeOf(source)
     374            0 :     while (prototype) {
     375            0 :       const descriptor = Object.getOwnPropertyDescriptor(prototype, key)
     376            0 :       if (descriptor) {
     377            0 :         return 'value' in descriptor && typeof descriptor.value === 'string'
     378              :           ? descriptor.value
     379              :           : REDACTION_SENTINEL
     380              :       }
     381            0 :       prototype = Object.getPrototypeOf(prototype)
     382              :     }
     383            0 :     return undefined
     384              :   } catch {
     385            0 :     return undefined
     386              :   }
     387              : }
     388              : 
     389            0 : function ownDataProperties(value: object): Record<string, unknown> | null {
     390            0 :   try {
     391            0 :     return Object.fromEntries(
     392              :       Object.entries(Object.getOwnPropertyDescriptors(value))
     393              :         .filter(([, descriptor]) => 'value' in descriptor)
     394              :         .map(([key, descriptor]) => [key, descriptor.value])
     395              :     )
     396              :   } catch {
     397            0 :     return null
     398              :   }
     399              : }
        

Generated by: LCOV version 2.0-1