you may already know that string interpolation attacks are an extremely common vulnerability. did you know that you can make custom template string functions in js to handle safe interpolation for you?
function path(strings: TemplateStringsArray, ...values: any[]): string {
return String.raw({ raw: strings }, ...values.map(encodeURIComponent));
}
for (const x of ["foo", "bar", "/", "../../hacker"]) {
console.log(path`/base-path/goes/here/${x}`);
}
/*
/base-path/goes/here/foo
/base-path/goes/here/bar
/base-path/goes/here/%2F
/base-path/goes/here/..%2F..%2Fhacker
*/syntax highlighting by codehost
you could even abstract this pretty easily by making it a higher order function that takes an escaper function, so you could make this for any kind of string you need to safely inject content into...
type StringTemplateFunction = (
strings: TemplateStringsArray,
...values: any[]
) => string;
function createSafeInterpolator(
interpolator: (value: any) => string
): StringTemplateFunction {
return function safeInterpolator(strings, ...values) {
return String.raw({ raw: strings }, ...values.map((v) => interpolator(v)));
};
}
const path = createSafeInterpolator(encodeURIComponent);
for (const x of ["foo", "bar", "/", "../../hacker"]) {
console.log(path`/base-path/goes/here/${x}`);
}
syntax highlighting by codehost
