@logtape/redaction 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/field.cjs CHANGED
@@ -95,11 +95,25 @@ function redactProperties(properties, options) {
95
95
  continue;
96
96
  }
97
97
  const value = copy[field];
98
- if (typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) copy[field] = redactProperties(value, options);
98
+ if (Array.isArray(value)) copy[field] = redactArray(value, options);
99
+ else if (typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) copy[field] = redactProperties(value, options);
99
100
  }
100
101
  return copy;
101
102
  }
102
103
  /**
104
+ * Redacts sensitive fields in an array recursively.
105
+ * @param array The array to process.
106
+ * @param options The redaction options.
107
+ * @returns A new array with redacted values.
108
+ */
109
+ function redactArray(array, options) {
110
+ return array.map((item) => {
111
+ if (Array.isArray(item)) return redactArray(item, options);
112
+ if (typeof item === "object" && item !== null && (Object.getPrototypeOf(item) === Object.prototype || Object.getPrototypeOf(item) === null)) return redactProperties(item, options);
113
+ return item;
114
+ });
115
+ }
116
+ /**
103
117
  * Checks if a field should be redacted based on the provided field patterns.
104
118
  * @param field The field name to check.
105
119
  * @param fieldPatterns The field patterns to match against.
package/dist/field.js CHANGED
@@ -94,11 +94,25 @@ function redactProperties(properties, options) {
94
94
  continue;
95
95
  }
96
96
  const value = copy[field];
97
- if (typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) copy[field] = redactProperties(value, options);
97
+ if (Array.isArray(value)) copy[field] = redactArray(value, options);
98
+ else if (typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) copy[field] = redactProperties(value, options);
98
99
  }
99
100
  return copy;
100
101
  }
101
102
  /**
103
+ * Redacts sensitive fields in an array recursively.
104
+ * @param array The array to process.
105
+ * @param options The redaction options.
106
+ * @returns A new array with redacted values.
107
+ */
108
+ function redactArray(array, options) {
109
+ return array.map((item) => {
110
+ if (Array.isArray(item)) return redactArray(item, options);
111
+ if (typeof item === "object" && item !== null && (Object.getPrototypeOf(item) === Object.prototype || Object.getPrototypeOf(item) === null)) return redactProperties(item, options);
112
+ return item;
113
+ });
114
+ }
115
+ /**
102
116
  * Checks if a field should be redacted based on the provided field patterns.
103
117
  * @param field The field name to check.
104
118
  * @param fieldPatterns The field patterns to match against.
package/dist/field.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"field.js","names":["DEFAULT_REDACT_FIELDS: FieldPatterns","sink: Sink | Sink & Disposable | Sink & AsyncDisposable","options: FieldRedactionOptions | FieldPatterns","record: LogRecord","properties: Record<string, unknown>","options: FieldRedactionOptions","field: string","fieldPatterns: FieldPatterns","template: string","placeholders: string[]","path: string","segments: string[]","message: readonly unknown[]","redactedIndices: Set<number>","wildcardIndices: Set<number>","redactedProperties: Record<string, unknown>","action: \"delete\" | ((value: unknown) => unknown) | undefined","result: unknown[]","original: Record<string, unknown>","redacted: Record<string, unknown>","map: Map<unknown, unknown>","redactedValues: Map<unknown, unknown>"],"sources":["../src/field.ts"],"sourcesContent":["import type { LogRecord, Sink } from \"@logtape/logtape\";\n\n/**\n * The type for a field pattern used in redaction. A string or a regular\n * expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPattern = string | RegExp;\n\n/**\n * An array of field patterns used for redaction. Each pattern can be\n * a string or a regular expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPatterns = FieldPattern[];\n\n/**\n * Default field patterns for redaction. These patterns will match\n * common sensitive fields such as passwords, tokens, and personal\n * information.\n * @since 0.10.0\n */\nexport const DEFAULT_REDACT_FIELDS: FieldPatterns = [\n /pass(?:code|phrase|word)/i,\n /secret/i,\n /token/i,\n /key/i,\n /credential/i,\n /auth/i,\n /signature/i,\n /sensitive/i,\n /private/i,\n /ssn/i,\n /email/i,\n /phone/i,\n /address/i,\n];\n\n/**\n * Options for redacting fields in a {@link LogRecord}. Used by\n * the {@link redactByField} function.\n * @since 0.10.0\n */\nexport interface FieldRedactionOptions {\n /**\n * The field patterns to match against. This can be an array of\n * strings or regular expressions. If a field matches any of the\n * patterns, it will be redacted.\n * @defaultValue {@link DEFAULT_REDACT_FIELDS}\n */\n readonly fieldPatterns: FieldPatterns;\n\n /**\n * The action to perform on the matched fields. If not provided,\n * the default action is to delete the field from the properties.\n * If a function is provided, it will be called with the\n * value of the field, and the return value will be used to replace\n * the field in the properties.\n * If the action is `\"delete\"`, the field will be removed from the\n * properties.\n * @default `\"delete\"`\n */\n readonly action?: \"delete\" | ((value: unknown) => unknown);\n}\n\n/**\n * Redacts properties and message values in a {@link LogRecord} based on the\n * provided field patterns and action.\n *\n * Note that it is a decorator which wraps the sink and redacts properties\n * and message values before passing them to the sink.\n *\n * For string templates (e.g., `\"Hello, {name}!\"`), placeholder names are\n * matched against the field patterns to determine which values to redact.\n *\n * For tagged template literals (e.g., `` `Hello, ${name}!` ``), redaction\n * is performed by comparing message values with redacted property values.\n *\n * @example\n * ```ts\n * import { getConsoleSink } from \"@logtape/logtape\";\n * import { redactByField } from \"@logtape/redaction\";\n *\n * const sink = redactByField(getConsoleSink());\n * ```\n *\n * @param sink The sink to wrap.\n * @param options The redaction options.\n * @returns The wrapped sink.\n * @since 0.10.0\n */\nexport function redactByField(\n sink: Sink | Sink & Disposable | Sink & AsyncDisposable,\n options: FieldRedactionOptions | FieldPatterns = DEFAULT_REDACT_FIELDS,\n): Sink | Sink & Disposable | Sink & AsyncDisposable {\n const opts = Array.isArray(options) ? { fieldPatterns: options } : options;\n const wrapped = (record: LogRecord) => {\n const redactedProperties = redactProperties(record.properties, opts);\n let redactedMessage = record.message;\n\n if (typeof record.rawMessage === \"string\") {\n // String template: redact by placeholder names\n const placeholders = extractPlaceholderNames(record.rawMessage);\n const { redactedIndices, wildcardIndices } =\n getRedactedPlaceholderIndices(\n placeholders,\n opts.fieldPatterns,\n );\n if (redactedIndices.size > 0 || wildcardIndices.size > 0) {\n redactedMessage = redactMessageArray(\n record.message,\n redactedIndices,\n wildcardIndices,\n redactedProperties,\n opts.action,\n );\n }\n } else {\n // Tagged template: redact by comparing values\n const redactedValues = getRedactedValues(\n record.properties,\n redactedProperties,\n );\n if (redactedValues.size > 0) {\n redactedMessage = redactMessageByValues(record.message, redactedValues);\n }\n }\n\n sink({\n ...record,\n message: redactedMessage,\n properties: redactedProperties,\n });\n };\n if (Symbol.dispose in sink) wrapped[Symbol.dispose] = sink[Symbol.dispose];\n if (Symbol.asyncDispose in sink) {\n wrapped[Symbol.asyncDispose] = sink[Symbol.asyncDispose];\n }\n return wrapped;\n}\n\n/**\n * Redacts properties from an object based on specified field patterns.\n *\n * This function creates a shallow copy of the input object and applies\n * redaction rules to its properties. For properties that match the redaction\n * patterns, the function either removes them or transforms their values based\n * on the provided action.\n *\n * The redaction process is recursive and will be applied to nested objects\n * as well, allowing for deep redaction of sensitive data in complex object\n * structures.\n * @param properties The properties to redact.\n * @param options The redaction options.\n * @returns The redacted properties.\n * @since 0.10.0\n */\nexport function redactProperties(\n properties: Record<string, unknown>,\n options: FieldRedactionOptions,\n): Record<string, unknown> {\n const copy = { ...properties };\n for (const field in copy) {\n if (shouldFieldRedacted(field, options.fieldPatterns)) {\n if (options.action == null || options.action === \"delete\") {\n delete copy[field];\n } else {\n copy[field] = options.action(copy[field]);\n }\n continue;\n }\n const value = copy[field];\n // Check if value is a vanilla object:\n if (\n typeof value === \"object\" && value !== null &&\n (Object.getPrototypeOf(value) === Object.prototype ||\n Object.getPrototypeOf(value) === null)\n ) {\n // @ts-ignore: value is always Record<string, unknown>\n copy[field] = redactProperties(value, options);\n }\n }\n return copy;\n}\n\n/**\n * Checks if a field should be redacted based on the provided field patterns.\n * @param field The field name to check.\n * @param fieldPatterns The field patterns to match against.\n * @returns `true` if the field should be redacted, `false` otherwise.\n * @since 0.10.0\n */\nexport function shouldFieldRedacted(\n field: string,\n fieldPatterns: FieldPatterns,\n): boolean {\n for (const fieldPattern of fieldPatterns) {\n if (typeof fieldPattern === \"string\") {\n if (fieldPattern === field) return true;\n } else {\n if (fieldPattern.test(field)) return true;\n }\n }\n return false;\n}\n\n/**\n * Extracts placeholder names from a message template string in order.\n * @param template The message template string.\n * @returns An array of placeholder names in the order they appear.\n */\nfunction extractPlaceholderNames(template: string): string[] {\n const placeholders: string[] = [];\n for (let i = 0; i < template.length; i++) {\n if (template[i] === \"{\") {\n // Check for escaped brace\n if (i + 1 < template.length && template[i + 1] === \"{\") {\n i++;\n continue;\n }\n const closeIndex = template.indexOf(\"}\", i + 1);\n if (closeIndex === -1) continue;\n const key = template.slice(i + 1, closeIndex).trim();\n placeholders.push(key);\n i = closeIndex;\n }\n }\n return placeholders;\n}\n\n/**\n * Parses a property path into its segments.\n * @param path The property path (e.g., \"user.password\" or \"users[0].email\").\n * @returns An array of path segments.\n */\nfunction parsePathSegments(path: string): string[] {\n const segments: string[] = [];\n let current = \"\";\n for (const char of path) {\n if (char === \".\" || char === \"[\") {\n if (current) segments.push(current);\n current = \"\";\n } else if (char === \"]\" || char === \"?\") {\n // Skip these characters\n } else {\n current += char;\n }\n }\n if (current) segments.push(current);\n return segments;\n}\n\n/**\n * Determines which placeholder indices should be redacted based on field\n * patterns, and which are wildcard placeholders.\n * @param placeholders Array of placeholder names from the template.\n * @param fieldPatterns Field patterns to match against.\n * @returns Object with redactedIndices and wildcardIndices.\n */\nfunction getRedactedPlaceholderIndices(\n placeholders: string[],\n fieldPatterns: FieldPatterns,\n): { redactedIndices: Set<number>; wildcardIndices: Set<number> } {\n const redactedIndices = new Set<number>();\n const wildcardIndices = new Set<number>();\n\n for (let i = 0; i < placeholders.length; i++) {\n const placeholder = placeholders[i];\n\n // Track wildcard {*} separately\n if (placeholder === \"*\") {\n wildcardIndices.add(i);\n continue;\n }\n\n // Check the full placeholder name\n if (shouldFieldRedacted(placeholder, fieldPatterns)) {\n redactedIndices.add(i);\n continue;\n }\n // For nested paths, check each segment\n const segments = parsePathSegments(placeholder);\n for (const segment of segments) {\n if (shouldFieldRedacted(segment, fieldPatterns)) {\n redactedIndices.add(i);\n break;\n }\n }\n }\n return { redactedIndices, wildcardIndices };\n}\n\n/**\n * Redacts values in the message array based on the redacted placeholder\n * indices and wildcard indices.\n * @param message The original message array.\n * @param redactedIndices Set of placeholder indices to redact.\n * @param wildcardIndices Set of wildcard placeholder indices.\n * @param redactedProperties The redacted properties object.\n * @param action The redaction action.\n * @returns New message array with redacted values.\n */\nfunction redactMessageArray(\n message: readonly unknown[],\n redactedIndices: Set<number>,\n wildcardIndices: Set<number>,\n redactedProperties: Record<string, unknown>,\n action: \"delete\" | ((value: unknown) => unknown) | undefined,\n): readonly unknown[] {\n if (redactedIndices.size === 0 && wildcardIndices.size === 0) return message;\n\n const result: unknown[] = [];\n let placeholderIndex = 0;\n\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n // Even index: text segment\n result.push(message[i]);\n } else {\n // Odd index: value/placeholder\n if (wildcardIndices.has(placeholderIndex)) {\n // Wildcard {*}: replace with redacted properties\n result.push(redactedProperties);\n } else if (redactedIndices.has(placeholderIndex)) {\n if (action == null || action === \"delete\") {\n result.push(\"\");\n } else {\n result.push(action(message[i]));\n }\n } else {\n result.push(message[i]);\n }\n placeholderIndex++;\n }\n }\n return result;\n}\n\n/**\n * Collects redacted value mappings from original to redacted properties.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @param map The map to populate with original -> redacted value pairs.\n */\nfunction collectRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n map: Map<unknown, unknown>,\n): void {\n for (const key in original) {\n const origVal = original[key];\n const redVal = redacted[key];\n\n if (origVal !== redVal) {\n map.set(origVal, redVal);\n }\n\n // Recurse into nested objects\n if (\n typeof origVal === \"object\" && origVal !== null &&\n typeof redVal === \"object\" && redVal !== null &&\n !Array.isArray(origVal)\n ) {\n collectRedactedValues(\n origVal as Record<string, unknown>,\n redVal as Record<string, unknown>,\n map,\n );\n }\n }\n}\n\n/**\n * Gets a map of original values to their redacted replacements.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @returns A map of original -> redacted values.\n */\nfunction getRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n): Map<unknown, unknown> {\n const map = new Map<unknown, unknown>();\n collectRedactedValues(original, redacted, map);\n return map;\n}\n\n/**\n * Redacts message array values by comparing with redacted property values.\n * Used for tagged template literals where placeholder names are not available.\n * @param message The original message array.\n * @param redactedValues Map of original -> redacted values.\n * @returns New message array with redacted values.\n */\nfunction redactMessageByValues(\n message: readonly unknown[],\n redactedValues: Map<unknown, unknown>,\n): readonly unknown[] {\n if (redactedValues.size === 0) return message;\n\n const result: unknown[] = [];\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n result.push(message[i]);\n } else {\n const val = message[i];\n if (redactedValues.has(val)) {\n result.push(redactedValues.get(val));\n } else {\n result.push(val);\n }\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;AAsBA,MAAaA,wBAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDD,SAAgB,cACdC,MACAC,UAAiD,uBACE;CACnD,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAAG,EAAE,eAAe,QAAS,IAAG;CACnE,MAAM,UAAU,CAACC,WAAsB;EACrC,MAAM,qBAAqB,iBAAiB,OAAO,YAAY,KAAK;EACpE,IAAI,kBAAkB,OAAO;AAE7B,aAAW,OAAO,eAAe,UAAU;GAEzC,MAAM,eAAe,wBAAwB,OAAO,WAAW;GAC/D,MAAM,EAAE,iBAAiB,iBAAiB,GACxC,8BACE,cACA,KAAK,cACN;AACH,OAAI,gBAAgB,OAAO,KAAK,gBAAgB,OAAO,EACrD,mBAAkB,mBAChB,OAAO,SACP,iBACA,iBACA,oBACA,KAAK,OACN;EAEJ,OAAM;G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AI,gBAAgB,IAAI,iBAAiB,CAEvC,QAAO,KAAK,mBAAmB;WACtB,gBAAgB,IAAI,iBAAiB,CAC9C,KAAI,UAAU,QAAQ,WAAW,SAC/B,QAAO,KAAK,GAAG;MAEf,QAAO,KAAK,OAAO,QAAQ,GAAG,CAAC;MAGjC,QAAO,KAAK,QAAQ,GAAG;AAEzB;CACD;AAEH,QAAO;AACR;;;;;;;AAQD,SAAS,sBACPC,UACAC,UACAC,KACM;AACN,MAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,UAAU,SAAS;EACzB,MAAM,SAAS,SAAS;AAExB,MAAI,YAAY,OACd,KAAI,IAAI,SAAS,OAAO;AAI1B,aACS,YAAY,YAAY,YAAY,eACpC,WAAW,YAAY,WAAW,SACxC,MAAM,QAAQ,QAAQ,CAEvB,uBACE,SACA,QACA,IACD;CAEJ;AACF;;;;;;;AAQD,SAAS,kBACPF,UACAC,UACuB;CACvB,MAAM,sBAAM,IAAI;AAChB,uBAAsB,UAAU,UAAU,IAAI;AAC9C,QAAO;AACR;;;;;;;;AASD,SAAS,sBACPP,SACAS,gBACoB;AACpB,KAAI,eAAe,SAAS,EAAG,QAAO;CAEtC,MAAMJ,SAAoB,CAAE;AAC5B,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,IAClC,KAAI,IAAI,MAAM,EACZ,QAAO,KAAK,QAAQ,GAAG;MAClB;EACL,MAAM,MAAM,QAAQ;AACpB,MAAI,eAAe,IAAI,IAAI,CACzB,QAAO,KAAK,eAAe,IAAI,IAAI,CAAC;MAEpC,QAAO,KAAK,IAAI;CAEnB;AAEH,QAAO;AACR"}
1
+ {"version":3,"file":"field.js","names":["DEFAULT_REDACT_FIELDS: FieldPatterns","sink: Sink | Sink & Disposable | Sink & AsyncDisposable","options: FieldRedactionOptions | FieldPatterns","record: LogRecord","properties: Record<string, unknown>","options: FieldRedactionOptions","array: unknown[]","field: string","fieldPatterns: FieldPatterns","template: string","placeholders: string[]","path: string","segments: string[]","message: readonly unknown[]","redactedIndices: Set<number>","wildcardIndices: Set<number>","redactedProperties: Record<string, unknown>","action: \"delete\" | ((value: unknown) => unknown) | undefined","result: unknown[]","original: Record<string, unknown>","redacted: Record<string, unknown>","map: Map<unknown, unknown>","redactedValues: Map<unknown, unknown>"],"sources":["../src/field.ts"],"sourcesContent":["import type { LogRecord, Sink } from \"@logtape/logtape\";\n\n/**\n * The type for a field pattern used in redaction. A string or a regular\n * expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPattern = string | RegExp;\n\n/**\n * An array of field patterns used for redaction. Each pattern can be\n * a string or a regular expression that matches field names.\n * @since 0.10.0\n */\nexport type FieldPatterns = FieldPattern[];\n\n/**\n * Default field patterns for redaction. These patterns will match\n * common sensitive fields such as passwords, tokens, and personal\n * information.\n * @since 0.10.0\n */\nexport const DEFAULT_REDACT_FIELDS: FieldPatterns = [\n /pass(?:code|phrase|word)/i,\n /secret/i,\n /token/i,\n /key/i,\n /credential/i,\n /auth/i,\n /signature/i,\n /sensitive/i,\n /private/i,\n /ssn/i,\n /email/i,\n /phone/i,\n /address/i,\n];\n\n/**\n * Options for redacting fields in a {@link LogRecord}. Used by\n * the {@link redactByField} function.\n * @since 0.10.0\n */\nexport interface FieldRedactionOptions {\n /**\n * The field patterns to match against. This can be an array of\n * strings or regular expressions. If a field matches any of the\n * patterns, it will be redacted.\n * @defaultValue {@link DEFAULT_REDACT_FIELDS}\n */\n readonly fieldPatterns: FieldPatterns;\n\n /**\n * The action to perform on the matched fields. If not provided,\n * the default action is to delete the field from the properties.\n * If a function is provided, it will be called with the\n * value of the field, and the return value will be used to replace\n * the field in the properties.\n * If the action is `\"delete\"`, the field will be removed from the\n * properties.\n * @default `\"delete\"`\n */\n readonly action?: \"delete\" | ((value: unknown) => unknown);\n}\n\n/**\n * Redacts properties and message values in a {@link LogRecord} based on the\n * provided field patterns and action.\n *\n * Note that it is a decorator which wraps the sink and redacts properties\n * and message values before passing them to the sink.\n *\n * For string templates (e.g., `\"Hello, {name}!\"`), placeholder names are\n * matched against the field patterns to determine which values to redact.\n *\n * For tagged template literals (e.g., `` `Hello, ${name}!` ``), redaction\n * is performed by comparing message values with redacted property values.\n *\n * @example\n * ```ts\n * import { getConsoleSink } from \"@logtape/logtape\";\n * import { redactByField } from \"@logtape/redaction\";\n *\n * const sink = redactByField(getConsoleSink());\n * ```\n *\n * @param sink The sink to wrap.\n * @param options The redaction options.\n * @returns The wrapped sink.\n * @since 0.10.0\n */\nexport function redactByField(\n sink: Sink | Sink & Disposable | Sink & AsyncDisposable,\n options: FieldRedactionOptions | FieldPatterns = DEFAULT_REDACT_FIELDS,\n): Sink | Sink & Disposable | Sink & AsyncDisposable {\n const opts = Array.isArray(options) ? { fieldPatterns: options } : options;\n const wrapped = (record: LogRecord) => {\n const redactedProperties = redactProperties(record.properties, opts);\n let redactedMessage = record.message;\n\n if (typeof record.rawMessage === \"string\") {\n // String template: redact by placeholder names\n const placeholders = extractPlaceholderNames(record.rawMessage);\n const { redactedIndices, wildcardIndices } =\n getRedactedPlaceholderIndices(\n placeholders,\n opts.fieldPatterns,\n );\n if (redactedIndices.size > 0 || wildcardIndices.size > 0) {\n redactedMessage = redactMessageArray(\n record.message,\n redactedIndices,\n wildcardIndices,\n redactedProperties,\n opts.action,\n );\n }\n } else {\n // Tagged template: redact by comparing values\n const redactedValues = getRedactedValues(\n record.properties,\n redactedProperties,\n );\n if (redactedValues.size > 0) {\n redactedMessage = redactMessageByValues(record.message, redactedValues);\n }\n }\n\n sink({\n ...record,\n message: redactedMessage,\n properties: redactedProperties,\n });\n };\n if (Symbol.dispose in sink) wrapped[Symbol.dispose] = sink[Symbol.dispose];\n if (Symbol.asyncDispose in sink) {\n wrapped[Symbol.asyncDispose] = sink[Symbol.asyncDispose];\n }\n return wrapped;\n}\n\n/**\n * Redacts properties from an object based on specified field patterns.\n *\n * This function creates a shallow copy of the input object and applies\n * redaction rules to its properties. For properties that match the redaction\n * patterns, the function either removes them or transforms their values based\n * on the provided action.\n *\n * The redaction process is recursive and will be applied to nested objects\n * as well, allowing for deep redaction of sensitive data in complex object\n * structures.\n * @param properties The properties to redact.\n * @param options The redaction options.\n * @returns The redacted properties.\n * @since 0.10.0\n */\nexport function redactProperties(\n properties: Record<string, unknown>,\n options: FieldRedactionOptions,\n): Record<string, unknown> {\n const copy = { ...properties };\n for (const field in copy) {\n if (shouldFieldRedacted(field, options.fieldPatterns)) {\n if (options.action == null || options.action === \"delete\") {\n delete copy[field];\n } else {\n copy[field] = options.action(copy[field]);\n }\n continue;\n }\n const value = copy[field];\n // Check if value is an array:\n if (Array.isArray(value)) {\n copy[field] = redactArray(value, options);\n } // Check if value is a vanilla object:\n else if (\n typeof value === \"object\" && value !== null &&\n (Object.getPrototypeOf(value) === Object.prototype ||\n Object.getPrototypeOf(value) === null)\n ) {\n // @ts-ignore: value is always Record<string, unknown>\n copy[field] = redactProperties(value, options);\n }\n }\n return copy;\n}\n\n/**\n * Redacts sensitive fields in an array recursively.\n * @param array The array to process.\n * @param options The redaction options.\n * @returns A new array with redacted values.\n */\nfunction redactArray(\n array: unknown[],\n options: FieldRedactionOptions,\n): unknown[] {\n return array.map((item) => {\n if (Array.isArray(item)) {\n return redactArray(item, options);\n }\n if (\n typeof item === \"object\" && item !== null &&\n (Object.getPrototypeOf(item) === Object.prototype ||\n Object.getPrototypeOf(item) === null)\n ) {\n return redactProperties(item as Record<string, unknown>, options);\n }\n return item;\n });\n}\n\n/**\n * Checks if a field should be redacted based on the provided field patterns.\n * @param field The field name to check.\n * @param fieldPatterns The field patterns to match against.\n * @returns `true` if the field should be redacted, `false` otherwise.\n * @since 0.10.0\n */\nexport function shouldFieldRedacted(\n field: string,\n fieldPatterns: FieldPatterns,\n): boolean {\n for (const fieldPattern of fieldPatterns) {\n if (typeof fieldPattern === \"string\") {\n if (fieldPattern === field) return true;\n } else {\n if (fieldPattern.test(field)) return true;\n }\n }\n return false;\n}\n\n/**\n * Extracts placeholder names from a message template string in order.\n * @param template The message template string.\n * @returns An array of placeholder names in the order they appear.\n */\nfunction extractPlaceholderNames(template: string): string[] {\n const placeholders: string[] = [];\n for (let i = 0; i < template.length; i++) {\n if (template[i] === \"{\") {\n // Check for escaped brace\n if (i + 1 < template.length && template[i + 1] === \"{\") {\n i++;\n continue;\n }\n const closeIndex = template.indexOf(\"}\", i + 1);\n if (closeIndex === -1) continue;\n const key = template.slice(i + 1, closeIndex).trim();\n placeholders.push(key);\n i = closeIndex;\n }\n }\n return placeholders;\n}\n\n/**\n * Parses a property path into its segments.\n * @param path The property path (e.g., \"user.password\" or \"users[0].email\").\n * @returns An array of path segments.\n */\nfunction parsePathSegments(path: string): string[] {\n const segments: string[] = [];\n let current = \"\";\n for (const char of path) {\n if (char === \".\" || char === \"[\") {\n if (current) segments.push(current);\n current = \"\";\n } else if (char === \"]\" || char === \"?\") {\n // Skip these characters\n } else {\n current += char;\n }\n }\n if (current) segments.push(current);\n return segments;\n}\n\n/**\n * Determines which placeholder indices should be redacted based on field\n * patterns, and which are wildcard placeholders.\n * @param placeholders Array of placeholder names from the template.\n * @param fieldPatterns Field patterns to match against.\n * @returns Object with redactedIndices and wildcardIndices.\n */\nfunction getRedactedPlaceholderIndices(\n placeholders: string[],\n fieldPatterns: FieldPatterns,\n): { redactedIndices: Set<number>; wildcardIndices: Set<number> } {\n const redactedIndices = new Set<number>();\n const wildcardIndices = new Set<number>();\n\n for (let i = 0; i < placeholders.length; i++) {\n const placeholder = placeholders[i];\n\n // Track wildcard {*} separately\n if (placeholder === \"*\") {\n wildcardIndices.add(i);\n continue;\n }\n\n // Check the full placeholder name\n if (shouldFieldRedacted(placeholder, fieldPatterns)) {\n redactedIndices.add(i);\n continue;\n }\n // For nested paths, check each segment\n const segments = parsePathSegments(placeholder);\n for (const segment of segments) {\n if (shouldFieldRedacted(segment, fieldPatterns)) {\n redactedIndices.add(i);\n break;\n }\n }\n }\n return { redactedIndices, wildcardIndices };\n}\n\n/**\n * Redacts values in the message array based on the redacted placeholder\n * indices and wildcard indices.\n * @param message The original message array.\n * @param redactedIndices Set of placeholder indices to redact.\n * @param wildcardIndices Set of wildcard placeholder indices.\n * @param redactedProperties The redacted properties object.\n * @param action The redaction action.\n * @returns New message array with redacted values.\n */\nfunction redactMessageArray(\n message: readonly unknown[],\n redactedIndices: Set<number>,\n wildcardIndices: Set<number>,\n redactedProperties: Record<string, unknown>,\n action: \"delete\" | ((value: unknown) => unknown) | undefined,\n): readonly unknown[] {\n if (redactedIndices.size === 0 && wildcardIndices.size === 0) return message;\n\n const result: unknown[] = [];\n let placeholderIndex = 0;\n\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n // Even index: text segment\n result.push(message[i]);\n } else {\n // Odd index: value/placeholder\n if (wildcardIndices.has(placeholderIndex)) {\n // Wildcard {*}: replace with redacted properties\n result.push(redactedProperties);\n } else if (redactedIndices.has(placeholderIndex)) {\n if (action == null || action === \"delete\") {\n result.push(\"\");\n } else {\n result.push(action(message[i]));\n }\n } else {\n result.push(message[i]);\n }\n placeholderIndex++;\n }\n }\n return result;\n}\n\n/**\n * Collects redacted value mappings from original to redacted properties.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @param map The map to populate with original -> redacted value pairs.\n */\nfunction collectRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n map: Map<unknown, unknown>,\n): void {\n for (const key in original) {\n const origVal = original[key];\n const redVal = redacted[key];\n\n if (origVal !== redVal) {\n map.set(origVal, redVal);\n }\n\n // Recurse into nested objects\n if (\n typeof origVal === \"object\" && origVal !== null &&\n typeof redVal === \"object\" && redVal !== null &&\n !Array.isArray(origVal)\n ) {\n collectRedactedValues(\n origVal as Record<string, unknown>,\n redVal as Record<string, unknown>,\n map,\n );\n }\n }\n}\n\n/**\n * Gets a map of original values to their redacted replacements.\n * @param original The original properties.\n * @param redacted The redacted properties.\n * @returns A map of original -> redacted values.\n */\nfunction getRedactedValues(\n original: Record<string, unknown>,\n redacted: Record<string, unknown>,\n): Map<unknown, unknown> {\n const map = new Map<unknown, unknown>();\n collectRedactedValues(original, redacted, map);\n return map;\n}\n\n/**\n * Redacts message array values by comparing with redacted property values.\n * Used for tagged template literals where placeholder names are not available.\n * @param message The original message array.\n * @param redactedValues Map of original -> redacted values.\n * @returns New message array with redacted values.\n */\nfunction redactMessageByValues(\n message: readonly unknown[],\n redactedValues: Map<unknown, unknown>,\n): readonly unknown[] {\n if (redactedValues.size === 0) return message;\n\n const result: unknown[] = [];\n for (let i = 0; i < message.length; i++) {\n if (i % 2 === 0) {\n result.push(message[i]);\n } else {\n const val = message[i];\n if (redactedValues.has(val)) {\n result.push(redactedValues.get(val));\n } else {\n result.push(val);\n }\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;AAsBA,MAAaA,wBAAuC;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDD,SAAgB,cACdC,MACAC,UAAiD,uBACE;CACnD,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAAG,EAAE,eAAe,QAAS,IAAG;CACnE,MAAM,UAAU,CAACC,WAAsB;EACrC,MAAM,qBAAqB,iBAAiB,OAAO,YAAY,KAAK;EACpE,IAAI,kBAAkB,OAAO;AAE7B,aAAW,OAAO,eAAe,UAAU;GAEzC,MAAM,eAAe,wBAAwB,OAAO,WAAW;GAC/D,MAAM,EAAE,iBAAiB,iBAAiB,GACxC,8BACE,cACA,KAAK,cACN;AACH,OAAI,gBAAgB,OAAO,KAAK,gBAAgB,OAAO,EACrD,mBAAkB,mBAChB,OAAO,SACP,iBACA,iBACA,oBACA,KAAK,OACN;EAEJ,OAAM;GAEL,MAAM,iBAAiB,kBACrB,OAAO,YACP,mBACD;AACD,OAAI,eAAe,OAAO,EACxB,mBAAkB,sBAAsB,OAAO,SAAS,eAAe;EAE1E;AAED,OAAK;GACH,GAAG;GACH,SAAS;GACT,YAAY;EACb,EAAC;CACH;AACD,KAAI,OAA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  "name": "@logtape/redaction",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "description": "Redact sensitive data from log messages",
5
5
  "keywords": [
6
6
  "logging",
@@ -45,8 +45,11 @@
45
45
  "./package.json": "./package.json"
46
46
  },
47
47
  "sideEffects": false,
48
+ "files": [
49
+ "dist/"
50
+ ],
48
51
  "peerDependencies": {
49
- "@logtape/logtape": "^1.1.4"
52
+ "@logtape/logtape": "^1.1.6"
50
53
  },
51
54
  "devDependencies": {
52
55
  "@alinea/suite": "^0.6.3",
package/deno.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "name": "@logtape/redaction",
3
- "version": "1.1.4",
4
- "license": "MIT",
5
- "exports": "./src/mod.ts",
6
- "exclude": [
7
- "coverage/",
8
- "npm/",
9
- ".dnt-import-map.json"
10
- ],
11
- "tasks": {
12
- "build": "pnpm build",
13
- "test": "deno test",
14
- "test:node": {
15
- "dependencies": [
16
- "build"
17
- ],
18
- "command": "node --experimental-transform-types --test"
19
- },
20
- "test:bun": {
21
- "dependencies": [
22
- "build"
23
- ],
24
- "command": "bun test"
25
- },
26
- "test-all": {
27
- "dependencies": [
28
- "test",
29
- "test:node",
30
- "test:bun"
31
- ]
32
- }
33
- }
34
- }
package/src/field.test.ts DELETED
@@ -1,421 +0,0 @@
1
- import { suite } from "@alinea/suite";
2
- import type { LogRecord, Sink } from "@logtape/logtape";
3
- import { assert } from "@std/assert/assert";
4
- import { assertEquals } from "@std/assert/equals";
5
- import { assertExists } from "@std/assert/exists";
6
- import { assertFalse } from "@std/assert/false";
7
- import {
8
- type FieldPatterns,
9
- redactByField,
10
- redactProperties,
11
- shouldFieldRedacted,
12
- } from "./field.ts";
13
-
14
- const test = suite(import.meta);
15
-
16
- test("shouldFieldRedacted()", () => {
17
- { // matches string pattern
18
- const fieldPatterns: FieldPatterns = ["password", "secret"];
19
- assertEquals(shouldFieldRedacted("password", fieldPatterns), true);
20
- assertEquals(shouldFieldRedacted("secret", fieldPatterns), true);
21
- assertEquals(shouldFieldRedacted("username", fieldPatterns), false);
22
- }
23
-
24
- { // matches regex pattern
25
- const fieldPatterns: FieldPatterns = [/pass/i, /secret/i];
26
- assertEquals(shouldFieldRedacted("password", fieldPatterns), true);
27
- assertEquals(shouldFieldRedacted("secretKey", fieldPatterns), true);
28
- assertEquals(shouldFieldRedacted("myPassword", fieldPatterns), true);
29
- assertEquals(shouldFieldRedacted("username", fieldPatterns), false);
30
- }
31
-
32
- { // case sensitivity in regex
33
- const caseSensitivePatterns: FieldPatterns = [/pass/, /secret/];
34
- const caseInsensitivePatterns: FieldPatterns = [/pass/i, /secret/i];
35
-
36
- assertEquals(shouldFieldRedacted("Password", caseSensitivePatterns), false);
37
- assertEquals(
38
- shouldFieldRedacted("Password", caseInsensitivePatterns),
39
- true,
40
- );
41
- }
42
- });
43
-
44
- test("redactProperties()", () => {
45
- { // delete action (default)
46
- const properties = {
47
- username: "user123",
48
- password: "secret123",
49
- email: "user@example.com",
50
- message: "Hello world",
51
- };
52
-
53
- const result = redactProperties(properties, {
54
- fieldPatterns: ["password", "email"],
55
- });
56
-
57
- assert("username" in result);
58
- assertFalse("password" in result);
59
- assertFalse("email" in result);
60
- assert("message" in result);
61
-
62
- const nestedObject = {
63
- ...properties,
64
- nested: {
65
- foo: "bar",
66
- baz: "qux",
67
- passphrase: "asdf",
68
- },
69
- };
70
- const result2 = redactProperties(nestedObject, {
71
- fieldPatterns: ["password", "email", "passphrase"],
72
- });
73
-
74
- assert("username" in result2);
75
- assertFalse("password" in result2);
76
- assertFalse("email" in result2);
77
- assert("message" in result2);
78
- assert("nested" in result2);
79
- assert(typeof result2.nested === "object");
80
- assertExists(result2.nested);
81
- assert("foo" in result2.nested);
82
- assert("baz" in result2.nested);
83
- assertFalse("passphrase" in result2.nested);
84
- }
85
-
86
- { // custom action function
87
- const properties = {
88
- username: "user123",
89
- password: "secret123",
90
- token: "abc123",
91
- message: "Hello world",
92
- };
93
-
94
- const result = redactProperties(properties, {
95
- fieldPatterns: [/password/i, /token/i],
96
- action: () => "REDACTED",
97
- });
98
-
99
- assertEquals(result.username, "user123");
100
- assertEquals(result.password, "REDACTED");
101
- assertEquals(result.token, "REDACTED");
102
- assertEquals(result.message, "Hello world");
103
- }
104
-
105
- { // preserves other properties
106
- const properties = {
107
- username: "user123",
108
- data: { nested: "value" },
109
- sensitive: "hidden",
110
- };
111
-
112
- const result = redactProperties(properties, {
113
- fieldPatterns: ["sensitive"],
114
- });
115
-
116
- assertEquals(result.username, "user123");
117
- assertEquals(result.data, { nested: "value" });
118
- assertFalse("sensitive" in result);
119
- }
120
- });
121
-
122
- test("redactByField()", async () => {
123
- { // wraps sink and redacts properties
124
- const records: LogRecord[] = [];
125
- const originalSink: Sink = (record) => records.push(record);
126
-
127
- const wrappedSink = redactByField(originalSink, {
128
- fieldPatterns: ["password", "token"],
129
- });
130
-
131
- const record: LogRecord = {
132
- level: "info",
133
- category: ["test"],
134
- message: ["Test message"],
135
- rawMessage: "Test message",
136
- timestamp: Date.now(),
137
- properties: {
138
- username: "user123",
139
- password: "secret123",
140
- token: "abc123",
141
- },
142
- };
143
-
144
- wrappedSink(record);
145
-
146
- assertEquals(records.length, 1);
147
- assert("username" in records[0].properties);
148
- assertFalse("password" in records[0].properties);
149
- assertFalse("token" in records[0].properties);
150
- }
151
-
152
- { // uses default field patterns when not specified
153
- const records: LogRecord[] = [];
154
- const originalSink: Sink = (record) => records.push(record);
155
-
156
- const wrappedSink = redactByField(originalSink);
157
-
158
- const record: LogRecord = {
159
- level: "info",
160
- category: ["test"],
161
- message: ["Test message"],
162
- rawMessage: "Test message",
163
- timestamp: Date.now(),
164
- properties: {
165
- username: "user123",
166
- password: "secret123",
167
- email: "user@example.com",
168
- apiKey: "xyz789",
169
- },
170
- };
171
-
172
- wrappedSink(record);
173
-
174
- assertEquals(records.length, 1);
175
- assert("username" in records[0].properties);
176
- assertFalse("password" in records[0].properties);
177
- assertFalse("email" in records[0].properties);
178
- assertFalse("apiKey" in records[0].properties);
179
- }
180
-
181
- { // preserves Disposable behavior
182
- let disposed = false;
183
- const originalSink: Sink & Disposable = Object.assign(
184
- (_record: LogRecord) => {},
185
- {
186
- [Symbol.dispose]: () => {
187
- disposed = true;
188
- },
189
- },
190
- );
191
-
192
- const wrappedSink = redactByField(originalSink) as Sink & Disposable;
193
-
194
- assert(Symbol.dispose in wrappedSink);
195
- wrappedSink[Symbol.dispose]();
196
- assert(disposed);
197
- }
198
-
199
- { // preserves AsyncDisposable behavior
200
- let disposed = false;
201
- const originalSink: Sink & AsyncDisposable = Object.assign(
202
- (_record: LogRecord) => {},
203
- {
204
- [Symbol.asyncDispose]: () => {
205
- disposed = true;
206
- return Promise.resolve();
207
- },
208
- },
209
- );
210
-
211
- const wrappedSink = redactByField(originalSink) as Sink & AsyncDisposable;
212
-
213
- assert(Symbol.asyncDispose in wrappedSink);
214
- await wrappedSink[Symbol.asyncDispose]();
215
- assert(disposed);
216
- }
217
-
218
- { // redacts values in message array (string template)
219
- const records: LogRecord[] = [];
220
- const wrappedSink = redactByField((r) => records.push(r), {
221
- fieldPatterns: ["password"],
222
- action: () => "[REDACTED]",
223
- });
224
-
225
- wrappedSink({
226
- level: "info",
227
- category: ["test"],
228
- message: ["Password is ", "supersecret", ""],
229
- rawMessage: "Password is {password}",
230
- timestamp: Date.now(),
231
- properties: { password: "supersecret" },
232
- });
233
-
234
- assertEquals(records[0].message, ["Password is ", "[REDACTED]", ""]);
235
- assertEquals(records[0].properties.password, "[REDACTED]");
236
- }
237
-
238
- { // redacts multiple sensitive fields in message
239
- const records: LogRecord[] = [];
240
- const wrappedSink = redactByField((r) => records.push(r), {
241
- fieldPatterns: ["password", "email"],
242
- action: () => "[REDACTED]",
243
- });
244
-
245
- wrappedSink({
246
- level: "info",
247
- category: ["test"],
248
- message: ["Login: ", "user@example.com", " with ", "secret123", ""],
249
- rawMessage: "Login: {email} with {password}",
250
- timestamp: Date.now(),
251
- properties: { email: "user@example.com", password: "secret123" },
252
- });
253
-
254
- assertEquals(records[0].message[1], "[REDACTED]");
255
- assertEquals(records[0].message[3], "[REDACTED]");
256
- }
257
-
258
- { // redacts nested property path in message
259
- const records: LogRecord[] = [];
260
- const wrappedSink = redactByField((r) => records.push(r), {
261
- fieldPatterns: ["password"],
262
- action: () => "[REDACTED]",
263
- });
264
-
265
- wrappedSink({
266
- level: "info",
267
- category: ["test"],
268
- message: ["User password: ", "secret", ""],
269
- rawMessage: "User password: {user.password}",
270
- timestamp: Date.now(),
271
- properties: { user: { password: "secret" } },
272
- });
273
-
274
- assertEquals(records[0].message[1], "[REDACTED]");
275
- }
276
-
277
- { // delete action uses empty string in message
278
- const records: LogRecord[] = [];
279
- const wrappedSink = redactByField((r) => records.push(r), {
280
- fieldPatterns: ["password"],
281
- });
282
-
283
- wrappedSink({
284
- level: "info",
285
- category: ["test"],
286
- message: ["Password: ", "secret", ""],
287
- rawMessage: "Password: {password}",
288
- timestamp: Date.now(),
289
- properties: { password: "secret" },
290
- });
291
-
292
- assertEquals(records[0].message[1], "");
293
- assertFalse("password" in records[0].properties);
294
- }
295
-
296
- { // non-sensitive field in message is not redacted
297
- const records: LogRecord[] = [];
298
- const wrappedSink = redactByField((r) => records.push(r), {
299
- fieldPatterns: ["password"],
300
- action: () => "[REDACTED]",
301
- });
302
-
303
- wrappedSink({
304
- level: "info",
305
- category: ["test"],
306
- message: ["Username: ", "johndoe", ""],
307
- rawMessage: "Username: {username}",
308
- timestamp: Date.now(),
309
- properties: { username: "johndoe" },
310
- });
311
-
312
- assertEquals(records[0].message[1], "johndoe");
313
- }
314
-
315
- { // wildcard {*} in message uses redacted properties
316
- const records: LogRecord[] = [];
317
- const wrappedSink = redactByField((r) => records.push(r), {
318
- fieldPatterns: ["password"],
319
- action: () => "[REDACTED]",
320
- });
321
-
322
- const props = { username: "john", password: "secret" };
323
- wrappedSink({
324
- level: "info",
325
- category: ["test"],
326
- message: ["Props: ", props, ""],
327
- rawMessage: "Props: {*}",
328
- timestamp: Date.now(),
329
- properties: props,
330
- });
331
-
332
- // The {*} should be replaced with redacted properties
333
- assertEquals(records[0].message[1], {
334
- username: "john",
335
- password: "[REDACTED]",
336
- });
337
- assertEquals(records[0].properties.password, "[REDACTED]");
338
- }
339
-
340
- { // escaped braces are not treated as placeholders
341
- const records: LogRecord[] = [];
342
- const wrappedSink = redactByField((r) => records.push(r), {
343
- fieldPatterns: ["password"],
344
- action: () => "[REDACTED]",
345
- });
346
-
347
- wrappedSink({
348
- level: "info",
349
- category: ["test"],
350
- message: ["Value: ", "secret", ""],
351
- rawMessage: "Value: {{password}} {password}",
352
- timestamp: Date.now(),
353
- properties: { password: "secret" },
354
- });
355
-
356
- // Only the second {password} is a placeholder
357
- assertEquals(records[0].message[1], "[REDACTED]");
358
- }
359
-
360
- { // tagged template literal - redacts by comparing values
361
- const records: LogRecord[] = [];
362
- const wrappedSink = redactByField((r) => records.push(r), {
363
- fieldPatterns: ["password"],
364
- action: () => "[REDACTED]",
365
- });
366
-
367
- const rawMessage = ["Password: ", ""] as unknown as TemplateStringsArray;
368
- Object.defineProperty(rawMessage, "raw", { value: rawMessage });
369
-
370
- wrappedSink({
371
- level: "info",
372
- category: ["test"],
373
- message: ["Password: ", "secret", ""],
374
- rawMessage,
375
- timestamp: Date.now(),
376
- properties: { password: "secret" },
377
- });
378
-
379
- // Message should be redacted by value comparison
380
- assertEquals(records[0].message[1], "[REDACTED]");
381
- assertEquals(records[0].properties.password, "[REDACTED]");
382
- }
383
-
384
- { // array access path in message
385
- const records: LogRecord[] = [];
386
- const wrappedSink = redactByField((r) => records.push(r), {
387
- fieldPatterns: ["password"],
388
- action: () => "[REDACTED]",
389
- });
390
-
391
- wrappedSink({
392
- level: "info",
393
- category: ["test"],
394
- message: ["First user password: ", "secret1", ""],
395
- rawMessage: "First user password: {users[0].password}",
396
- timestamp: Date.now(),
397
- properties: { users: [{ password: "secret1" }] },
398
- });
399
-
400
- assertEquals(records[0].message[1], "[REDACTED]");
401
- }
402
-
403
- { // regex pattern matches in message placeholder
404
- const records: LogRecord[] = [];
405
- const wrappedSink = redactByField((r) => records.push(r), {
406
- fieldPatterns: [/pass/i],
407
- action: () => "[REDACTED]",
408
- });
409
-
410
- wrappedSink({
411
- level: "info",
412
- category: ["test"],
413
- message: ["Passphrase: ", "mysecret", ""],
414
- rawMessage: "Passphrase: {passphrase}",
415
- timestamp: Date.now(),
416
- properties: { passphrase: "mysecret" },
417
- });
418
-
419
- assertEquals(records[0].message[1], "[REDACTED]");
420
- }
421
- });