Skip to content

Commit

Permalink
f
Browse files Browse the repository at this point in the history
  • Loading branch information
XadillaX committed Oct 8, 2022
1 parent c43f223 commit 08dfdac
Showing 1 changed file with 13 additions and 22 deletions.
35 changes: 13 additions & 22 deletions lib/buffer.js
Expand Up @@ -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
Expand All @@ -1266,7 +1268,6 @@ function atob(input) {
}

input = `${input}`;
const initLength = input.length;
let nonAsciiWhitespaceCharCount = 0;
let equalCharCount = 0;

Expand All @@ -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');
}
Expand All @@ -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');
}

Expand Down

0 comments on commit 08dfdac

Please sign in to comment.