GithubHelp home page GithubHelp logo

azu / restrict-javascript Goto Github PK

View Code? Open in Web Editor NEW
7.0 3.0 0.0 51 KB

Define restrict JavaScript syntax and validate it.

License: MIT License

TypeScript 100.00%
validation javascript ast safe subset

restrict-javascript's Introduction

restrict-javascript

Define restrict JavaScript syntax and validate it.

Motivation

This validation library aim to define limited JavaScript subset. That subset will be safe by default. Safe means that does not call any untrusted function.

Do

Validate following untrusted function calls and get errors.

alert("hello");
alert`hello`;
const a = alert;
a("hello");
const alertName = "alert";
window[alertName]("hello");

Following code is passed, because it is safe.

`text`;

Do Not

This validation does not provide sandbox feature. It means that the code can refer to any object like window by default. In other hands, __proto__ and construsctor is restricted by default.

This validation will be used with vm modules.

Install

Install with npm:

npm install restrict-javascript

Usage

This validation is used with Espree.

๐Ÿ“ Pass loc: true option to espree.parse function. It is needed to error position.

import { validateAST } from "restrict-javascript";
const espree = require("espree");
const untrustedJSCode = `
function add(x, y){
    return x + y
}

const total = add(1, 2);
`;
const AST = espree.parse(untrustedJSCode, {
    loc: true, // <= require `loc` option
    // Other options is optional
    ecmaVersion: 2015
});
const validationResult = validateAST(AST);
if (!validationResult.ok) {
    assert.deepStrictEqual(validationResult.errors, [
            {id: 'DISALLOW_NODE_TYPE', line: 2, column: 0}, // function
            {id: 'DISALLOW_NODE_TYPE', line: 6, column: 0}, // const
            {id: 'DISALLOW_NODE_TYPE', line: 6, column: 6}, // =
            {id: 'DISALLOW_UNTRUSTED_FUNCTION_CALL', line: 6, column: 14}, // add(1, 2)
            {id: 'DISALLOW_NODE_TYPE', line: 6, column: 14} //function call node
        ]
    )
}

Default Options

Default Config is very strict setting.

It aim to prevent to define untrusted function/variables and invoke untrusted functions.

  • Disallow any function/method/class call
    • includes normal function call, new expression, and Tagged Function call
  • Disallow any function/method/class declaration
    • NG: function, class, =>
  • Disallow any declaration variables
    • NG: use var, let, const
  • Disallow any assignment variables
    • NG: foo = "value";
  • Disallow lookup __proto__ and constructor property

Summary: Disallow to create functions and call functions, and lookup the above

You can add allow list by allow* option.

allowFunctionNames: string[]

This options allow calling specified function names.

Example: Allow String() and alert()

{
    allowFunctionNames: ["String", "alert"]
}

allowMethodNames: string[]

This options allow calling specified method names.

Example: Allow Math.random()

{
    allowMethodNames: ["Math.random"]
}

This options accept ? as place holder value. ? match any name.

Example: Allow "string".replace("a", "b"). ? match "string".

{
    allowMethodNames: ["?.replace"]
}

Note: method chain matching. You can match [].map().filter() by following options.

{
    allowMethodNames: ["?.map.filter"]
}

allowNodeTypes: string[]

This options allow to use specified ESTree.Node.

Default: allow safe Node types.

This options will be override default options. Be careful.

allowNodesIncludesChildren: ESTree.Node[]

This options allow node and node's children. Specify ESTree node object and match it partially.

This options allow especial patterns.

For example, You can allow new Date().getTime() signature by following options:

{
    allowNodesIncludesChildren: [
        {
            type: "ExpressionStatement",
            expression: {
                type: "CallExpression",
                callee: {
                    type: "MemberExpression",
                    object: {
                        type: "NewExpression",
                        callee: {
                            type: "Identifier",
                            name: "Date"
                        },
                        arguments: []
                    },
                    property: {
                        type: "Identifier",
                        name: "getTime"
                    },
                    computed: false
                },
                arguments: []
            }
        }
    ]
}

See also test/fixtures/ok.options.allowNodesIncludesChildren/

๐Ÿ“ Notice: This options force skip matched node, be careful treat!

Tips: AST explorer is useful for the options.

debug: boolean

Enable debug options. It is useful for debugging.

  • Add node property to each errors.

Changelog

See Releases page.

Running tests

Install devDependencies and Run npm test:

npm test

Contributing

Pull requests and stars are always welcome.

For bugs and feature requests, please create an issue.

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

Author

License

MIT ยฉ azu

restrict-javascript's People

Contributors

azu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.