From ec7c9a8e607d63a008d06747f89c9512f5b3171e Mon Sep 17 00:00:00 2001 From: ST-DDT Date: Thu, 20 Feb 2025 00:01:02 +0100 Subject: [PATCH] fix: test before using Buffers (#3400) --- src/internal/base64.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/internal/base64.ts b/src/internal/base64.ts index c1f309fba48..13cb5c5257f 100644 --- a/src/internal/base64.ts +++ b/src/internal/base64.ts @@ -14,7 +14,7 @@ * @example const encodedHeader = toBase64(JSON.stringify(header)); */ export const toBase64: (input: string) => string = - typeof Buffer === 'undefined' + typeof Buffer === 'undefined' || !bufferFeatureCheck('base64') ? (input) => { const utf8Bytes = new TextEncoder().encode(input); const binaryString = Array.from(utf8Bytes, (byte) => @@ -39,10 +39,27 @@ export const toBase64: (input: string) => string = * @example const encodedHeader = toBase64Url(JSON.stringify(header)); */ export const toBase64Url: (input: string) => string = - typeof Buffer === 'undefined' + typeof Buffer === 'undefined' || !bufferFeatureCheck('base64url') ? (input) => toBase64(input) .replaceAll('+', '-') .replaceAll('/', '_') .replaceAll(/=+$/g, '') : (input) => Buffer.from(input).toString('base64url'); + +/** + * Checks whether the environment supports the given encoding on the `Buffer` class. + * This is required because some `Buffer` polyfills do not support all encodings. + * + * @param encoding The encoding to check. + * + * @see https://www.npmjs.com/package/buffer + * @see https://github.com/feross/buffer/issues/309 + */ +function bufferFeatureCheck(encoding: BufferEncoding): boolean { + try { + return typeof Buffer.from('test').toString(encoding) === 'string'; + } catch { + return false; + } +}