OTPAuth

repository·master·Indexed 23 days ago

https://github.com/hectorm/otpauth

A multi-platform library for generating and validating HMAC-Based One-Time Passwords (HOTP) and Time-Based One-Time Passwords (TOTP) for Node.js, Deno, Bun, and browsers. It provides tools for managing cryptographic secrets, handling Google Authenticator compatible URI strings for QR codes, and supports various HMAC hashing algorithms. Version 9.5.1.

Tokens
3.2K
Snippets
5
Records
27
Agent score
80%

What's inside otpauth

  1. Use OTPAuth slim and bare builds

    master

    OTPAuth provides different build variants for Node.js/Bun:

    • otpauth/slim: A slim build without bundled dependencies.
    • otpauth/bare: A bare build with no bundled crypto. This requires you to provide a custom hmac function in the configuration.
    import * as OTPAuth from "otpauth";
    // import * as OTPAuth from "otpauth/slim";
    // import * as OTPAuth from "otpauth/bare";
  2. Install OTPAuth in Node.js, Bun, and Deno

    master

    OTPAuth can be installed and imported depending on your runtime environment:

    • Node.js / Bun: Use npm install otpauth and import via import * as OTPAuth from "otpauth";.
    • Deno: Use the JSR registry with import * as OTPAuth from "jsr:@hectorm/otpauth";.
    • Browsers (ESM): Use an import map pointing to a CDN like jsDelivr.
    • Browsers (UMD): Include the UMD build via a <script> tag.
    // Node.js / Bun
    import * as OTPAuth from "otpauth";
    
    // Deno
    import * as OTPAuth from "jsr:@hectorm/otpauth";
  3. The otpauth:// URI format

    master

    The URI class follows the Google Authenticator Key URI Format.

    Structure

    otpauth://TYPE/[ISSUER:]LABEL?PARAMETERS

    Components

    • TYPE: Either totp or hotp.
    • LABEL: The account identifier (e.g., user@example.com).
    • ISSUER: (Optional) The name of the service or issuer.
    • PARAMETERS: A query string containing:
      • secret (Required): The base32 encoded secret.
      • algorithm (Optional): The HMAC algorithm (e.g., SHA1, SHA256).
      • digits (Optional): The number of digits for the code.
      • period (Optional, TOTP only): The time step in seconds.
      • counter (Required, HOTP only): The current counter value.
      • issuer (Optional): The issuer name.
  4. Convert between TOTP objects and URI strings

    master
    You can convert a TOTP instance into a URI string (useful for QR codes) using totp.toString() or OTPAuth.URI.stringify(totp). To reconstruct a TOTP object from a URI string, use OTPAuth.URI.parse(uri).
  5. Create and use TOTP tokens

    master

    To implement Time-Based One-Time Passwords (TOTP), instantiate a new OTPAuth.TOTP() object. You can provide an issuer, label, algorithm, digits, period, and a secret (as a base32 string or OTPAuth.Secret instance).

    Common methods include:

    • .generate(): Returns the current token as a string.
    • .validate({ token, window }): Validates a token against a search window to account for clock drift. Returns the token delta or null if invalid.
    • .counter(): Returns the current counter value.
    • .remaining(): Returns milliseconds until the next token change.
    • .toString(): Converts the TOTP object to a Google Authenticator compatible URI string.
    import * as OTPAuth from "otpauth";
    
    let totp = new OTPAuth.TOTP({
      issuer: "ACME",
      label: "Alice",
      algorithm: "SHA1",
      digits: 6,
      period: 30,
      secret: "US3WHSG7X5KAPV27VANWKQHF3SH3HULL",
    });
    
    let token = totp.generate();
    let delta = totp.validate({ token, window: 1 });
    let uri = totp.toString();
  6. Generate a secure random secret

    master

    Use new OTPAuth.Secret({ size: N }) to generate a cryptographically secure random secret. It is recommended to use at least 128 bits (16 bytes) for security.

    let secret = new OTPAuth.Secret({ size: 20 });
  7. Configure TOTP options

    master

    When instantiating OTPAuth.TOTP, you can configure the following options:

    OptionDescription
    issuerProvider or service the account is associated with
    labelAccount identifier
    algorithmHMAC function: "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3-224", "SHA3-256", "SHA3-384", "SHA3-512"
    digitsLength of the generated tokens
    periodInterval of time for which a token is valid, in seconds
    secretBase32 encoded string or OTPAuth.Secret instance
    hmacCustom HMAC function (required for otpauth/bare build)
  8. Convert an HOTP/TOTP object to a URI with URI.stringify()

    master

    Use URI.stringify(otp) to convert an existing HOTP or TOTP instance back into its otpauth:// URI string representation. This is useful for generating QR codes or sharing credentials in URI format.

    Parameters

    • otp (HOTP|TOTP): An instance of an HOTP or TOTP object.

    Errors

    • Throws TypeError if the provided object is not an instance of HOTP or TOTP.
  9. Validate a TOTP token

    master

    Validate a token to check if it is currently valid or was valid within a specific time window.

    Returns:

    • A number (the delta/offset of the counter) if the token is valid within the window.
    • null if the token is not found in the search window (invalid).
  10. Generate a TOTP token

    master

    You can generate a token using either a TOTP instance or the static TOTP.generate method.

    • Instance method: Uses the configuration stored in the instance.
    • Static method: Requires all necessary parameters (secret, algorithm, digits, etc.) to be passed in the config object.
  11. Configure the TOTP class

    master

    The TOTP class implements the Time-Based One-Time Password algorithm (RFC 6238). You can instantiate it with a configuration object to define the behavior of generated tokens and validation.

    If you provide a secret as a string, it is automatically converted from Base32 using Secret.fromBase32().