Skip to content

Instantly share code, notes, and snippets.

@jamesholcomb
Last active March 2, 2022 15:25
Show Gist options
  • Save jamesholcomb/8d3ec81b02482c1cb134e79d75134e02 to your computer and use it in GitHub Desktop.
Save jamesholcomb/8d3ec81b02482c1cb134e79d75134e02 to your computer and use it in GitHub Desktop.
Deeply traverse an object to replace or redact values using a regex and replacer function
export const assignDeep = (input, regex, replacer) => {
const json = JSON.stringify(input)
return JSON.parse(json, (k, v) =>
typeof v === "string" && regex.test(k) ? replacer(v) : v
)
}
export const redactDeep = (input, regex) =>
assignDeep(input, regex, () => "[REDACTED]")
export const redactEllipsisDeep = (input, regex, minLength = 15) =>
assignDeep(input, regex, (val) => {
if (val.length <= minLength) {
return "..."
}
const start = val.slice(0, 3)
const end = val.slice(val.length - 3, val.length)
return `${start}...${end}`
})
const obj = {
x: 1,
y: 2,
api_key: "hideme",
f: (arg) => ({ x: 1}),
a: [{
z: 1,
accessToken: "23u42u3i4kj3k4j2l3kj4",
refreshToken: "4n53l4kj5kj4lk5j3lk4j5l3k4j5lk3j4",
}],
superSecret: "secret",
}
const result = assign(obj, /key|secret|token/i, (val) => "[REDACTED]")
/*
{ x: 1, 
y: 2, 
api_key: '[REDACTED]', 
a: [ { z: 1, accessToken: '[REDACTED]', refreshToken: '[REDACTED]' } ], 
superSecret: '[REDACTED]' }
*/
@jamesholcomb
Copy link
Author

Useful for redacting secrets, api keys and tokens during logging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment