From ef6eccec4a4d0d8c710a361c33ebbe81f051a904 Mon Sep 17 00:00:00 2001 From: Khafra <42794878+KhafraDev@users.noreply.github.com> Date: Wed, 3 Aug 2022 18:46:17 -0400 Subject: [PATCH] feat(webidl): better error message for ByteString converter Fixes https://github.com/nodejs/undici/issues/1590 --- lib/fetch/webidl.js | 15 +++++++++------ test/webidl/converters.js | 9 +++++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/fetch/webidl.js b/lib/fetch/webidl.js index 293199e8f9b..430e657e275 100644 --- a/lib/fetch/webidl.js +++ b/lib/fetch/webidl.js @@ -388,10 +388,6 @@ webidl.converters.DOMString = function (V, opts = {}) { return String(V) } -// Check for 0 or more characters outside of the latin1 range. -// eslint-disable-next-line no-control-regex -const isLatin1 = /^[\u0000-\u00ff]{0,}$/ - // https://webidl.spec.whatwg.org/#es-ByteString webidl.converters.ByteString = function (V) { // 1. Let x be ? ToString(V). @@ -400,8 +396,15 @@ webidl.converters.ByteString = function (V) { // 2. If the value of any element of x is greater than // 255, then throw a TypeError. - if (!isLatin1.test(x)) { - throw new TypeError('Argument is not a ByteString') + for (let index = 0; index < x.length; index++) { + const charCode = x.charCodeAt(index) + + if (charCode > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at' + + `index ${index} has a value of ${charCode} which is greater than 255.` + ) + } } // 3. Return an IDL ByteString value whose length is the diff --git a/test/webidl/converters.js b/test/webidl/converters.js index d1404a2ebcd..504bc98690a 100644 --- a/test/webidl/converters.js +++ b/test/webidl/converters.js @@ -189,5 +189,14 @@ test('ByteString', (t) => { webidl.converters.ByteString('') }) + // https://github.com/nodejs/undici/issues/1590 + t.throws(() => { + const char = String.fromCharCode(256) + webidl.converters.ByteString(`invalid${char}char`) + }, { + message: 'Cannot convert argument to a ByteString because the character at' + + 'index 7 has a value of 256 which is greater than 255.' + }) + t.end() })