### Install and Help Commands Source: https://otplib.yeojz.dev/guide/cli.html Install the otplib-cli globally or run commands without installation using npx. Displays help information for both `otplibx` and `otplib` commands. ```bash # Global install npm install -g otplib-cli otplibx --help otplib --help # Run as needed (no install required) npx -p otplib-cli otplibx --help npx -p otplib-cli otplib --help ``` -------------------------------- ### Install @otplib/plugin-base32-alt Source: https://otplib.yeojz.dev/api/%40otplib/plugin-base32-alt Install the plugin using npm, pnpm, or yarn. ```bash npm install @otplib/plugin-base32-alt pnpm add @otplib/plugin-base32-alt yarn add @otplib/plugin-base32-alt ``` -------------------------------- ### Install @otplib/plugin-crypto-web Source: https://otplib.yeojz.dev/api/%40otplib/plugin-crypto-web Install the plugin using npm, pnpm, or yarn. ```bash npm install @otplib/plugin-crypto-web pnpm add @otplib/plugin-crypto-web yarn add @otplib/plugin-crypto-web ``` -------------------------------- ### Install otplib for Other Runtimes Source: https://otplib.yeojz.dev/api Install the otplib package for Bun and Deno runtimes. ```bash # Other runtimes bun add otplib denp install npm:otplib ``` -------------------------------- ### Install @otplib/hotp Source: https://otplib.yeojz.dev/api/%40otplib/hotp Install the @otplib/hotp package using npm, pnpm, or yarn. ```bash npm install @otplib/hotp pnpm install @otplib/hotp yarn add @otplib/hotp ``` -------------------------------- ### Install otplib with Bun Source: https://otplib.yeojz.dev/guide/runtime-compatibility Install the otplib package in a Bun project using the `bun add` command. ```bash bun add otplib ``` -------------------------------- ### Install @otplib/plugin-crypto-noble Source: https://otplib.yeojz.dev/api/%40otplib/plugin-crypto-noble Install the plugin using npm, pnpm, or yarn. ```bash npm install @otplib/plugin-crypto-noble pnpm add @otplib/plugin-crypto-noble yarn add @otplib/plugin-crypto-noble ``` -------------------------------- ### Install @otplib/totp Source: https://otplib.yeojz.dev/api/%40otplib/totp Install the @otplib/totp package using npm, pnpm, or yarn. ```bash npm install @otplib/totp pnpm install @otplib/totp yarn add @otplib/totp ``` -------------------------------- ### Install otplib for Node.js Source: https://otplib.yeojz.dev/api Install the otplib package for Node.js environments using npm, pnpm, or yarn. ```bash # Node npm install otplib pnpm add otplib yarn add otplib ``` -------------------------------- ### Install otplib Main Package Source: https://otplib.yeojz.dev/guide/getting-started Install the main otplib package which works across Node.js, browsers, and edge environments. ```bash npm install otplib ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://otplib.yeojz.dev/api/_media/CONTRIBUTING.html Clone the otplib repository and install project dependencies using pnpm. ```bash git clone https://github.com/yeojz/otplib.git cd otplib pnpm install ``` -------------------------------- ### Install Individual otplib Packages Source: https://otplib.yeojz.dev/guide/getting-started Install individual otplib modules for smaller bundle sizes or platform-specific optimizations. ```bash # Core functionality npm install @otplib/core @otplib/totp # For Node.js npm install @otplib/plugin-crypto-node # For browsers npm install @otplib/plugin-crypto-web # For Base32 encoding npm install @otplib/plugin-base32-scure # For Error types and Core utilities npm install @otplib/core ``` -------------------------------- ### Install @otplib/plugin-crypto-node Source: https://otplib.yeojz.dev/api/%40otplib/plugin-crypto-node Install the Node.js crypto plugin for otplib using npm, pnpm, or yarn. ```bash npm install @otplib/plugin-crypto-node pnpm add @otplib/plugin-crypto-node yarn add @otplib/plugin-crypto-node ``` -------------------------------- ### Install otplib-cli Source: https://otplib.yeojz.dev/tools/cli.html Install the otplib-cli globally using npm. This command makes the otplib-cli tool available in your terminal. ```bash npm install -g otplib-cli ``` -------------------------------- ### QR Code Integration Example Source: https://otplib.yeojz.dev/api/%40otplib/uri Demonstrates how to generate an otpauth:// URI and then use an external library (like qrcode) to create a QR code from it. ```typescript import { generateTOTP } from "@otplib/uri"; import QRCode from "qrcode"; // Example library const uri = generateTOTP({ issuer: "MyApp", label: "user@example.com", secret: "GEZDGNBVGY3TQOJQGEZDGNBVGY", }); // Generate QR code as data URL const qrDataUrl = await QRCode.toDataURL(uri); // Or generate as SVG const qrSvg = await QRCode.toString(uri, { type: "svg" }); ``` -------------------------------- ### Creating a Custom Base32 Plugin (Plaintext Example) Source: https://otplib.yeojz.dev/api/%40otplib/core Use `createBase32Plugin` to wrap encode/decode functions. The plaintext example demonstrates bypassing Base32 encoding by using UTF-8 passthrough. ```typescript import { createBase32Plugin, stringToBytes, bytesToString } from "@otplib/core"; // Example: UTF-8 passthrough (no Base32 encoding) const plaintextPlugin = createBase32Plugin({ name: "plaintext", encode: bytesToString, decode: stringToBytes, }); ``` -------------------------------- ### Run Deno Distribution Tests Source: https://otplib.yeojz.dev/guide/testing.html Execute distribution tests for the Deno runtime. Requires Deno to be installed locally. ```bash pnpm test:dist-deno ``` -------------------------------- ### Run Bun Distribution Tests Source: https://otplib.yeojz.dev/guide/testing.html Execute distribution tests for the Bun runtime. Requires Bun to be installed locally. ```bash pnpm test:dist-bun ``` -------------------------------- ### Using Noble Crypto Plugin with generate Source: https://otplib.yeojz.dev/guide/plugins Example of using the universal Noble crypto plugin with the otplib generate function for cross-platform token creation. ```typescript import { generate } from "otplib"; import { crypto } from "@otplib/plugin-crypto-noble"; const token = await generate({ secret, crypto, }); ``` -------------------------------- ### Base32 Secret Example Source: https://otplib.yeojz.dev/api/otplib Demonstrates the standard Base32 secret format expected by otplib for authenticator compatibility. ```typescript // Base32 secret (standard format for authenticator compatibility) const secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY"; ``` -------------------------------- ### Conventional Commits Example Source: https://otplib.yeojz.dev/api/_media/CONTRIBUTING.html Examples of commit message formats following the conventional commits specification. ```text feat: add new feature fix: resolve issue with token generation docs: update API documentation test: add edge case tests refactor: simplify validation logic chore: update dependencies ``` -------------------------------- ### Using Node.js Crypto Plugin with generate Source: https://otplib.yeojz.dev/guide/plugins Example of using the Node.js crypto plugin with the otplib generate function for token creation. ```typescript import { generate } from "otplib"; import { crypto } from "@otplib/plugin-crypto-node"; const token = await generate({ secret, crypto, }); ``` -------------------------------- ### Using Web Crypto Plugin with generate Source: https://otplib.yeojz.dev/guide/plugins Example of using the Web Crypto API plugin with the otplib generate function for token creation in browser environments. ```typescript import { generate } from "otplib"; import { crypto } from "@otplib/plugin-crypto-web"; const token = await generate({ secret, crypto, }); ``` -------------------------------- ### Docker-based Multi-Runtime Testing Source: https://otplib.yeojz.dev/api/_media/CONTRIBUTING.html Execute tests across multiple runtimes (Node.js, Bun, Deno) using Docker without local installation. ```bash # Test a specific runtime ./scripts/test-docker.sh node-20 ./scripts/test-docker.sh bun ./scripts/test-docker.sh deno-2 # Test all runtimes ./scripts/test-docker.sh all ``` -------------------------------- ### Cloudflare Worker Example Source: https://otplib.yeojz.dev/api/%40otplib/plugin-crypto-web Example of integrating the Web Crypto API plugin for OTP operations within a Cloudflare Worker environment. ```typescript // Cloudflare Worker example import { crypto } from "@otplib/plugin-crypto-web"; export default { async fetch(request) { // Use crypto for OTP operations }, }; ``` -------------------------------- ### Initialize otplibx with Encrypted Storage Source: https://otplib.yeojz.dev/tools/cli.html Initialize otplibx to use an encrypted .env file for storing OTP secrets. This is part of the setup for using otplibx's built-in encryption. ```bash otplibx init ``` -------------------------------- ### Complete Example with Database Replay Protection Source: https://otplib.yeojz.dev/guide/advanced-usage Implement replay protection by storing and updating the last used time step in a database. This prevents tokens from being reused. ```typescript import { verify } from "otplib"; import { Database } from "your-database"; const db = new Database(); async function login(userId: string, token: string): Promise { // Get user's secret and last used time step const { secret, lastTimeStep } = await db.getUser(userId); // Verify token with replay protection const result = await verify({ secret, token, afterTimeStep: lastTimeStep, // Reject previously used time steps }); if (result.valid) { // Update last used time step to prevent reuse await db.updateLastTimeStep(userId, result.timeStep); return true; } return false; } // Usage const success = await login("user-123", "123456"); if (success) { console.log("Login successful!"); } else { console.log("Invalid token or token already used"); } ``` -------------------------------- ### Generate and Verify TOTP Token Source: https://otplib.yeojz.dev/api Example of generating a secret, generating a TOTP token, and verifying it using otplib. ```typescript import { generateSecret, generate, verify, generateURI } from "otplib"; // Generate a secret const secret = generateSecret(); // Generate a TOTP token const token = await generate({ secret }); // Verify a token const result = await verify({ secret, token }); console.log(result.valid); // true ``` -------------------------------- ### TOTP Example with Guardrail Overrides Source: https://otplib.yeojz.dev/guide/danger-zone Configures a TOTP instance with custom guardrails for period and window size, and demonstrates token generation and verification with epoch tolerance. ```typescript import { TOTP, createGuardrails } from "@otplib/totp"; import { crypto } from "@otplib/plugin-crypto-node"; import { base32 } from "@otplib/plugin-base32-scure"; const totp = new TOTP({ secret: "GEZDGNBVGY3TQOJQGEZDGNBVGY", period: 60, // 60-second periods crypto, base32, guardrails: createGuardrails({ MAX_PERIOD: 120, // Allow up to 2-minute periods MAX_WINDOW: 5, // Tighter window than default }), }); const token = await totp.generate(); const result = await totp.verify(token, { epochTolerance: 30 }); ``` -------------------------------- ### Using Custom OTP Hooks with Steam Guard Source: https://otplib.yeojz.dev/api/%40otplib/core/types/type-aliases/OTPHooks.html Demonstrates how to integrate custom OTP hooks, such as those provided by the Steam Guard plugin, into the token generation process. This example shows the usage of the 'steam' plugin which includes custom encodeToken and validateToken hooks. ```typescript import { generate } from '@otplib/totp'; import { steam } from '@otplib/community-plugin-steam'; const code = await generate({ secret, crypto, ...steam, // { digits: 5, hooks: { encodeToken, validateToken } } }); ``` -------------------------------- ### Generating Secret with Explicit Plugins Source: https://otplib.yeojz.dev/api/%40otplib/core When using `@otplib/core` directly, you must supply crypto and Base32 plugins explicitly. This example uses Node.js crypto and scure-base32 plugins. ```typescript import { generateSecret } from "@otplib/core"; import { NodeCryptoPlugin } from "@otplib/plugin-crypto-node"; import { ScureBase32Plugin } from "@otplib/plugin-base32-scure"; const secret = generateSecret({ crypto: new NodeCryptoPlugin(), base32: new ScureBase32Plugin(), length: 20, // 160 bits — RFC 4226 recommendation }); ``` -------------------------------- ### Get Remaining Time for TOTP Source: https://otplib.yeojz.dev/api/%40otplib/totp/functions/getRemainingTime.html Calculates the remaining seconds in the current TOTP window. Defaults to a 30-second period. Ensure @otplib/totp is installed and imported. ```javascript import { getRemainingTime } from '@otplib/totp'; const remaining = getRemainingTime(); // Returns: 15 (seconds remaining in current 30-second window) ``` -------------------------------- ### dynamicTruncate() Source: https://otplib.yeojz.dev/api/%40otplib/core/utils/functions/dynamicTruncate.html Performs Dynamic Truncation as per RFC 4226 Section 5.3. It takes the low-order 4 bits of the last byte as an offset, extracts 4 bytes starting at that offset, and masks the most significant bit to get a 31-bit unsigned integer. This ensures consistent extraction across different HMAC output sizes while producing a value that fits in a signed 32-bit integer. ```APIDOC ## Function: dynamicTruncate() ### Description Performs Dynamic Truncation as per RFC 4226 Section 5.3. The algorithm involves taking the low-order 4 bits of the last byte as an offset, extracting 4 bytes starting at that offset, and masking the most significant bit to obtain a 31-bit unsigned integer. This process guarantees consistent extraction across various HMAC output sizes and yields a value compatible with a signed 32-bit integer. ### Signature `dynamicTruncate(hmacResult: Uint8Array): number` ### Parameters #### hmacResult - **Type**: `Uint8Array` - **Description**: HMAC result (at least 20 bytes for SHA-1). ### Returns - **Type**: `number` - **Description**: Truncated 31-bit unsigned integer. ### See - RFC 4226 Section 5.3 - Generating an HOTP Value ``` -------------------------------- ### Configure Deno import map for otplib: Source: https://otplib.yeojz.dev/guide/runtime-compatibility Set up an import map in 'deno.json' to alias 'otplib' for easier imports. ```json { "imports": { "otplib": "npm:otplib" } } ``` -------------------------------- ### OTP Class Initialization and Basic Usage (TOTP) Source: https://otplib.yeojz.dev/api/otplib/class/classes/OTP.html Demonstrates creating an OTP instance with the TOTP strategy, generating a secret, and then generating and verifying a token. ```typescript import { OTP } from 'otplib'; // Create OTP instance with TOTP strategy (default) const otp = new OTP({ strategy: 'totp' }); // Generate and verify const secret = otp.generateSecret(); const token = await otp.generate({ secret }); const result = await otp.verify({ secret, token }); ``` -------------------------------- ### HOTP Class Initialization and Usage Source: https://otplib.yeojz.dev/api/%40otplib/hotp/classes/HOTP.html Demonstrates how to initialize the HOTP class with custom crypto and base32 plugins, generate a secret, generate a token for a specific counter, and verify a token. ```typescript import { HOTP } from '@otplib/hotp'; import { NodeCryptoPlugin } from '@otplib/plugin-crypto-node'; import { ScureBase32Plugin } from '@otplib/plugin-base32-scure'; const hotp = new HOTP({ issuer: 'MyApp', label: 'user@example.com', counter: 0, crypto: new NodeCryptoPlugin(), base32: new ScureBase32Plugin(), }); const secret = hotp.generateSecret(); const token = await hotp.generate(0); const isValid = await hotp.verify({ token, counter: 0 }); ``` -------------------------------- ### Run all benchmarks Source: https://otplib.yeojz.dev/guide/benchmarks.html Execute all available benchmarks within the @repo/benchmarks package using pnpm. ```bash pnpm --filter @repo/benchmarks bench ``` -------------------------------- ### Rate Limiting Strategy Example Source: https://otplib.yeojz.dev/guide/rfc-implementations.html An example rate limiting strategy based on RFC 4226 Section 7.3. Implements a maximum number of failed attempts before lockout. ```typescript // Example rate limiting strategy const MAX_ATTEMPTS = 3; const LOCKOUT_DURATION = 30 * 60; // 30 minutes function checkRateLimit(userId: string): boolean { const attempts = getFailedAttempts(userId); if (attempts >= MAX_ATTEMPTS) { const lockoutEnd = getLockoutEndTime(userId); if (Date.now() < lockoutEnd) { return false; // Locked out } } return true; } ``` -------------------------------- ### OTP Class Initialization and Basic Usage (HOTP) Source: https://otplib.yeojz.dev/api/otplib/class/classes/OTP.html Shows how to initialize the OTP class with the HOTP strategy and generate a token using a provided secret and counter. ```typescript import { OTP } from 'otplib'; const otp = new OTP({ strategy: 'hotp' }); const token = await otp.generate({ secret: 'ABC123', counter: 0 }); ``` -------------------------------- ### Initialize TOTP and Generate Token Source: https://otplib.yeojz.dev/api/%40otplib/totp/classes/TOTP.html Demonstrates initializing the TOTP class with crypto and base32 plugins, generating a secret, and then generating a TOTP token. It also shows how to verify the generated token. ```typescript import { TOTP } from '@otplib/totp'; import { NodeCryptoPlugin } from '@otplib/plugin-crypto-node'; import { ScureBase32Plugin } from '@otplib/plugin-base32-scure'; const totp = new TOTP({ issuer: 'MyApp', label: 'user@example.com', crypto: new NodeCryptoPlugin(), base32: new ScureBase32Plugin(), }); const secret = totp.generateSecret(); const token = await totp.generate(); const isValid = await totp.verify(token); ``` -------------------------------- ### Recommended Workflow: Pre-Push Distribution Tests Source: https://otplib.yeojz.dev/guide/testing.html Before pushing, verify that distribution tests pass across Node.js, Bun, and Deno runtimes to ensure published packages work correctly in target environments. ```bash pnpm build && pnpm test:dist-node pnpm test:dist-bun pnpm test:dist-deno ``` -------------------------------- ### Get Current TOTP Counter Value Source: https://otplib.yeojz.dev/api/%40otplib/totp/functions/getTimeStepUsed.html Call getTimeStepUsed without arguments to get the current counter value. The function uses the current Unix timestamp and a default period of 30 seconds. ```javascript import { getTimeStepUsed } from '@otplib/totp'; const counter = getTimeStepUsed(); // Returns: 12345 (current counter value) ``` -------------------------------- ### Run distribution tests for different runtimes: Source: https://otplib.yeojz.dev/guide/runtime-compatibility Test the distributed builds of otplib across Node.js, Bun, and Deno. ```bash # Distribution tests (requires pnpm build first) pnpm test:dist-node # Node.js pnpm test:dist-bun # Bun pnpm test:dist-deno # Deno ``` -------------------------------- ### Initialize and Use WebCryptoPlugin Source: https://otplib.yeojz.dev/api/%40otplib/plugin-crypto-web/classes/WebCryptoPlugin.html Instantiate the WebCryptoPlugin and perform HMAC and random byte generation. Requires importing the class. ```typescript import { WebCryptoPlugin } from '@otplib/plugin-crypto-web'; const crypto = new WebCryptoPlugin(); const hmac = await crypto.hmac('sha1', key, data); const random = crypto.randomBytes(20); ``` -------------------------------- ### Basic Usage of @otplib/plugin-base32-scure Source: https://otplib.yeojz.dev/api/%40otplib/plugin-base32-scure Demonstrates how to integrate the base32 plugin with otplib for generating secrets and tokens. Requires crypto and base32 plugins. ```typescript import { generateSecret, generate } from "otplib"; import { base32 } from "@otplib/plugin-base32-scure"; import { crypto } from "@otplib/plugin-crypto-node"; // Generate a secret const secret = generateSecret({ crypto, base32 }); // Generate a token const token = await generate({ secret, crypto, base32, }); ``` -------------------------------- ### Import otplib in Deno using npm: Source: https://otplib.yeojz.dev/guide/runtime-compatibility Import directly from npm using the 'npm:' specifier for Deno. ```typescript import { generate, generateSecret } from "npm:otplib"; const secret = generateSecret(); const token = await generate({ secret, strategy: "totp" }); ``` -------------------------------- ### Generate Token with Base64-Encoded Secret Source: https://otplib.yeojz.dev/api/%40otplib/plugin-base32-alt Use bypassAsBase64 to generate a token from a Base64-encoded secret. Ensure otplib, @otplib/plugin-crypto-node, and @otplib/plugin-base32-alt are installed. ```typescript import { generate } from "otplib"; import { crypto } from "@otplib/plugin-crypto-node"; import { bypassAsBase64 } from "@otplib/plugin-base32-alt"; const token = await generate({ secret: "SGVsbG8=", // "Hello" in base64 base32: bypassAsBase64, crypto, }); ``` -------------------------------- ### Verifying Token with Only Digits Source: https://otplib.yeojz.dev/guide/troubleshooting Tokens must contain only digits (0-9). This example shows a verification failure due to non-digit characters. ```typescript // Wrong - contains non-digit characters const result = await verify({ secret, token: "12345a", // 'a' is not a digit }); // Correct const result = await verify({ secret, token: "123456", }); ``` -------------------------------- ### Create Default and Custom Guardrails Source: https://otplib.yeojz.dev/api/%40otplib/core/utils/functions/createGuardrails.html Demonstrates how to create default guardrails and custom guardrails with specific overrides. Use this to understand the basic usage and how to check for overrides. ```typescript import { createGuardrails, hasGuardrailOverrides } from '@otplib/core' // Returns default singleton (no overrides) const defaults = createGuardrails(); hasGuardrailOverrides(defaults); // false // Creates new object with overrides const custom = createGuardrails({ MIN_SECRET_BYTES: 8, MAX_WINDOW: 200 }); hasGuardrailOverrides(custom); // true ``` -------------------------------- ### Use otplib in Cloudflare Workers / Vercel Edge: Source: https://otplib.yeojz.dev/guide/runtime-compatibility Example of generating a TOTP token in edge environments using specific plugins. ```typescript // Cloudflare Workers / Vercel Edge import { generate } from "otplib"; import { crypto } from "@otplib/plugin-crypto-web"; import { base32 } from "@otplib/plugin-base32-scure"; export default { async fetch(request: Request): Promise { const token = await generate({ secret: "GEZDGNBVGY3TQOJQGEZDGNBVGY", crypto, base32, }); return new Response(token); }, }; ``` -------------------------------- ### Capture Stack Trace Example Source: https://otplib.yeojz.dev/api/%40otplib/core/errors/classes/Base32PluginMissingError.html Demonstrates how to use Error.captureStackTrace to create a .stack property on an object. This is useful for custom error handling and debugging. ```javascript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` -------------------------------- ### Generate HMAC using crypto.hmac Source: https://otplib.yeojz.dev/api/%40otplib/plugin-crypto-web/variables/crypto.html Use the crypto.hmac function to generate a Hash-based Message Authentication Code (HMAC). This example demonstrates generating an HMAC-SHA1. ```typescript import { crypto } from '@otplib/plugin-crypto-web'; const hmac = await crypto.hmac('sha1', key, data); ``` -------------------------------- ### OTP Class Overview Source: https://otplib.yeojz.dev/api/otplib/class/classes/OTP.html This snippet shows how to instantiate the OTP class with different strategies and perform basic operations like generating secrets, tokens, and verifying tokens. It also demonstrates generating an otpauth URI. ```APIDOC ## Class: OTP ### Description A wrapper class that dynamically handles TOTP and HOTP strategies. ## Constructors ### new OTP(options?) Creates an instance of the OTP class. #### Parameters * `options?` (`OTPClassOptions`): Optional configuration object for the OTP class. Defaults to an empty object. ## Methods ### generate(options) Generates an OTP token based on the configured strategy. #### Parameters * `options` (`OTPGenerateOptions`): Generation options. #### Returns `Promise`: The generated OTP code. ### generateSecret(length?) Generates a random secret key. #### Parameters * `length?` (`number`): The number of random bytes for the secret. Defaults to 20. #### Returns `string`: The Base32-encoded secret key. ### generateSync(options) Generates an OTP token based on the configured strategy synchronously. #### Parameters * `options` (`OTPGenerateOptions`): Generation options. #### Returns `string`: The generated OTP code. #### Throws If the crypto plugin doesn't support sync operations. ### generateURI(options) Generates an otpauth:// URI for QR code generation. Supports both TOTP and HOTP strategies. #### Parameters * `options` (`OTPURIGenerateOptions`): URI generation options. #### Returns `string`: The otpauth:// URI string. ### getStrategy() Gets the current strategy configured for the OTP instance. #### Returns `OTPStrategy`: The current OTP strategy (e.g., 'totp' or 'hotp'). ### verify(options) Verifies an OTP token based on the configured strategy. #### Parameters * `options` (`OTPVerifyOptions`): Verification options. #### Returns `Promise`: Verification result with validity and optional delta. ### verifySync(options) Verifies an OTP token based on the configured strategy synchronously. #### Parameters * `options` (`OTPVerifyOptions`): Verification options. #### Returns `VerifyResult`: Verification result with validity and optional delta. #### Throws If the crypto plugin doesn't support sync operations. ``` -------------------------------- ### Generate Token with UTF-8 String Secret Source: https://otplib.yeojz.dev/api/%40otplib/plugin-base32-alt Use bypassAsString to generate a token directly from a UTF-8 string secret. Ensure otplib, @otplib/plugin-crypto-node, and @otplib/plugin-base32-alt are installed. ```typescript import { generate } from "otplib"; import { crypto } from "@otplib/plugin-crypto-node"; import { bypassAsString } from "@otplib/plugin-base32-alt"; const token = await generate({ secret: "mysecretkey", base32: bypassAsString, crypto, }); ``` -------------------------------- ### Manual Instantiation of NodeCryptoPlugin Source: https://otplib.yeojz.dev/guide/plugins Demonstrates how to manually instantiate the NodeCryptoPlugin for custom configuration or dependency injection. ```typescript import { NodeCryptoPlugin } from "@otplib/plugin-crypto-node"; // Create your own instance const validCrypto = new NodeCryptoPlugin(); ``` -------------------------------- ### HOTP Constructor Source: https://otplib.yeojz.dev/api/%40otplib/hotp/classes/HOTP.html Initializes a new instance of the HOTP class. It accepts an optional options object for configuration. ```APIDOC ## new HOTP() ### Description Initializes a new instance of the HOTP class. ### Method `new HOTP(options?)` ### Parameters #### Options - **options** (HOTPOptions) - Optional - Configuration options for the HOTP instance. ``` -------------------------------- ### Use noble plugin for Deno compatibility: Source: https://otplib.yeojz.dev/guide/runtime-compatibility Troubleshoot 'crypto is not defined' errors in Deno by using the '@otplib/plugin-crypto-noble' for universal compatibility. ```typescript // Use noble plugin for universal compatibility import { crypto } from "@otplib/plugin-crypto-noble"; ``` -------------------------------- ### Bun/Deno Runtime Crypto Generation Source: https://otplib.yeojz.dev/guide/runtime-compatibility For Bun and Deno, `@otplib/plugin-crypto-noble` is recommended for its pure JavaScript implementation and consistent cross-runtime behavior. ```typescript import { generate, verify, generateSecret } from "otplib"; import { crypto } from "@otplib/plugin-crypto-noble"; import { base32 } from "@otplib/plugin-base32-scure"; const secret = generateSecret({ crypto, base32 }); const token = await generate({ secret, crypto, base32 }); ``` -------------------------------- ### VerifyResultValid Example with Epoch Source: https://otplib.yeojz.dev/api/%40otplib/totp/type-aliases/VerifyResultValid.html Demonstrates how to access the epoch timestamp of the matched period after a successful token verification. This is useful for logging and advanced time drift analysis. ```typescript const result = await verify({ secret, token, epochTolerance: 30 }); if (result.valid) { console.log(`Token matched at epoch: ${result.epoch}`); console.log(`Token was ${result.delta} periods away`); } ``` -------------------------------- ### Run All Unit Tests Source: https://otplib.yeojz.dev/guide/testing.html Execute all unit tests for the project using Vitest. ```bash pnpm test ``` -------------------------------- ### Get Remaining Time for TOTP Period Source: https://otplib.yeojz.dev/api/%40otplib/totp Calculates the remaining seconds until the next TOTP period. Defaults to current time and a 30-second period if no epoch or period is provided. ```typescript import { getRemainingTime } from "@otplib/totp"; const seconds = getRemainingTime(); // uses current time, period=30, t0=0 const seconds2 = getRemainingTime(epoch, 30); // explicit time and period ``` -------------------------------- ### Unsafe Secret Generation Examples Source: https://otplib.yeojz.dev/guide/security Avoid using predictable or weak random sources for generating OTP secrets. Always use a cryptographically secure random number generator. ```typescript // UNSAFE: Predictable values const secret = "AAAAAAAAAAAAAAAA"; const secret = "user123secret"; ``` ```typescript // UNSAFE: Weak random sources const secret = Math.random().toString(36); const secret = Date.now().toString(); ``` -------------------------------- ### Run tests in Node.js (Vitest): Source: https://otplib.yeojz.dev/guide/runtime-compatibility Execute tests for otplib within a Node.js environment using Vitest. ```bash # Node.js (Vitest) pnpm test ``` -------------------------------- ### Example Usage of Error.captureStackTrace Source: https://otplib.yeojz.dev/api/%40otplib/core/errors/classes/AfterTimeStepNegativeError.html Demonstrates how to use Error.captureStackTrace to create a .stack property on an object. This is useful for capturing stack traces and can be used to hide implementation details of error generation. ```javascript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` ```javascript function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` -------------------------------- ### Get Remaining Time Until Token Expiration Source: https://otplib.yeojz.dev/guide/getting-started Calculates the remaining time in seconds until the current TOTP token expires. Supports custom parameters for time, period, and initial epoch. ```typescript import { getRemainingTime } from "@otplib/totp"; // Seconds until current token expires const remaining = getRemainingTime(); console.log(`Token expires in ${remaining}s`); // With custom parameters const remainingCustom = getRemainingTime( Math.floor(Date.now() / 1000), // current time 30, // period in seconds 0, // t0 (initial Unix time) ); ``` -------------------------------- ### Serve locally with HTTPS for Web Crypto: Source: https://otplib.yeojz.dev/guide/runtime-compatibility Use HTTPS for local development when Web Crypto API is required, or use the noble plugin as an alternative. ```bash # Use HTTPS locally npx serve -s build --ssl-cert cert.pem --ssl-key key.pem ``` -------------------------------- ### Get Current TOTP Time Step Source: https://otplib.yeojz.dev/api/%40otplib/totp Retrieves the current TOTP counter (time step) value. Defaults to current time and a 30-second period if no epoch or period is provided. ```typescript import { getTimeStepUsed } from "@otplib/totp"; const counter = getTimeStepUsed(); // uses current time, period=30, t0=0 const counter2 = getTimeStepUsed(epoch, 30); // explicit time and period ``` -------------------------------- ### Sample storage.json for otplib CLI Source: https://otplib.yeojz.dev/guide/cli.html This JSON object represents a sample storage file used with the otplib CLI. It contains a key-value pair where the key is a unique identifier and the value is a base64-encoded OTP entry. ```json { "A1B2C3D4": "eyJkYXRhIjp7InR5cGUiOiJ0b3RwIiwic2VjcmV0IjoiSkJTV1kzRFBFSFBLM1BYUCIsImlzc3VlciI6IlNlcnZpY2UiLCJhbGdvcml0aG0iOiJTSEExIiwiZGlnaXRzIjo2LCJwZXJpb2QiOjMwfX0=" } ``` -------------------------------- ### WebCryptoPlugin Constructor Source: https://otplib.yeojz.dev/api/%40otplib/plugin-crypto-web/classes/WebCryptoPlugin.html Initializes a new instance of the WebCryptoPlugin. This plugin leverages the browser's Web Crypto API for secure and efficient cryptographic operations. ```APIDOC ## new WebCryptoPlugin() ### Description Initializes a new instance of the WebCryptoPlugin. ### Returns `WebCryptoPlugin` An instance of the WebCryptoPlugin. ``` -------------------------------- ### Using bypassAsBase64 with TOTP generate Source: https://otplib.yeojz.dev/api/%40otplib/plugin-base32-alt/variables/bypassAsBase64.html Use bypassAsBase64 when your secret is a base64 string that should be converted directly to bytes without Base32 encoding. This example demonstrates its usage with the generate function from @otplib/totp. ```typescript import { bypassAsBase64 } from '@otplib/plugin-base32-alt'; import { generate } from '@otplib/totp'; await generate({ secret: "SGVsbG8=", base32: bypassAsBase64, crypto }); ``` -------------------------------- ### Generate TOTP Code Source: https://otplib.yeojz.dev/api/%40otplib/totp/functions/generate.html Example of generating a TOTP code using the generate function. It requires importing the function and a crypto plugin, and provides options for the secret, time, period, digits, and crypto implementation. ```typescript import { generate } from '@otplib/totp'; import { NodeCryptoPlugin } from '@otplib/plugin-crypto-node'; const totp = generate({ secret: new Uint8Array([1, 2, 3, 4, 5]), time: Date.now() / 1000, period: 30, digits: 6, crypto: new NodeCryptoPlugin(), }); // Returns: '123456' ``` -------------------------------- ### Validating Guardrails in Production Source: https://otplib.yeojz.dev/api/%40otplib/core/utils/functions/hasGuardrailOverrides.html Shows an example of using hasGuardrailOverrides within a validation function to prevent the use of custom guardrails in a production environment. This helps enforce security policies by disallowing non-standard configurations. ```typescript function validateGuardrails(guardrails: OTPGuardrails) { if (hasGuardrailOverrides(guardrails)) { throw new Error('Custom guardrails not allowed in production'); } } ``` -------------------------------- ### Use otplib via CDN in Browser Source: https://otplib.yeojz.dev/api/otplib Include the otplib IIFE build from a CDN using a script tag for direct browser usage. This bundles all dependencies. ```html ``` -------------------------------- ### Build Packages Source: https://otplib.yeojz.dev/guide/testing.html Compile all packages in the project, generating distributable artifacts in the `dist/` directory. This is a prerequisite for running distribution tests. ```bash pnpm build ``` -------------------------------- ### VerifyResultValid Example with TimeStep for Replay Protection Source: https://otplib.yeojz.dev/api/%40otplib/totp/type-aliases/VerifyResultValid.html Shows how to use the timeStep property for replay attack prevention. The timeStep is saved after a successful verification and then used in subsequent verifications to reject tokens from past time steps. ```typescript const result = await verify({ secret, token, crypto }); if (result.valid) { // Save timeStep to prevent reuse await db.saveLastTimeStep(userId, result.timeStep); } // Later: verify with replay protection const lastTimeStep = await db.getLastTimeStep(userId); const result2 = await verify({ secret, token: newToken, crypto, afterTimeStep: lastTimeStep, // Rejects timeStep <= lastTimeStep }); ``` -------------------------------- ### Normalize Counter Tolerance Examples Source: https://otplib.yeojz.dev/api/%40otplib/core/utils/functions/normalizeCounterTolerance.html Demonstrates how normalizeCounterTolerance handles different input types: zero, a positive number for look-ahead tolerance, and explicit [past, future] tuples. The default behavior with a number prioritizes security by enabling look-ahead only. ```typescript normalizeCounterTolerance(0) // [0, 0] normalizeCounterTolerance(5) // [0, 5] - look-ahead only (secure default) normalizeCounterTolerance([10, 5]) // [10, 5] - explicit past/future normalizeCounterTolerance([5, 5]) // [5, 5] - explicit symmetric (use with caution) ``` -------------------------------- ### Select entry interactively and copy token Source: https://otplib.yeojz.dev/guide/cli.html This snippet shows how to interactively select an OTP entry using fzf and then copy the generated token to the clipboard. It demonstrates piping output between commands for a streamlined workflow. ```bash npx otplibx token -n "$(npx otplibx list | fzf | cut -f2)" | pbcopy ``` ```bash npx otplibx list | fzf | cut -f2 | xargs -I {} npx otplibx token -n {} | pbcopy ```