UNPKG

@ideem/zsm-client-sdk

Version:

ZSM makes 2FA easy and invisible for everyone, all the time, using advanced cryptography like MPC to establish cryptographic proof of the origin of any transaction or login attempt, while eliminating opportunities for social engineering. ZSM has no relian

45 lines (35 loc) 2.71 kB
/** * @name b64urlToBuf * @description Converts a Base64 URL-encoded string to an ArrayBuffer. * @param {string} b64url The Base64 URL-encoded string to convert. * @returns {ArrayBuffer} The converted ArrayBuffer. * @throws {TypeError} Throws a TypeError if the input is not a valid Base64 URL-encoded string. * @example b64urlToBuf('c29tZV9iYXNlNjRfdGVzdA') // Converts to ArrayBuffer * @see https://developer.mozilla.org/en-US/docs/Web/API/Base64/Using_Base64_encoding#base64url, https://developer.mozilla.org/en-US/docs/Web/API/atob, https://developer.mozilla.org/en-US/docs/Web/API/Uint8Array, https://developer.mozilla.org/en-US/docs/Web/API/ArrayBuffer * @memberof Utils */ const b64urlToBuf = (b64url) => { if (typeof b64url !== 'string' || b64url.length === 0) throw new TypeError(`[Utils] :: b64urlToBuf :: This method expects a base64 encoded string as input. Received: "${b64url}" (of type ${typeof b64url} and length ${b64url.length}).`); const padded = (b64url + '====').slice(0, -b64url.length % 4); const binary = atob(padded.replace(/-/g, '+').replace(/_/g, '/')); const buffer = Uint8Array.from(binary, c => c.charCodeAt(0)).buffer; return buffer; } /** * @name toObject * @description Recursively converts potentially-nested data structures (Map, Array, Object) to a plain object. * @ This is in use specifically because of wasm-bindgen's proclivity to OCCASIONALLY return Map objects instead of plain objects. * @param {any} inp The input data structure to convert. * @returns {Object} The converted plain object. * @throws {TypeError} Throws a TypeError if the input is not a valid data structure. * @example toObject(new Map([['key', 'value']])) * @memberof Utils */ const toObject = (inp) => { if (inp === null || typeof inp !== 'object') return inp; // Primitives & functions pass through if (inp instanceof Map) return Object.fromEntries([...inp].map(([k, v]) => [k, toObject(v)])); // Recursively convert Map's nodes if (Array.isArray(inp)) return inp.map(toObject); // Recursively convert arrays' nodes return Object.fromEntries(Object.entries(inp).map(([k, v]) => [k, toObject(v)])); // Recursively convert plain objects' nodes }; export { b64urlToBuf, toObject };