DEV Community

BrantLockwood468
BrantLockwood468

Posted on

Node.js SMS API Code: 3 Evidence Signals for Support Signup

Signup path Pick this when Evidence to collect
SMS code, then account activation The signup flow needs to verify control of a phone number Challenge creation, gateway acceptance, successful code consumption
Email verification link The signup flow needs to verify control of an email address Link creation, submission for delivery, successful redemption

For a support signup, start with Node.js code generating one-time passwords and sending them via an SMS API only if the account needs a verified phone contact. Keep the activation decision in the application. A customer should be able to finish signup without opening a support ticket about the verification step.

TL;DR: For generating and sending one-time passwords via an SMS API in Node.js, use a cryptographic random generator, store a keyed digest with an expiry, and consume the challenge once. Track three separate signals: creation, gateway acceptance, and successful verification. An accepted send request is insufficient evidence to activate an account or declare that the verification link reached its recipient.

This field guide uses a phone-first signup flow. The SMS carries a code. After the customer enters it successfully, the application can authorize the next signup step, including access to a verification link. If the requirement is email ownership, use the email path instead; a phone challenge cannot establish control of an inbox.

Pick SMS when phone possession is the requirement

Choose this path when the support account needs a verified phone contact. The useful operational question is how far a particular challenge progressed. A single green "sent" counter hides that answer.

Draw the flow in words: signup request → challenge stored → message submitted → gateway accepts → customer receives → code consumed → account activation permitted. The application directly observes some of these transitions. A delivery receipt supplies additional evidence about transport, subject to its documented meaning. The customer's successful code submission establishes a different fact. Keep those events separate.

Receipt isn't redemption.

There is a security trade-off here. NIST treats authentication over the public telephone network as restricted and calls for considering risks such as SIM changes and number porting. A signup phone check also does not become two-factor authentication merely because a code is involved. For an existing login, the surrounding authentication ceremony determines what factors have been established.

Pick an email link when inbox control is the requirement

An email link fits a support account whose recovery and notifications depend on email. Apply the same expiration and single-use principles to its token. Keep phone verification and email verification as separate account attributes if the workflow requires both.

SPF has a narrower job. RFC 7208 describes authorization of sending hosts for an email domain. Passing that check does not prove that the intended customer received or redeemed a signup link. That distinction matters when a dashboard shows successful email submission while the customer still cannot activate an account.

How should Node.js code handle sending one-time passwords via an SMS API?

Here is a TypeScript example for Node.js. It uses built-in cryptography and a small HTTP adapter. The adapter contract is application-owned: a gateway accepts a JSON object with a recipient and message, and returns an HTTP success status when it accepts the submission. Map that contract to your actual SMS API according to its documentation. The field names below are not a claim about a public provider's API.

The example policy uses 6 digits, a 5-minute lifetime, a 30-second issuance cooldown, and 5 guesses. These are explicit sample settings, not measured delivery times or a complete abuse policy. The observability callback must avoid recording message bodies, raw codes, credentials, and phone numbers. Its challenge ID is for correlation; keep access to those events controlled.

import {
  createHmac, randomInt, randomUUID, timingSafeEqual
} from "node:crypto";

type Event =
  | "challenge_created"
  | "gateway_accepted"
  | "submission_unknown"
  | "challenge_verified";
type Challenge = {
  id: string; digest: Buffer; expiresAt: number; attempts: number;
};
type Emit = (event: Event, challengeId: string) => void;

// Contract for an application-owned gateway, not a public SMS API.
export function httpSmsGateway(endpoint: URL, bearerToken: string) {
  if (endpoint.protocol !== "https:") throw new Error("HTTPS required");
  return async (to: string, message: string): Promise<void> => {
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${bearerToken}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ to, message }),
      signal: AbortSignal.timeout(8000)
    });
    const accepted = response.ok;
    await response.body?.cancel();
    if (!accepted) throw new Error("Gateway did not accept submission");
  };
}

export function signupOtp(
  key: Buffer,
  sendSms: (to: string, message: string) => Promise<void>,
  emit: Emit
) {
  if (key.length < 32) throw new Error("Supply a secret of at least 32 bytes");
  const challenges = new Map<string, Challenge>();
  const nextIssueAt = new Map<string, number>();
  const digest = (id: string, code: string) =>
    createHmac("sha256", key).update(`${id}:${code}`).digest();

  // Telemetry must be nonthrowing and must never control authentication.
  const record = (event: Event, id: string) => {
    try { emit(event, id); } catch { /* Preserve authentication state. */ }
  };

  return {
    async issue(subject: string, validatedPhone: string) {
      // Both arguments come from trusted signup-session state.
      const now = Date.now();
      if (now < (nextIssueAt.get(subject) ?? 0)) {
        throw new Error("Issuance cooldown active");
      }
      const id = randomUUID();
      const code = randomInt(0, 1_000_000).toString().padStart(6, "0");
      challenges.set(subject, {
        id, digest: digest(id, code),
        expiresAt: now + 5 * 60_000, attempts: 0
      });
      nextIssueAt.set(subject, now + 30_000);
      record("challenge_created", id);
      try {
        await sendSms(validatedPhone, `Your support signup code is ${code}.`);
        record("gateway_accepted", id);
      } catch {
        // A timeout can happen after acceptance. Do not retry blindly.
        record("submission_unknown", id);
      }
      return { challengeId: id };
    },

    verify(subject: string, challengeId: string, code: string): boolean {
      const item = challenges.get(subject);
      if (!item || item.id !== challengeId) return false;
      if (Date.now() >= item.expiresAt || item.attempts >= 5) {
        challenges.delete(subject);
        return false;
      }
      item.attempts += 1;
      const valid = /^[0-9]{6}$/.test(code) &&
        timingSafeEqual(item.digest, digest(item.id, code));
      if (valid || item.attempts >= 5) challenges.delete(subject);
      if (valid) record("challenge_verified", item.id);
      return valid;
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

The application must bind subject to its signup session and bind the phone to that session's validated input. Here, "validated" means checked as input, not already proven to belong to the customer. Do not accept an arbitrary subject from a verification request. Activate only the account associated with the consumed challenge.

A keyed digest avoids storing the raw code. It also avoids treating an ordinary hash of a small numeric space as adequate protection against offline guessing. Keep the key outside the challenge store, and generate it with a cryptographically secure source. Never put it in the browser.

Notice the timeout path. Once an HTTP request leaves the application, a timeout alone cannot establish whether the gateway accepted it. The example conservatively records an unknown result and retains the challenge, allowing an already delivered code to work. A documented rejection could be classified separately in a real adapter. Automatic retries need the gateway's documented idempotency behavior; guessing at that contract can produce duplicate messages. Requesting another code creates another trap: this implementation replaces the previous challenge for the session. An earlier SMS may arrive after its replacement. Imagine two requests, A and B, separated by the sample's 30-second cooldown. B replaces A in storage, but A's message arrives last. Entering A's code must fail even if the digits are correct for that earlier challenge. The interface should explain that only the latest code works, and verification requests must carry the matching challenge ID. Otherwise, an old browser tab can obscure what the user is trying to verify. This is a hypothetical ordering example, not a measured incident.

Keep that ordering visible in the trace.

Make the three signals useful to support

A before-and-after dashboard sketch helps. Before: one count labeled "SMS sent." After: challenge creation, gateway acceptance, and successful consumption, with elapsed time between the relevant events. The second view lets the team investigate the actual transition that stopped progressing. It still cannot tell you why a person abandoned signup.

Use challenge IDs in restricted event records and traces. Use low-cardinality labels, such as channel and outcome, for metric series. Putting a fresh challenge ID into every metric label turns each request into another series, which makes aggregation and storage harder without helping the team compare signup behavior.

Compare completed cohorts. A challenge created seconds ago has not had the same opportunity to be verified as one whose 5-minute validity window has ended. Also count replacements separately: a deliberate repeat request should not silently look like another independent customer abandoning signup.

Define the denominator before alerting on a conversion ratio.

Testing can make these distinctions tangible. Inject a sender that resolves, one that rejects, and one that records acceptance before reporting a timeout. Confirm that no send result activates an account, that an accepted submission still needs a correct code, and that consumption makes replay fail. Exercise expiration and the fifth failed guess too. For the HTTP adapter, contract tests should check the real gateway's authentication, payload, and definition of acceptance without sending live customer messages.

During deployment, compare the event transitions for the new release with the prior release using a documented observation window. Set alert thresholds from the service's own baseline and delivery objective. A universal delivery-time threshold would hide differences in recipient networks, traffic patterns, and how each gateway defines its receipts.

Limits before this reaches production

This example owns state in one process. A restart loses challenges and cooldowns. Multiple instances do not share them. For production, move expiry, failed-attempt increments, replacement, and successful consumption into a shared store with atomic operations. Bind account activation to successful consumption through a durable transition so a crash between those actions cannot leave the workflow ambiguous.

Add issuance limits beyond a session identifier, request-size limits, expiry cleanup, and a retention policy for telemetry. Session-only cooldowns are easy to evade by starting another signup. The in-memory maps also retain inactive entries until explicitly cleaned up. Keep gateway calls on the server and audit telemetry delivery separately; the nonthrowing callback prevents logging failures from changing authentication outcomes, but it can lose events.

The engineering trade-off is extra state and operational work in exchange for a signup path the support team can explain. Measure messages per completed signup to expose repeat-message churn, alongside delivery evidence and successful verification. That makes delivery reliability visible without treating transport acceptance as proof that a customer finished.

References

These primary sources cover the cryptographic primitives, authentication constraints, token lifecycle, and email authorization boundary discussed above.

Further reading

Top comments (0)