Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions src/api/environment.cc
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ Environment* CreateEnvironment(
CHECK(!context.IsEmpty());
Context::Scope context_scope(context);

if (InitializeContextRuntime(context).IsNothing()) {
if (InitializeContextRuntime(context, isolate_data).IsNothing()) {
FreeEnvironment(env);
return nullptr;
}
Expand Down Expand Up @@ -669,11 +669,12 @@ MaybeLocal<Object> GetPerContextExports(Local<Context> context,
// InitializeContext, because embedders don't necessarily
// call NewContext and so they will experience breakages.
Local<Context> NewContext(Isolate* isolate,
Local<ObjectTemplate> object_template) {
Local<ObjectTemplate> object_template,
IsolateData* isolate_data) {
auto context = Context::New(isolate, nullptr, object_template);
if (context.IsEmpty()) return context;

if (InitializeContext(context).IsNothing()) {
if (InitializeContext(context, isolate_data).IsNothing()) {
return Local<Context>();
}

Expand All @@ -686,7 +687,8 @@ void ProtoThrower(const FunctionCallbackInfo<Value>& info) {

// This runs at runtime, regardless of whether the context
// is created from a snapshot.
Maybe<void> InitializeContextRuntime(Local<Context> context) {
Maybe<void> InitializeContextRuntime(Local<Context> context,
IsolateData* isolate_data) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope handle_scope(isolate);

Expand All @@ -698,6 +700,18 @@ Maybe<void> InitializeContextRuntime(Local<Context> context) {
// to the runtime flags, propagate the value to the embedder data.
bool is_code_generation_from_strings_allowed =
Copy link
Member

@legendecas legendecas Nov 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The V8Option{} is removed in node_options.cc for --disallow-code-generation-from-strings, this will always be true. Because the flag is not set in V8.

context->IsCodeGenerationFromStringsAllowed();

// Check if the Node.js option --disallow-code-generation-from-strings is set
// Use the isolate-specific options if available, otherwise use per_process
bool disallow_codegen = isolate_data
? isolate_data->options()->disallow_code_generation_from_strings
: per_process::cli_options->per_isolate
->disallow_code_generation_from_strings;

if (disallow_codegen) {
is_code_generation_from_strings_allowed = false;
}

context->AllowCodeGenerationFromStrings(false);
context->SetEmbedderData(
ContextEmbedderIndex::kAllowCodeGenerationFromStrings,
Expand Down Expand Up @@ -921,12 +935,13 @@ Maybe<void> InitializePrimordials(Local<Context> context,
}

// This initializes the main context (i.e. vm contexts are not included).
Maybe<bool> InitializeContext(Local<Context> context) {
Maybe<bool> InitializeContext(Local<Context> context,
IsolateData* isolate_data) {
if (InitializeMainContextForSnapshot(context).IsNothing()) {
return Nothing<bool>();
}

if (InitializeContextRuntime(context).IsNothing()) {
if (InitializeContextRuntime(context, isolate_data).IsNothing()) {
return Nothing<bool>();
}
return Just(true);
Expand Down
7 changes: 5 additions & 2 deletions src/node.h
Original file line number Diff line number Diff line change
Expand Up @@ -565,11 +565,14 @@ NODE_EXTERN v8::Isolate* NewIsolate(
NODE_EXTERN v8::Local<v8::Context> NewContext(
v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> object_template =
v8::Local<v8::ObjectTemplate>());
v8::Local<v8::ObjectTemplate>(),
IsolateData* isolate_data = nullptr);

// Runs Node.js-specific tweaks on an already constructed context
// Return value indicates success of operation
NODE_EXTERN v8::Maybe<bool> InitializeContext(v8::Local<v8::Context> context);
NODE_EXTERN v8::Maybe<bool> InitializeContext(
v8::Local<v8::Context> context,
IsolateData* isolate_data = nullptr);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jasnell I think this likely incorrect. Can you recommend a different implementation?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mcollina You can look up the current Environment from a Local<Context> via Environment::GetCurrent(), and then use env->isolate_data(); no need to pass this parameter separately

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@addaleax Unfortunately, Environment::GetCurrent() doesn't work in this scenario because InitializeContextRuntime is called during context initialization, before the Environment is created and attached to the context.

The call flow for workers is:

  1. Context::FromSnapshot() or Context::New() creates the V8 context
  2. InitializeContextRuntime(context) is called to set up Node.js-specific runtime settings
  3. At this point, Environment::GetCurrent(context) returns nullptr because the Environment hasn't been created yet
  4. Later, Environment is created and attached to the context


// If `platform` is passed, it will be used to register new Worker instances.
// It can be `nullptr`, in which case creating new Workers inside of
Expand Down
2 changes: 1 addition & 1 deletion src/node_contextify.cc
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ ContextifyContext* ContextifyContext::New(Local<Context> v8_context,
// only initialized when needed because even deserializing them slows
// things down significantly and they are only needed in rare occasions
// in the vm contexts.
if (InitializeContextRuntime(v8_context).IsNothing()) {
if (InitializeContextRuntime(v8_context, env->isolate_data()).IsNothing()) {
return {};
}

Expand Down
3 changes: 2 additions & 1 deletion src/node_internals.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,8 @@ std::string GetHumanReadableProcessName();

v8::Maybe<void> InitializeBaseContextForSnapshot(
v8::Local<v8::Context> context);
v8::Maybe<void> InitializeContextRuntime(v8::Local<v8::Context> context);
v8::Maybe<void> InitializeContextRuntime(v8::Local<v8::Context> context,
IsolateData* isolate_data);
v8::Maybe<void> InitializePrimordials(v8::Local<v8::Context> context,
IsolateData* isolate_data);
v8::MaybeLocal<v8::Object> InitializePrivateSymbols(
Expand Down
2 changes: 1 addition & 1 deletion src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1172,7 +1172,7 @@ PerIsolateOptionsParser::PerIsolateOptionsParser(
kAllowedInEnvvar);
AddOption("--disallow-code-generation-from-strings",
"disallow eval and friends",
V8Option{},
&PerIsolateOptions::disallow_code_generation_from_strings,
kAllowedInEnvvar);
AddOption("--jitless",
"disable runtime allocation of executable memory",
Expand Down
1 change: 1 addition & 0 deletions src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ class PerIsolateOptions : public Options {
std::string max_old_space_size;
int64_t stack_trace_limit = 10;
std::string report_signal = "SIGUSR2";
bool disallow_code_generation_from_strings = false;
bool build_snapshot = false;
std::string build_snapshot_config;
inline EnvironmentOptions* get_per_env_options();
Expand Down
5 changes: 3 additions & 2 deletions src/node_worker.cc
Original file line number Diff line number Diff line change
Expand Up @@ -352,13 +352,14 @@ void Worker::Run() {
SnapshotData::kNodeBaseContextIndex)
.ToLocalChecked();
if (!context.IsEmpty() &&
!InitializeContextRuntime(context).IsJust()) {
!InitializeContextRuntime(context, data.isolate_data_.get()).IsJust()) {
context = Local<Context>();
}
} else {
Debug(
this, "Worker %llu builds context from scratch\n", thread_id_.id);
context = NewContext(isolate_);
context = NewContext(isolate_, Local<ObjectTemplate>(),
data.isolate_data_.get());
}
if (context.IsEmpty()) {
// TODO(joyeecheung): maybe this should be kBootstrapFailure instead?
Expand Down
76 changes: 76 additions & 0 deletions test/parallel/test-worker-disallow-code-generation-from-strings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const { Worker } = require('worker_threads');

// Test that --disallow-code-generation-from-strings can be passed to workers
// and properly blocks eval() and related code generation functions.

// Test 1: Worker with --disallow-code-generation-from-strings should block eval
{
const worker = new Worker(`
const { parentPort } = require('worker_threads');
try {
eval('"test"');
parentPort.postMessage({ evalBlocked: false });
} catch (err) {
parentPort.postMessage({ evalBlocked: true, errorName: err.name });
}
`, {
eval: true,
execArgv: ['--disallow-code-generation-from-strings']
});

worker.on('message', common.mustCall((msg) => {
assert.strictEqual(msg.evalBlocked, true);
assert.strictEqual(msg.errorName, 'EvalError');
}));

worker.on('error', common.mustNotCall());
}

// Test 2: Worker without the flag should allow eval
{
const worker = new Worker(`
const { parentPort } = require('worker_threads');
try {
const result = eval('"test"');
parentPort.postMessage({ evalBlocked: false, result });
} catch (err) {
parentPort.postMessage({ evalBlocked: true });
}
`, {
eval: true,
execArgv: []
});

worker.on('message', common.mustCall((msg) => {
assert.strictEqual(msg.evalBlocked, false);
assert.strictEqual(msg.result, 'test');
}));

worker.on('error', common.mustNotCall());
}

// Test 3: Verify the flag also blocks Function constructor
{
const worker = new Worker(`
const { parentPort } = require('worker_threads');
try {
new Function('return 42')();
parentPort.postMessage({ functionBlocked: false });
} catch (err) {
parentPort.postMessage({ functionBlocked: true, errorName: err.name });
}
`, {
eval: true,
execArgv: ['--disallow-code-generation-from-strings']
});

worker.on('message', common.mustCall((msg) => {
assert.strictEqual(msg.functionBlocked, true);
assert.strictEqual(msg.errorName, 'EvalError');
}));

worker.on('error', common.mustNotCall());
}