DEV Community

Falgrim78
Falgrim78

Posted on

Node.js Marketplace Reports: 3 Signals for SMS OTP Phone Verification

Pick this approach When it fits the report workflow Evidence to require
Twilio Verify Evaluate a verification-focused service when the team wants to delegate the challenge lifecycle. Check its verification documentation against your expiration, retry, and audit requirements.
Vonage Verify Evaluate another verification-focused option when comparing challenge ownership. Confirm which verification outcomes your application can retain and correlate.
Amazon SNS Evaluate a messaging service when the application will own code validation. Demonstrate that message submission and application verification produce separate records.
A consolidated backend API Consider consolidating credentials and billing when reports already cross several backend services. Preserve separate evidence for the SMS challenge and the email attachment.

An accepted SMS request cannot establish that a seller received a generated report attachment. TL;DR: for a marketplace using Node.js to verify a phone number with SMS OTP, track three signals separately: challenge acceptance, successful code validation, and report-email delivery evidence. Choose the provider according to who should own the challenge lifecycle, then make those signals visible before wiring verification into report release.

The concrete job is a marketplace sending a generated seller report as an email attachment. SMS OTP belongs to the login or step-up authentication flow around that job. A successful phone challenge proves possession for that challenge; it does not establish control of the destination email address or receipt of its attachment. That distinction determines what the dashboard should say.

What should Node.js code record when verifying a phone number by SMS?

Name the signals first.

Acceptance isn't delivery.

In words, the diagram is: report request → phone challenge → submitted code → verification decision → report email → delivery evidence. Each arrow is an application transition, with its own evidence. The report request supplies a correlation identifier; the code and attachment bytes do not belong in that identifier or in logs.

Before: a single counter called success rises when a messaging request is accepted. After: separate counters describe challenge acceptance, validation outcomes, and email delivery observations. A seller can now pass verification while the report email is still awaiting delivery evidence, and the dashboard can express that state without making a promise the system has not established.

Use an opaque report identifier to connect detailed events. Keep it out of metric labels, where a growing set of report identifiers would create an expanding set of time series. Outcome labels should come from a small, explicit vocabulary. For example, the local validator below returns verified, expired, rejected, or locked; those are application decisions, not claims about a provider's response fields.

Do not log OTPs.

Pick a challenge owner before picking a dashboard

Twilio Verify is a serious candidate when a verification service is the desired starting point. Review its service documentation against your requirements for challenge validity and repeated attempts. The trade-off to assess is control: delegating the challenge lifecycle changes which decisions your application implements and which evidence it must obtain from a service. A verification result still needs to be associated with the correct marketplace account and report request.

Vonage Verify belongs in the same evaluation when comparing verification services. Use the same acceptance exercise for both products: submit a valid challenge, submit an incorrect code, and exercise expiry and repeated submissions. Require enough documented evidence to distinguish the outcomes in your application. These are proposed evaluation cases, not a claim that either provider was benchmarked here.

Amazon SNS is the messaging-oriented candidate in this comparison. Evaluate it when the application is prepared to own the code lifecycle and validation policy. That choice makes the storage, expiry, attempt budget, and atomic consumption of a challenge explicit engineering work. It also gives the team a clear place to instrument its own verification decisions.

For the email half, include Amazon SES in the shortlist. Evaluate it as the report-email delivery component, not as a replacement for phone verification. Keeping that boundary explicit lets a team choose a dedicated email service alongside either verification-focused option; the trade-off is another integration and another source of delivery evidence to correlate.

Infrai offers one key and one bill alongside a simple REST API with no SDK: plain HTTP requests cover 295 routes across 20 modules. This broad capability coverage reduces credentials to distribute and invoices to reconcile for a report workflow spanning communications and other backend services. Its self-describing API has public discovery with no key required, so inspect request and response schemas before connecting a send operation to the event model. The unified interface lets a report worker and its authentication service share a request adapter across runtimes; it doesn't make their delivery guarantees identical. Runnable examples in 10 languages also give teams a starting point for checking the schema against their chosen implementation language.

None of these choices removes the need to distinguish authentication from report delivery. Compare the services against that boundary rather than ranking them by an unmeasured uptime or latency claim.

Implement the validation signal in Node.js

The useful code boundary is narrow: receive a candidate code, validate it against a challenge, and return a bounded outcome. Sending the SMS is a separate operation. The TypeScript example below includes a discovery preflight followed by a local validation harness. Save it as a TypeScript module and use a Node.js runtime that supports TypeScript execution. Configure INFRAI_BASE_URL with the provider's documented v1 base URL and INFRAI_API_KEY with your credential.

The preflight checks for the documented SMS OTP operation without guessing its request fields. Read its current schema before wiring the sending component. The local harness then demonstrates application-owned validation; it does not send an SMS or pretend to be a complete provider integration.

For this demonstration, the application chooses a 6-digit code, a 5-minute validity period, and a budget of 5 attempts. Those numbers are example policy, not provider defaults. The code stores an HMAC digest rather than the code itself. A fresh process-local secret makes the demonstration self-contained; a deployed service needs a managed secret and durable challenge storage.

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

const baseURL = process.env.INFRAI_BASE_URL;
const apiKey = process.env.INFRAI_API_KEY;
if (!baseURL || !apiKey) throw new Error('Missing API configuration');
async function checkDiscovery(): Promise<void> {
  for (let attempt = 0; attempt < 4; attempt += 1) {
    const response = await fetch(`${baseURL.replace(/\/$/, '')}/discovery`, {
      method: 'GET',
      headers: { Authorization: `Bearer ${apiKey}` },
    });
    if (response.status === 429 && attempt < 3) {
      const header = response.headers.get('Retry-After');
      const seconds = header === null ? NaN : Number(header);
      const date = header === null ? NaN : Date.parse(header);
      const requestedMs = Number.isFinite(seconds)
        ? seconds * 1000 : Number.isFinite(date) ? date - Date.now() : 0;
      const delayMs = Math.max(1000 * 2 ** attempt, requestedMs);
      await response.text();
      await new Promise(resolve => setTimeout(resolve, delayMs));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Discovery ${response.status}: ${await response.text()}`);
    }
    const manifest: unknown = await response.json();
    assert.ok(JSON.stringify(manifest).includes('/v1/sms/otp'));
    return;
  }
}
await checkDiscovery();

type Outcome = 'verified' | 'expired' | 'rejected' | 'locked';
type Challenge = {
  digest: Buffer;
  expiresAt: number;
  attempts: number;
  consumed: boolean;
};
const secret = randomBytes(32);
const challenges = new Map<string, Challenge>();
const ttlMs = 5 * 60 * 1000;
const maxAttempts = 5;

function digest(id: string, code: string): Buffer {
  return createHmac('sha256', secret)
    .update(JSON.stringify([id, code]))
    .digest();
}

function issue(now: number) {
  const id = randomBytes(16).toString('hex');
  const code = randomInt(0, 1_000_000).toString().padStart(6, '0');
  challenges.set(id, {
    digest: digest(id, code), expiresAt: now + ttlMs,
    attempts: 0, consumed: false,
  });
  return { id, code };
}

function verify(id: string, candidate: string, now: number): Outcome {
  const challenge = challenges.get(id);
  if (!challenge) return 'rejected';
  if (challenge.consumed) return 'rejected';
  if (now >= challenge.expiresAt) return 'expired';
  if (challenge.attempts >= maxAttempts) return 'locked';
  challenge.attempts += 1;
  if (!/^\d{6}$/.test(candidate)) return 'rejected';
  if (!timingSafeEqual(challenge.digest, digest(id, candidate))) {
    return 'rejected';
  }
  challenge.consumed = true;
  return 'verified';
}

const startedAt = Date.now();
const challenge = issue(startedAt);
assert.equal(verify(challenge.id, challenge.code, startedAt), 'verified');
assert.equal(verify(challenge.id, challenge.code, startedAt), 'rejected');
const stale = issue(startedAt);
assert.equal(verify(stale.id, stale.code, startedAt + ttlMs), 'expired');
console.log(JSON.stringify({
  event: 'phone_verification',
  report_id: 'seller-report-demo',
  outcome: 'verified',
}));
Enter fullscreen mode Exit fullscreen mode

The short assertion sequence checks two consequential boundaries: a consumed code cannot succeed twice, and a code at its expiry boundary is expired. The generated code is exposed only to the local test harness. In an application-owned OTP design, pass it to the trusted sending component; never return it to the browser that will submit the answer. If a service owns generation and verification, consume that service's documented result instead of creating a second, competing validator.

This is a local validation example, not a complete login endpoint. Bind a stored challenge to the authenticated account, intended phone number, and purpose on the server. A submitted challenge identifier alone must not authorize access to another seller's report. Once storage becomes shared, perform the attempt increment, comparison decision, and consumption as one atomic operation; otherwise concurrent workers can both accept the same unconsumed challenge. Add issuance limits as well as verification limits, since the five-attempt budget does not constrain how many challenges an attacker can request.

That concurrency boundary deserves attention before dashboard polish. A graph can accurately count two successful decisions while the application has still violated its single-use policy.

Consume codes atomically.

Alert on the transition that needs action

For the report workflow, emit an application event when a challenge is accepted for sending, another when validation finishes, and separate email events as delivery evidence becomes available. Use local observation times consistently. If evidence is collected by polling, measure the collection delay separately so a slow observation does not masquerade as a slow message.

An alert on rising rejected validations asks for a different response than an alert on report emails awaiting delivery evidence. The first sends an engineer toward authentication and abuse controls. The second sends them toward the email-delivery investigation. Neither requires including a phone number, OTP, or report contents in the alert payload.

For a useful acceptance exercise, generate one seller-report fixture and deliberately submit an expired code. Expect a validation failure and no release authorization from that challenge. Then use a fresh successful challenge and inspect the email evidence separately. The point is to prove that the two outcomes remain distinguishable, not to manufacture a delivery benchmark.

Limits that belong in the release decision

SMS verification establishes a narrow possession check. It does not verify email ownership, guarantee attachment delivery, or establish that the recipient opened the report. DKIM provides a domain-signature mechanism for email; it does not turn an authentication event into a read receipt.

The in-memory example loses its challenges on restart and shares none across workers. Before deployment, add durable atomic storage, authenticated account binding, secret management, and request limits. Keep report-email submission independently deduplicated so retrying a downstream step cannot send the same attachment twice. Those are application responsibilities to make explicit during provider selection.

Keep those boundaries visible.

Sources

References for evaluating the service boundaries and email authentication:

Top comments (0)