Skip to content

Commit

Permalink
Add Options extension method for DisableStringCompilation (#1498)
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Mar 16, 2023
1 parent fbaad9f commit 6333d28
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
8 changes: 5 additions & 3 deletions Jint.Tests/Runtime/EngineTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2890,14 +2890,16 @@ public void CanDisableCompilation()
{
var engine = new Engine(options =>
{
options.StringCompilationAllowed = false;
options.DisableStringCompilation();
});

const string ExpectedExceptionMessage = "String compilation has been disabled in engine options";

var ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("eval('1+1');"));
Assert.Equal("String compilation is not allowed", ex.Message);
Assert.Equal(ExpectedExceptionMessage, ex.Message);

ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("new Function('1+1');"));
Assert.Equal("String compilation is not allowed", ex.Message);
Assert.Equal(ExpectedExceptionMessage, ex.Message);
}

[Fact]
Expand Down
10 changes: 10 additions & 0 deletions Jint/Options.Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,16 @@ public static Options LocalTimeZone(this Options options, TimeZoneInfo timeZoneI
return options;
}

/// <summary>
/// Disables calling 'eval' with custom code and function constructors taking function code as string.
/// By default eval and function code parsing is allowed.
/// </summary>
public static Options DisableStringCompilation(this Options options, bool disable = true)
{
options.StringCompilationAllowed = !disable;
return options;
}

public static Options AddExtensionMethods(this Options options, params Type[] types)
{
options.Interop.ExtensionMethodTypes.AddRange(types);
Expand Down
2 changes: 1 addition & 1 deletion Jint/Runtime/Host.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public virtual void EnsureCanCompileStrings(Realm callerRealm, Realm evalRealm)
{
if (!Engine.Options.StringCompilationAllowed)
{
ExceptionHelper.ThrowJavaScriptException(callerRealm.Intrinsics.TypeError, "String compilation is not allowed");
ExceptionHelper.ThrowJavaScriptException(callerRealm.Intrinsics.TypeError, "String compilation has been disabled in engine options");
}
}

Expand Down

0 comments on commit 6333d28

Please sign in to comment.