/JavetSanitizer

A JavaScript sanitizer framework for parsing and validating JavaScript code on JVM.

Primary LanguageJavaApache License 2.0Apache-2.0

Javet Sanitizer

This project is archived. All features are moved to swc4j. Please review Hello Swc4j, Goodbye Antlr for more details.

Maven Central Discord Donate

Build

Javet Sanitizer is a sanitizer framework for parsing and validating JavaScript code on JVM. It is built on top of antlr4 and grammars-v4.

Javet Sanitizer provides a set of rich checkers at AST level for Javet so that applications can address and eliminate the potential threats before the JavaScript code is executed.

Why do I need to sanitize the JavaScript code?

A script engine like Javet can be shared by multiple scripts, however one script may tamper the script engine to hack the next script to be executed. For instance, the built-in JSON can be hijacked so that stringify, parse may work improperly during the JSON serialization or deserialization.

Javet Sanitizer is designed to protect the script engine from that kind of attacks.

Why not use Babel?

  • Babel is too slow.
  • Babel AST cannot be easily imported to JVM.

Features

Quick Start

  • Follow the installation to set up the project dependency.
  • Create a Java file as follows.
public static void main(String[] args) {
    JavetSanitizerStatementListChecker checker = new JavetSanitizerStatementListChecker();

    // 1. Check if keyword const can be used.
    String codeString = "const a = 1;";
    try {
        checker.check(codeString);
        System.out.println("1. " + codeString + " // Valid.");
    } catch (JavetSanitizerException ignored) {
    }

    // 2. Check if keyword var can be used.
    codeString = "var a = 1;";
    try {
        checker.check(codeString);
    } catch (JavetSanitizerException e) {
        System.out.println("2. " + codeString + " // Invalid: " + e.getMessage());
    }

    // 3. Check if Object is mutable.
    codeString = "Object = {};";
    try {
        checker.check(codeString);
    } catch (JavetSanitizerException e) {
        System.out.println("3. " + codeString + " // Invalid: " + e.getMessage());
    }
}
  • The output is as follows.
1. const a = 1; // Valid.
2. var a = 1; // Invalid: Keyword var is not allowed.
3. Object = {}; // Invalid: Identifier Object is not allowed.

Blog

Document

License

APACHE LICENSE, VERSION 2.0