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
108 changes: 108 additions & 0 deletions lib/v8.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -451,18 +457,112 @@ function arrayBufferViewIndexToType(index) {
}

const kX509CertificateHostObject = 14;
const kDOMExceptionHostObject = 15;
const kDOMExceptionSubtype = 0;
const kQuotaExceededErrorSubtype = 1;
let x509Serialization;

function getX509Serialization() {
x509Serialization ??= require('internal/crypto/x509');
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);
}

/**
Expand All @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down
37 changes: 37 additions & 0 deletions src/node_serdes.cc
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,15 @@ class SerializerContext : public BaseObject,

void ThrowDataCloneError(Local<String> message) override;
Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object) override;
bool HasCustomHostObject(Isolate* isolate) override { return true; }
Maybe<bool> IsHostObject(Isolate* isolate, Local<Object> object) override;
Maybe<uint32_t> GetSharedArrayBufferId(
Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer) override;

static void SetTreatArrayBufferViewsAsHostObjects(
const FunctionCallbackInfo<Value>& args);
static void SetTreatDOMExceptionsAsHostObjects(
const FunctionCallbackInfo<Value>& args);

static void New(const FunctionCallbackInfo<Value>& args);
static void WriteHeader(const FunctionCallbackInfo<Value>& args);
Expand All @@ -61,6 +65,7 @@ class SerializerContext : public BaseObject,

private:
ValueSerializer serializer_;
bool treat_dom_exceptions_as_host_objects_ = false;
};

class DeserializerContext : public BaseObject,
Expand Down Expand Up @@ -170,6 +175,23 @@ Maybe<bool> SerializerContext::WriteHostObject(Isolate* isolate,
return Just(true);
}

Maybe<bool> SerializerContext::IsHostObject(Isolate* isolate,
Local<Object> 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<bool>();
}
if (has_transfer_mode) return Just(true);
}
return ValueSerializer::Delegate::IsHostObject(isolate, object);
}

void SerializerContext::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
if (!args.IsConstructCall()) {
Expand Down Expand Up @@ -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<Value>& 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<Value>& args) {
SerializerContext* ctx;
ASSIGN_OR_RETURN_UNWRAP(&ctx, args.This());
Expand Down Expand Up @@ -494,6 +526,10 @@ void Initialize(Local<Object> target,

ser->ReadOnlyPrototype();
SetConstructorFunction(context, target, "Serializer", ser);
SetMethod(context,
target,
"setTreatDOMExceptionsAsHostObjects",
SerializerContext::SetTreatDOMExceptionsAsHostObjects);

Local<FunctionTemplate> des =
NewFunctionTemplate(isolate, DeserializerContext::New);
Expand Down Expand Up @@ -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);
Expand Down
81 changes: 81 additions & 0 deletions test/parallel/test-v8-serdes-domexception.js
Original file line number Diff line number Diff line change
@@ -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);
}