diff --git a/src/api/environment.cc b/src/api/environment.cc index b82324484da2c8..e50ca1f0ea267f 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -67,15 +67,13 @@ MaybeLocal PrepareStackTraceCallback(Local context, if (env == nullptr) { return exception->ToString(context).FromMaybe(Local()); } - Realm* current_realm = Realm::GetCurrent(context); + Realm* realm = Realm::GetCurrent(context); Local prepare; - if (current_realm != nullptr && - current_realm->kind() != Realm::Kind::kPrincipal) { - // If we are in a Realm that is not the principal Realm (e.g. ShadowRealm), - // call the realm specific prepareStackTrace callback to avoid passing the - // JS objects (the exception and trace) across the realm boundary with the - // `Error.prepareStackTrace` override. - prepare = current_realm->prepare_stack_trace_callback(); + if (realm != nullptr) { + // If we are in a Realm, call the realm specific prepareStackTrace callback + // to avoid passing the JS objects (the exception and trace) across the + // realm boundary with the `Error.prepareStackTrace` override. + prepare = realm->prepare_stack_trace_callback(); } else { // The context is created with ContextifyContext, call the principal // realm's prepareStackTrace callback. diff --git a/src/node_shadow_realm.cc b/src/node_shadow_realm.cc index 197cfb35c0a193..95a48ba3ff0934 100644 --- a/src/node_shadow_realm.cc +++ b/src/node_shadow_realm.cc @@ -4,7 +4,6 @@ namespace node { namespace shadow_realm { using v8::Context; -using v8::EscapableHandleScope; using v8::HandleScope; using v8::Local; using v8::MaybeLocal; diff --git a/test/parallel/test-shadow-realm-prepare-stack-trace.js b/test/parallel/test-shadow-realm-prepare-stack-trace.js index 0c681c12beaa7e..2460f017ee91b3 100644 --- a/test/parallel/test-shadow-realm-prepare-stack-trace.js +++ b/test/parallel/test-shadow-realm-prepare-stack-trace.js @@ -4,6 +4,12 @@ require('../common'); const assert = require('assert'); +let principalRealmPrepareStackTraceCalled = false; +Error.prepareStackTrace = (error, trace) => { + principalRealmPrepareStackTraceCalled = true; + return `${String(error)}\n at ${trace.join('\n at ')}`; +}; + { // Validates inner Error.prepareStackTrace can not leak into the outer realm. const shadowRealm = new ShadowRealm(); @@ -11,7 +17,7 @@ const assert = require('assert'); const stack = shadowRealm.evaluate(` Error.prepareStackTrace = (error, trace) => { globalThis.leaked = 'inner'; - return String(error); + return 'from shadow realm'; }; try { @@ -20,7 +26,8 @@ try { e.stack; } `); - assert.strictEqual(stack, 'Error: boom'); + assert.ok(!principalRealmPrepareStackTraceCalled); + assert.strictEqual(stack, 'from shadow realm'); assert.strictEqual('leaked' in globalThis, false); } @@ -39,6 +46,7 @@ try { e.stack; } `); + assert.ok(!principalRealmPrepareStackTraceCalled); const lines = stack.split('\n'); assert.strictEqual(lines[0], 'Error: boom'); assert.match(lines[1], /^ {4}at myFunc \(.*\)/);