From 08dfdac507b19dd4a56ccf3e93c47ec00c80029b Mon Sep 17 00:00:00 2001 From: XadillaX Date: Thu, 28 Jul 2022 20:25:49 +0800 Subject: [PATCH] f --- lib/buffer.js | 35 +++++++++++++---------------------- 1 file changed, 13 insertions(+), 22 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index bbb393b94c844c..7c0bbbc81c6398 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -1256,6 +1256,8 @@ const kForgivingBase64AllowedChars = [ 0x2F, // / 0x3D, // = ]; +const kEqualSignIndex = ArrayPrototypeIndexOf(kForgivingBase64AllowedChars, + 0x3D); function atob(input) { // The implementation here has not been performance optimized in any way and @@ -1266,7 +1268,6 @@ function atob(input) { } input = `${input}`; - const initLength = input.length; let nonAsciiWhitespaceCharCount = 0; let equalCharCount = 0; @@ -1280,10 +1281,14 @@ function atob(input) { // ASCII whitespace char codes. nonAsciiWhitespaceCharCount++; - if (index === kForgivingBase64AllowedChars.length - 1 && equalCharCount !== 2) { - // The last element of `kForgivingBase64AllowedChars` is the `=` + if (index === kEqualSignIndex) { equalCharCount++; } else if (equalCharCount) { + // The `=` char is only allowed at the end. + throw lazyDOMException('Invalid character', 'InvalidCharacterError'); + } + + if (equalCharCount > 2) { // Only one more `=` is permitted after the first equal sign. throw lazyDOMException('Invalid character', 'InvalidCharacterError'); } @@ -1292,28 +1297,14 @@ function atob(input) { } } - // See #2 and #4 - https://infra.spec.whatwg.org/#forgiving-base64 - if (equalCharCount > 2) { - throw lazyDOMException('Invalid character', 'InvalidCharacterError'); - } - let reminder = nonAsciiWhitespaceCharCount % 4; - // See #2 - https://infra.spec.whatwg.org/#forgiving-base64 + // See #2, #3, #4 - https://infra.spec.whatwg.org/#forgiving-base64 if (!reminder) { - // Remove all trailing `=` characters (whitespace characters will be - // ignored). - input = input.replace(/(=\s*){1,2}$/, (s) => { - return s.replace(/=/gi, ''); - }); - const deltaLength = initLength - input.length; - nonAsciiWhitespaceCharCount -= deltaLength; - equalCharCount -= deltaLength; - reminder = nonAsciiWhitespaceCharCount % 4; - } - - // See #4 - https://infra.spec.whatwg.org/#forgiving-base64 - if (equalCharCount) { + // Remove all trailing `=` characters and get the new reminder. + reminder = (nonAsciiWhitespaceCharCount - equalCharCount) % 4; + } else if (equalCharCount) { + // `=` should not in the input if there's a reminder. throw lazyDOMException('Invalid character', 'InvalidCharacterError'); }