UNPKG

@adorsys-gis/web-auth-prf

Version:

A WebAuthn library implementing password-based key derivation functions (PRF) for secure authentication and encryption

60 lines (59 loc) 2.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebAuthnService = void 0; // convert ArrayBuffer to Base64 string function arrayBufferToBase64(buffer) { const binary = String.fromCharCode.apply(null, new Uint8Array(buffer)); return window.btoa(binary); } class WebAuthnService { // generate a secure salt. generateSalt() { return crypto.getRandomValues(new Uint8Array(16)); } async register(options) { try { const rawCredential = (await navigator.credentials.create({ publicKey: options, })); if (!rawCredential || !rawCredential.rawId) { throw new Error("Registration failed: No credential returned."); } // Generate a unique salt for registration. const salt = this.generateSalt(); // Store salt in localStorage localStorage.setItem("registrationSalt", arrayBufferToBase64(salt.buffer)); return { credentialId: rawCredential.rawId, rawCredential }; } catch (error) { throw new Error(`Registration error: ${error.message}`); } } async authenticate(options) { try { const assertion = (await navigator.credentials.get({ publicKey: options, })); if (!assertion) { throw new Error("Authentication failed: No assertion returned."); } // Retrieve the stored salt from localStorage. const storedSaltBase64 = localStorage.getItem("registrationSalt"); if (!storedSaltBase64) { throw new Error("No stored salt found for authentication."); } // Extract the PRF output from extension results. const clientExtResults = assertion.getClientExtensionResults(); if (!clientExtResults?.prf?.results?.first) { throw new Error("PRF result missing in the assertion."); } const prfResult = new Uint8Array(clientExtResults.prf.results.first); // Use the stored salt and PRF result in key derivation. return { assertion, prfResult }; } catch (error) { throw new Error(`Authentication error: ${error.message}`); } } } exports.WebAuthnService = WebAuthnService;