@hackylabs/deep-redact

中文文档
4.1.0发布于 2026/08/28MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 34.5万

Deeply redact sensitive data from objects, arrays and arbitrary strings (e.g. XML or raw cookies data) with a composable, function-first API.

原始使用文档
文档目录22 节
  1. Features
  2. Contributor Baseline
  3. Installation
  4. Quick Start
  5. Benchmarks
  6. TLDR Headline
  7. Structured output ( serialise: false )
  8. Serialised output ( serialise: true )
  9. Configuration
  10. Top-level options
  11. KeySelector
  12. PathEntry
  13. StringTest
  14. TransformersOption
  15. DiagnosticsOptions
  16. Public API
  17. Documentation
  18. Worked examples
  19. Migration guides
  20. Architecture and design
  21. Platform and security teams
  22. Scripts

Deep Redact

npm version GitHub license

@hackylabs/deep-redact is a rule-driven redaction library for Node.js and Deno. It lets you express what to redact — a key name, a path, a regex, or a substring — and the runtime locates and replaces it everywhere in the payload without requiring exhaustive path enumeration. Policies are compiled once at initialisation and reused across every request, making it suitable for high-throughput production use.

Libraries like fast-redact require an explicit path for every location where a sensitive field might appear (a.b.password, a.c.password, …). Deep Redact inverts this: a single keys: ['password'] rule targets every password field at any depth. It also adds capabilities that path-enumeration libraries cannot offer, such as partial string redaction (targeting a sensitive pattern inside a larger value) and wildcard path selectors for repeated structures.

ko-fi

Features

  • Depth-agnostic key rules — redact any field by name at any nesting depth; no path enumeration required
  • Exact and structured path targeting — pin redaction to a specific location when precision is needed
  • Regex property matching — match field names by regular expression
  • Substring targeting — redact a sensitive string that appears inside a larger value, not just whole-value replacement
  • Wildcard and exclusion path selectors — handle repeated structures at virtually any depth (['addresses.*', { ignore: 'country' }]) without listing every index
  • Structured and serialised output — return a live object graph or a guaranteed-JSON-safe string (serialise: true)
  • Built-in and custom transformers — override how specific runtime types are represented in serialised output
  • Built-in security — prevent prototype pollution and DoS by memory exhaustion
  • Console adapter — optional console.* redaction via an explicit adapter

Contributor Baseline

Installation

npm install @hackylabs/deep-redact
pnpm add @hackylabs/deep-redact
yarn add @hackylabs/deep-redact
bun add @hackylabs/deep-redact

Deno — add the package to your import map (deno.json):

{
  "imports": {
    "@hackylabs/deep-redact": "npm:@hackylabs/[email protected]"
  }
}

Quick Start

import { deepRedact } from '@hackylabs/deep-redact'

const redact = deepRedact({ keys: ['password', 'token'] })

redact({ user: { password: 'secret', safe: 'keep this' }, token: 'abc123', id: 1 })
// { user: { password: '[REDACTED]', safe: 'keep this' }, token: '[REDACTED]', id: 1 }

Benchmarks

Generated from committed artefacts in test/artefacts/benchmarks/speed/. Node.js 24 LTS, Apple M-series. Steady-state after 10,000 warmup iterations.

TLDR Headline

If raw throughput is your primary constraint and you can accept exhaustive path enumeration, use fast-redact instead. It is purpose-built for maximum JSON-string output speed and will outperform any rule-driven library in that narrow scenario. Use Deep Redact when you need depth-agnostic targeting, wildcard paths, substring redaction, or built-in security guarantees.

If you choose fast-redact instead, be aware of the trade-offs:

  • No depth-agnostic key rules — every sensitive path must be enumerated explicitly
  • No double-wildcard (**) path selectors — you cannot target records.**.email without listing every depth
  • No substring targeting — whole-value replacement only; partial string redaction is not supported
  • No serialisation-safe transformer pipeline — no built-in handling for BigInt, Date, Map, Set, Error, RegExp, or URL values
  • No prototype pollution protection — no guard against __proto__ and constructor.prototype injection
  • No configurable depth or node limits — no protection against DoS via deeply nested or excessively large payloads

Structured output (serialise: false)

v4, v3, and fast-redact all return a plain JavaScript object.

Speed comparison — structured output

† fast-redact is a third-party library, not a deep-redact version. It is shown as a throughput reference; its feature set and guarantees differ from deep-redact's, so it is not a like-for-like comparison.

v4 is ~17× faster than v3 on path-based workloads and ~10× faster on wildcard workloads.

Serialised output (serialise: true)

All four solutions return a JSON string.

Speed comparison — serialised output

† fast-redact is a third-party library; json-stringify-regex is a naive native approach (JSON.stringify(value).replace(pattern, replacement)), not a library. Neither performs deep-redact's structured redaction or offers its guarantees, so both are shown as throughput references rather than like-for-like comparisons.

v4 remains faster than v3 in serialised mode. fast-redact and json-stringify-regex have a throughput advantage because their output path is oriented entirely toward string production.

Against deep-redact v2 the serialised picture is mixed: v4 is roughly at parity on path-based workloads but slower on breadth-heavy (wildcard) ones. That gap is the cost of safety v2 does not provide — under serialise: true, v4 runs the type transformers that make BigInt, Date, Map, Set, Error, RegExp, and URL values JSON-safe, and it detects and neutralises circular references instead of throwing on them. (Node and depth budgeting via maxNodes/maxDepth runs by default — 500 / 50,000 — and throws on breach; the checks are counter increments and add negligible cost. Set onBudgetExceeded: 'truncate' to fail closed with a [TRUNCATED] marker instead of throwing.)

These safety passes are intrinsic to serialise: true and cannot be switched off individually. If you do not need those guarantees and want to match v2's throughput (or better), set serialise: false and run your own JSON.stringify: the structured-output path skips the transformer and circular-reference passes entirely. This restores v2's trade-offs too — your JSON.stringify will throw on BigInt and circular references, Map/Set serialise as {}, and undefined is dropped.

Full speed and resource benchmark results: docs/benchmarks/speed-results.md and docs/benchmarks/resource-results.md.

Configuration

deepRedact(options) accepts a single options object. All options are optional.

Top-level options

OptionTypeDefaultRequiredDescription
keysKeySelector[][]NoRedact any field matching a listed key, at any depth
pathsPathEntry[][]NoRedact fields at specific paths; supports exact strings, structured paths, wildcards, and exclusion selectors
stringTestsStringTest[][]NoRedact matching patterns inside string values
censorstring | function'[REDACTED]'NoReplacement value, or a function (value, context) => replacement
serialiseboolean | functionfalseNotrue returns a JSON-safe string; a function receives the safe graph and may return any string
removebooleanfalseNoRemove matched keys from the output instead of replacing their values
retainStructurebooleanfalseNoKeep descendant nodes traversable for lower-precedence rules when a parent is matched
replaceStringByLengthbooleanfalseNoRepeat the censor string to match the character length of the redacted value
typesValueTypeName[]['string']Notypeof categories eligible for redaction; a matched key whose value's type is not listed is left untouched
fuzzyKeyMatchbooleanfalseNoMatch when the configured key is a substring of the field name (e.g. 'pass' matches 'password')
caseSensitiveKeyMatchbooleantrueNoWhen false, normalises key names (strips non-word characters, lowercases) before comparing
maxDepthnumber500NoStop traversal beyond this nesting depth; guards against deeply nested payload DoS
maxNodesnumber50000NoStop traversal after this many nodes; guards against excessively large payload DoS
onBudgetExceeded'throw' | 'truncate''throw'NoOn a maxDepth/maxNodes breach, 'throw' raises an internal budget error; 'truncate' replaces the offending node with [TRUNCATED] and stops, failing closed
transformersTransformersOptionbuilt-in defaultsNoOverride how runtime types are represented in serialised output
diagnosticsDiagnosticsOptions—NoOpt-in sink for structured degrade/budget events; silent by default (no console output). Pass getNodeConsoleDiagnosticSink() as the sink to log to the console

ValueTypeName is one of: 'string', 'number', 'bigint', 'boolean', 'object', 'function', 'symbol', 'undefined'.

KeySelector

Each entry in keys may be a plain string, a RegExp, or a KeyRule object for per-key overrides.

keys traverses plain objects, arrays, class instances' own enumerable fields, and Map/Set contents. Map entry keys are matched by their rendered string form while preserving the original key object in structured output; Set members are traversed in insertion order, but their numeric positions are path segments rather than synthetic keys.

FieldTypeDefaultRequiredDescription
keystring | RegExp—YesThe key to match
censorstring | functiontop-level censorNoOverride the censor for this key only
removebooleantop-level removeNoOverride remove for this key only
retainStructurebooleantop-level retainStructureNoOverride retainStructure for this key only
replaceStringByLengthbooleantop-level replaceStringByLengthNoOverride replaceStringByLength for this key only
fuzzyKeyMatchbooleantop-level fuzzyKeyMatchNoOverride fuzzyKeyMatch for this key only
caseSensitiveKeyMatchbooleantop-level caseSensitiveKeyMatchNoOverride caseSensitiveKeyMatch for this key only

PathEntry

Each entry in paths may be a plain dot-notation string (e.g. 'user.profile.ssn'), a structured path array, or a PathRule object for per-path overrides.

Structured path arrays may contain:

Segment typeExampleMatches
string or number'password'Exact key or index
RegExp/^pass/iKeys matching the regex
{ any: true }—Any single key (*)
{ anyDepth: true }—Zero or more keys at any depth (**)
{ ignore: string | number | RegExp }{ ignore: 'country' }Excludes a key from a surrounding wildcard
FieldTypeDefaultRequiredDescription
pathstring | PathSegments[]—YesThe path to match
censorstring | functiontop-level censorNoOverride the censor for this path only
removebooleantop-level removeNoOverride remove for this path only
retainStructurebooleantop-level retainStructureNoOverride retainStructure for this path only
replaceStringByLengthbooleantop-level replaceStringByLengthNoOverride replaceStringByLength for this path only

StringTest

Each entry in stringTests may be a bare RegExp (whole-value replacement with censor) or a SubstringRule for partial replacement.

FieldTypeRequiredDescription
patternRegExpYesRegular expression tested against string values
replacer(value: string, pattern: RegExp) => stringYesReturns the redacted string; called only when pattern matches

TransformersOption

Transformers control how non-JSON-safe runtime types are represented when serialise: true. Each transformer is a function (value: unknown) => unknown that either returns a transformed value or returns the value unchanged to pass to the next transformer in the chain.

FieldTypeDescription
byType.bigintTransformer[]Applied to BigInt values (does not consult byType.object)
byType.objectTransformer[]Applied first for built-in constructor types and unknown object types
byConstructor.DateTransformer[]Applied to Date instances
byConstructor.ErrorTransformer[]Applied to Error instances
byConstructor.MapTransformer[]Applied to Map instances
byConstructor.RegExpTransformer[]Applied to RegExp instances
byConstructor.SetTransformer[]Applied to Set instances
byConstructor.URLTransformer[]Applied to URL instances
byConstructor.customCustomConstructorTransformerRegistration[]Custom types matched by instanceof in declaration order
fallbackTransformer[]Applied when no earlier transformer returns a changed value

The built-in transformers produce deterministic marker objects (e.g. { _transformer: 'date', datetime: '<ISO string>' }). See docs/architecture/serialise-output.md for the full dispatch order and marker shapes.

Execution phases. User byConstructor.custom and byConstructor.Error transformers run before regular traversal, in both serialise modes: the matched class instance is converted to the plain object you return, which is then scrubbed by your keys/paths rules. This is how PII nested inside a class instance — for example an Error/AxiosError carrying a config.data payload — gets redacted without a pre-normalise step (see Redacting PII inside Error instances). Every other bucket (byType, fallback, and user byConstructor.{Date,Map,RegExp,Set,URL}) runs only during the serialise: true pass; relying on that serialise-only behaviour — where the transformer output escapes redaction — is deprecated in favour of the per-class buckets above.

DiagnosticsOptions

FieldTypeDescription
sink(event: DiagnosticEvent) => voidCalled with a structured event when a value is degraded to '[UNSUPPORTED]' during serialisation

Public API

import { createRedactor, deepRedact } from '@hackylabs/deep-redact'

// deepRedact and createRedactor are the same factory under different names
const redact = deepRedact({ keys: ['secret'] })
const same = createRedactor({ keys: ['secret'] })

Documentation

Worked examples

Migration guides

Architecture and design

Platform and security teams

  • Standardisation guide — supported capabilities, targeting semantics, verification evidence, and adoption decision scope

Scripts

  • pnpm run build
  • pnpm run lint
  • pnpm run test
  • pnpm run generate-exports
  • pnpm run generate-readme
  • pnpm run verify-generated-files
  • pnpm run bench
  • pnpm run bench:generate-charts

版本与发布记录

@hackylabs/deep-redact 共发布 19 个版本,首次发布于 2024/07/27;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.1.0latest2026/08/282 个月前
4.0.22026/07/014 个月前
4.0.12026/06/204 个月前
2.2.2legacy-v22026/06/135 个月前
4.0.02026/06/075 个月前
3.0.5legacy-v32026/03/088 个月前

关于 @hackylabs/deep-redact 的常见问题

@hackylabs/deep-redact 是什么?

Deeply redact sensitive data from objects, arrays and arbitrary strings (e.g. XML or raw cookies data) with a composable, function-first API.

如何安装 @hackylabs/deep-redact?

在项目目录运行 npm install @hackylabs/deep-redact,或使用 pnpm add / yarn add / bun add。

@hackylabs/deep-redact 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@hackylabs/deep-redact 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@hackylabs/deep-redact 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.18.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@hackylabs/deep-redact 可以商用吗?

@hackylabs/deep-redact 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@hackylabs/deep-redact 的下载量有多少?

根据 npm 官方下载统计,@hackylabs/deep-redact 在 2026/10/17 – 2026/11/15 这 30 天内被下载 344,875 次,日均约 11,496 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@hackylabs/deep-redact 还在维护吗?

最新版本 4.1.0 发布于 2026/08/28(2 个月前);至今共发布 19 个版本,其中过去 12 个月发布了 6 个;首次发布于 2024/07/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。