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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@pake/otp

v0.7.3

Published

Simple and powerful way to implement your own OTP workflows

Downloads

11

Readme

@pake/otp

A simple and scalable javascript library to perform OTP operations. Works in Node, Deno, and Bun runtimes.

Benefits:

  • Requires a single key-value pair storage server
  • Almost stateless operation, straightforward client/server logic
  • Very easy to implement in server-side rendered applications

Installation

npm install @pake/otp
yarn add @pake/otp
pnpm install @pake/otp
bun install @pake/otp

How to use

To create a storage adapter, implement the OtpStorage interface

export interface OtpStorage {
  set(key: string, value: string, ttl: number /* in seconds! */): Promise<void>;
  get(key: string): Promise<string | null>;
  invalidate(key: string): Promise<void>;
}

Or use UnstorageAdapter to support many different backend key-value data stores. The complete list can be found in the official documentation here

Examples will use the MemoryStorage implementation, which is a simple wrapper around js Map()

Create an instance of OtpService

import { OtpService, OtpError } from '@pake/otp';
import Storage from '@pake/otp/storage/MemoryStorage';
type SendArgs = { locale: string };

export const otpService = new OtpService({
  storage: new Storage(),
  maxAttempts: 3,
  timeToResend: 60 * 1000, // units in milliseconds
  timeToSolve: 5 * 60 * 1000, // units in milliseconds
  generateSolution: () => '1234',
  sendOtp: async (account, solution, args: SendArgs) => {
    console.log('sent otp to', account, 'with solution', solution);
    // write code to send otp to the user
  },
});

Issue a token, route POST /otp/issue

try {
  const { token, data, error, meta } = await otpService.issue(
    body.phone,
    undefined, // custom data to attach to otp
    { locale: 'en' } // args passed to sendOtp
  );

  // redirect to correct page
  set.headers['HX-Location'] = `/otp/${token}/`;
} catch (error: unknown) {
  // Typed error is returned
  if (error instanceof OtpError) {
    if (error.message == 'BAD_REQUEST') set.status = 400;
    else if (error.message == 'INTERNAL_ERROR') set.status = 500;
  }
}

Get token information GET /otp/:token

try {
  const { token, data, error, meta } = await otpService.getTokenInformation(
    params.token
  );

  return (
    <RootLayout title="Confirm OTP page">
      <OtpPage token={token} data={data} meta={meta} error={error}></OtpPage>
    </RootLayout>
  );
} catch (error: unknown) {
  if (error instanceof OtpError) {
    if (error.message == 'BAD_REQUEST') set.status = 400;
    else if (error.message == 'INTERNAL_ERROR') set.status = 500;

    return (
      <RootLayout title="Confirm OTP page">
        {error.message == 'INTERNAL_ERROR' && (
          <div>Internal server error. Cause: {error.cause}</div>
        )}
        {error.message == 'BAD_REQUEST' && (
          <div>Bad request. Cause: {error.cause}</div>
        )}
      </RootLayout>
    );
  }
}

Please note that all methods of OtpService can throw OtpError. These functions throw when a malicious request is made by the client or when experiencing technical problems in storage. In the following examples, try-catch error handling is omitted for brevity.

Check solution, route POST /otp/:token/check

const { token, data, meta, error } = await otpService.check(
  params.token, // token from the client
  body.solution // solution from the clent
);

if (!meta.isSolved) {
  // set new token on the client
  set.headers['HX-Replace-Url'] = `/otp/${token}/`;
  // re-render otp form with error message
  return (
    <OtpForm token={token} data={data} meta={meta} error={error}></OtpForm>
  );
}

// proceed to business logic
const { account, customData } = data;

Resend a token, route POST /otp/:token/resend

const { token, data, meta, error } = await otpService.resend(params.token, {
  locale: 'en',
});

set.headers['HX-Replace-Url'] = `/otp/${token}/`;
return <OtpForm token={token} data={data} meta={meta} error={error}></OtpForm>;

All of the functions above return the OtpResult type.

export type OtpResult<Data = unknown> = {
  token: string;
  data: {
    id: string;
    account: string;
    expiresAt: number;
    resendAt: number;
    attemptsRemaining: number;
    customData: Data;
  };
  meta: {
    isSolved: boolean;
    canResend: boolean;
    canAttempt: boolean;
    isExpired: boolean;
  };
  error: 'NO_ATTEMPTS_REMAINING' | 'EXPIRED' | 'BAD_SOLUTION' | null;
};

How to use UnstorageAdapter

import { OtpService } from '@pake/otp';
import Storage from '@pake/otp/storage/UnstorageAdapter';
import redisDriver from 'unstorage/drivers/redis';

const otpService = new OtpService({
  storage: new Storage(
    redisDriver({
      // driver options
    })
  ),
  generateSolution: () => '1234',
});

Helper functions

import {
  numericalSolutionGenerator,
  browserDecodeToken,
} from '@pake/otp/helpers';

// 6-digit code generator
const generateSolution = numericalSolutionGenerator(6);

// decode token value into data of OtpResult in the browser
const { account, expiresAt, resendAt, attemptsRemaining } =
  browserDecodeToken('...');

Typedoc API overview

Available here

Examples:

Example workflows

User authentication via SMS/email codes

See htmx example. TODO add diagrams and a description of how it works.

Verify ownership of phone and/or email before registration

TODO

Verify the user before performing privileged actions

TODO

How it works

This library operates on the idea of unique tokens and cache keys. Every time a new token is issued, the following data is encoded as base64url:

  • unique id
  • account (email or phone number)
  • number of attempts remaining
  • expiration time
  • resend time
  • any custom data

The generated token string is hashed, and the solution to the OTP is stored in a centralized cache, using the hashed token as a cache key.

This token is then sent to the client to decode and display interactive UI. Or even better, it can be server-side rendered. When the client sends a solution to the server, the server looks up the solution in the cache. If it is correct, it is marked as solved. If the solution is wrong, the server invalidates the previous hash and creates a new one, which is sent back to the client.

I am looking for feedback and potential vulnerabilities in this method of OTP validation.

Security

Security comes from hashing. Since the token is derived from a random ID, account name, issue time, and attempts remaining count, the current token value cannot be guessed by a 3rd party. Every time the token is used, it is invalidated (except when explicitly told to allowReuseOfSolvedToken; more on this later)

The tokens are protected from modification by indexing them in the cache by hashed value (with sha256 as default); the server simply can not find a maliciously modified token in the hash. Since every token is given a small number of attempts, it is unlikely for the 1st party to go around it without entering the correct solution.

The customData field can store arbitrary JSON-encodable information inside the token, allowing the developer to ensure that solved tokens are not used for other purposes.

When issuing a token with allowReuseOfSolvedToken enabled, values for solved tokens in storage are overridden to s constant value S. The next time getTokenInformation is called, it will know that the token is solved.

This library depends on the crypto module. All cryptographic operations are performed using this module.

Important notes

Always implement some sort of rate limit by IP or account to prevent abuse. Sending text messages costs money, and email spam is terrible for domain-name reputation. Rate-limit both solving and issuing of tokens before using this library.

Validate and normalize the account field before issuing the tokens: trim whitespaces, convert emails to lowercase, remove "+" in phone numbers, use Google's libphonenumber, etc.

Always validate token data when OTP is solved correctly. Grant login/registration to [email protected] only if the token has an account of [email protected]. If not careful, an attacker with the email [email protected] could log in to the account of [email protected] by substituting the solved token before hitting the login API endpoint.

Use at least 6-digit OTP codes, allow no more than 3 attempts, and expire tokens after no more than 5 minutes.

TODOS

  • [ ] Better readme, add workflow diagram
  • [ ] More helper functions
  • [ ] Client-side react example
  • [ ] TsDoc autodocumentation