Skip to content

Instantly share code, notes, and snippets.

@joekiller
Last active September 28, 2022 05:40
Show Gist options
  • Save joekiller/9613007a67a835d97069fd9b9b34bb8b to your computer and use it in GitHub Desktop.
Save joekiller/9613007a67a835d97069fd9b9b34bb8b to your computer and use it in GitHub Desktop.
Strip token secrets in javascript
/**
* Very useful for pumping through logs that you don't want to leak stuff.
* @param {string} [target] string to scrub
* @param {(string | RegExp)[]} tokens to be scrubbed, regex match or exact string match
*/
function scrubString(target, tokens) {
if(!target || !tokens || tokens.length === 0) {
return;
}
let scrubbed = target;
tokens.forEach(token => {
let match, matches;
if (typeof token === "string") {
matches = [token];
} else {
match = token;
matches = target.match(match);
if(!matches) {
return target;
}
}
matches.forEach(replace => {
const replacement = [replace.slice(0, 2), replace.slice(2, replace.length - 2).replace(/./ig, '*'), replace.slice(replace.length - 2)].join('');
scrubbed = scrubbed.replace(replace, replacement)
});
})
return scrubbed;
}
let stripToken = /(?<=token":\s*")[^"]*(?=")/gm;
let testStr = '{"my_token":"issooooooooSecret"}';
scrubString(testStr, [stripToken]) === '{"my_token":"is*************et"}'
console.log(scrubString(testStr, [stripToken]));
testStr = '{"my_token":"WHATABOUTTHISYO", "and_token": "thisonetoo"}';
scrubString(testStr, [stripToken]) === '{"my_token":"is*************et", "and_token": "th******oo"}'
console.log(scrubString(testStr, [stripToken]));
testStr = '{"my_token":"WHATABOUTTHISYO"}';
stripToken = "WHATABOUTTHISYO"
scrubString(testStr, [stripToken]) === '{"my_token":"WH***********YO"}'
console.log(scrubString(testStr, [stripToken]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment