firebase-auth-cloudflare-workers
Version:
Zero-dependencies firebase auth library for Cloudflare Workers.
25 lines (24 loc) • 1.11 kB
JavaScript
import { utf8Encoder } from './utf8';
export const decodeBase64Url = (str) => {
return decodeBase64(str.replace(/_|-/g, m => ({ _: '/', '-': '+' })[m] ?? m));
};
export const encodeBase64Url = (buf) => encodeBase64(buf).replace(/\/|\+/g, m => ({ '/': '_', '+': '-' })[m] ?? m);
// This approach is written in MDN.
// btoa does not support utf-8 characters. So we need a little bit hack.
export const encodeBase64 = (buf) => {
const binary = String.fromCharCode(...new Uint8Array(buf));
return btoa(binary);
};
// atob does not support utf-8 characters. So we need a little bit hack.
export const decodeBase64 = (str) => {
const binary = atob(str);
const bytes = new Uint8Array(new ArrayBuffer(binary.length));
const half = binary.length / 2;
for (let i = 0, j = binary.length - 1; i <= half; i++, j--) {
bytes[i] = binary.charCodeAt(i);
bytes[j] = binary.charCodeAt(j);
}
return bytes;
};
const jsonUTF8Stringify = (obj) => utf8Encoder.encode(JSON.stringify(obj));
export const encodeObjectBase64Url = (obj) => encodeBase64Url(jsonUTF8Stringify(obj).buffer);