CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-otplib

HMAC-based (HOTP) and Time-based (TOTP) One-Time Password library compatible with Google Authenticator

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

presets.mddocs/

Environment Presets

OTPLib provides different preset packages optimized for specific environments. Each preset includes pre-configured crypto and base32 implementations suitable for their target platform.

Capabilities

Default Preset (Node.js)

The main otplib package and @otplib/preset-default provide Node.js optimized implementations.

// Main package (re-exports preset-default)
import { authenticator, totp, hotp } from "otplib";

// Direct preset import
import { authenticator, totp, hotp } from "@otplib/preset-default";

Features:

  • Node.js crypto module for HMAC operations
  • thirty-two library for Base32 encoding/decoding
  • Optimized for server-side applications
  • Full TypeScript support

Usage Example:

import { authenticator, totp, hotp } from "otplib";

// All instances pre-configured for Node.js
const secret = authenticator.generateSecret();
const token = authenticator.generate(secret);
const isValid = authenticator.check(token, secret);

// Direct usage without additional setup
const totpToken = totp.generate("secret-key");
const hotpToken = hotp.generate("secret-key", 0);

Browser Preset

Browser-compatible preset using pure JavaScript crypto implementations.

import { authenticator, totp, hotp } from "@otplib/preset-browser";

Features:

  • crypto-js library for HMAC operations (no Node.js dependencies)
  • base32-encode/base32-decode for Base32 operations
  • UMD bundle available for direct browser inclusion
  • Automatic Buffer polyfill injection

Installation:

npm install @otplib/preset-browser

Browser Usage:

<!-- Include Buffer polyfill first -->
<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/buffer.js"></script>
<!-- Include OTPLib browser preset -->
<script src="https://unpkg.com/@otplib/preset-browser@^12.0.0/index.js"></script>

<script>
  // Available as window.otplib
  const secret = window.otplib.authenticator.generateSecret();
  const token = window.otplib.authenticator.generate(secret);
  const isValid = window.otplib.authenticator.check(token, secret);
  
  console.log('Secret:', secret);
  console.log('Token:', token);
  console.log('Valid:', isValid);
</script>

Module Usage:

import { authenticator, totp, hotp } from "@otplib/preset-browser";

// Works in browser environments without Node.js dependencies
const secret = authenticator.generateSecret();
const token = authenticator.generate(secret);

// All functionality available as in Node.js preset
totp.options = { digits: 8 };
const totpToken = totp.generate("browser-secret");

v11 Compatibility Preset

Backward compatibility preset providing v11.x API compatibility.

import { authenticator, totp, hotp } from "@otplib/preset-v11";

Features:

  • Compatible with otplib v11.x API
  • Provides deprecated method warnings
  • Same crypto implementations as default preset
  • Gradual migration support

Installation:

npm install @otplib/preset-v11

Usage Example:

import { authenticator, totp, hotp } from "@otplib/preset-v11";

// v11 API compatibility
const secret = 'KVKFKRCPNZQUYMLXOVYDSQKJKZDTSRLD';
const token = authenticator.generate(secret);
const isValid = authenticator.check(token, secret);

// Deprecated methods will show console warnings but still work
// This helps with gradual migration to v12 API

Migration Pattern:

// Old v11 code
import { authenticator } from 'otplib';

// Migration step 1: Use v11 preset
import { authenticator } from '@otplib/preset-v11';

// Migration step 2: Update to v12 API
import { authenticator } from 'otplib';

Async Preset

Async-compatible preset for environments requiring async crypto operations.

import { authenticator, totp, hotp } from "@otplib/preset-default-async";

Features:

  • All methods return Promises
  • Compatible with async crypto libraries
  • Useful for React Native, Expo, and Web Crypto API
  • Same API but with async/await support

Usage Example:

import { authenticator, totp, hotp } from "@otplib/preset-default-async";

async function handleOTP() {
  // All operations are async
  const secret = await authenticator.generateSecret();
  const token = await authenticator.generate(secret);
  const isValid = await authenticator.check(token, secret);
  
  console.log('Generated:', token);
  console.log('Valid:', isValid);
}

// TOTP async usage
async function handleTOTP() {
  const token = await totp.generate("secret-key");
  const isValid = await totp.check(token, "secret-key");
  
  return { token, isValid };
}

Custom Preset Creation

Create custom presets with specific crypto and base32 implementations.

import { HOTP, TOTP, Authenticator } from "@otplib/core";
import { createDigest, createRandomBytes } from "custom-crypto-plugin";
import { keyEncoder, keyDecoder } from "custom-base32-plugin";

// Create custom instances
const customHOTP = new HOTP({ createDigest });
const customTOTP = new TOTP({ createDigest });
const customAuthenticator = new Authenticator({
  createDigest,
  createRandomBytes,
  keyEncoder,
  keyDecoder
});

export { customHOTP as hotp, customTOTP as totp, customAuthenticator as authenticator };

Preset Comparison

Feature Matrix

FeatureDefaultBrowserv11Async
Node.js
Browser⚠️
TypeScript
Bundle SizeSmallMediumSmallSmall
Async Methods
v11 Compatibility

Performance Characteristics

// Default preset - Fastest (Node.js crypto)
import { authenticator } from "otplib";

// Browser preset - Slower (pure JS crypto)
import { authenticator } from "@otplib/preset-browser";

// Async preset - Variable (depends on crypto implementation)
import { authenticator } from "@otplib/preset-default-async";

Environment-Specific Usage

React Native / Expo

// Use browser preset or create custom with React Native crypto
import { authenticator } from "@otplib/preset-browser";

// Or with async preset if using crypto-js async
import { authenticator } from "@otplib/preset-default-async";

Webpack/Bundler Environments

// Browser preset recommended for webpack builds
import { authenticator } from "@otplib/preset-browser";

// Avoid Node.js preset in browser bundles
// import { authenticator } from "otplib"; // ❌ Will bundle Node.js dependencies

Electron Applications

// Main process (Node.js)
import { authenticator } from "otplib";

// Renderer process (Browser-like)
import { authenticator } from "@otplib/preset-browser";

Web Workers

// Use browser preset in web workers
import { authenticator } from "@otplib/preset-browser";

self.onmessage = function(e) {
  const token = authenticator.generate(e.data.secret);
  self.postMessage({ token });
};

Types

// All presets export the same interface types
interface PresetExports {
  authenticator: Authenticator;
  totp: TOTP;
  hotp: HOTP;
}

// Async preset returns Promise-wrapped methods
interface AsyncPresetExports {
  authenticator: AsyncAuthenticator;
  totp: AsyncTOTP;
  hotp: AsyncHOTP;
}

interface AsyncAuthenticator {
  generate(secret: string): Promise<string>;
  check(token: string, secret: string): Promise<boolean>;
  verify(opts: { token: string; secret: string }): Promise<boolean>;
  generateSecret(numberOfBytes?: number): Promise<string>;
  keyuri(accountName: string, issuer: string, secret: string): Promise<string>;
}

Install with Tessl CLI

npx tessl i tessl/npm-otplib

docs

authenticator.md

configuration.md

hotp.md

index.md

presets.md

totp.md

tile.json