Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1232,12 +1232,14 @@ function btoa(input) {
return buf.toString('base64');
}

// Refs: https://infra.spec.whatwg.org/#forgiving-base64-decode
const kForgivingBase64AllowedChars = [
const asciiWhitespaceCharacters = [
// ASCII whitespace
// Refs: https://infra.spec.whatwg.org/#ascii-whitespace
0x09, 0x0A, 0x0C, 0x0D, 0x20,
];

// Refs: https://infra.spec.whatwg.org/#forgiving-base64-decode
const kForgivingBase64AllowedChars = [
// Uppercase letters
...ArrayFrom({ length: 26 }, (_, i) => StringPrototypeCharCodeAt('A') + i),

Expand All @@ -1259,12 +1261,30 @@ function atob(input) {
if (arguments.length === 0) {
throw new ERR_MISSING_ARGS('input');
}

input = `${input}`;
let nonAsciiWhitespaceCharCount = 0;

for (let n = 0; n < input.length; n++) {
if (!ArrayPrototypeIncludes(kForgivingBase64AllowedChars,
StringPrototypeCharCodeAt(input, n)))
const char = StringPrototypeCharCodeAt(input, n);

if (ArrayPrototypeIncludes(kForgivingBase64AllowedChars, char)) {
nonAsciiWhitespaceCharCount++;
} else if (!ArrayPrototypeIncludes(asciiWhitespaceCharacters, char)) {
throw lazyDOMException('Invalid character', 'InvalidCharacterError');
}
}

// If data's code point length divides by 4 leaving a remainder of 1, then
// return failure.
//
// See #3 - https://infra.spec.whatwg.org/#forgiving-base64
if (nonAsciiWhitespaceCharCount % 4 === 1) {
throw lazyDOMException(
'The string to be decoded is not correctly encoded.',
'ValidationError');
}

return Buffer.from(input, 'base64').toString('latin1');
}

Expand Down
14 changes: 14 additions & 0 deletions test/parallel/test-btoa-atob.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,17 @@ throws(() => buffer.btoa(), /TypeError/);

strictEqual(atob(' '), '');
strictEqual(atob(' YW\tJ\njZA=\r= '), 'abcd');

strictEqual(atob(null), '\x9Eée');
strictEqual(atob(NaN), '5£');
strictEqual(atob(Infinity), '"wâ\x9E+r');
strictEqual(atob(true), '¶»\x9E');
strictEqual(atob(1234), '×mø');
strictEqual(atob([]), '');
strictEqual(atob({ toString: () => '' }), '');
strictEqual(atob({ [Symbol.toPrimitive]: () => '' }), '');

throws(() => atob(), /ERR_MISSING_ARGS/);
throws(() => atob(Symbol()), /TypeError/);
[undefined, false, () => {}, 0, 1, 0n, 1n, -Infinity, [1], {}].forEach((value) =>
throws(() => atob(value), { constructor: DOMException }));