npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nbssf-secure-otp-generator

v1.0.1

Published

A secure OTP generation and verification package supporting Numeric, Alphanumeric, TOTP, HOTP, Email OTP, SMS OTP, Authenticator Apps, QR Code onboarding, and enterprise-grade verification workflows.

Downloads

147

Readme

secure-otp-generator

Enterprise-grade OTP generation and verification for modern authentication systems.

npm CI codecov npm downloads License: MIT TypeScript PRs Welcome


A secure, zero-dependency OTP (One-Time Password) library for Node.js. Built for production environments where security, scalability, and reliability are critical. Supports Numeric, Alphanumeric, TOTP (RFC 6238), HOTP (RFC 4226), QR code onboarding, and enterprise verification workflows with pluggable storage adapters.

Features

🔐 Security First

  • Cryptographically secure — Uses Node.js crypto.randomInt and crypto.randomBytes
  • Constant-time comparison — XOR-based timing attack prevention on all verifications
  • SHA-256 hashing — OTP codes are never stored in plaintext
  • Brute-force protection — Configurable attempt limits, cooldowns, and lockout windows
  • Rate limiting — Sliding window rate limiter (IP, user, or global scope)
  • Replay prevention — One-time use enforcement with consumed-token tracking
  • Device fingerprinting — Signed device identification for multi-device security
  • Zero runtime dependencies — No supply chain risk from third-party packages

📋 OTP Types

| Type | Description | Use Case | |------|-------------|----------| | Numeric | crypto.randomInt digits | SMS/Email verification codes | | Alphabetic | Random letters | Promo codes, backup codes | | Alphanumeric | Mixed letters + digits | Secure tokens, API keys | | TOTP | Time-based (RFC 6238) | Authenticator apps (Google, Microsoft, Authy) | | HOTP | HMAC-based (RFC 4226) | Hardware tokens, counter-based auth |

🗄️ Storage Adapters

| Adapter | Status | Production Ready | |---------|--------|-----------------| | Memory | ✅ Built-in | ❌ Dev/test only | | Redis | ✅ Built-in | ✅ Yes | | MongoDB | ✅ Built-in | ✅ Yes | | PostgreSQL | ✅ Built-in | ✅ Yes | | MySQL | ✅ Built-in | ✅ Yes |

📬 Delivery Providers

| Provider | Type | Status | |----------|------|--------| | Twilio | SMS | ✅ | | AWS SNS | SMS | ✅ | | SendGrid | Email | ✅ | | Nodemailer | Email | ✅ |

🏗️ Enterprise Architecture

  • Clean Architecture — Separation of concerns with core, adapters, and services layers
  • SOLID Principles — Interface-based design with dependency injection
  • Repository Pattern — Pluggable storage backends
  • Strategy Pattern — Swappable SMS/email providers
  • Observer Pattern — Typed event hooks for observability
  • Middleware Pattern — Drop-in Express middleware

Installation

npm install secure-otp-generator
# or
pnpm add secure-otp-generator
# or
yarn add secure-otp-generator

Quick Start

Basic OTP Generation & Verification

import { OtpService, MemoryStorageAdapter } from 'secure-otp-generator';

const storage = new MemoryStorageAdapter();
const service = new OtpService(storage);

// Generate a 6-digit numeric OTP
const { otp, id, expiresAt } = await service.generate({
  identifier: '[email protected]',
});

console.log(`Your OTP is: ${otp}`); // Send via SMS/email

// Verify the OTP
const result = await service.verify({
  id,
  otp,
  identifier: '[email protected]',
});

if (result.valid) {
  console.log('✅ Verified successfully');
} else {
  console.log(`❌ Failed: ${result.reason}`);
}

TOTP / Authenticator App

import { Totp, QrService } from 'secure-otp-generator';
import { createHash, randomBytes } from 'node:crypto';

const totp = new Totp();
const qrService = new QrService();

// Generate a secret (store this for the user)
const secret = randomBytes(20);

// Generate current TOTP code
const code = totp.generate({ secret, period: 30 });
console.log(code.otp); // 6-digit code

// Verify TOTP code
const isValid = totp.verify({
  secret,
  otp: code.otp,
  timestamp: Date.now(),
  skew: 1, // Allow 1 period skew
});

// Generate QR code URI for authenticator app setup
const uri = totp.generateAuthenticatorURI({
  label: '[email protected]',
  secret,
  issuer: 'MyApp',
});

const qrData = qrService.generateQrCodeData({
  label: '[email protected]',
  secret: secret.toString('base64'),
  issuer: 'MyApp',
});

console.log(`Scan this URI: ${qrData.uri}`);
// Use with any QR code library to render a QR code

With Event Hooks

import { OtpService, MemoryStorageAdapter } from 'secure-otp-generator';

const service = new OtpService(new MemoryStorageAdapter(), {
  events: {
    onGenerate: (payload) => {
      console.log(`OTP generated for ${payload.identifier}`);
      // Send SMS/email here
    },
    onVerify: (payload) => {
      if (payload.success) {
        console.log(`User ${payload.identifier} verified`);
      }
    },
    onFail: (payload) => {
      console.warn(`Failed attempt ${payload.attempt}/${payload.maxAttempts}`);
    },
    onLockout: (payload) => {
      console.error(`User ${payload.identifier} locked out for ${payload.duration}ms`);
    },
  },
});

With Brute Force Protection

import { OtpService, MemoryStorageAdapter } from 'secure-otp-generator';

const service = new OtpService(new MemoryStorageAdapter(), {
  security: {
    bruteForce: {
      enabled: true,
      maxAttempts: 3,
      cooldownMs: 60_000,    // 1 minute between attempts
      lockoutMs: 300_000,     // 5 minute lockout
      scope: 'identifier',
      attemptTrackingWindowMs: 300_000,
    },
    rateLimiter: {
      enabled: true,
      maxRequests: 5,
      windowMs: 60_000,
      blockDurationMs: 300_000,
      scope: 'ip',
    },
  },
});

With Redis Storage

import { OtpService, RedisStorageAdapter } from 'secure-otp-generator';
import { createClient } from 'redis';

const redisClient = createClient({ url: 'redis://localhost:6379' });
await redisClient.connect();

const storage = new RedisStorageAdapter(redisClient);
const service = new OtpService(storage);

// Works the same as memory adapter but persists across restarts
const result = await service.generate({ identifier: '[email protected]' });

Express Middleware

import express from 'express';
import { OtpService, MemoryStorageAdapter, createOtpMiddleware, RateLimiter } from 'secure-otp-generator';

const app = express();
app.use(express.json());

const otpService = new OtpService(new MemoryStorageAdapter());
const rateLimiter = new RateLimiter({ maxRequests: 3, windowMs: 60000 });
const otpMiddleware = createOtpMiddleware({ otpService, rateLimiter });

app.post('/api/otp/generate', otpMiddleware.generate);
app.post('/api/otp/verify', otpMiddleware.verify);

app.listen(3000);

API Reference

OtpService

The main service orchestrator.

class OtpService {
  constructor(storage: IStorageAdapter, config?: OtpServiceConfig);

  generate(options: OtpGenerateOptions): Promise<GenerateResult>;
  verify(options: OtpVerifyOptions): Promise<VerifyServiceResult>;
  invalidate(id: string): Promise<void>;
  cleanupExpired(): Promise<number>;

  on<K extends keyof EventMap>(event: K, handler: Function): void;
  setBruteForceProtector(protector: BruteForceProtector): void;
  setRateLimiter(limiter: RateLimiter): void;
  getEventEmitter(): OtpEventEmitter;
  getAuditLogger(): AuditLogger;
}

OtpGenerator

Low-level OTP generation without storage.

class OtpGenerator {
  generate(config: OtpConfig): GeneratedOtp;
}

Totp

Time-based OTP (RFC 6238) — compatible with Google/Microsoft/Authy authenticators.

class Totp {
  generate(options: TotpOptions, encoding?: 'hex' | 'base32'): TotpResult;
  verify(options: TotpOptions & { otp: string }, encoding?: 'hex' | 'base32'): boolean;
  generateAuthenticatorURI(options: {
    label: string;
    secret: string | Buffer;
    issuer?: string;
    period?: number;
    digits?: number;
    algorithm?: HashAlgorithm;
  }): string;
}

Hotp

HMAC-based OTP (RFC 4226).

class Hotp {
  generate(options: HotpOptions, encoding?: 'hex' | 'base32'): HotpResult;
  verify(options: HotpOptions & { otp: string }, encoding?: 'hex' | 'base32'): boolean;
  verifyWithWindow(options: HotpOptions & { otp: string; window?: number }, encoding?: 'hex' | 'base32'): {
    valid: boolean;
    counter?: number;
  };
}

Storage Adapters

interface IStorageAdapter {
  create(record: OtpRecord): Promise<void>;
  findById(id: string): Promise<OtpRecord | null>;
  findByIdentifier(identifier: string): Promise<OtpRecord | null>;
  update(record: OtpRecord): Promise<void>;
  delete(id: string): Promise<void>;
  deleteExpired(): Promise<number>;
  incrementAttempts(id: string): Promise<number>;
  markVerified(id: string): Promise<void>;
  markConsumed(id: string): Promise<void>;
}

// Built-in implementations:
class MemoryStorageAdapter implements IStorageAdapter {}
class RedisStorageAdapter implements IStorageAdapter {}
class MongoDbStorageAdapter implements IStorageAdapter {}
class PostgresStorageAdapter implements IStorageAdapter {}
class MySqlStorageAdapter implements IStorageAdapter {}

Security

// Brute Force Protection
class BruteForceProtector {
  recordAttempt(key: string): { allowed: boolean; remainingAttempts: number; lockedUntil?: number };
  checkLockout(key: string): { locked: boolean; remainingLockoutMs: number };
  reset(key: string): void;
}

// Rate Limiting
class RateLimiter {
  check(key: string): { allowed: boolean; remaining: number; resetAt: number };
  checkOrThrow(key: string): void;
  reset(key: string): void;
}

// Device Fingerprinting
class DeviceFingerprint {
  generate(input: DeviceFingerprintInput): DeviceInfo;
  generateSigned(input: DeviceFingerprintInput, signingKey: string): string;
  verifySigned(signedFingerprint: string, input: DeviceFingerprintInput, signingKey: string): boolean;
}

// Hashing
class Hasher {
  sha256(input: string): string;
  sha256WithSalt(input: string, salt?: string): HashResult;
  sha512(input: string): string;
  pbkdf2(password: string, salt?: string, iterations?: number, keyLength?: number): HashResult;
  verify(input: string, hash: string, salt?: string, algorithm?: string): boolean;
}

Events

interface EventMap {
  generate: [GenerateEventPayload];
  verify: [VerifyEventPayload];
  expire: [ExpireEventPayload];
  fail: [FailEventPayload];
  lockout: [LockoutEventPayload];
}

class OtpEventEmitter {
  on<K extends keyof EventMap>(event: K, handler: (...args: EventMap[K]) => void | Promise<void>): void;
  once<K extends keyof EventMap>(event: K, handler: (...args: EventMap[K]) => void | Promise<void>): void;
  off(event: string, handler: Function): void;
  emit<K extends keyof EventMap>(event: K, ...args: EventMap[K]): Promise<void>;
  removeAllListeners(event?: string): void;
}

Security Best Practices

  1. Use a production storage adapter — Never use MemoryStorageAdapter in production. Use Redis, PostgreSQL, or MongoDB.

  2. Enable brute-force protection — Set maxAttempts to 3-5 with a lockout period of at least 5 minutes.

  3. Enable rate limiting — Prevent API abuse with the built-in rate limiter.

  4. Use HTTPS — Always serve OTP endpoints over HTTPS to prevent interception.

  5. Set appropriate TTLs — Numeric OTPs: 30-300 seconds. TOTP codes: 30 seconds (standard).

  6. Never log OTP codes — Log the OTP ID (for auditing), never the actual code.

  7. Rotate encryption secrets — If using encrypted storage, rotate keys regularly.

  8. Enable audit logging — Track all OTP events for security monitoring.

  9. Send OTPs server-side — Never expose OTP codes in API responses to client-side code.

  10. Use device fingerprinting — Verify device identity as an additional security layer.

Performance

| Operation | Ops/sec | Latency (p50) | |-----------|---------|---------------| | Generate (6-digit numeric) | ~500,000 | < 2μs | | Generate (8-char alphanumeric) | ~480,000 | < 2.1μs | | Verify (constant-time) | ~420,000 | < 2.4μs | | TOTP generation | ~350,000 | < 2.9μs | | HOTP generation | ~380,000 | < 2.6μs | | Full generate + verify flow | ~100,000 | < 10μs |

Benchmarked on Node.js 22 with 8 vCPUs. Results may vary.

Architecture

┌─────────────────────────────────────────────────────────────┐
│                        Application                           │
├─────────────────────────────────────────────────────────────┤
│                   OtpService (Orchestrator)                   │
├─────────────────────────────────────────────────────────────┤
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────────┐ │
│  │ Generator│  │ Verifier │  │ Event    │  │ Audit       │ │
│  │          │  │          │  │ Emitter  │  │ Logger      │ │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └──────┬──────┘ │
├───────┴─────────────┴─────────────┴───────────────┴────────┤
│                     Security Layer                           │
│  ┌──────────┐  ┌─────────────┐  ┌──────────────────────┐   │
│  │ Brute    │  │ Rate        │  │ Device               │   │
│  │ Force    │  │ Limiter     │  │ Fingerprint          │   │
│  └──────────┘  └─────────────┘  └──────────────────────┘   │
├────────────────────────────────────────────────────────────┤
│                     Storage Layer                            │
│  ┌──────┐ ┌─────┐ ┌────────┐ ┌──────────┐ ┌─────┐         │
│  │Memory│ │Redis│ │MongoDB │ │PostgreSQL│ │MySQL│         │
│  └──────┘ └─────┘ └────────┘ └──────────┘ └─────┘         │
├────────────────────────────────────────────────────────────┤
│                   Delivery Layer                             │
│  ┌────────┐ ┌────────┐ ┌──────────┐ ┌─────────────┐       │
│  │Twilio  │ │AWS SNS │ │SendGrid  │ │Nodemailer   │       │
│  └────────┘ └────────┘ └──────────┘ └─────────────┘       │
└────────────────────────────────────────────────────────────┘

Framework Integrations

See the examples directory for complete integration examples:

Contributing

Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.

License

This project is MIT licensed.

Support