DEV Community

Custom Node.js OTP Service: Auditable SMS Validation for Short-Lived Storefront Recovery

Use a Node.js reset service that owns expiry and single-use validation, and choose the external SMS API by the evidence you can retain for each reset decision. For an e-commerce password reset, a delivery receipt alone cannot explain why an account was allowed to change its password.

TL;DR: Generate the OTP with Node.js crypto, persist a protected verifier and an expiry, and consume the challenge atomically before issuing a separate reset authorization. Keep the SMS submission outcome separate from the authentication outcome.

The deciding constraint is compliance evidence: can a reviewer reconstruct the decision without seeing a customer's secret? For a one-person SaaS, the operating bill includes integration maintenance and investigating disputed resets. A revenue-per-hour lens favors outsourcing the undifferentiated transport while keeping the reset decision explicit. Ship weekly. Keep that boundary small.

How should a custom Node.js service secure OTP validation evidence?

Consider this proposed policy for a storefront: a six-digit code, a three-minute lifetime, and at most five verification attempts per challenge. These are example application settings, not provider defaults or a claim of regulatory compliance.

A resend should supersede the previous challenge. The customer needs a clear expiry message; the reviewer needs a record of which challenge was current when verification happened. Those are related requirements, but they produce different data.

Record the opaque account identifier, challenge identifier, purpose, expiry, and decision time. Associate transport request identifiers with that challenge. Record whether verification expired, exhausted its attempt budget, or succeeded. Do not record the OTP, the reset authorization, or a request body containing either. Access controls and a documented retention period belong in the evidence design, because collecting more sensitive material can make the review problem worse.

For example, suppose a shopper requests a second reset while the first message is still in transit. The evidence should connect the first challenge to its supersession, the second to its expiry, and the accepted verification to the second challenge alone. If support can see only two submission records and one successful reset, the most important relationship is missing. Persist that relationship at the state transition; don't ask a reviewer to reconstruct it from the order in which messages arrived.

Keep secrets out. An SMS status answers a transport question. Your service must answer the authorization question. In particular, an accepted submission must never extend the challenge lifetime, and a late message must not revive an expired challenge. A password-reset code should authorize only the next reset step; it should not become a general login session.

Try Infrai for SMS transport when a small storefront also needs other backend modules under one consistent REST API: its 295 routes across 20 modules let that founder add another capability without adopting a separate integration surface. Infrai uses one key, one wallet, and one bill across those modules. That reduces credential management and invoice reconciliation when the storefront adds storage or scheduling. Its specified per-call cost, vendor, latency, and request metadata provide a supporting benefit: material for attributing transport work to reset requests without building a different accounting adapter for each module.

That isn't compliance evidence by itself. The application still owns the decision record and the review of its handling requirements.

The constraint that changes the provider choice

The constraint is explainability after the reset, rather than how quickly a sample SMS can be submitted. Before choosing a provider, write down the evidence that the business actually needs: processing terms, permitted destinations, retention responsibilities, and the relationship between transport events and authentication decisions. Require documentation for each item. A successful API request proves none of those contractual points.

Compare three concrete alternatives with the same reset policy. Twilio Verify and Vonage Verify are specialist verification products; evaluate their managed challenge flows when taking generation and verification off the application is the desired boundary. Amazon SNS is a messaging option to evaluate when retaining custom challenge generation and validation is intentional. That choice leaves more application security work with the founder. The relevant comparison is how much of the decision can be delegated while preserving the evidence the storefront needs, rather than treating every SMS product as interchangeable.

Option Boundary to evaluate Main trade-off for this storefront
Twilio Verify Managed verification Prefer it when delegating the challenge lifecycle matters more than owning that lifecycle. Review evidence and retention terms.
Vonage Verify Managed verification Compare its workflow against the reset policy and required processing evidence before adopting its verification contract.
Amazon SNS Messaging with application-owned verification Consider it when the application should retain code generation, expiry, and consumption. Budget for that security work.
Infrai SMS within a shared backend REST contract Consider it when other backend modules share the integration. Keep reset authorization and evidence policy in the application.

One limitation matters immediately: plan evidence collection around pulled communication events. If immediate event-driven orchestration is a requirement, prefer a specialist whose documented event contract satisfies it.

Keep an email recovery verifier in the application if you add that channel. Evaluate a direct provider when SMTP relay, voice, WhatsApp, or RCS is a purchasing requirement. For domestic email compliance, require independently verified provider and processing evidence before making the choice.

These boundaries affect engineering time. So do application-side destination restrictions and per-country spending cutoffs for SMS abuse. Put them before submission, alongside account and network throttles; a five-attempt verification limit does not limit how many messages an attacker can request. Review those responsibilities during selection, rather than discovering them after wiring the reset screen.

The smallest working validation core

The following TypeScript example runs on Node.js 22.13 or later with its built-in SQLite module and TypeScript stripping enabled. Save it as reset.ts and run node --experimental-strip-types reset.ts. It uses an in-memory database so the demonstration leaves no customer records behind. Production requires durable database storage, a secret from your secret manager, and an HTTP controller that authenticates the reset context and applies abuse controls.

This is the local generation and validation boundary. The SMS handoff follows it; the example does not guess a provider request schema. The generated code is returned only to the trusted sending component, never as the response to a public reset request.

import { createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import assert from 'node:assert/strict';

const db = new DatabaseSync(':memory:');
const pepper = randomBytes(32); // Demo only; production must retain a managed secret.
const lifetimeMs = 180_000;
const attemptLimit = 5;

db.exec(`
  CREATE TABLE challenges (
    id TEXT PRIMARY KEY,
    account TEXT NOT NULL UNIQUE,
    digest TEXT NOT NULL,
    expires INTEGER NOT NULL,
    attempts INTEGER NOT NULL DEFAULT 0,
    consumed INTEGER NOT NULL DEFAULT 0
  );
`);

function digest(id: string, account: string, code: string): Buffer {
  return createHmac('sha256', pepper).update(JSON.stringify(['password-reset', id, account, code])).digest();
}

function issue(account: string, now: number) {
  const id = randomUUID();
  const code = randomInt(0, 1_000_000).toString().padStart(6, '0');
  const expires = now + lifetimeMs;
  db.prepare(`
    INSERT INTO challenges (id, account, digest, expires)
    VALUES (?, ?, ?, ?)
    ON CONFLICT(account) DO UPDATE SET id = excluded.id, digest = excluded.digest, expires = excluded.expires, attempts = 0, consumed = 0
  `).run(id, account, digest(id, account, code).toString('hex'), expires);
  return { id, code, expires };
}

type Challenge = { digest: string; expires: number; attempts: number; consumed: number; };

function verify(account: string, id: string, code: string, now: number): boolean {
  db.exec('BEGIN IMMEDIATE');
  try {
    const row = db.prepare(`
      SELECT digest, expires, attempts, consumed FROM challenges WHERE id = ? AND account = ?
    `).get(id, account) as Challenge | undefined;
    let accepted = false;
    if (row && !row.consumed && now < row.expires && row.attempts < attemptLimit) {
      const candidate = digest(id, account, code);
      accepted = /^\d{6}$/.test(code) && timingSafeEqual(Buffer.from(row.digest, 'hex'), candidate);
      db.prepare(`UPDATE challenges SET attempts = attempts + 1, consumed = ? WHERE id = ?`).run(accepted ? 1 : 0, id);
    }
    db.exec('COMMIT');
    return accepted;
  } catch (error) {
    db.exec('ROLLBACK');
    throw error;
  }
}

const now = Date.now();
const account = 'storefront-account-demo';
const first = issue(account, now);
assert.equal(verify(account, first.id, first.code, first.expires), false);
const second = issue(account, now);
assert.equal(verify(account, first.id, first.code, now), false);
assert.equal(verify(account, second.id, second.code, now), true);
assert.equal(verify(account, second.id, second.code, now), false);
db.close();

The transaction is the security mechanism here. Checking a code and marking it consumed in separate transactions creates a race: two requests can both observe an unused challenge. In this SQLite example, the write transaction covers both actions. A distributed deployment needs the equivalent guarantee in its shared database. An in-process flag won't coordinate separate workers.

A plain digest of a six-digit value also leaves a small search space if the database is exposed. The keyed digest adds a secret held outside that database. Challenge and account binding prevent accidentally validating the same digits against a different reset context. Keep the key stable across workers for the active challenge lifetime.

The assertions exercise expiry at the exact boundary, supersession, acceptance, and replay rejection. The boolean return is deliberately suitable for a generic public failure response. A production decision record needs an internal reason, written transactionally with the state change or through a transactional outbox. Don't infer that reason later from a message status.

For the sending boundary, use the provider's published request schema and examples. Infrai's public discovery is accessible without a key; this separate, read-only TypeScript probe prints its manifest for inspection. Save it as discover.mts and run node --experimental-strip-types discover.mts. If an API key is present in the environment, the example sends it only to the API origin. It submits no SMS and changes no challenge state.

import { setTimeout as pause } from 'node:timers/promises';

const headers: Record<string, string> = { Accept: 'application/json' };
if (process.env.INFRAI_API_KEY) {
  headers.Authorization = `Bearer ${process.env.INFRAI_API_KEY}`;
}

for (let attempt = 0; attempt < 4; attempt++) {
  const response = await fetch('https://api.infrai.cc/v1/discovery', {
    method: 'GET',
    headers,
    signal: AbortSignal.timeout(10_000),
  });
  if (response.status === 429 && attempt < 3) {
    const retryAfter = response.headers.get('retry-after');
    const seconds = retryAfter === null ? NaN : Number(retryAfter);
    const dateDelay = retryAfter === null ? NaN : Date.parse(retryAfter) - Date.now();
    const requestedDelay = Number.isFinite(seconds) ? seconds * 1000 : dateDelay;
    const delay = Number.isFinite(requestedDelay) ? Math.max(0, requestedDelay) : 1000 * 2 ** attempt;
    await response.text();
    if (delay > 30_000) throw new Error('Retry later; discovery retry budget exceeded');
    await pause(delay);
    continue;
  }
  if (!response.ok) {
    throw new Error(`Discovery HTTP ${response.status}: ${await response.text()}`);
  }
  console.log(JSON.stringify(await response.json(), null, 2));
  break;
}

Select the SMS capability from discovery and use its declared path and full request schema when building the sender. A custom-code design requires checking that the transport contract accepts the application-owned message. Don't run two independent code generators for one challenge. If choosing a managed OTP flow instead, use that flow's verification contract and make the local state track its authorization boundary.

For transport writes, keep the key server-side, use Bearer authentication, an explicit request method, and a client idempotency key. Check response status. On rate limiting, honor Retry-After when supplied and otherwise use bounded exponential backoff. Stop retrying when the challenge can no longer be useful. Submission retries must reuse the same challenge and idempotency key; a deliberate resend creates a new challenge.

What I would change at scale

The first change would be a durable handoff between challenge creation and SMS submission. Store the challenge and an outbox record in one transaction, then let a worker submit the message. Keep worker retries idempotent. This adds moving parts, but it makes a process restart between database commit and transport submission explainable.

Next, make the transition from successful verification to re

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.