11/**
22 * Converts a decimal number to a hexadecimal string with proper padding
3- *
3+ *
44 * @param dec - The decimal number to convert
55 * @returns A hexadecimal string representation
66 * @internal This is a utility function used by generateRandomString
@@ -11,9 +11,9 @@ function dec2hex(dec: number) {
1111
1212/**
1313 * Generates a cryptographically secure random string
14- *
14+ *
1515 * @returns A random hexadecimal string of 56 characters
16- *
16+ *
1717 * @example
1818 * const randomStr = generateRandomString();
1919 * // e.g. "7b8d4f2e9a1c6b3d5e8f2a7c9b4d1e6f3a8c5b2d7e9f1a3c8b6d4e7f2a9c5"
@@ -24,12 +24,30 @@ export function generateRandomString() {
2424 return Array . from ( array , dec2hex ) . join ( "" ) ;
2525}
2626
27+ /**
28+ * Generates a PKCE verifier string with length 128 characters
29+ *
30+ * @returns a random string of 128 characters
31+ *
32+ * @example
33+ * const verifier = generatePkceVerifier();
34+ * // e.g. "7b8d4f2e9a1c6b3d5e8f2a7c9b4d1e6f3a8c5b2d7e9f1a3c8b6d4e7f2a9c5"
35+ */
36+ export function generatePkceVerifier ( ) : string {
37+ const arr = new Uint8Array ( 96 ) ;
38+ window . crypto . getRandomValues ( arr ) ;
39+ return btoa ( String . fromCharCode ( ...arr ) )
40+ . replace ( / \+ / g, "-" )
41+ . replace ( / \/ / g, "_" )
42+ . replace ( / = + $ / , "" ) ;
43+ }
44+
2745/**
2846 * Computes the SHA-256 hash of a string
29- *
47+ *
3048 * @param plain - The input string to hash
3149 * @returns A Promise that resolves to an ArrayBuffer containing the hash
32- *
50+ *
3351 * @example
3452 * const hashBuffer = await sha256("hello world");
3553 */
@@ -41,15 +59,15 @@ export function sha256(plain: string) {
4159
4260/**
4361 * Encodes an ArrayBuffer to base64url format (URL-safe base64)
44- *
62+ *
4563 * Base64url encoding is a variant of base64 that is URL and filename safe:
4664 * - Replaces '+' with '-'
4765 * - Replaces '/' with '_'
4866 * - Removes padding '=' characters
49- *
67+ *
5068 * @param a - The ArrayBuffer to encode
5169 * @returns The base64url-encoded string
52- *
70+ *
5371 * @example
5472 * const hashBuffer = await sha256("hello world");
5573 * const base64urlStr = base64urlencode(hashBuffer);
0 commit comments