diff --git a/lib/util.js b/lib/util.js index f6f99f82b45722..f58f0e7a3e7605 100644 --- a/lib/util.js +++ b/lib/util.js @@ -194,9 +194,16 @@ function callbackify(original) { (rej) => process.nextTick(callbackifyOnRejected, rej, cb)); } - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - Object.getOwnPropertyDescriptors(original)); + const descriptors = Object.getOwnPropertyDescriptors(original); + // It is possible to manipulate a functions `length` or `name` property. This + // guards against the manipulation. + if (typeof descriptors.length.value === 'number') { + descriptors.length.value++; + } + if (typeof descriptors.name.value === 'string') { + descriptors.name.value += 'Callbackified'; + } + Object.defineProperties(callbackified, descriptors); return callbackified; } diff --git a/test/parallel/test-util-callbackify.js b/test/parallel/test-util-callbackify.js index 9be3b132f95172..2a956d06beef3e 100644 --- a/test/parallel/test-util-callbackify.js +++ b/test/parallel/test-util-callbackify.js @@ -74,6 +74,8 @@ const values = [ } const cbAsyncFn = callbackify(asyncFn); + assert.strictEqual(cbAsyncFn.length, 1); + assert.strictEqual(cbAsyncFn.name, 'asyncFnCallbackified'); cbAsyncFn(common.mustCall((err, ret) => { assert.strictEqual(ret, undefined); if (err instanceof Error) { @@ -93,8 +95,16 @@ const values = [ function promiseFn() { return Promise.reject(value); } + const obj = {}; + Object.defineProperty(promiseFn, 'name', { + value: obj, + writable: false, + enumerable: false, + configurable: true + }); const cbPromiseFn = callbackify(promiseFn); + assert.strictEqual(promiseFn.name, obj); cbPromiseFn(common.mustCall((err, ret) => { assert.strictEqual(ret, undefined); if (err instanceof Error) { @@ -146,6 +156,12 @@ const values = [ } const cbAsyncFn = callbackify(asyncFn); + assert.strictEqual(cbAsyncFn.length, 2); + assert.notStrictEqual( + Object.getPrototypeOf(cbAsyncFn), + Object.getPrototypeOf(asyncFn) + ); + assert.strictEqual(Object.getPrototypeOf(cbAsyncFn), Function.prototype); cbAsyncFn(value, common.mustCall((err, ret) => { assert.ifError(err); assert.strictEqual(ret, value); @@ -155,8 +171,16 @@ const values = [ assert.strictEqual(arg, value); return Promise.resolve(arg); } + const obj = {}; + Object.defineProperty(promiseFn, 'length', { + value: obj, + writable: false, + enumerable: false, + configurable: true + }); const cbPromiseFn = callbackify(promiseFn); + assert.strictEqual(promiseFn.length, obj); cbPromiseFn(value, common.mustCall((err, ret) => { assert.ifError(err); assert.strictEqual(ret, value);