Use Case
I need to run some user submitted JavaScript which will interact with an API object that only contains data and API functions. I am expecting simple linear logic from user submitted code which will only use data provided by the API object as input and will write output to the API object as well.
My Plan
const userSubmittedCode = //get it from somewhere
// If user code contains keywords like 'this', 'prototype', 'constructor', etc, do not continue.
// (Basically anything that the user won't need but seems dangerous)
const callUserCode = Function(
"apiObject",
"const globalThis = window = document = {}; // + anything I want to hide" + userSubmittedCode);
callUserCode(myAPIObject);
// Do things according to myAPIObject's internal state.
I am not super familiar with JavaScript and am not sure if this is sufficient (don't really care about memory exhaustion and timeout attacks right now). Any thoughts would be welcome.
Thanks in advance.
You can store the keywords which you don't want the string to contain in an array, and use Array.some to check whether the string contains one of the items:
const bannedKeywords = ['this', 'prototype', 'constructor']
function isSafe(str){
return !bannedKeywords.some(e => str.includes(e))
}
console.log(isSafe('a'))
console.log(isSafe('this'))