Upgrading Uint8Array.fromBase64

The ES2027 specification

does not acknowledge the fact most applications using Base64Url do not support padding.

The current specification supports this for toBase64 through the option omitPadding. This option could be added to fromBase64 without any backward compatibility issues.

It is an issue for other languages as well:

If you simply want to decode base64url strings without padding: Uint8Array.fromBase64 already does that. Uint8Array.fromBase64("AA", { alphabet: "base64url" }) is the same as Uint8Array.fromBase64("AA==", { alphabet: "base64url" }).

If you also want to reject non-canonical encodings: a lastChunkHandling: "strict-no-padding" option was discussed before and decided to be not worth it, because it is a relatively uncommon use case, and also straightforward to implement in userland (see example below).

function fromBase64urlStrictNoPadding(input) {
  if (/[^\w-]/.test(input)) {
    throw new SyntaxError("input contains a non-base64url character");
  }
  switch (input.length % 4) {
    case 0: break;
    case 2: input += "=="; break;
    case 3: input += "="; break;
    default: throw new SyntaxError("input.length % 4 === 1");
  }
  return Uint8Array.fromBase64(input, {
    alphabet: "base64url",
    lastChunkHandling: "strict",
  });
}
1 Like

Thanx! I’m aware of this but RFC 7515 which is an extremely wide-spread standard, actually forbids padding.