Skip to content

Instantly share code, notes, and snippets.

@metanomial
Last active January 13, 2022 12:21
Show Gist options
  • Save metanomial/1ed83b001e5130d649f98bcae90a9e6c to your computer and use it in GitHub Desktop.
Save metanomial/1ed83b001e5130d649f98bcae90a9e6c to your computer and use it in GitHub Desktop.
const Ω = new Proxy(new WeakMap, {
set (weakmap, reference, input) {
const invocable = eval(reference);
if (typeof invocable != 'function') return;
weakmap.set(invocable,
Array.isArray(input)
? invocable(...input)
: invocable(input)
);
},
get (weakmap, reference) {
const invocable = eval(reference);
return weakmap.get(invocable);
},
deleteProperty (weakmap, reference) {
const invocable = eval(reference);
weakmap.delete(invocable);
},
has (weakmap, reference) {
const invocable = eval(reference);
return weakmap.has(invocable);
}
});
@zorgick
Copy link

zorgick commented Jan 13, 2022

That is actually a really interesting way of invoking functions. For example, not so long ago I was creating the service, that allowed the user to write the code and to execute it on our server. We were extracting data from many sources modifying it and storing it in our database according to the instructions from the user code.

The problem is the security. Lots of data, lots of users, big companies yada yada... Which we solved by creating a JSON lexer that extended JSON schema with allowed functions. Our lexer parsed this json and built an AST tree of functions in a correct order with a white-list of functions.

Your way makes the use of a JSON and parsing it redundant and unnecessary. Now we can use this Proxy, define a white list of functions and let Ω invoke and execute the code. The user writes the js file using only types and data structures (with no prototypes). Brilliant! Any other functions are inaccessible because this "user instructions" file will be loaded in a sandboxed environment, where Environment Object is empty and has only Ω in it. The order of the execution can be achieved by another Ω util function like in https://docs.mongodb.com/manual/meta/aggregation-quick-reference/

You have a nice idea of using modern features of JS! 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment