Last active
February 7, 2024 18:13
-
-
Save rbonestell/b421cd21d168a91e0958da43773b9900 to your computer and use it in GitHub Desktop.
JS/TS Redact Specific Fields From Object: Prototype Pollution?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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