@bazariodev/winnow
v0.1.0
Published
Bounded JSON value conversion and application-selected redaction.
Readme
@bazariodev/winnow
Convert arbitrary values into bounded JSON-compatible data and apply application-selected redaction. Use it for diagnostic reports, telemetry, and support exports without a logging model.
Install
pnpm add @bazariodev/winnowThere are no runtime or peer dependencies. Hash algorithms and keys belong to the application.
Node.js support is ^22.12.0 || ^24.0.0 || >=26.0.0.
Usage
import { createRedactor } from '@bazariodev/winnow';
const redactor = createRedactor({ fields: { password: 'drop' } });
const report = redactor.redactValue({
password: 'private',
message: 'Contact [email protected]',
});
// report: { message: 'Contact [redacted]' }Behavior
- Copy retained data through property descriptors. Do not call application getters or
toJSON. Read Error stacks and DOMException names/messages through captured runtime accessors. Skip a lazy stack when its header has an application accessor or an object value. Runtime stack formatting can call application code throughError.prepareStackTrace. A failed Error field does not remove other Error fields. Read inherited Error names through at most 16 prototype objects. - Handle Error causes, aggregate errors, dates, bigint, cycles, sparse arrays, and unsupported values. Convert non-finite numbers to null. Error schema fields remain under an allow-list policy; arbitrary Error properties follow the field policy. Mark omitted aggregate children with an Error-shaped truncation marker. Binary views, ArrayBuffer, Map, Set, and RegExp use the unsupported marker. Other object instances use their enumerable own properties.
- Recognize Errors from another realm when
Error.isErroris available. Otherwise, useinstanceof Error; Node.js 22 does not recognize foreign Errors. Foreign runtime stack getters are not captured, so their stacks can be absent. Foreign Dates, Maps, Sets, RegExps, and ArrayBuffers use plain-object conversion. Arrays and binary views keep their usual handling. - Match field rules without case at every depth.
keepstill applies nested and text rules.dropremoves a field before key redaction.maskkeeps part of a string.hashcalls the supplied function. Field rules also apply to Error keysname,message,stack,cause, anderrors. Convert numbers and bigint to strings for mask/hash actions. Other non-string values useMARKERS.MASKdirectly, without calling the hash function. Reject field names that match after conversion to lowercase. If redacted keys collide, keep the first value and mark the session as truncated. Redact each retained key before its value. Skip a colliding value before conversion, so its callbacks do not run. This rule also applies to internal marker keys. - Text rules default to email, Bearer and Basic credentials, JWT, IP addresses, SIP/tel URIs,
E.164 numbers, URL credentials, and user paths.
text: []disables them. This set cannot cover every private value. ThebearerTokenrule covers both authentication schemes and retains the scheme's letter case. - Require global, non-sticky patterns. Copy each RegExp once at construction. Apply rules in order.
Read named rule fields through normal property access, including prototype methods.
Custom callbacks and patterns are trusted application code. Replacements must return strings.
Built-in rules run in linear time. They cover long valid URIs and JWTs within the input limit,
read URL credentials first, and keep times and stack positions unchanged.
IPv6 rules retain labels such as
ip:before a valid address. - Apply the string limit to generated Date text and field-mask results. The direct
maskutility does not apply this limit. - Redact before truncating. Input above four times
maxStringLengthbecomes a fixed marker before text rules run. Serialized value output abovemaxOutputSizebecomesMARKERS.LIMIT. Standalone conversion stops when retained output at any depth exceeds that limit. The current Error can still run text rules for its name, message, and stack before the stop. Later callbacks need not run after this stop. The final check still measures exact JSON output. - Fixed markers can exceed very small configured limits. Limits count string units and JSON characters, not UTF-8 bytes. They do not bound total heap use, Proxy work, or callback cost.
- Calls to
redactValueandredactTextstart independent operations. Returned data is copied; the caller can freeze it if required. No record schema or log headers are added. - Capture and validate the hash function at construction. Later changes to
policy.hashdo not replace it. Call the captured function with the supplied policy as its receiver.
API
| Export or method | Contract |
| --- | --- |
| createRedactor(policy?) | Compile one policy and return a frozen redactor. |
| redactValue(value) | Convert and redact arbitrary input; enforce the final output-size limit. |
| redactText(text) | Apply text rules and the string limit. |
| mask(text) | Keep the last four digits of a long number, or the first and last character; hide short strings. |
| hash(text) | Present only with an injected hash function. Check its synchronous string result. Input longer than four times maxStringLength returns MARKERS.LIMIT without calling the function. |
| limits | All resolved positive safe integer limits. |
| createSession() | Return a frozen session instance with shared structural budgets and truncation state. |
| TEXT_RULES | Frozen built-in text-rule map. |
| DEFAULT_LIMITS, MARKERS | Frozen defaults and serialized marker values. |
| Policy option | Meaning |
| --- | --- |
| fields | Field names mapped to keep, drop, mask, or hash. |
| unknownFields | keep by default; drop permits only named arbitrary fields. |
| text | Ordered replacement rules: name, pattern, replace(match, redactor), optional requiresHash. |
| hash | Application-owned synchronous function. Required by selected hash rules. |
| limits | Override default depth 6, string length 16,384, array length 100, keys 100, nodes 1,000, output size 65,536. |
Limit names are maxDepth, maxStringLength, maxArrayLength, maxKeys, maxNodes, and
maxOutputSize. The package does not supply a hash algorithm or key management.
A session is the converter instance. Call its methods through the instance. For callbacks, use
values.map((value) => session.redactValue(value)). Redactor methods can be passed as callbacks.
The session is frozen; its private counters and truncation state can still change.
A session provides redactValue, redactText, redactError(value, field), fieldRule(name), and
readonly truncated. Error-field conversion applies the selected field rule and retains an Error
shape. After node exhaustion, retained Error mask/hash actions return an Error-shaped truncation
marker without calling the hash function. A session shares one structural traversal budget.
It does not apply maxOutputSize to each root: the owner of an assembled document must check its
final aggregate size. Use the ordinary
redactValue method for a complete standalone value.
URL query policy
Built-in rules do not remove arbitrary URL query secrets. Add an application rule for the query names used by that application. This example covers four selected names; it is not a complete list.
import { createRedactor, TEXT_RULES } from '@bazariodev/winnow';
const redactor = createRedactor({
text: [
{
name: 'query-secrets',
pattern: /[?&](?:access_token|token|api_key|sig)=[^&#\s]*/gi,
replace: (match) => `${match.slice(0, match.indexOf('=') + 1)}[redacted]`,
},
...Object.values(TEXT_RULES),
],
});
redactor.redactText('wss://example.com/ws?token=private');Errors
Invalid limits, field policies, duplicate field names, hash providers, patterns, replacements,
or hash results throw TypeError.
Conversion contains ordinary Proxy inspection failures with markers. User callbacks can throw;
those errors reach the caller. A bounded shape does not prove that a privacy policy is complete.
TypeScript
import { createRedactor, type JsonValue } from '@bazariodev/winnow';
const redactor = createRedactor();
const result: JsonValue = redactor.redactValue(new Error('failed'));ESM and CommonJS declarations require only ES2022. No DOM or Node declaration package is needed.
License
MIT.
