Escape string from remote file to prevent script injection

The Review of my add-on arrived and I got the comment
“the ... line ... seems to create a script from strings with dynamic parameters and it looks like these are coming from a remote file. Given the dynamic parameters are not escaped script injection could occur. Please make sure the values are escaped.“

Can anyone tell me how to escape these parameters in a secure way? Is there a single JS-Function to call?

Here is some comparable code:

var jsCode = "var injectObject = new Object();" +
"injectObject .valueToInject = '" + valueFromRemoteFile + "';";
browser.tabs.executeScript(tabId, {code: jsCode });
1 Like

This should be ok:

const jsonValue = JSON.stringify(valueFromRemoteFile);
var jsCode = `var injectObject = { };
injectObject .valueToInject = JSON.parse("${ jsonValue }");`;
browser.tabs.executeScript(tabId, {code: jsCode });
2 Likes

Thanks. It looks very good. :+1:

For someone with a similar problem:
You had to be very careful with the quotes.
Here is my code:

var valueFromRemoteFile = "test";
var jsCode = "var injectObject = {}; injectObject.valueToInject = JSON.parse('" + JSON.stringify(valueFromRemoteFile) + "');";
console.log(jsCode);

And here is the output

var injectObject = {}; injectObject.valueToInject = JSON.parse('"test"');

Indeed, an oversight by me. One should not quote the jsonValue, and also not call JSON.parse.

const jsonValue = JSON.stringify(valueFromRemoteFile);
var jsCode = `var injectObject = { };
injectObject .valueToInject = ${ jsonValue };`;
browser.tabs.executeScript(tabId, {code: jsCode });

Since we know that jsonValue is in fact valid JSON, it is ok to directly paste it into the code.
(Your solution would break if the string is for example "a ' single quote").

On a site note: If you work with code that needs to be evaluated in a different context, you can also do this:

const jsonValue = JSON.stringify(valueFromRemoteFile);
var jsCode = '('+ function(valueToInject ) {
    const injectObject = { valueToInject, };
    return injectObject;
} +`)(${ jsonValue });`
browser.tabs.executeScript(tabId, {code: jsCode });

This way you get syntax highlighting and linting for your code, if you’ve set that up.

2 Likes

You’re right.

Thanks for your help.