Skip to content

OTP Code Generator — TypeScript source

Generate time-based one-time passwords (RFC 6238 TOTP) from a Base32 secret, with selectable algorithm, digit count, and period - updating live, entirely in your browser.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// TOTP (RFC 6238) code generator/validator backed by `otpauth`. Injectable
// timestamp for deterministic tests. The unit-test surface for the OTP Code
// Generator tool.

import { Secret, TOTP } from 'otpauth';

export interface TotpOptions {
  secret: string; // Base32 (per RFC 4648); spaces/case tolerated
  algorithm?: string; // 'SHA1' | 'SHA256' | 'SHA512' (default 'SHA1')
  digits?: number; // default 6
  period?: number; // seconds, default 30
  timestamp?: number; // ms epoch (injectable for tests); defaults to now
}

function secretFrom(opts: TotpOptions): Secret {
  return Secret.fromBase32(opts.secret.replace(/\s+/g, '').toUpperCase());
}

function config(opts: TotpOptions) {
  return {
    algorithm: opts.algorithm ?? 'SHA1',
    digits: opts.digits ?? 6,
    period: opts.period ?? 30,
    timestamp: opts.timestamp ?? Date.now(),
  };
}

/** Generate a TOTP token for the given secret + options, or null if the secret is invalid. */
export function generateTotp(opts: TotpOptions): string | null {
  try {
    return TOTP.generate({ secret: secretFrom(opts), ...config(opts) });
  } catch {
    return null;
  }
}

/** Validate a token against the secret + options (within one period window). */
export function validateTotp(token: string, opts: TotpOptions): boolean {
  try {
    return TOTP.validate({ token, secret: secretFrom(opts), ...config(opts) }) !== null;
  } catch {
    return false;
  }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →