locqr/companion/src/base64url.ts

23 lines
851 B
TypeScript

// base64url (RFC 4648 §5), no padding — interfaces.md's shared conventions.
// Same implementation as extension/src/base64url.ts; duplicated rather than
// shared across the two independent build targets.
export function base64UrlDecode(s: string): Uint8Array {
const unpadded = s.replace(/-/g, '+').replace(/_/g, '/');
const padded = unpadded + '='.repeat((4 - (unpadded.length % 4)) % 4);
const binary = atob(padded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
export function base64UrlEncode(bytes: Uint8Array): string {
let binary = '';
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}