diff --git a/lib/v8.js b/lib/v8.js index 6ae1d2c8ee65..909f7fd2f8e4 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -46,7 +46,12 @@ const { const { Serializer, Deserializer, + setTreatDOMExceptionsAsHostObjects, } = internalBinding('serdes'); +const { + messaging_clone_symbol, + messaging_deserialize_symbol, +} = internalBinding('symbols'); const { namespace: startupSnapshot, } = require('internal/v8/startup_snapshot'); @@ -74,6 +79,7 @@ const { }, } = require('internal/errors'); const { inspect } = require('internal/util/inspect'); +const { isNativeError } = require('internal/util/types'); const { FastBuffer } = require('internal/buffer'); const { getValidatedPath } = require('internal/fs/utils'); const { @@ -451,6 +457,9 @@ function arrayBufferViewIndexToType(index) { } const kX509CertificateHostObject = 14; +const kDOMExceptionHostObject = 15; +const kDOMExceptionSubtype = 0; +const kQuotaExceededErrorSubtype = 1; let x509Serialization; function getX509Serialization() { @@ -458,11 +467,102 @@ function getX509Serialization() { return x509Serialization; } +function writeDOMExceptionString(serializer, str) { + const buf = Buffer.from(str, 'utf8'); + serializer.writeUint32(buf.byteLength); + serializer.writeRawBytes(buf); +} + +function writeDOMExceptionNullableDouble(serializer, value) { + if (value === null) { + serializer.writeUint32(0); + } else { + serializer.writeUint32(1); + serializer.writeDouble(value); + } +} + +// Follows the DOMException serialization steps in +// https://webidl.spec.whatwg.org/#idl-DOMException, carrying the same data +// as structuredClone(). +function writeDOMException(serializer, obj) { + const { data, deserializeInfo } = obj[messaging_clone_symbol](); + let subtype; + if (deserializeInfo === + 'internal/worker/clone_dom_exception:DOMException') { + subtype = kDOMExceptionSubtype; + } else if (deserializeInfo === + 'internal/worker/clone_dom_exception:QuotaExceededError') { + subtype = kQuotaExceededErrorSubtype; + } else { + throw new serializer._getDataCloneError( + `Unserializable host object: ${inspect(obj)}`); + } + serializer.writeUint32(kDOMExceptionHostObject); + serializer.writeUint32(subtype); + writeDOMExceptionString(serializer, data.name); + writeDOMExceptionString(serializer, data.message); + if (typeof data.stack === 'string') { + serializer.writeUint32(1); + writeDOMExceptionString(serializer, data.stack); + } else { + serializer.writeUint32(0); + } + if (subtype === kQuotaExceededErrorSubtype) { + writeDOMExceptionNullableDouble(serializer, data.quota); + writeDOMExceptionNullableDouble(serializer, data.requested); + } +} + +function readDOMExceptionString(deserializer) { + const length = deserializer.readUint32(); + return deserializer.readRawBytes(length).toString('utf8'); +} + +function readDOMExceptionNullableDouble(deserializer) { + return deserializer.readUint32() === 0 ? null : deserializer.readDouble(); +} + +function readDOMException(deserializer) { + const subtype = deserializer.readUint32(); + if (subtype !== kDOMExceptionSubtype && + subtype !== kQuotaExceededErrorSubtype) { + throw new ERR_INVALID_STATE('Invalid serialized DOMException'); + } + const name = readDOMExceptionString(deserializer); + const message = readDOMExceptionString(deserializer); + const stack = deserializer.readUint32() === 0 ? + undefined : readDOMExceptionString(deserializer); + const { + DOMException, + QuotaExceededError, + } = require('internal/worker/clone_dom_exception'); + let instance; + let quota; + let requested; + if (subtype === kQuotaExceededErrorSubtype) { + quota = readDOMExceptionNullableDouble(deserializer); + requested = readDOMExceptionNullableDouble(deserializer); + instance = new QuotaExceededError(); + } else { + instance = new DOMException(); + } + instance[messaging_deserialize_symbol]({ + name, + message, + stack, + quota, + requested, + }); + return instance; +} + class DefaultSerializer extends Serializer { constructor() { super(); this._setTreatArrayBufferViewsAsHostObjects(true); + setTreatDOMExceptionsAsHostObjects(this); } /** @@ -479,6 +579,11 @@ class DefaultSerializer extends Serializer { // serialization. Because a) those may contain sensitive data and the user // may not be aware of that and b) they are often much larger than the // `Buffer` itself, custom serialization is applied. + if (isNativeError(abView)) { + // Only DOMException-like errors are reported as host objects. + writeDOMException(this, abView); + return; + } if (!ArrayBufferIsView(abView) && hasOpenSSL) { const { getX509CertificateSnapshot, @@ -520,6 +625,9 @@ class DefaultDeserializer extends Deserializer { */ _readHostObject() { const typeIndex = this.readUint32(); + if (typeIndex === kDOMExceptionHostObject) { + return readDOMException(this); + } if (typeIndex === kX509CertificateHostObject) { const count = this.readUint32(); if (!hasOpenSSL || count === 0) { diff --git a/src/node_serdes.cc b/src/node_serdes.cc index 00fcd4b6afcc..c78375b790e7 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -39,11 +39,15 @@ class SerializerContext : public BaseObject, void ThrowDataCloneError(Local message) override; Maybe WriteHostObject(Isolate* isolate, Local object) override; + bool HasCustomHostObject(Isolate* isolate) override { return true; } + Maybe IsHostObject(Isolate* isolate, Local object) override; Maybe GetSharedArrayBufferId( Isolate* isolate, Local shared_array_buffer) override; static void SetTreatArrayBufferViewsAsHostObjects( const FunctionCallbackInfo& args); + static void SetTreatDOMExceptionsAsHostObjects( + const FunctionCallbackInfo& args); static void New(const FunctionCallbackInfo& args); static void WriteHeader(const FunctionCallbackInfo& args); @@ -61,6 +65,7 @@ class SerializerContext : public BaseObject, private: ValueSerializer serializer_; + bool treat_dom_exceptions_as_host_objects_ = false; }; class DeserializerContext : public BaseObject, @@ -170,6 +175,23 @@ Maybe SerializerContext::WriteHostObject(Isolate* isolate, return Just(true); } +Maybe SerializerContext::IsHostObject(Isolate* isolate, + Local object) { + // DOMException is a native error whose data lives in internal state, so + // V8's default error serialization would lose it. Let JS serialize it. + if (treat_dom_exceptions_as_host_objects_ && object->IsNativeError()) { + bool has_transfer_mode; + if (!object + ->HasPrivate(env()->context(), + env()->transfer_mode_private_symbol()) + .To(&has_transfer_mode)) { + return Nothing(); + } + if (has_transfer_mode) return Just(true); + } + return ValueSerializer::Delegate::IsHostObject(isolate, object); +} + void SerializerContext::New(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); if (!args.IsConstructCall()) { @@ -204,6 +226,16 @@ void SerializerContext::SetTreatArrayBufferViewsAsHostObjects( ctx->serializer_.SetTreatArrayBufferViewsAsHostObjects(value); } +// Called with the serializer as its only argument. Exposed on the binding +// object rather than the prototype so it does not become public API. +void SerializerContext::SetTreatDOMExceptionsAsHostObjects( + const FunctionCallbackInfo& args) { + CHECK(args[0]->IsObject()); + SerializerContext* ctx; + ASSIGN_OR_RETURN_UNWRAP(&ctx, args[0]); + ctx->treat_dom_exceptions_as_host_objects_ = true; +} + void SerializerContext::ReleaseBuffer(const FunctionCallbackInfo& args) { SerializerContext* ctx; ASSIGN_OR_RETURN_UNWRAP(&ctx, args.This()); @@ -494,6 +526,10 @@ void Initialize(Local target, ser->ReadOnlyPrototype(); SetConstructorFunction(context, target, "Serializer", ser); + SetMethod(context, + target, + "setTreatDOMExceptionsAsHostObjects", + SerializerContext::SetTreatDOMExceptionsAsHostObjects); Local des = NewFunctionTemplate(isolate, DeserializerContext::New); @@ -534,6 +570,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(SerializerContext::WriteDouble); registry->Register(SerializerContext::WriteRawBytes); registry->Register(SerializerContext::SetTreatArrayBufferViewsAsHostObjects); + registry->Register(SerializerContext::SetTreatDOMExceptionsAsHostObjects); registry->Register(DeserializerContext::New); registry->Register(DeserializerContext::ReadHeader); diff --git a/test/parallel/test-v8-serdes-domexception.js b/test/parallel/test-v8-serdes-domexception.js new file mode 100644 index 000000000000..1fef2fba93f3 --- /dev/null +++ b/test/parallel/test-v8-serdes-domexception.js @@ -0,0 +1,81 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); +const v8 = require('v8'); + +function roundTrip(value) { + return v8.deserialize(v8.serialize(value)); +} + +function assertDOMException(actual, expected) { + assert.strictEqual(actual instanceof DOMException, true); + assert.strictEqual(Object.getPrototypeOf(actual), + Object.getPrototypeOf(expected)); + assert.strictEqual(actual.message, expected.message); + assert.strictEqual(actual.name, expected.name); + assert.strictEqual(actual.code, expected.code); + assert.strictEqual(actual.stack, expected.stack); +} + +function check(e) { + const clone = roundTrip(e); + assertDOMException(clone, e); + assertDOMException(clone, structuredClone(e)); + assertDOMException(roundTrip(clone), e); + return clone; +} + +{ + // AbortSignal reason (https://github.com/nodejs/node/issues/53225) + const reason = AbortSignal.abort().reason; + const clone = check(reason); + assert.strictEqual(clone.name, 'AbortError'); + assert.strictEqual(clone.message, 'This operation was aborted'); +} + +{ + const e = new DOMException('msg', 'DataCloneError'); + const clone = check(e); + assert.strictEqual(clone.name, 'DataCloneError'); + assert.strictEqual(clone.message, 'msg'); + assert.strictEqual(clone.code, 25); +} + +{ + const e = new QuotaExceededError('quota', { quota: 10, requested: 20 }); + const clone = check(e); + assert.strictEqual(clone instanceof QuotaExceededError, true); + assert.strictEqual(clone.quota, 10); + assert.strictEqual(clone.requested, 20); + const sc = structuredClone(e); + assert.strictEqual(clone.quota, sc.quota); + assert.strictEqual(clone.requested, sc.requested); +} + +{ + const e = new QuotaExceededError('no quota'); + const clone = check(e); + assert.strictEqual(clone instanceof QuotaExceededError, true); + assert.strictEqual(clone.quota, null); + assert.strictEqual(clone.requested, null); +} + +{ + // DOMException nested inside objects and arrays + const e = new DOMException('nested', 'NotFoundError'); + const clone = roundTrip({ a: [1, e], b: { e } }); + assertDOMException(clone.a[1], e); + assertDOMException(clone.b.e, e); +} + +{ + // Plain v8.Serializer keeps its previous behavior and does not throw. + const ser = new v8.Serializer(); + ser.writeHeader(); + assert.strictEqual(ser.writeValue(new DOMException('msg')), true); + const des = new v8.Deserializer(ser.releaseBuffer()); + des.readHeader(); + const result = des.readValue(); + assert.strictEqual(result instanceof DOMException, false); +}