Skip to content

Instantly share code, notes, and snippets.

@rbonestell
Last active February 7, 2024 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbonestell/b421cd21d168a91e0958da43773b9900 to your computer and use it in GitHub Desktop.
Save rbonestell/b421cd21d168a91e0958da43773b9900 to your computer and use it in GitHub Desktop.
JS/TS Redact Specific Fields From Object: Prototype Pollution?
/* eslint-disable @typescript-eslint/no-explicit-any */
export function redactSpecifiedProperties(target: any, fields: string[], redactedMessage = 'REDACTED'): any {
// Return if target is not a redactable datatype or no redactable fields were provided
if (!target || typeof target !== 'object' || fields?.length === 0) {
return target;
}
// Iterate through all items in an array
if (Array.isArray(target)) {
return target.map(item => redactSpecifiedProperties(item, fields, redactedMessage));
} else {
const result: { [key: string]: any } = {};
for (const key in target) {
// Ensure the key is an own property and not from the prototype chain
if (Object.prototype.hasOwnProperty.call(target, key)) {
let value = target[key];
if (typeof value === 'object') {
value = redactSpecifiedProperties(value, fields, redactedMessage);
} else if (fields.includes(key)) {
value = `[${redactedMessage}]`;
}
result[key] = value;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment