Skip to content

Commit 269c1d6

Browse files
committed
worker: add typechecking for postMessage transfer list
If the transfer list argument is present, it should be an array. This commit adds typechecking to that effect. This aligns behaviour with browsers. PR-URL: #28033 Reviewed-By: Rich Trott <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent 7bd2a3f commit 269c1d6

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/node_messaging.cc

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,15 @@ void MessagePort::PostMessage(const FunctionCallbackInfo<Value>& args) {
714714
return THROW_ERR_MISSING_ARGS(env, "Not enough arguments to "
715715
"MessagePort.postMessage");
716716
}
717+
if (!args[1]->IsNullOrUndefined() && !args[1]->IsObject()) {
718+
// Browsers ignore null or undefined, and otherwise accept an array or an
719+
// options object.
720+
// TODO(addaleax): Add support for an options object and generic sequence
721+
// support.
722+
// Refs: https://github.com/nodejs/node/pull/28033#discussion_r289964991
723+
return THROW_ERR_INVALID_ARG_TYPE(env,
724+
"Optional transferList argument must be an array");
725+
}
717726

718727
MessagePort* port = Unwrap<MessagePort>(args.This());
719728
// Even if the backing MessagePort object has already been deleted, we still

test/parallel/test-worker-message-port.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,27 @@ const { MessageChannel, MessagePort } = require('worker_threads');
7070
});
7171
}
7272

73+
{
74+
const { port1, port2 } = new MessageChannel();
75+
port2.on('message', common.mustCall(4));
76+
port1.postMessage(1, null);
77+
port1.postMessage(2, undefined);
78+
port1.postMessage(3, []);
79+
port1.postMessage(4, {});
80+
81+
const err = {
82+
constructor: TypeError,
83+
code: 'ERR_INVALID_ARG_TYPE',
84+
message: 'Optional transferList argument must be an array'
85+
};
86+
87+
assert.throws(() => port1.postMessage(5, 0), err);
88+
assert.throws(() => port1.postMessage(5, false), err);
89+
assert.throws(() => port1.postMessage(5, 'X'), err);
90+
assert.throws(() => port1.postMessage(5, Symbol('X')), err);
91+
port1.close();
92+
}
93+
7394
{
7495
assert.deepStrictEqual(
7596
Object.getOwnPropertyNames(MessagePort.prototype).sort(),

0 commit comments

Comments
 (0)