From e39d1b7d822c5aa374fa5d188da45c963d6b09c4 Mon Sep 17 00:00:00 2001 From: Max Peintner Date: Tue, 13 Jun 2023 07:37:22 +0200 Subject: [PATCH] fix(console): url safe base64 to array buffer (#6019) fix: console base64 to array buffer Co-authored-by: Livio Spring --- .../app/pages/users/user-detail/u2f-util.ts | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/console/src/app/pages/users/user-detail/u2f-util.ts b/console/src/app/pages/users/user-detail/u2f-util.ts index b19c61a546..fab5a8afff 100644 --- a/console/src/app/pages/users/user-detail/u2f-util.ts +++ b/console/src/app/pages/users/user-detail/u2f-util.ts @@ -1,9 +1,31 @@ -export function _base64ToArrayBuffer(base64: string): any { - const binaryString = atob(base64); - const len = binaryString.length; - const bytes = new Uint8Array(len); - for (let i = 0; i < len; i++) { - bytes[i] = binaryString.charCodeAt(i); +export function _base64ToArrayBuffer(thing: any) { + if (typeof thing === 'string') { + // base64url to base64 + thing = thing.replace(/-/g, '+').replace(/_/g, '/'); + + // base64 to Uint8Array + var str = window.atob(thing); + var bytes = new Uint8Array(str.length); + for (var i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + thing = bytes; } - return bytes.buffer; + + // Array to Uint8Array + if (Array.isArray(thing)) { + thing = new Uint8Array(thing); + } + + // Uint8Array to ArrayBuffer + if (thing instanceof Uint8Array) { + thing = thing.buffer; + } + + // error if none of the above worked + if (!(thing instanceof ArrayBuffer)) { + throw new TypeError('could not coerce to ArrayBuffer'); + } + + return thing; }