Log Scrubber Redacting Secret Values
A structured log scrubber that masks known secret keys and bearer tokens before serialization, without mutating the original object.
Code
export const REDACTED = "[REDACTED]";
const DEFAULT_SECRET_KEYS = new Set([
"password",
"passwd",
"secret",
"token",
"accessToken",
"refreshToken",
"apiKey",
"authorization",
]);
const BEARER_RE = /(Bearer\s+)[A-Za-z0-9._~+/-]+=*/g;
function maskString(value) {
return value.replace(BEARER_RE, "$1" + REDACTED);
}
export function scrub(value, options = {}) {
const secretKeys = new Set([...DEFAULT_SECRET_KEYS, ...(options.extraKeys ?? [])]);
const seen = new WeakMap();
function walk(node) {
if (node === null || typeof node !== "object") {
return typeof node === "string" ? maskString(node) : node;
}
if (seen.has(node)) return seen.get(node);
if (Array.isArray(node)) {
const copy = [];
seen.set(node, copy);
for (const item of node) copy.push(walk(item));
return copy;
}
const copy = {};
seen.set(node, copy);
for (const [key, val] of Object.entries(node)) {
copy[key] = secretKeys.has(key) ? REDACTED : walk(val);
}
return copy;
}
return walk(value);
}Logging a whole request object leaks tokens and passwords into log storage, where they live forever and are readable by anyone with log access.
Use case: engineers logging request payloads that may carry credentials
Inputs / outputs
- Input: any value (object, array or scalar) plus an optional key denylist
- Output: a deep copy with secret values replaced by a redaction marker
Error conditions
- value contains cycles (handled via seen map)
- custom denylist keys
- bearer tokens inside strings
Approach
walk the structure; keys matching the denylist have values replaced; string values matching a bearer pattern are masked in place; cycles are tracked with a WeakMap.
Implementation
export const REDACTED = "[REDACTED]";
const DEFAULT_SECRET_KEYS = new Set([
"password",
"passwd",
"secret",
"token",
"accessToken",
"refreshToken",
"apiKey",
"authorization",
]);
const BEARER_RE = /(Bearer\s+)[A-Za-z0-9._~+/-]+=*/g;
function maskString(value) {
return value.replace(BEARER_RE, "$1" + REDACTED);
}
export function scrub(value, options = {}) {
const secretKeys = new Set([...DEFAULT_SECRET_KEYS, ...(options.extraKeys ?? [])]);
const seen = new WeakMap();
function walk(node) {
if (node === null || typeof node !== "object") {
return typeof node === "string" ? maskString(node) : node;
}
if (seen.has(node)) return seen.get(node);
if (Array.isArray(node)) {
const copy = [];
seen.set(node, copy);
for (const item of node) copy.push(walk(item));
return copy;
}
const copy = {};
seen.set(node, copy);
for (const [key, val] of Object.entries(node)) {
copy[key] = secretKeys.has(key) ? REDACTED : walk(val);
}
return copy;
}
return walk(value);
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { REDACTED, scrub } from "./example.mjs";
test("redacts denylisted keys at any depth", () => {
const out = scrub({ user: "ada", credentials: { password: "hunter2", token: "abc" } });
assert.deepEqual(out, {
user: "ada",
credentials: { password: REDACTED, token: REDACTED },
});
});
test("masks bearer tokens inside strings", () => {
const out = scrub({ note: "Authorization: Bearer abc.def.ghi done" });
assert.equal(out.note, "Authorization: Bearer " + REDACTED + " done");
});
test("does not mutate the original object", () => {
const input = { password: "keep-me" };
const out = scrub(input);
assert.equal(input.password, "keep-me");
assert.equal(out.password, REDACTED);
assert.notEqual(out, input);
});
test("supports extra keys and handles cycles", () => {
const cyclic = { label: "root" };
cyclic.self = cyclic;
cyclic.internalId = "id-1";
const out = scrub(cyclic, { extraKeys: ["internalId"] });
assert.equal(out.internalId, REDACTED);
assert.equal(out.self, out);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node example.mjs
Limitations and error handling
pattern based only; cannot detect secrets in unusual encodings; no key allowlist.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.