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

sms-based-auth

v0.1.0

Published

Framework-neutral, security-first SMS authentication for Node.js

Readme

sms-based-auth

Security-first, framework-neutral SMS authentication for Node.js. It generates purpose-bound OTP challenges, delegates delivery to a typed host SMS manager, and manages short-lived access tokens plus rotating opaque refresh sessions.

SMS OTP is not phishing-resistant and is not strong MFA. Use a phishing-resistant factor for high-value operations.

Features

  • Iranian mobile normalization to E.164, including Persian and Arabic-Indic digits
  • Explicit isolated purposes: login, phone_verification, account_recovery, and sensitive_action
  • CSPRNG OTPs, keyed hashes, attempt limits, resend cooldown, abuse buckets, atomic single use
  • Actor/session-bound sensitive challenges
  • Rotating refresh tokens, family reuse detection, session listing and revocation
  • HS256 for single-service deployments and ES256/RS256/EdDSA for multi-service or Edge verification
  • JSON, hardened cookie, hybrid, and custom delivery
  • Express, NestJS, Next.js App Router, and Web-Crypto Edge exports
  • Caller-supplied Mongoose and Redis clients; no hidden connections
  • ESM, CommonJS, and declarations for every subpath

Install

npm install sms-based-auth jose zod

Install only the optional peers you use: express, mongoose, redis, @nestjs/common, @nestjs/core, reflect-metadata, and rxjs.

Core setup

import { randomBytes } from "node:crypto";
import { createSmsBasedAuth } from "sms-based-auth";
import {
  MemoryChallengeStore,
  MemoryRateLimiter,
  MemorySessionStore,
} from "sms-based-auth/memory";

const signingSecret = randomBytes(32);
const pepperSecret = randomBytes(32);

const auth = createSmsBasedAuth({
  config: {
    issuer: "https://api.example.com",
    audience: "example-app",
    accessTokenKeys: [
      { kid: "access-2026-01", algorithm: "HS256", secret: signingSecret },
    ],
    activeAccessTokenKid: "access-2026-01",
    pepper: { kid: "pepper-2026-01", algorithm: "HS256", secret: pepperSecret },
  },
  challenges: new MemoryChallengeStore(),
  sessions: new MemorySessionStore(),
  rateLimiter: new MemoryRateLimiter(),
  sms: smsManager,
  smsActions: {
    login: "auth",
    phone_verification: "verify",
    account_recovery: "recover",
    sensitive_action: "sensitive",
  },
  authorizeScope: async (scope, context) => tenantPolicy.allows(scope, context),
  identities: {
    resolve: ({ phone, purpose, scope, createIfMissing }) =>
      userRepository.resolvePhone({ phone, purpose, scope, createIfMissing }),
    reauthorize: ({ userId, scope, sessionId }) =>
      userRepository.loadAuthorization({ userId, scope, sessionId }),
  },
});

Memory stores are single-process development references, not production stores.

await auth.requestCode({
  phone: "09123456789",
  purpose: "login",
  scope: "tenant-id",
  context: { ip, userAgent },
});

const result = await auth.verifyCode({
  phone: "09123456789",
  purpose: "login",
  code: "483291",
  scope: "tenant-id",
  context: { ip, userAgent },
});

For phone_verification and sensitive_action, provide actorAccessToken. The core verifies the token and active session and binds both user and session IDs into the challenge. Never accept a client-provided user ID as the actor.

Production persistence

Use createAuthModels, MongooseChallengeStore, and MongooseSessionStore from sms-based-auth/mongoose. A MongoDB replica set is mandatory because security transitions use transactions. Run syncIndexes() during a controlled migration, not on every application start. Challenges use a grace-period cleanup TTL and a partial unique active-challenge index.

Use RedisRateLimiter from sms-based-auth/redis with a caller-owned connected Redis client. Rate-limit context IPs must come only from a correctly configured trusted-proxy chain. Device IDs and user agents are hints, not identities.

Token delivery

deliverTokens(tokens, mode, cookieOptions) supports:

  • cookie: HttpOnly access and refresh cookies
  • json: response-body tokens for native, CLI, or trusted non-browser clients
  • hybrid: access token in memory/JSON and refresh token in HttpOnly cookie
  • custom: transport-neutral token result for host delivery

Defaults are __Host-sba_access (Secure; Path=/) and __Secure-sba_refresh with the narrow /auth/refresh path. Cookie-authenticated state changes must use allowed origins and createCsrfTokenCookie plus the adapter CSRF guard. Never store durable browser secrets in localStorage.

Framework adapters

import { createExpressAuth } from "sms-based-auth/express";
const expressAuth = createExpressAuth(auth, {
  csrf: { expectedOrigin: "https://app.example.com" },
});
app.get("/profile", expressAuth.requireAuth(), handler);
app.get(
  "/orders",
  expressAuth.requireAuth(),
  expressAuth.requirePermissions("orders.read"),
  handler,
);
app.post("/settings", expressAuth.requireCsrf(), handler);

NestJS exports SmsBasedAuthModule, SmsAuthGuard, CurrentAuth, RequireRoles, and RequirePermissions, with forRoot and forRootAsync. Controllers can be disabled. The built-in controller accepts transport: { mode, cookies }, reads refresh cookies when no body token is provided, clears cookies at logout, and enforces the configured CSRF origin/token pair for unsafe cookie-authenticated routes.

Next.js exports withAuth for Node App Router handlers. Pages Router is deferred. Mark routes using database/session checks as runtime = "nodejs".

The edge export only verifies short-lived asymmetric tokens and makes routing decisions. It contains no signing/private key or stateful revocation check. Re-check sensitive authorization in a trusted Node backend.

Security and operations

Read THREAT_MODEL.md, DEPLOYMENT.md, SECURITY.md, and MIGRATION.md before production use. Keep access-token signing keys, OTP peppers, refresh hashes, OTPs, cookies, and provider secrets out of logs.

For pepper rotation, make the new pepper active and retain prior keys in verificationPeppers until all live challenges and refresh sessions using them have expired. Configure a separate, stable fingerprintPepper so rotating OTP and refresh secrets does not reset abuse buckets. When identities.reauthorize is supplied, every refresh atomically persists and mints the latest trusted roles, permissions, and claims; an unresolved or ineligible identity revokes that user's scoped sessions.

Validation

npm run check
npm run package:check
npm run integration:up
npm run test:integration
npm run integration:down
npm audit

The integration suite uses a real MongoDB replica set and Redis instance.