### Install OTPAuth via npm or JSR
Source: https://context7.com/hectorm/otpauth/llms.txt
Install the OTPAuth library using npm for Node.js/Bun or import from JSR for Deno.
```bash
# Node.js / Bun
npm install otpauth
# Deno (JSR)
# import * as OTPAuth from "jsr:@hectorm/otpauth";
```
--------------------------------
### Get Library Version
Source: https://context7.com/hectorm/otpauth/llms.txt
Access the `version` constant to retrieve the current version string of the otpauth library. This value is populated during the build process.
```javascript
import { version } from "otpauth";
console.log(version); // e.g. "9.5.1"
```
--------------------------------
### Secret Accessors
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/Secret.html
Get string representations of the secret key in different encodings.
```APIDOC
## base32
### Description
Base32 string representation of secret key.
### Returns string
```
```APIDOC
## buffer
### Description
Secret key buffer.
### Returns ArrayBufferLike
### Deprecated
For backward compatibility, the "bytes" property should be used instead.
```
```APIDOC
## hex
### Description
Hexadecimal string representation of secret key.
### Returns string
```
```APIDOC
## latin1
### Description
Latin-1 string representation of secret key.
### Returns string
```
```APIDOC
## utf8
### Description
UTF-8 string representation of secret key.
### Returns string
```
--------------------------------
### Configure Mocha and Run Tests
Source: https://github.com/hectorm/otpauth/blob/master/test/browser.test.html
Sets up Mocha with the BDD interface and HTML reporter, then imports and runs the test suite. Ensure Chai is available globally for assertions.
```javascript
Mocha { "imports": { "chai": "../node_modules/chai/index.js", "test": "./test.mjs" } } import { assert } from "chai"; globalThis.assert = assert; globalThis.assertEquals = assert.deepEqual; globalThis.assertMatch = assert.match; mocha.setup({ ui: "bdd", reporter: "html" }); await import("test"); mocha.run();
```
--------------------------------
### HOTP Instance Methods
Source: https://context7.com/hectorm/otpauth/llms.txt
Illustrates using an HOTP instance to generate sequential tokens and validate user-submitted tokens, managing the counter state.
```APIDOC
## HOTP Instance Methods
### Description
Generates and validates counter-based tokens using an HOTP instance. The instance automatically increments its internal counter upon token generation. Validation includes a window to tolerate counter drift.
### Methods
- `generate()`: Generates the next HOTP token and increments the internal counter.
- `generate(options)`: Generates an HOTP token for a specific counter without mutating the internal state (but still increments it).
- `validate(options)`: Validates a submitted token against a specified counter and window.
### Parameters
#### `generate(options)`
- `options` (object) - Optional. Configuration for token generation.
- `counter` (number) - The specific counter value for which to generate the token. Note: This method still increments `this.counter` after generation.
#### `validate(options)`
- `options` (object) - Required. Configuration for token validation.
- `token` (string) - The token to validate.
- `counter` (number) - The expected counter value.
- `window` (number) - The validation window size to check for counter drift.
### Request Example
```javascript
const hotp = new OTPAuth.HOTP({
issuer: "ACME Corp",
label: "bob@example.com",
algorithm: "SHA1",
digits: 6,
counter: 0,
secret: OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL"),
});
const token0 = hotp.generate(); // counter becomes 1
const delta = hotp.validate({ token: token0, counter: 0, window: 2 });
```
### Response
#### `generate()`
- Returns: (string) The generated HOTP token.
#### `validate()`
- Returns: (number | null) The delta (how far ahead the token's counter was) or null if the token is invalid.
```
--------------------------------
### TOTP Instance Methods
Source: https://context7.com/hectorm/otpauth/llms.txt
Demonstrates creating a TOTP instance and using its methods for generating and validating tokens, as well as checking token expiration.
```APIDOC
## TOTP Instance Methods
### Description
Generates and validates time-based tokens using an instance of the TOTP class. Allows for configuration of issuer, label, algorithm, digits, period, and secret.
### Methods
- `generate()`: Generates the current TOTP token.
- `generate(options)`: Generates a TOTP token for a specific timestamp.
- `validate(options)`: Validates a submitted token against the current or adjacent time windows.
- `counter()`: Returns the current counter value.
- `remaining()`: Returns the milliseconds remaining until the current token expires.
### Parameters
#### `generate(options)`
- `options` (object) - Optional. Configuration for token generation.
- `timestamp` (number) - Unix timestamp in milliseconds for which to generate the token.
#### `validate(options)`
- `options` (object) - Required. Configuration for token validation.
- `token` (string) - The token to validate.
- `window` (number) - The number of adjacent time windows to check (e.g., 1 for current and adjacent windows).
### Request Example
```javascript
const totp = new OTPAuth.TOTP({
issuer: "ACME Corp",
label: "alice@example.com",
algorithm: "SHA1",
digits: 6,
period: 30,
secret: "US3WHSG7X5KAPV27VANWKQHF3SH3HULL",
});
const token = totp.generate();
const delta = totp.validate({ token: token, window: 1 });
```
### Response
#### `generate()`
- Returns: (string) The generated TOTP token.
#### `validate()`
- Returns: (number | null) The delta (0 for exact match, ±1 for adjacent window) or null if the token is invalid.
```
--------------------------------
### Create and Use TOTP in Node.js/Bun
Source: https://github.com/hectorm/otpauth/blob/master/README.md
Demonstrates creating a TOTP object with custom or default parameters, generating a token, validating a token with a window for clock drift, and retrieving counter and remaining time. It also shows how to convert to and from the Google Authenticator key URI format.
```javascript
import * as OTPAuth from "otpauth";
// import * as OTPAuth from "otpauth/slim"; // Slim build without bundled dependencies.
// import * as OTPAuth from "otpauth/bare"; // Bare build with no bundled crypto (requires providing a custom HMAC function).
// Create a new TOTP object.
let totp = new OTPAuth.TOTP({
// Provider or service the account is associated with.
issuer: "ACME",
// Account identifier.
label: "Alice",
// Algorithm used for the HMAC function, possible values are:
// "SHA1", "SHA224", "SHA256", "SHA384", "SHA512",
// "SHA3-224", "SHA3-256", "SHA3-384" and "SHA3-512".
algorithm: "SHA1",
// Length of the generated tokens.
digits: 6,
// Interval of time for which a token is valid, in seconds.
period: 30,
// Arbitrary key encoded in base32 or `OTPAuth.Secret` instance
// (if omitted, a cryptographically secure random secret is generated).
secret: "US3WHSG7X5KAPV27VANWKQHF3SH3HULL",
// or: `OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL")`
// or: `new OTPAuth.Secret()`
// Custom HMAC function (required for bare build, optional otherwise).
// hmac: (algorithm, key, message) => Uint8Array,
});
// Unless you know what you are doing, it is recommended to use the default
// values for the algorithm, digits, and period options, as these are the most
// common values used by most services.
// Generate a cryptographically secure random secret.
// It is NOT recommended to use less than 128 bits (16 bytes).
let secret = new OTPAuth.Secret({ size: 20 });
// Generate a token (returns the current token as a string).
let token = totp.generate();
// Validate a token (returns the token delta or null if it is not found in the
// search window, in which case it should be considered invalid).
//
// A search window is useful to account for clock drift between the client and
// server; however, it should be kept as small as possible to prevent brute
// force attacks. In most cases, a value of 1 is sufficient. Furthermore, it is
// essential to implement a throttling mechanism on the server.
//
// For further details on the security considerations, it is advised to refer
// to Section 7 of RFC 4226 and Section 5 of RFC 6238:
// https://datatracker.ietf.org/doc/html/rfc4226#section-7
// https://datatracker.ietf.org/doc/html/rfc6238#section-5
let delta = totp.validate({ token, window: 1 });
// Get the counter value (number of intervals since the Unix epoch).
// Useful for implementing techniques against token reuse during the validity
// period.
let counter = totp.counter();
// Get the remaining milliseconds until the current token changes.
let remaining = totp.remaining();
// Convert to Google Authenticator key URI format.
// Usually the URI is encoded in a QR code that can be scanned by the user.
// This functionality is outside the scope of the project, but there are many
// libraries that can be used for this purpose, such as npmjs.com/package/qr
let uri = totp.toString();
// or: `OTPAuth.URI.stringify(totp)`
// returns: `otpauth://totp/ACME:Alice?issuer=ACME&secret=US3WHSG7X5KAPV27VANWKQHF3SH3HULL&algorithm=SHA1&digits=6&period=30`
// Convert from Google Authenticator key URI format.
totp = OTPAuth.URI.parse(uri);
```
--------------------------------
### HOTP.generate (Instance Method)
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/HOTP.html
Generates an HOTP token using the instance's configuration.
```APIDOC
## generate(config?: { counter?: number }): string
### Description
Generates an HOTP token.
### Parameters
- **config** (object) - Optional configuration options.
- **counter** (number) - Optional. The counter value to use for generation.
### Returns
- **string** - The generated HOTP token.
```
--------------------------------
### HOTP Static Methods
Source: https://context7.com/hectorm/otpauth/llms.txt
Demonstrates using the static `generate` and `validate` methods of the HOTP class for counter-based token operations without instance management.
```APIDOC
## HOTP Static Methods
### Description
Provides static methods for generating and validating HOTP tokens directly, without requiring an instance. This is useful for scenarios where counter state is managed externally or for simple, one-off operations.
### Methods
- `HOTP.generate(options)`: Generates an HOTP token using provided options.
- `HOTP.validate(options)`: Validates a submitted token using provided options.
### Parameters
#### `HOTP.generate(options)`
- `options` (object) - Required. Configuration for token generation.
- `secret` (Secret | string) - The secret key (Base32 string or Secret instance).
- `algorithm` (string) - The hashing algorithm (e.g., "SHA1", "SHA256").
- `digits` (number) - The number of digits in the token.
- `counter` (number) - The counter value for which to generate the token.
#### `HOTP.validate(options)`
- `options` (object) - Required. Configuration for token validation.
- `token` (string) - The token to validate.
- `secret` (Secret | string) - The secret key (Base32 string or Secret instance).
- `algorithm` (string) - The hashing algorithm.
- `digits` (number) - The number of digits in the token.
- `counter` (number) - The expected counter value.
- `window` (number) - The validation window size.
### Request Example
```javascript
const s = OTPAuth.HOTP.generate({
secret: OTPAuth.Secret.fromBase32("JBSWY3DPEHPK3PXP"),
algorithm: "SHA1",
digits: 6,
counter: 100,
});
const d = OTPAuth.HOTP.validate({
token: s,
secret: OTPAuth.Secret.fromBase32("JBSWY3DPEHPK3PXP"),
algorithm: "SHA1",
digits: 6,
counter: 100,
window: 1,
});
```
### Response
#### `HOTP.generate()`
- Returns: (string) The generated HOTP token.
#### `HOTP.validate()`
- Returns: (number | null) The delta or null if the token is invalid.
```
--------------------------------
### Generate and Validate TOTP Tokens with Instance
Source: https://context7.com/hectorm/otpauth/llms.txt
Create a TOTP instance with specific configurations for issuer, label, algorithm, digits, period, and secret. Use instance methods to generate tokens for the current or specific timestamps, and validate submitted tokens within a given window. Remember to implement server-side token reuse prevention using totp.counter().
```javascript
import * as OTPAuth from "otpauth";
// Create a TOTP instance with explicit configuration.
const totp = new OTPAuth.TOTP({
issuer: "ACME Corp", // Service/provider name
label: "alice@example.com", // User account identifier
algorithm: "SHA1", // One of: SHA1, SHA224, SHA256, SHA384, SHA512, SHA3-*
digits: 6, // Token length (typically 6 or 8)
period: 30, // Validity window in seconds (typically 30 or 60)
secret: "US3WHSG7X5KAPV27VANWKQHF3SH3HULL", // Base32 string or Secret instance
});
// Generate the current token.
const token = totp.generate();
console.log(token); // e.g. "123456" — changes every 30 seconds
// Generate a token for a specific timestamp (useful for testing).
const pastToken = totp.generate({ timestamp: 1609459200000 }); // 2021-01-01T00:00:00Z
// Validate a token submitted by the user.
// Returns the counter delta (0 = exact match, ±1 = adjacent window) or null if invalid.
const delta = totp.validate({ token, window: 1 });
if (delta === null) {
console.log("Invalid token — reject the request");
} else {
console.log(`Valid token (delta: ${delta}) — proceed`);
// IMPORTANT: Implement server-side token reuse prevention using totp.counter().
}
// Get the current counter value (number of completed 30s periods since Unix epoch).
// Use this to prevent token reuse within the same validity period.
const counter = totp.counter();
console.log(`Current counter: ${counter}`);
// Get milliseconds remaining until the current token expires.
const remaining = totp.remaining();
console.log(`Token expires in ${remaining}ms`);
```
--------------------------------
### Import OTPAuth in Deno
Source: https://github.com/hectorm/otpauth/blob/master/README.md
Import the OTPAuth library in Deno using the provided JSR package.
```javascript
import * as OTPAuth from "jsr:@hectorm/otpauth";
// Same as above.
```
--------------------------------
### HOTP Constructor
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/HOTP.html
Creates an HOTP object with optional configuration for algorithm, counter, digits, HMAC function, issuer, label, and secret.
```APIDOC
## constructor
### Description
Creates an HOTP object.
### Parameters
* `Optional` config: {
algorithm?: string;
counter?: number;
digits?: number;
hmac?: (algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array;
issuer?: string;
issuerInLabel?: boolean;
label?: string;
secret?: string | [Secret](Secret.html);
}
Configuration options.
* ##### `Optional` algorithm?: string
HMAC hashing algorithm.
* ##### `Optional` counter?: number
Initial counter value.
* ##### `Optional` digits?: number
Token length.
* ##### `Optional` hmac?: (algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array
Custom HMAC function.
* ##### `Optional` issuer?: string
Account provider.
* ##### `Optional` issuerInLabel?: boolean
Include issuer prefix in label.
* ##### `Optional` label?: string
Account label.
* ##### `Optional` secret?: string | [Secret](Secret.html)
Secret key.
### Returns HOTP
* Defined in [hotp.js:47](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L47)
```
--------------------------------
### TOTP Static Methods
Source: https://context7.com/hectorm/otpauth/llms.txt
Shows how to use the static `generate` and `validate` methods of the TOTP class without creating an instance.
```APIDOC
## TOTP Static Methods
### Description
Provides static methods for generating and validating TOTP tokens directly, without the need for an instance. Useful for one-off operations or when an instance is not maintained.
### Methods
- `TOTP.generate(options)`: Generates a TOTP token using provided options.
- `TOTP.validate(options)`: Validates a submitted token using provided options.
### Parameters
#### `TOTP.generate(options)`
- `options` (object) - Required. Configuration for token generation.
- `secret` (Secret | string) - The secret key (Base32 string or Secret instance).
- `algorithm` (string) - The hashing algorithm (e.g., "SHA1", "SHA256").
- `digits` (number) - The number of digits in the token.
- `period` (number) - The time period in seconds for the token.
- `timestamp` (number) - Unix timestamp in milliseconds for which to generate the token.
#### `TOTP.validate(options)`
- `options` (object) - Required. Configuration for token validation.
- `token` (string) - The token to validate.
- `secret` (Secret | string) - The secret key (Base32 string or Secret instance).
- `algorithm` (string) - The hashing algorithm.
- `digits` (number) - The number of digits in the token.
- `period` (number) - The time period in seconds for the token.
- `window` (number) - The number of adjacent time windows to check.
### Request Example
```javascript
const staticToken = OTPAuth.TOTP.generate({
secret: OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL"),
algorithm: "SHA256",
digits: 8,
period: 60,
timestamp: Date.now(),
});
const staticDelta = OTPAuth.TOTP.validate({
token: staticToken,
secret: OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL"),
algorithm: "SHA256",
digits: 8,
period: 60,
window: 1,
});
```
### Response
#### `TOTP.generate()`
- Returns: (string) The generated TOTP token.
#### `TOTP.validate()`
- Returns: (number | null) The delta (0 for exact match, ±1 for adjacent window) or null if the token is invalid.
```
--------------------------------
### Import OTPAuth in Node.js, Bun, and Browsers
Source: https://context7.com/hectorm/otpauth/llms.txt
Import the OTPAuth library in various JavaScript environments including Node.js (ESM/CJS), Bun, and browsers (ESM/UMD via CDN).
```javascript
// Node.js / Bun (ESM)
import * as OTPAuth from "otpauth";
// Node.js (CJS)
const OTPAuth = require("otpauth");
// Slim build (no bundled dependencies)
import * as OTPAuth from "otpauth/slim";
// Bare build (no bundled crypto — must supply custom HMAC)
import * as OTPAuth from "otpauth/bare";
// Browser (ESM via CDN)
//
//
// Browser (UMD via CDN)
//
```
--------------------------------
### URI.stringify
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/URI.html
Converts an HOTP or TOTP object into a Google Authenticator key URI string.
```APIDOC
## Static stringify
### Description
Converts an HOTP/TOTP object to a Google Authenticator key URI.
### Method
`static stringify(otp: HOTP | TOTP) => string`
### Parameters
#### Path Parameters
* **otp** ([HOTP](HOTP.html) | [TOTP](TOTP.html)) - Required - HOTP/TOTP object.
### Returns
string - Google Authenticator Key URI.
```
--------------------------------
### Import OTPAuth in Browser
Source: https://github.com/hectorm/otpauth/blob/master/README.md
Use this snippet to import the OTPAuth library in your browser's console for interactive testing.
```javascript
const OTPAuth = await import("otpauth");
```
--------------------------------
### TOTP Constructor
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Initializes a new instance of the TOTP class. It accepts an optional configuration object to set properties like secret, issuer, label, algorithm, digits, and period.
```APIDOC
## Constructor
### Description
Initializes a new instance of the TOTP class.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (object) - Optional - Configuration options for the TOTP instance.
- **secret** (string) - The secret key for OTP generation.
- **issuer** (string) - The issuer name.
- **label** (string) - The label for the OTP.
- **algorithm** (string) - The hashing algorithm (e.g., 'SHA1', 'SHA256', 'SHA512'). Defaults to 'SHA1'.
- **digits** (number) - The number of digits in the OTP. Defaults to 6.
- **period** (number) - The time period in seconds for the OTP. Defaults to 30.
```
--------------------------------
### HOTP.toString
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/HOTP.html
Returns a Google Authenticator key URI for the HOTP instance.
```APIDOC
## toString(): string
### Description
Returns a Google Authenticator key URI.
### Returns
- **string** - The Google Authenticator key URI.
```
--------------------------------
### HOTP Defaults
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/HOTP.html
Retrieves the default configuration values for HOTP.
```APIDOC
## Static defaults()
### Description
Gets the default configuration.
### Returns
- **algorithm** (string) - The HMAC hashing algorithm.
- **counter** (number) - The initial counter value.
- **digits** (number) - The number of digits in the token.
- **issuer** (string) - The issuer name.
- **issuerInLabel** (boolean) - Whether to include the issuer in the label.
- **label** (string) - The label for the OTP.
- **window** (number) - The validation window size.
```
--------------------------------
### HOTP.generate (Static Method)
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/HOTP.html
Generates an HOTP token with custom configuration.
```APIDOC
## Static generate(config: { algorithm?: string; counter?: number; digits?: number; hmac?: (algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array; secret: Secret }): string
### Description
Generates an HOTP token with specified configuration.
### Parameters
- **config** (object) - Required. Configuration options.
- **algorithm** (string) - Optional. HMAC hashing algorithm (e.g., 'SHA1', 'SHA256', 'SHA512').
- **counter** (number) - Optional. Counter value.
- **digits** (number) - Optional. Token length (number of digits).
- **hmac** ((algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array) - Optional. Custom HMAC function.
- **secret** (Secret) - Required. The secret key.
### Returns
- **string** - The generated HOTP token.
```
--------------------------------
### TOTP Constructor
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Creates a new TOTP object with optional configuration for algorithm, digits, HMAC function, issuer, label, period, and secret.
```APIDOC
## new TOTP(config?)
### Description
Creates a TOTP object.
### Parameters
* `Optional` config: {
algorithm?: string;
digits?: number;
hmac?: (algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array;
issuer?: string;
issuerInLabel?: boolean;
label?: string;
period?: number;
secret?: string | Secret;
} = {}
Configuration options.
* ##### `Optional` algorithm?: string
HMAC hashing algorithm.
* ##### `Optional` digits?: number
Token length.
* ##### `Optional` hmac?: (algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array
Custom HMAC function.
* ##### `Optional` issuer?: string
Account provider.
* ##### `Optional` issuerInLabel?: boolean
Include issuer prefix in label.
* ##### `Optional` label?: string
Account label.
* ##### `Optional` period?: number
Token time-step duration.
* ##### `Optional` secret?: string | Secret
Secret key.
### Returns TOTP
* Defined in [totp.js:46](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/totp.js#L46)
```
--------------------------------
### version Variable
Source: https://github.com/hectorm/otpauth/blob/master/docs/index.html
The current version of the otpauth library.
```APIDOC
## Variable: version
### Description
Exposes the semantic version string of the otpauth library.
### Usage
```javascript
import { version } from 'otpauth';
console.log(version); // e.g., '1.0.0'
```
```
--------------------------------
### generate
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Generates a TOTP token based on the provided configuration.
```APIDOC
## generate
### Description
Generates a TOTP token.
### Method
`Static`generate
### Parameters
* **config** (object) - Required
* **algorithm** (string) - Optional - HMAC hashing algorithm.
* **digits** (number) - Optional - Token length.
* **hmac** (function) - Optional - Custom HMAC function. Signature: `(algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array`.
* **period** (number) - Optional - Token time-step duration.
* **secret** ([Secret](Secret.html)) - Required - Secret key.
* **timestamp** (number) - Optional - Timestamp value in milliseconds.
### Returns
* **string[]** - Token.
```
--------------------------------
### URI Parsing and Serialization
Source: https://context7.com/hectorm/otpauth/llms.txt
Convert HOTP/TOTP objects to and from the otpauth:// Key URI format. This URI is typically encoded in a QR code for user enrollment. URI.parse() accepts a URI string and returns a fully configured HOTP or TOTP instance; URI.stringify() (or otp.toString()) serializes an instance back to a URI string.
```APIDOC
## `URI` — Google Authenticator Key URI Parsing and Serialization
`URI` converts HOTP/TOTP objects to and from the `otpauth://` Key URI format used by Google Authenticator and compatible apps. This URI is typically encoded in a QR code for user enrollment. `URI.parse()` accepts a URI string and returns a fully configured `HOTP` or `TOTP` instance; `URI.stringify()` (or `otp.toString()`) serializes an instance back to a URI string.
```javascript
import * as OTPAuth from "otpauth";
// Serialize a TOTP object to an otpauth:// URI for QR code generation.
const totp = new OTPAuth.TOTP({
issuer: "MyApp",
label: "user@myapp.com",
algorithm: "SHA1",
digits: 6,
period: 30,
secret: "US3WHSG7X5KAPV27VANWKQHF3SH3HULL",
});
const uri = OTPAuth.URI.stringify(totp);
// or equivalently: totp.toString()
console.log(uri);
// "otpauth://totp/MyApp:user%40myapp.com?issuer=MyApp&secret=US3WHSG7X5KAPV27VANWKQHF3SH3HULL&algorithm=SHA1&digits=6&period=30"
// Parse a URI string back into a TOTP or HOTP instance.
try {
const parsed = OTPAuth.URI.parse(uri);
console.log(parsed instanceof OTPAuth.TOTP); // true
console.log(parsed.issuer); // "MyApp"
console.log(parsed.label); // "user@myapp.com"
console.log(parsed.secret.base32); // "US3WHSG7X5KAPV27VANWKQHF3SH3HULL"
console.log(parsed.generate()); // current TOTP token
} catch (e) {
if (e instanceof URIError) console.error("Malformed URI");
if (e instanceof TypeError) console.error("Invalid parameter:", e.message);
}
// Parse an HOTP URI (counter parameter is required).
const hotpUri = "otpauth://hotp/ACME:alice?secret=JBSWY3DPEHPK3PXP&issuer=ACME&counter=0&algorithm=SHA1&digits=6";
const hotpObj = OTPAuth.URI.parse(hotpUri);
console.log(hotpObj instanceof OTPAuth.HOTP); // true
console.log(hotpObj.counter); // 0
// Full round-trip example.
const original = new OTPAuth.TOTP({ secret: new OTPAuth.Secret(), issuer: "Demo", label: "test" });
const roundTripped = OTPAuth.URI.parse(original.toString());
console.log(original.generate() === roundTripped.generate()); // true
```
```
--------------------------------
### URI Class
Source: https://github.com/hectorm/otpauth/blob/master/docs/index.html
Facilitates the creation and parsing of OTPAuth URIs.
```APIDOC
## Class: URI
### Description
Handles the construction and interpretation of OTPAuth URIs for provisioning OTP accounts.
### Usage
```javascript
import { URI } from 'otpauth';
// Example usage (details not provided in source)
```
```
--------------------------------
### TOTP.defaults
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Retrieves the default configuration values for TOTP.
```APIDOC
## Static defaults
### Description
Default configuration.
### Returns
- algorithm (string)
- digits (number)
- issuer (string)
- issuerInLabel (boolean)
- label (string)
- period (number)
- window (number)
```
--------------------------------
### Import OTPAuth in Browsers (ESM)
Source: https://github.com/hectorm/otpauth/blob/master/README.md
Use this snippet to import the otpauth package using the ESM module format in browsers. Ensure your project supports ES modules and includes the provided import map.
```html
```
--------------------------------
### Secret Constructor
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/Secret.html
Creates a secret key object. You can provide an existing buffer or specify a size for a new random key.
```APIDOC
## new Secret(config?: { buffer?: ArrayBufferLike; size?: number })
### Description
Creates a secret key object.
### Parameters
* `Optional` config: { buffer?: ArrayBufferLike; size?: number } = {}
* Configuration options.
* ##### `Optional` buffer?: ArrayBufferLike
* Secret key buffer.
* ##### `Optional` size?: number
* Number of random bytes to generate, ignored if 'buffer' is provided.
### Returns Secret
* Secret object.
```
--------------------------------
### HOTP Properties
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/HOTP.html
Details of the properties available on an HOTP instance.
```APIDOC
### Properties
#### algorithm
algorithm: string
HMAC hashing algorithm.
* Defined in [hotp.js:81](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L81)
#### counter
counter: number
Initial counter value.
* Defined in [hotp.js:91](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L91)
#### digits
digits: number
Token length.
* Defined in [hotp.js:86](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L86)
#### hmac
hmac: (algorithm: string, key: Uint8Array, message: Uint8Array) => Uint8Array | undefined
Custom HMAC function.
* Defined in [hotp.js:96](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L96)
#### issuer
issuer: string
Account provider.
* Defined in [hotp.js:61](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L61)
#### issuerInLabel
issuerInLabel: boolean
Include issuer prefix in label.
* Defined in [hotp.js:71](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L71)
#### label
label: string
Account label.
* Defined in [hotp.js:66](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L66)
#### secret
secret: [Secret](Secret.html)
Secret key.
* Defined in [hotp.js:76](https://github.com/hectorm/otpauth/blob/b5c6df797de549f1eb880594318796fd3f89b948/src/hotp.js#L76)
```
--------------------------------
### TOTP.toString
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Returns a Google Authenticator key URI.
```APIDOC
## toString
### Description
Returns a Google Authenticator key URI.
### Returns
- string - URI.
```
--------------------------------
### Generate and Validate HOTP Tokens with Instance
Source: https://context7.com/hectorm/otpauth/llms.txt
Instantiate an HOTP object with issuer, label, algorithm, digits, initial counter, and secret. The `generate()` method automatically increments the internal counter, which must be persisted and synchronized server-side. The `validate()` method checks tokens against a specified counter within a given window to handle counter drift.
```javascript
import * as OTPAuth from "otpauth";
// Create an HOTP instance.
const hotp = new OTPAuth.HOTP({
issuer: "ACME Corp",
label: "bob@example.com",
algorithm: "SHA1",
digits: 6,
counter: 0, // Starting counter value; must be persisted and synchronized server-side
secret: OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL"),
});
// Generate tokens sequentially — each call increments the internal counter by 1.
const token0 = hotp.generate(); // counter=0, then counter becomes 1
const token1 = hotp.generate(); // counter=1, then counter becomes 2
console.log(token0, token1);
// Generate a token for a specific counter without mutating internal state.
const specificToken = hotp.generate({ counter: 42 });
// Note: this still increments this.counter; use static method to avoid side effects.
// Validate a user-submitted token against a known counter.
// Returns the delta (how far ahead of the expected counter the token was) or null if invalid.
const delta = hotp.validate({ token: token0, counter: 0, window: 2 });
if (delta !== null) {
console.log(`Valid — advance server counter by ${delta + 1}`);
// Server should set its stored counter to: expected_counter + delta + 1
} else {
console.log("Invalid token");
}
```
--------------------------------
### Library Version
Source: https://context7.com/hectorm/otpauth/llms.txt
The exported `version` constant contains the current library version string, populated at build time.
```APIDOC
## `version` — Library Version
The exported `version` constant contains the current library version string, populated at build time.
```javascript
import { version } from "otpauth";
console.log(version); // e.g. "9.5.1"
```
```
--------------------------------
### Include OTPAuth in Browsers (UMD)
Source: https://github.com/hectorm/otpauth/blob/master/README.md
This snippet demonstrates how to include the otpauth package in browsers using the UMD (Universal Module Definition) format. This is useful for older browsers or environments that do not support ES modules directly.
```html
```
--------------------------------
### Serialize and Parse Google Authenticator URIs
Source: https://context7.com/hectorm/otpauth/llms.txt
Use `URI.stringify` to convert TOTP/HOTP objects to `otpauth://` URIs for QR codes. Use `URI.parse` to convert a URI string back into a TOTP or HOTP instance. Ensure the URI is valid to avoid errors.
```javascript
import * as OTPAuth from "otpauth";
// Serialize a TOTP object to an otpauth:// URI for QR code generation.
const totp = new OTPAuth.TOTP({
issuer: "MyApp",
label: "user@myapp.com",
algorithm: "SHA1",
digits: 6,
period: 30,
secret: "US3WHSG7X5KAPV27VANWKQHF3SH3HULL",
});
const uri = OTPAuth.URI.stringify(totp);
// or equivalently: totp.toString()
console.log(uri);
// "otpauth://totp/MyApp:user%40myapp.com?issuer=MyApp&secret=US3WHSG7X5KAPV27VANWKQHF3SH3HULL&algorithm=SHA1&digits=6&period=30"
// Parse a URI string back into a TOTP or HOTP instance.
try {
const parsed = OTPAuth.URI.parse(uri);
console.log(parsed instanceof OTPAuth.TOTP); // true
console.log(parsed.issuer); // "MyApp"
console.log(parsed.label); // "user@myapp.com"
console.log(parsed.secret.base32); // "US3WHSG7X5KAPV27VANWKQHF3SH3HULL"
console.log(parsed.generate()); // current TOTP token
} catch (e) {
if (e instanceof URIError) console.error("Malformed URI");
if (e instanceof TypeError) console.error("Invalid parameter:", e.message);
}
// Parse an HOTP URI (counter parameter is required).
const hotpUri = "otpauth://hotp/ACME:alice?secret=JBSWY3DPEHPK3PXP&issuer=ACME&counter=0&algorithm=SHA1&digits=6";
const hotpObj = OTPAuth.URI.parse(hotpUri);
console.log(hotpObj instanceof OTPAuth.HOTP); // true
console.log(hotpObj.counter); // 0
// Full round-trip example.
const original = new OTPAuth.TOTP({ secret: new OTPAuth.Secret(), issuer: "Demo", label: "test" });
const roundTripped = OTPAuth.URI.parse(original.toString());
console.log(original.generate() === roundTripped.generate()); // true
```
--------------------------------
### TOTP Class
Source: https://github.com/hectorm/otpauth/blob/master/docs/index.html
Implements the Time-based One-Time Password algorithm.
```APIDOC
## Class: TOTP
### Description
Enables the generation and validation of TOTP tokens based on time.
### Usage
```javascript
import { TOTP } from 'otpauth';
// Example usage (details not provided in source)
```
```
--------------------------------
### Secret Static Methods
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/Secret.html
Create Secret objects from various string formats.
```APIDOC
## fromBase32(str: string): Secret
### Description
Converts a base32 string to a Secret object.
### Parameters
* str: string
* Base32 string.
### Returns Secret
* Secret object.
```
```APIDOC
## fromHex(str: string): Secret
### Description
Converts a hexadecimal string to a Secret object.
### Parameters
* str: string
* Hexadecimal string.
### Returns Secret
* Secret object.
```
```APIDOC
## fromLatin1(str: string): Secret
### Description
Converts a Latin-1 string to a Secret object.
### Parameters
* str: string
* Latin-1 string.
### Returns Secret
* Secret object.
```
--------------------------------
### TOTP.toString()
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Returns the OTPAuth URI string for the TOTP instance, which can be used for provisioning authenticator apps.
```APIDOC
## toString(): string
### Description
Returns the OTPAuth URI string for the TOTP instance.
### Method
`toString()`
### Parameters
None
### Response
- **uri** (string) - The OTPAuth URI.
```
--------------------------------
### remaining
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Calculates the remaining time in milliseconds until the next token is generated.
```APIDOC
## remaining
### Description
Calculates the remaining time in milliseconds until the next token is generated.
### Method
`Static`remaining
### Parameters
* **config** (object) - Optional
* **period** (number) - Optional - Token time-step duration.
* **timestamp** (number) - Optional - Timestamp value in milliseconds.
### Returns
* **number** - Counter representing remaining time.
```
--------------------------------
### TOTP.generate
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Generates a TOTP token.
```APIDOC
## generate
### Description
Generates a TOTP token.
### Parameters
#### Optional config: { timestamp?: number }
- timestamp (number) - Optional - Timestamp value in milliseconds.
### Returns
- string - Token.
```
--------------------------------
### TOTP.counter
Source: https://github.com/hectorm/otpauth/blob/master/docs/classes/TOTP.html
Calculates the counter based on the provided configuration.
```APIDOC
## Static counter
### Description
Calculates the counter. i.e. the number of periods since timestamp 0.
### Parameters
#### Optional config: { period?: number; timestamp?: number }
- period (number) - Optional - Token time-step duration.
- timestamp (number) - Optional - Timestamp value in milliseconds.
### Returns
- number - Counter.
```
--------------------------------
### Static TOTP API for Generation and Validation
Source: https://context7.com/hectorm/otpauth/llms.txt
Utilize the static TOTP API for generating and validating tokens without needing to create an instance. This is useful for one-off operations or when managing state is not required. Ensure correct parameters like secret, algorithm, digits, period, and timestamp are provided.
```javascript
// Static API — no instance required.
const staticToken = OTPAuth.TOTP.generate({
secret: OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL"),
algorithm: "SHA256",
digits: 8,
period: 60,
timestamp: Date.now(),
});
const staticDelta = OTPAuth.TOTP.validate({
token: staticToken,
secret: OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL"),
algorithm: "SHA256",
digits: 8,
period: 60,
window: 1,
});
console.log(staticDelta); // 0
```
--------------------------------
### Generate and Manage OTP Secrets
Source: https://context7.com/hectorm/otpauth/llms.txt
Use the `Secret` class to generate random secrets, or construct them from Base32, Hex, UTF-8, or raw buffers. Supports various encodings like Base32, Hex, Latin-1, and UTF-8.
```javascript
import * as OTPAuth from "otpauth";
// Generate a new cryptographically secure random secret (default: 20 bytes / 160 bits).
// RFC 4226 recommends a minimum of 128 bits (16 bytes); 160 bits (20 bytes) is the default.
const secret = new OTPAuth.Secret({ size: 20 });
console.log(secret.bytes); // Uint8Array(20) [...]
console.log(secret.base32); // e.g. "JBSWY3DPEHPK3PXP..." (Base32-encoded, used in QR codes)
console.log(secret.hex); // e.g. "48656c6c6f..."
console.log(secret.latin1); // Latin-1 string representation
console.log(secret.utf8); // UTF-8 string representation
// Construct from a known Base32 string (e.g., shared with a user via QR code).
const fromBase32 = OTPAuth.Secret.fromBase32("US3WHSG7X5KAPV27VANWKQHF3SH3HULL");
console.log(fromBase32.hex); // deterministic hex representation
// Construct from a hexadecimal string.
const fromHex = OTPAuth.Secret.fromHex("48656c6c6f21deadbeef");
console.log(fromHex.base32);
// Construct from a UTF-8 passphrase (NOT recommended for production; use random bytes instead).
const fromUTF8 = OTPAuth.Secret.fromUTF8("my-secret-passphrase");
// Construct from a raw ArrayBuffer.
const buffer = crypto.getRandomValues(new Uint8Array(32)).buffer;
const fromBuffer = new OTPAuth.Secret({ buffer });
console.log(fromBuffer.base32);
```