UNPKG

@dvcol/common-utils

Version:

Typescript library for common utility functions and constants

32 lines (24 loc) 1.51 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); var _class;// lib/common/utils/crypto.utils.ts var randomHex = (n = 8) => { const bytes = new Uint8Array(n); crypto.getRandomValues(bytes); return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); }; var getCodeVerifier = async (length = 24) => randomHex(length); var getCodeChallenge = async (verifier) => { const hashedValue = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)); return btoa(String.fromCharCode(...new Uint8Array(hashedValue))).replace(/=/g, ""); }; var verifyCodeChallenge = async (codeVerifier, codeChallenge) => getCodeChallenge(codeVerifier).then((challenge) => challenge === codeChallenge); var PKCECodeGenerator = (_class = class { static __initStatic() {this.code = getCodeVerifier} static __initStatic2() {this.challenge = getCodeChallenge} static __initStatic3() {this.verify = verifyCodeChallenge} static async codes(length = 24) { const verifier = await this.code(length); const challenge = await this.challenge(verifier); const verify = () => this.verify(verifier, challenge); return { verifier, challenge, verify }; } }, _class.__initStatic(), _class.__initStatic2(), _class.__initStatic3(), _class); exports.randomHex = randomHex; exports.getCodeVerifier = getCodeVerifier; exports.getCodeChallenge = getCodeChallenge; exports.verifyCodeChallenge = verifyCodeChallenge; exports.PKCECodeGenerator = PKCECodeGenerator;