Skip to content

Latest commit

 

History

History
58 lines (47 loc) · 2.83 KB

README.md

File metadata and controls

58 lines (47 loc) · 2.83 KB

evalish

A maybe slightly safer-ish wrapper around eval Function constructors

Please maybe try something else first.. Please.


NPM Version License Minified gzip size

evalish is a small helper library that only exports a wrapper for the Function constructor: SafeFunction.

The SafeFunction constructor allows you to evaluate code and dynamically create a new function. In most environments, which at least don't have their CSP configured to disallow this, this will give you a fully executable function based on a string. As Function by default is a little safer than eval and runs everything in the global context, SafeFunction goes a step further and attempts to isolate the environment as much as possible.

It only does three simple things:

  • Isolate the global object and uses a separate object using a with statement
  • Wraps all passed through globals, like Array, in a recursive masking object that disallows access to object prototype properties
  • In the browser: Creates an iframe element and uses that frame's globals instead to prvent prototype pollution.

If you haven't run away screaming yet, maybe that's what you're looking for. Just a bit more safety. But really, I wrote this just for fun and I haven't written any tests yet and neither have I tested all edge cases. The export being named SafeFunction is really just ambitious.

However, if you found a way to break out of SafeFunction and did something to the outside JS environment, let me know and file an issue. I'm curious to see how far evalish would have to go to fully faux-isolate eval'ed code!

Usage

First install evalish alongside react:

yarn add evalish
# or
npm install --save evalish

You'll then be able to import SafeFunction and pass it argument names and code, just like the regular Function constructor.

import { SafeFunction } from 'evalish';

new SafeFunction('a', 'b', 'return a + b')(1, 2); // returns `3`
new SafeFunction('return window')(); // returns `undefined`
new SafeFunction('return Array.isArray.constructor')(); // returns `undefined`