From 41d0be38caf87dd69af34b92ab617ac7208dc109 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Thu, 3 Oct 2019 02:38:37 +0200 Subject: [PATCH] util: validate formatWithOptions inspectOptions This makes sure that the `inspectOptions` are validated. This could otherwise cause confusion. Fixes: https://github.com/nodejs/node/issues/29726 --- lib/internal/util/inspect.js | 17 ++++++++++++----- test/parallel/test-util-format.js | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 6401e30e921cb4..83baeb571c0ed1 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1542,11 +1542,6 @@ function reduceToSingleString( return `${braces[0]}${ln}${join(output, `,\n${indentation} `)} ${braces[1]}`; } -function format(...args) { - return formatWithOptions(undefined, ...args); -} - - const firstErrorLine = (error) => error.message.split('\n')[0]; let CIRCULAR_ERROR_MESSAGE; function tryStringify(arg) { @@ -1569,7 +1564,19 @@ function tryStringify(arg) { } } +function format(...args) { + return formatWithOptionsInternal(undefined, ...args); +} + function formatWithOptions(inspectOptions, ...args) { + if (typeof inspectOptions !== 'object' || inspectOptions === null) { + throw new ERR_INVALID_ARG_TYPE( + 'inspectOptions', 'object', inspectOptions); + } + return formatWithOptionsInternal(inspectOptions, ...args); +} + +function formatWithOptionsInternal(inspectOptions, ...args) { const first = args[0]; let a = 0; let str = ''; diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js index 810e9ac1146d97..2ef05284902995 100644 --- a/test/parallel/test-util-format.js +++ b/test/parallel/test-util-format.js @@ -408,3 +408,20 @@ assert.strictEqual( ), '[ 1, [Object] ]' ); + +[ + undefined, + null, + false, + 5n, + 5, + 'test', + Symbol() +].forEach((invalidOptions) => { + assert.throws(() => { + util.formatWithOptions(invalidOptions, { a: true }); + }, { + code: 'ERR_INVALID_ARG_TYPE', + message: /"inspectOptions".+object/ + }); +});