@dvcol/common-utils
Version:
Typescript library for common utility functions and constants
32 lines (30 loc) • 1.16 kB
JavaScript
// 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 {
static code = getCodeVerifier;
static challenge = getCodeChallenge;
static 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 };
}
};
export {
randomHex,
getCodeVerifier,
getCodeChallenge,
verifyCodeChallenge,
PKCECodeGenerator
};