### Multi-Factor Authentication Setup Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/README.md Illustrates the setup process for multi-factor authentication (MFA) using OTP, including secret generation, OTP instance creation, and code verification. ```typescript import { createOTP } from "@better-auth/utils/otp"; import { base32 } from "@better-auth/utils/base32"; // 1. Generate secret const secretGen = createRandomStringGenerator("A-Z", "2-7"); const secret = secretGen(32); // 2. Create OTP instance const otp = createOTP(secret, { digits: 6 }); // 3. Generate QR code URL const qrUrl = otp.url("MyApp", "user@example.com"); // 4. User confirms by entering code const isValid = await otp.verify(userProvidedCode); ``` -------------------------------- ### Install Better Auth Utils Source: https://github.com/better-auth/utils/blob/main/README.md Install the @better-auth/utils package using pnpm. ```bash pnpm add @better-auth/utils ``` -------------------------------- ### Install Better Auth Utils Source: https://github.com/better-auth/utils/blob/main/_autodocs/README.md Install the library using npm. This command adds the @better-auth/utils package to your project dependencies. ```bash npm install @better-auth/utils ``` -------------------------------- ### Complete OTP Workflow Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/otp.md Provides a comprehensive example of setting up and using OTP utilities for both Time-based One-Time Password (TOTP) and Hash-based One-Time Password (HOTP). This includes secret generation, OTP instance creation, QR code URL generation, code verification, and HOTP generation. ```typescript import { createOTP } from "@better-auth/utils/otp"; // === Setup Phase (during user MFA enrollment) === // 1. Generate or receive secret (typically base32-encoded) const secret = "JBSWY3DPEBLW64TMMQ======"; // Example base32 secret // 2. Create OTP instance const otp = createOTP(secret, { digits: 6, period: 30 }); // 3. Generate QR code URL for user to scan const qrUrl = otp.url("MyApp", "user@example.com"); console.log("Scan this URL with authenticator app:"); console.log(qrUrl); // === Verification Phase (during login) === // 4. User scans QR and enters code from their authenticator const userProvidedCode = "123456"; // 5. Verify the code const isValid = await otp.verify(userProvidedCode, { window: 1 }); if (isValid) { console.log("MFA verified!"); } else { console.log("Invalid code"); } // === Counter-based alternative (HOTP) === // For systems without synchronized time, use HOTP const otpCounter = createOTP("my-secret", { digits: 6 }); let counter = 0; const code1 = await otpCounter.hotp(counter++); const code2 = await otpCounter.hotp(counter++); ``` -------------------------------- ### Complete ECDSA Key Workflow Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/ecdsa.md Illustrates a full ECDSA workflow including key generation, import, signing, verification, and exporting/re-importing keys. This example covers common use cases for managing ECDSA keys. ```typescript import { ecdsa } from "@better-auth/utils/ecdsa"; // 1. Generate key pair const { privateKey, publicKey } = await ecdsa.generateKeyPair("P-256"); // 2. Import keys for use const signingKey = await ecdsa.importPrivateKey(privateKey, "P-256"); const verifyKey = await ecdsa.importPublicKey(publicKey, "P-256"); // 3. Sign a message const message = "Important transaction"; const signature = await ecdsa.sign(signingKey, message, "SHA-256"); // 4. Verify the signature const isValid = await ecdsa.verify(verifyKey, { signature, data: message, hash: "SHA-256", }); console.log(isValid); // true // 5. Export keys for storage const publicJwk = await ecdsa.exportKey(verifyKey, "jwk"); console.log(publicJwk); // { kty: "EC", crv: "P-256", x: "...", y: "..." } // 6. Reimport from JWK const importedKey = await ecdsa.importPublicKey( JSON.stringify(publicJwk), "P-256" ); ``` -------------------------------- ### Usage Guide Source: https://github.com/better-auth/utils/blob/main/_autodocs/DOCUMENTATION-MANIFEST.txt A guide to help users navigate and utilize the documentation effectively, catering to different experience levels and tasks. ```APIDOC ## Usage Guide Quick Start: 1. Open README.md for overview 2. Use QUICK-REFERENCE.md for function signatures 3. Go to api-reference/{module}.md for full documentation 4. Check types.md for type definitions By Experience Level: - Beginner: Start with hash, random, base64 modules - Intermediate: Password, HMAC, OTP modules - Advanced: RSA, ECDSA, complete type system By Task: - User Authentication → password, random, otp modules - API Security → hmac, rsa, ecdsa modules - Data Encoding → base64, base32, hex, binary modules - Cryptography → hash, hmac, rsa, ecdsa modules ``` -------------------------------- ### Authentication Workflow Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/README.md Demonstrates a typical user authentication process involving password hashing, session token generation, and login verification. ```typescript import { hashPassword, verifyPassword } from "@better-auth/utils/password"; import { createRandomStringGenerator } from "@better-auth/utils/random"; import { createHash } from "@better-auth/utils/hash"; // 1. User registration const password = userInput.password; const passwordHash = await hashPassword(password); // 2. Generate session token const tokenGen = createRandomStringGenerator("A-Z", "a-z", "0-9"); const sessionToken = tokenGen(32); // 3. Login verification const isValid = await verifyPassword(passwordHash, loginPassword); if (isValid) { // Create session with token } ``` -------------------------------- ### Complete RSA Workflow Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/rsa.md Demonstrates a full RSA workflow: key pair generation, encryption/decryption, signing/verification, and key export/import. Imports the rsa utility from @better-auth/utils/rsa. ```typescript import { rsa } from "@better-auth/utils/rsa"; // 1. Generate key pair const { publicKey, privateKey } = await rsa.generateKeyPair(2048, "SHA-256"); // 2. Encrypt data with public key const plaintext = "Sensitive information"; const encrypted = await rsa.encrypt(publicKey, plaintext); // 3. Decrypt with private key const decrypted = await rsa.decrypt(privateKey, encrypted); const restored = new TextDecoder().decode(decrypted); console.log(restored === plaintext); // true // 4. Sign message with private key const signature = await rsa.sign(privateKey, "Important message"); // 5. Verify signature with public key const isValid = await rsa.verify(publicKey, { signature, data: "Important message", }); console.log(isValid); // true // 6. Export for storage/transmission const publicJwk = await rsa.exportKey(publicKey, "jwk"); const importedPublicKey = await rsa.importKey(publicJwk); ``` -------------------------------- ### OTP Secret Provisioning Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/base32.md Example demonstrating how to encode a raw secret into Base32 format for use in OTP authentication URLs. ```APIDOC ### OTP Secret Provisioning ```typescript import { base32 } from "@better-auth/utils/base32"; // OTP secrets are typically base32-encoded for QR codes const rawSecret = "my-super-secret-key"; const base32Secret = base32.encode(rawSecret, { padding: false }); // Use in otpauth:// URL const otpauthUrl = `otpauth://totp/MyApp:user@example.com?secret=${base32Secret}&issuer=MyApp`; ``` ``` -------------------------------- ### API Signature Generation Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/README.md Shows how to generate and verify API signatures using HMAC for secure request authentication. ```typescript import { createHMAC } from "@better-auth/utils/hmac"; import { hex } from "@better-auth/utils/hex"; const apiSecret = "api-secret-key"; const hmac = createHMAC("SHA-256", "hex"); // Sign request const signature = await hmac.sign(apiSecret, requestBody); const authHeader = `Signature ${signature}`; // Verify on server const isValid = await hmac.verify(apiSecret, requestBody, signature); ``` -------------------------------- ### Verify Password Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/password.md Demonstrates how to use verifyPassword to check a user's password against a stored hash. This includes hashing a password during registration and then verifying it during login. ```typescript import { hashPassword, verifyPassword } from "@better-auth/utils/password"; // During registration const password = "my-secure-password"; const hash = await hashPassword(password); // Store hash in database // During login const isValid = await verifyPassword(hash, password); console.log(isValid); // true // Wrong password const isInvalid = await verifyPassword(hash, "wrong-password"); console.log(isInvalid); // false ``` -------------------------------- ### Importing Utilities from Better Auth Source: https://github.com/better-auth/utils/blob/main/_autodocs/README.md Demonstrates how to import individual utility functions from the @better-auth/utils package using subpath imports. Ensure you have the package installed. ```typescript import { createHash } from "@better-auth/utils/hash"; import { createHMAC } from "@better-auth/utils/hmac"; import { createRandomStringGenerator } from "@better-auth/utils/random"; import { rsa } from "@better-auth/utils/rsa"; import { ecdsa } from "@better-auth/utils/ecdsa"; import { createOTP } from "@better-auth/utils/otp"; import { base64, base64Url } from "@better-auth/utils/base64"; import { hex } from "@better-auth/utils/hex"; import { binary } from "@better-auth/utils/binary"; import { base32, base32hex } from "@better-auth/utils/base32"; import { hashPassword, verifyPassword } from "@better-auth/utils/password"; ``` -------------------------------- ### Decoding OTP Secrets Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/base32.md Example showing how to decode a Base32 encoded secret string obtained from a QR code. ```APIDOC ### Decoding OTP Secrets ```typescript // User provides base32 secret from QR code scanning const userProvidedSecret = "JBSWY3DPEBLW64TMMQ======"; // Decode to binary const decodedSecret = base32.decode(userProvidedSecret); console.log(decodedSecret instanceof Uint8Array); // true // Use with HMAC or other crypto functions import { createHMAC } from "@better-auth/utils/hmac"; const hmac = createHMAC("SHA-1"); const signature = await hmac.sign(decodedSecret, "data"); ``` ``` -------------------------------- ### Create SHA-512 Hash with Binary Output Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hash.md This example demonstrates how to create a SHA-512 hash and retrieve the raw binary output as an ArrayBuffer. The default encoding is 'none', resulting in binary output. ```typescript const hash = createHash("SHA-512"); const buffer = await hash.digest("data"); console.log(buffer instanceof ArrayBuffer); // true console.log(buffer.byteLength); // 64 (512 bits) ``` -------------------------------- ### Create Hash in Deno Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Example of using the `createHash` utility for hashing data in Deno environments, utilizing its Web Crypto API support. Requires importing from `@better-auth/utils/hash`. ```typescript import { createHash } from "@better-auth/utils/hash"; // Works with Deno's Web Crypto API const hash = await createHash("SHA-256", "hex").digest("data"); ``` -------------------------------- ### MFA Enrollment with OTP Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/otp.md Generates an OTP object and its enrollment URL for user MFA setup. The user scans the QR code and then verifies with a code. ```typescript const otp = createOTP(generatedSecret); const enrollmentUrl = otp.url("MyService", userEmail); // Display QR code to user // User scans with authenticator // User enters code for verification const isConfirmed = await otp.verify(userProvidedCode, { window: 1 }); ``` -------------------------------- ### Create Hash in Node.js Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Example of using the `createHash` utility for hashing data in Node.js environments (version 15+). Requires importing from `@better-auth/utils/hash`. ```typescript import { createHash } from "@better-auth/utils/hash"; // Works with Node.js 15+ (crypto.webcrypto API available) const hash = await createHash("SHA-256", "hex").digest("data"); ``` -------------------------------- ### Data Transmission with Encoding Example Source: https://github.com/better-auth/utils/blob/main/_autodocs/README.md Demonstrates encrypting sensitive data using RSA and encoding it with Base64URL for secure transmission, followed by decryption and decoding. ```typescript import { rsa } from "@better-auth/utils/rsa"; import { base64Url } from "@better-auth/utils/base64"; // Encrypt const encrypted = await rsa.encrypt(publicKey, "Sensitive data"); const encoded = base64Url.encode(encrypted, { padding: false }); const transmit = `data:${encoded}`; // Receive and decrypt const decoded = base64Url.decode(encoded); const decrypted = await rsa.decrypt(privateKey, decoded); const text = new TextDecoder().decode(decrypted); ``` -------------------------------- ### Create Hash in Browsers Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Example of using the `createHash` utility for hashing data in modern web browsers that support the Web Crypto API. Requires importing from `@better-auth/utils/hash`. ```typescript import { createHash } from "@better-auth/utils/hash"; // Works in all modern browsers with Web Crypto API support const hash = await createHash("SHA-256", "hex").digest("data"); ``` -------------------------------- ### API Reference Structure Source: https://github.com/better-auth/utils/blob/main/_autodocs/DOCUMENTATION-MANIFEST.txt Each API reference file in the @better-auth/utils library follows a structured format to provide comprehensive documentation for users. This includes function signatures, parameter details, return types, code examples, and more. ```APIDOC ## API Reference File Structure Each API Reference File Contains: ✓ Full function signatures with TypeScript types ✓ Parameter descriptions table (type, default, description) ✓ Return type with detailed explanation ✓ Complete, runnable code examples ✓ Typical use cases and patterns ✓ Algorithm details and security notes ✓ Error conditions and handling ✓ Cross-references to related functions ✓ Source code location references Each Type Reference Includes: ✓ Exact type definition (code block) ✓ Field and property descriptions ✓ Cross-references to using functions ✓ Algorithm characteristics ✓ Comparison tables ``` -------------------------------- ### Cross-Module Data Flow with ECDSA and Base64URL Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Illustrates signing data with ECDSA and then encoding the binary signature using Base64URL for transmission. The example also shows decoding and verification later. ```typescript import { base64Url } from "@better-auth/utils/base64"; import { ecdsa } from "@better-auth/utils/ecdsa"; // ECDSA signature (binary) → Encode for transmission const signature = await ecdsa.sign(privateKey, "message"); const encodedSig = base64Url.encode(signature, { padding: false }); // Later: Decode and verify const decodedSig = base64Url.decode(encodedSig); const isValid = await ecdsa.verify(publicKey, { signature: decodedSig, data: "message", }); ``` -------------------------------- ### Create Hash in Cloudflare Workers Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Example of using the `createHash` utility for hashing data within Cloudflare Workers, leveraging their crypto API. Requires importing from `@better-auth/utils/hash`. ```typescript import { createHash } from "@better-auth/utils/hash"; // Works with Cloudflare Workers' crypto API const hash = await createHash("SHA-256", "hex").digest("data"); ``` -------------------------------- ### HMAC Signing and Verification Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hmac.md Demonstrates the basic usage of creating an HMAC instance, signing a message with a raw secret key, and verifying the signature. ```APIDOC ## createHMAC ### Description Creates an HMAC object for signing and verifying messages using a specified algorithm and encoding. ### Method Signature `createHMAC(algorithm: string, encoding?: string)` ### Parameters - **algorithm** (string) - Required - The hashing algorithm to use (e.g., "SHA-256", "SHA-384", "SHA-512"). - **encoding** (string) - Optional - The encoding for the signature. Supported values are "hex", "base64url", or "none" (for ArrayBuffer). Defaults to "hex" if not provided. ### sign #### Description Signs a message using the provided key. #### Method Signature `sign(key: string | ArrayBuffer | CryptoKey, message: string | ArrayBuffer): Promise` #### Parameters - **key** (string | ArrayBuffer | CryptoKey) - Required - The secret key for signing. Can be a raw key string, ArrayBuffer, or a CryptoKey object. - **message** (string | ArrayBuffer) - Required - The message to sign. #### Returns - `Promise` - The generated signature in the configured encoding or as an ArrayBuffer. ### verify #### Description Verifies if a given signature is valid for a message using the provided key. #### Method Signature `verify(key: string | ArrayBuffer | CryptoKey, message: string | ArrayBuffer, signature: string | ArrayBuffer): Promise` #### Parameters - **key** (string | ArrayBuffer | CryptoKey) - Required - The secret key for verification. Can be a raw key string, ArrayBuffer, or a CryptoKey object. - **message** (string | ArrayBuffer) - Required - The message to verify. - **signature** (string | ArrayBuffer) - Required - The signature to verify. #### Returns - `Promise` - `true` if the signature is valid, `false` otherwise. ### importKey #### Description Imports a raw key into a CryptoKey object for use with `sign` or `verify`. #### Method Signature `importKey(key: string | ArrayBuffer, usage: "sign" | "verify" | "sign" | "verify"): Promise` #### Parameters - **key** (string | ArrayBuffer) - Required - The raw key material. - **usage** (string) - Required - The intended usage of the key ("sign" or "verify"). #### Returns - `Promise` - The imported CryptoKey object. ``` -------------------------------- ### Create and Use SHA-256 Hash Source: https://github.com/better-auth/utils/blob/main/_autodocs/MODULES-SUMMARY.md Demonstrates how to create a SHA-256 hash object with hex encoding and compute a digest for given data. This is useful for data fingerprinting or integrity verification. ```typescript const hash = createHash("SHA-256", "hex"); const digest = await hash.digest(data); ``` -------------------------------- ### Encode Data for HTTP Transmission Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/base64.md Encodes data into a URL-safe Base64 string without padding, optimized for use in URL parameters. Includes an example of decoding on the server. ```typescript // Encode for URL parameter (no padding to save space) const data = "sensitive data"; const encoded = base64Url.encode(data, { padding: false }); const url = `https://example.com/api?data=${encoded}`; // Decode on server const decoded = base64Url.decode(encoded); ``` -------------------------------- ### OTP Generation and Verification Configuration Source: https://github.com/better-auth/utils/blob/main/_autodocs/MODULES-SUMMARY.md Shows how to create an OTP generator with custom digits and period, generate a TOTP code, verify a user-provided OTP with a time window, and generate a QR code URL. ```typescript const otp = createOTP(secret, { digits: 6, period: 30 }); const code = await otp.totp(); const valid = await otp.verify(userCode, { window: 1 }); const qrUrl = otp.url("MyApp", "user@example.com"); ``` -------------------------------- ### QR Code Integration for OTP Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/otp.md Demonstrates how to generate a QR code data URL from an otpauth:// URL using a QR code library. This QR code can then be displayed to users for provisioning authenticator apps. ```typescript // Using a QR code library (e.g., qrcode) import QRCode from 'qrcode'; const qrUrl = otp.url("MyApp", "user@example.com"); const qrCodeDataUrl = await QRCode.toDataURL(qrUrl); // Display qrCodeDataUrl in tag ``` -------------------------------- ### Using Utility Types Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Demonstrates how to import and use utility types like SHAFamily and EncodingFormat for parameter validation in TypeScript. ```typescript import type { SHAFamily, EncodingFormat } from "@better-auth/utils"; function hashData(algorithm: SHAFamily, encoding: EncodingFormat) { // Typed parameter validation } ``` -------------------------------- ### Base64 URL-Safe Encoding Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hmac.md Example of creating an HMAC signature using Base64 URL-safe encoding. This is useful for transmitting signatures in URLs or other contexts where '+' and '/' characters are problematic. ```typescript const hmac = createHMAC("SHA-256", "base64url"); const signature = await hmac.sign("secret", "data"); console.log(signature); // "...a_b-cDE=" (URL-safe format) ``` -------------------------------- ### Create SHA-256 Hash with Hex Encoding Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hash.md Use this snippet to generate a SHA-256 hash of a string and get the output in hexadecimal format. Ensure the createHash function is imported from '@better-auth/utils/hash'. ```typescript import { createHash } from "@better-auth/utils/hash"; const hash = createHash("SHA-256", "hex"); const digest = await hash.digest("password"); console.log(digest); // "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ``` -------------------------------- ### Environment Support Source: https://github.com/better-auth/utils/blob/main/_autodocs/DOCUMENTATION-MANIFEST.txt Information on the environments and platforms that are officially supported by the @better-auth/utils library. ```APIDOC ## Environment Support Documented Support For: ✓ Node.js 15+ (crypto.webcrypto) ✓ Modern Browsers (Web Crypto API) ✓ Cloudflare Workers (Workers crypto API) ✓ Deno (Web Crypto API) Browser Compatibility: ✓ Chrome/Edge 37+ ✓ Firefox 34+ ✓ Safari 11+ ✓ Opera 24+ ``` -------------------------------- ### OTP Generation and Verification Source: https://github.com/better-auth/utils/blob/main/_autodocs/QUICK-REFERENCE.md Shows how to create and use One-Time Password (OTP) generators for both HOTP (counter-based) and TOTP (time-based) authentication, including verification and generating QR code URLs. ```APIDOC ## OTP ### Description Provides functionalities for generating and verifying One-Time Passwords (OTP), supporting both HMAC-based One-Time Password (HOTP) and Time-based One-Time Password (TOTP) algorithms. ### Usage **Create OTP Generator** ```typescript const otp = createOTP("secret", { digits: 6, period: 30 }); ``` **Generate HOTP** ```typescript const hotp = await otp.hotp(1234); // counter ``` **Generate TOTP** ```typescript const totp = await otp.totp(); ``` **Verify TOTP** ```typescript const isValid = await otp.verify(code, { window: 1 }); // window default: 1 ``` **Generate QR Code URL** ```typescript const url = otp.url("Issuer", "account@example.com"); ``` ``` -------------------------------- ### Get Web Crypto Subtle Interface Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Retrieves the Web Crypto API's `SubtleCrypto` interface, compatible with Node.js, browsers, and Cloudflare Workers. This utility is used internally by cryptographic modules. ```typescript import { getWebcryptoSubtle } from "@better-auth/utils"; const subtle = getWebcryptoSubtle(); const hashBuffer = await subtle.digest("SHA-256", data); ``` -------------------------------- ### Processing UTF-16 Network Data Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/binary.md Decode network data that is encoded using UTF-16. This example shows decoding UTF-16 Little Endian data, including handling the Byte Order Mark (BOM). ```typescript // Receive UTF-16 encoded data from network const networkData = new Uint8Array([ // UTF-16 LE BOM 0xFF, 0xFE, // "Hi" in UTF-16 LE 0x48, 0x00, 0x69, 0x00 ]); const text = binary.decode(networkData, "utf-16"); console.log(text); // Contains "Hi" (BOM handling varies) ``` -------------------------------- ### Base64 Encoding and Decoding Source: https://github.com/better-auth/utils/blob/main/_autodocs/QUICK-REFERENCE.md Illustrates how to perform Base64 encoding and decoding using both standard and URL-safe variants. ```APIDOC ## Base64 ### Description Provides utilities for Base64 encoding and decoding, including a URL-safe variant. ### Usage **Encode Data** ```typescript const encoded = base64.encode(data, { padding: true }); // data: string | ArrayBuffer | TypedArray const encoded2 = base64Url.encode(data, { padding: true }); // URL-safe variant ``` **Decode Data** ```typescript const decoded = base64.decode(data); // Returns Uint8Array const decoded2 = base64Url.decode(data); ``` ``` -------------------------------- ### Generate RSA Key Pair and Perform Operations Source: https://github.com/better-auth/utils/blob/main/_autodocs/MODULES-SUMMARY.md Demonstrates generating an RSA key pair, encrypting data with the public key, and signing data with the private key. Supports configurable modulus length and hash algorithms. ```typescript const { publicKey, privateKey } = await rsa.generateKeyPair(2048, "SHA-256"); const encrypted = await rsa.encrypt(publicKey, data); const sig = await rsa.sign(privateKey, data); ``` -------------------------------- ### Importing Multiple Modules from @better-auth/utils Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Demonstrates how to import and use different functionalities from various submodules of the @better-auth/utils library. Each module can be imported independently. ```typescript import { createHash } from "@better-auth/utils/hash"; import { createHMAC } from "@better-auth/utils/hmac"; import { rsa } from "@better-auth/utils/rsa"; // Each module is independently importable const hash = createHash("SHA-256", "hex"); const hmac = createHMAC("SHA-256", "hex"); const keyPair = await rsa.generateKeyPair(2048); ``` -------------------------------- ### Module Exports and Public API Structure Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md The main entry point of `@better-auth/utils` exports only the `getWebcryptoSubtle()` utility. Other functionalities are accessed through submodule imports, providing a clear structure for public API usage. ```APIDOC ## Module Exports The main entry point exports only the `getWebcryptoSubtle()` utility. All other functionality is accessed through submodule imports: ### Public API Structure ``` @better-auth/utils ├── hash → Hash functions (SHA family) ├── hmac → HMAC signing and verification ├── random → Cryptographically secure random strings ├── rsa → RSA encryption, decryption, signing, verification ├── ecdsa → ECDSA signing and verification ├── otp → One-time password generation (HOTP/TOTP) ├── base64 → Base64 encoding and decoding ├── hex → Hexadecimal encoding and decoding ├── binary → Binary data encoding with multiple text formats ├── base32 → Base32 and Base32hex encoding/decoding └── password → Password hashing with Scrypt ``` ### Example of Using Multiple Modules ```typescript import { createHash } from "@better-auth/utils/hash"; import { createHMAC } from "@better-auth/utils/hmac"; import { rsa } from "@better-auth/utils/rsa"; // Each module is independently importable const hash = createHash("SHA-256", "hex"); const hmac = createHMAC("SHA-256", "hex"); const keyPair = await rsa.generateKeyPair(2048); ``` ``` -------------------------------- ### Unified Crypto Operations with Better Auth Utilities Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/index-and-utilities.md Demonstrates combining hashing, HMAC signing, and encoding utilities for common security tasks like password storage and API signature generation. Ensure necessary modules are imported. ```typescript import { createHash } from "@better-auth/utils/hash"; import { createHMAC } from "@better-auth/utils/hmac"; import { hex } from "@better-auth/utils/hex"; import { base64Url } from "@better-auth/utils/base64"; // All utilities work seamlessly together const password = "user-password"; // 1. Hash for password field storage const pwHash = await createHash("SHA-256", "hex").digest(password); // 2. HMAC for API signature const signature = await createHMAC("SHA-256", "hex").sign("api-secret", password); // 3. Encoding for API token const token = base64Url.encode(hex.decode(signature), { padding: false }); ``` -------------------------------- ### Backup Codes Generation with HOTP Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/otp.md Generates a list of 10 backup codes using the HOTP algorithm. These codes should be stored securely for the user. ```typescript const baseSecret = "backup-secret-key"; const codes: string[] = []; for (let i = 0; i < 10; i++) { const code = await createOTP(baseSecret).hotp(i); codes.push(code); } // Store codes for user to write down ``` -------------------------------- ### ECDSA Operations Source: https://github.com/better-auth/utils/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to generate key pairs, import keys, sign data, verify signatures, and export keys using the ECDSA utility. ```APIDOC ## ECDSA ### Description Provides functionalities for Elliptic Curve Digital Signature Algorithm (ECDSA) operations including key generation, signing, verification, and key management. ### Usage **Generate Key Pair** ```typescript const { privateKey, publicKey } = await ecdsa.generateKeyPair("P-256"); // Supported Curves: "P-256" | "P-384" | "P-521" ``` **Import Keys** ```typescript const privKey = await ecdsa.importPrivateKey(privateKey, "P-256", false); // extractable default: false const pubKey = await ecdsa.importPublicKey(publicKey, "P-256", false); ``` **Sign Data** ```typescript const signature = await ecdsa.sign(privKey, data, "SHA-256"); // hash default: "SHA-256" ``` **Verify Signature** ```typescript const isValid = await ecdsa.verify(pubKey, { signature, data, hash: "SHA-256" }); ``` **Export Key** ```typescript const jwk = await ecdsa.exportKey(pubKey, "jwk"); // format: "jwk" | "spki" | "pkcs8" | "raw" ``` ``` -------------------------------- ### Create HMAC Instance Source: https://github.com/better-auth/utils/blob/main/README.md Use `createHMAC` to initialize an HMAC instance. Customize the hashing algorithm (e.g., 'SHA-256') and encoding format (e.g., 'hex'). ```typescript import { createHMAC } from './hmac'; const hmac = createHMAC("SHA-256", "hex"); // Customize algorithm and encoding ``` -------------------------------- ### Create and Use HMAC with SHA-256 Source: https://github.com/better-auth/utils/blob/main/_autodocs/MODULES-SUMMARY.md Shows how to create an HMAC object using SHA-256 with hex encoding, sign data with a secret key, and verify the signature. This is suitable for API request signing and message authentication. ```typescript const hmac = createHMAC("SHA-256", "hex"); const sig = await hmac.sign("secret", data); const valid = await hmac.verify("secret", data, sig); ``` -------------------------------- ### Generate Key Pair, Sign, and Verify Data with ECDSA Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/ecdsa.md Demonstrates the full cycle of generating an ECDSA key pair, signing a message, and then verifying the signature using the public key. Ensures data integrity and authenticity. ```typescript const { privateKey, publicKey } = await ecdsa.generateKeyPair("P-256"); const signingKey = await ecdsa.importPrivateKey(privateKey, "P-256"); const verifyKey = await ecdsa.importPublicKey(publicKey, "P-256"); const message = "Important message"; const signature = await ecdsa.sign(signingKey, message, "SHA-256"); const isValid = await ecdsa.verify(verifyKey, { signature, data: message, hash: "SHA-256", }); console.log(isValid); // true ``` -------------------------------- ### Secure Login with Password Verification Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/password.md Demonstrates a secure login function that verifies a user's password against a stored hash. It includes error handling for invalid credentials and potential database corruption, ensuring timing-safe behavior. ```typescript import { verifyPassword } from "@better-auth/utils/password"; async function login(email: string, password: string) { const user = await db.getUserByEmail(email); if (!user) { // Don't reveal whether email exists (timing-safe behavior) throw new Error("Invalid credentials"); } try { const isValid = await verifyPassword(user.passwordHash, password); if (!isValid) { throw new Error("Invalid credentials"); } } catch (error) { if (error.message === "Invalid password hash") { // Corrupted hash in database console.error("Database corruption detected"); throw new Error("System error during authentication"); } throw error; } } ``` -------------------------------- ### Sign with Imported Key Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hmac.md Shows how to import a secret key once and reuse it for signing multiple messages. This is more efficient if signing many messages. ```typescript const hmac = createHMAC("SHA-256", "hex"); const secretKey = "my-secret"; // Import key once const key = await hmac.importKey(secretKey, "sign"); // Sign multiple messages with same key const sig1 = await hmac.sign(key, "message1"); const sig2 = await hmac.sign(key, "message2"); ``` -------------------------------- ### Module Import Map for Better-Auth Utils Source: https://github.com/better-auth/utils/blob/main/_autodocs/QUICK-REFERENCE.md This map shows the available modules within the @better-auth/utils package and their primary exported functions. Use these paths to import specific utilities into your project. ```text @better-auth/utils ├── /hash → { createHash } ├── /hmac → { createHMAC } ├── /random → { createRandomStringGenerator } ├── /rsa → { rsa } ├── /ecdsa → { ecdsa } ├── /otp → { createOTP } ├── /base64 → { base64, base64Url } ├── /hex → { hex } ├── /binary → { binary } ├── /base32 → { base32, base32hex } └── /password → { hashPassword, verifyPassword } ``` -------------------------------- ### Create OTP Generator Instance Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/otp.md Use `createOTP` to initialize an OTP generator with a secret key and optional configuration for digits and TOTP period. The returned object provides methods for HOTP, TOTP, verification, and URL generation. ```typescript import { createOTP } from "@better-auth/utils/otp"; const otp = createOTP("my-secret-key", { digits: 6 }); // Generate OTP at counter 1234 const hotp1 = await otp.hotp(1234); console.log(hotp1); // "123456" (example, actual value varies) // Next counter const hotp2 = await otp.hotp(1235); console.log(hotp2); // "654321" ``` -------------------------------- ### ID Generation with Base32 Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/base32.md Demonstrates generating a random string and encoding it to Base32 for URL-safe identifiers. ```APIDOC ### ID Generation with Base32 ```typescript import { base32 } from "@better-auth/utils/base32"; import { createRandomStringGenerator } from "@better-auth/utils/random"; // Generate random bytes const randomGen = createRandomStringGenerator("0-9", "a-z"); const randomId = randomGen(16); // Encode to base32 for URL safety const base32Id = base32.encode(randomId, { padding: false }); console.log(base32Id); // Can be used in URLs without encoding ``` ``` -------------------------------- ### Signing Data with HMAC Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hmac.md This snippet demonstrates how to sign arbitrary data using a secret key and a specified HMAC instance. The output signature format is determined by the encoding set during HMAC creation. ```typescript const hmac = createHMAC("SHA-256", "hex"); const signature = await hmac.sign("secret-key", "text to sign"); console.log(signature); // "a1b2c3d4e5f6..." (hex string) ``` -------------------------------- ### Authentication & Random Source: https://github.com/better-auth/utils/blob/main/_autodocs/INDEX.md Provides utilities for One-Time Password (OTP) generation/verification and cryptographically secure random string generation. ```APIDOC ## Authentication & Random ### `otp.md` One-time password generation and verification for 2FA/MFA. **Functions:** - `createOTP(secret, opts?)` — Create OTP instance - `.hotp(counter)` — Generate HOTP - `.totp()` — Generate TOTP - `.verify(otp, options?)` — Verify TOTP - `.url(issuer, account)` — Generate QR code URL **Standards:** RFC 4226 (HOTP), RFC 6238 (TOTP) ### `random.md` Cryptographically secure random string generation. **Functions:** - `createRandomStringGenerator(...baseAlphabets)` — Create generator - Returns function `(length, ...alphabets?)` for generating random strings **Alphabets:** a-z, A-Z, 0-9, -_ ``` -------------------------------- ### Format Conversion Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/base32.md Illustrates converting data between standard Base32 and Base32hex formats. ```APIDOC ### Format Conversion ```typescript // Convert between base32 and base32hex const data = "test data"; const base32Encoded = base32.encode(data, { padding: false }); console.log(base32Encoded); // "ORSXG5DFORZA====" // Decode and re-encode to hex variant const decoded = base32.decode(base32Encoded); const hexEncoded = base32hex.encode(decoded, { padding: false }); console.log(hexEncoded); // "0D4FB6U4F9CA" ``` ``` -------------------------------- ### verify() Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/otp.md Verifies a provided TOTP against the secret key. It allows for an optional time window tolerance to account for clock drift between the client and server. Uses constant-time comparison for security. ```APIDOC ## verify() ### Description Verifies a TOTP against the secret with optional time window tolerance. ### Signature ```typescript async verify( otp: string, options?: { window?: number }, ): Promise ``` ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `otp` | `string` | — | OTP code to verify (any length, though must match generated format) | | `options.window` | `number` | `1` | Time window tolerance in periods (e.g., window=1 checks current ± 1 period) | ### Return Type ```typescript Promise ``` `true` if OTP is valid within the time window, `false` otherwise. ### Example ```typescript const otp = createOTP("my-secret-key", { digits: 6, period: 30 }); // Generate a TOTP const code = await otp.totp(); // Verify immediately const isValid = await otp.verify(code); console.log(isValid); // true // Verify with wider window (±1 period = ±30 seconds) const isValidWithWindow = await otp.verify(code, { window: 1 }); console.log(isValidWithWindow); // true // Verify wrong code const isInvalid = await otp.verify("000000"); console.log(isInvalid); // false ``` ### Window Behavior | Window | Tolerance | Use Case | |--------|-----------|----------| | `0` | Current period only | Strict verification (rare) | | `1` | ±1 period (±30s default) | Standard MFA (recommended) | | `2` | ±2 periods (±60s default) | Lenient (for slower connections) | The function checks OTP validity for: current time, current-period, current+period, ..., current-(window)×period, ..., current+(window)×period. ### Timing Safety - **Constant-time comparison**: Verification uses constant-time string comparison to prevent timing attacks (implementation checks all characters regardless of early mismatch). ``` -------------------------------- ### ECDSA Key Pair Generation, Signing, and Verification Source: https://github.com/better-auth/utils/blob/main/_autodocs/MODULES-SUMMARY.md Demonstrates generating an ECDSA key pair, signing data with the private key, and verifying the signature with the public key. Supports P-256 curve and SHA-256 hash. ```typescript const { privateKey, publicKey } = await ecdsa.generateKeyPair("P-256"); const sig = await ecdsa.sign(privateKey, data, "SHA-256"); const valid = await ecdsa.verify(publicKey, {signature, data, hash: "SHA-256"}); ``` -------------------------------- ### Password Hashing Implementation by Environment Source: https://github.com/better-auth/utils/blob/main/_autodocs/README.md Shows conditional exports for the password module. The browser/default path uses an async JavaScript implementation, while Node.js and Cloudflare Workers automatically select a native implementation. ```typescript // Browser/Default: Async JavaScript implementation import { hashPassword } from "@better-auth/utils/password"; // Node.js & Cloudflare Workers: Native implementation // (Auto-selected based on environment) ``` -------------------------------- ### Import RSA Public Key Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/rsa.md Imports a JWK-formatted RSA public key for encryption. Ensure the JWK object is correctly formatted. ```typescript const publicJwk = { kty: "RSA", n: "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtV...", e: "AQAB" }; const publicKey = await rsa.importKey(publicJwk, "encrypt", "SHA-256"); ``` -------------------------------- ### Create HMAC Instance, Sign, and Verify Source: https://github.com/better-auth/utils/blob/main/_autodocs/QUICK-REFERENCE.md The `createHMAC` function generates an HMAC instance. Use `importKey` to load a secret key, `sign` to create a signature for data, and `verify` to check if a signature is valid for the given data. ```typescript import { createHMAC } from "@better-auth/utils/hmac"; const hmac = createHMAC("SHA-256", "hex"); // Import key const key = await hmac.importKey("secret", "sign"); // Returns CryptoKey // Sign const signature = await hmac.sign(hmacKey, data); // Verify const isValid = await hmac.verify(hmacKey, data, signature); ``` -------------------------------- ### createHMAC() Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hmac.md Creates an HMAC instance with specified SHA algorithm and output encoding format. This function returns an object containing methods for importing keys, signing data, and verifying signatures. ```APIDOC ## createHMAC() ### Description Creates an HMAC instance with specified SHA algorithm and output encoding format. This function returns an object containing methods for importing keys, signing data, and verifying signatures. ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `algorithm` | `SHAFamily` | `"SHA-256"` | Hash algorithm: `"SHA-1"`, `"SHA-256"`, `"SHA-384"`, or `"SHA-512"` | | `encoding` | `EncodingFormat` | `"none"` | Output format for signatures: `"none"` (binary), `"hex"`, `"base64"`, `"base64url"`, or `"base64urlnopad"` | ### Return Type Returns an object with three async methods: #### importKey() ```typescript importKey( key: string | ArrayBuffer | TypedArray, keyUsage: "sign" | "verify", ): Promise ``` Imports a raw secret key into a `CryptoKey` object for use with `sign()` and `verify()`. **Parameters:** - `key`: Secret key as string (UTF-8 encoded), `ArrayBuffer`, or `TypedArray` - `keyUsage`: `"sign"` (for use with `sign()`) or `"verify"` (for use with `verify()`) **Returns:** Promise resolving to a `CryptoKey` suitable for the specified usage. **Example:** ```typescript const hmac = createHMAC("SHA-256"); const secretKey = "my-secret-key"; const key = await hmac.importKey(secretKey, "sign"); ``` #### sign() ```typescript sign( hmacKey: string | CryptoKey, data: string | ArrayBuffer | TypedArray, ): Promise ``` Signs data using a secret key, returning a signature in the specified encoding format. **Parameters:** - `hmacKey`: Secret key as string (auto-imported), or a `CryptoKey` from `importKey()` - `data`: Data to sign as string (UTF-8 encoded), `ArrayBuffer`, or `TypedArray` **Returns:** Promise resolving to: - If `encoding` is `"none"`: `ArrayBuffer` with raw signature bytes - Otherwise: String in the specified encoding format (`"hex"`, `"base64"`, `"base64url"`, `"base64urlnopad"`) **Example:** ```typescript const hmac = createHMAC("SHA-256", "hex"); const signature = await hmac.sign("secret-key", "text to sign"); console.log(signature); // "a1b2c3d4e5f6..." (hex string) ``` #### verify() ```typescript verify( hmacKey: CryptoKey | string, data: string | ArrayBuffer | TypedArray, signature: string | ArrayBuffer | TypedArray, ): Promise ``` Verifies that a signature matches the original data using a secret key. **Parameters:** - `hmacKey`: Secret key as string (auto-imported), or a `CryptoKey` from `importKey()` - `data`: Original data that was signed (string, `ArrayBuffer`, or `TypedArray`) - `signature`: Signature to verify in the same encoding format as `sign()` output **Returns:** Promise resolving to `true` if signature is valid, `false` otherwise. **Example:** ```typescript const hmac = createHMAC("SHA-256", "hex"); const key = await hmac.importKey("secret-key", "verify"); const isValid = await hmac.verify(key, "text to sign", "a1b2c3d4e5f6..."); ``` ``` -------------------------------- ### Sign and Verify with Auto-Imported Key Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/hmac.md Demonstrates signing and verifying a message using a raw secret key. The key is automatically imported by the HMAC utility. ```typescript import { createHMAC } from "@better-auth/utils/hmac"; const hmac = createHMAC("SHA-256", "hex"); // Sign using raw secret key const signature = await hmac.sign("my-secret", "message"); // Verify using same raw secret key const isValid = await hmac.verify("my-secret", "message", signature); console.log(isValid); // true ``` -------------------------------- ### Create SHA-256 Hash Source: https://github.com/better-auth/utils/blob/main/README.md Create a SHA-256 hash of a given input. The output can be encoded as a buffer, hex, or base64 string. ```typescript import { createHash } from "@better-auth/utils/hash" const hashBuffer = await createHash("SHA-256").digest("text"); ``` ```typescript const hashInHex = await createHash("SHA-256", "hex").digest("text"); ``` ```typescript const hashInBase64 = await createHash("SHA-256", "base64").digest("text"); ``` -------------------------------- ### Migrate from bcrypt to @better-auth/utils/password Source: https://github.com/better-auth/utils/blob/main/_autodocs/api-reference/password.md Use this function to verify a password against an existing bcrypt hash and then generate a new hash using @better-auth/utils/password. This is useful during a transition period. ```typescript import bcrypt from 'bcrypt'; import { hashPassword, verifyPassword } from "@better-auth/utils/password"; // Verify with bcrypt during transition async function migrateFromBcrypt(oldBcryptHash: string, password: string) { const isValid = await bcrypt.compare(password, oldBcryptHash); if (!isValid) throw new Error("Invalid password"); // Generate new Scrypt hash return await hashPassword(password); } ```