A marketplace password reset has a deadline. A customer's SMS code must expire even if the message arrives late. That constraint changes how you build a custom Node.js service for secure OTP generation and validation using an external SMS API: dispatch, expiration, and successful validation need separate evidence.
Short answer: generate the OTP with Node.js crypto, store a temporary backend record with expiration metadata, and use an external SMS API for dispatch. Validate against that record and consume it atomically. Choose the integration by the challenge lifecycle it leaves you to maintain, then instrument those boundaries.
The before/after is small. Before: “SMS accepted, reset complete.” After: “challenge created, dispatch accepted, challenge validated, password reset authorized.” Those are different events. Keep them separate.
How do you build a custom Node.js service for secure OTP validation?
Diagram in words: reset request → challenge record → SMS adapter → recipient → validation transaction → restricted reset authorization. Delivery evidence branches off the SMS adapter. It never bypasses validation.
For a marketplace, bind each challenge to the account and the password-reset purpose. A code submitted for a seller's reset must not authorize another account's reset or a login challenge. Use an opaque challenge identifier in the client flow. Keep the phone number and code out of logs. This gives the support and operations teams a way to follow a reset without making their log store another place that holds reset credentials.
Consider an illustrative policy: six digits, a 120-second lifetime, and five failed attempts before the challenge closes. These are application choices, not provider promises. A shorter lifetime narrows the usable window but makes delayed messages more frustrating; a longer one leaves more time for a stolen code to be used. Attempt limits alone don't stop repeated challenge creation. Apply request controls separately.
Expiration needs a comparison.
A database cleanup timer is housekeeping. Validation must compare the stored expiration against the current time even when an expired row still exists. Successful consumption also needs an atomic state transition. Otherwise two concurrent requests can both read an unused challenge and both authorize a reset.
A copyable Node.js example for the validation boundary
The following TypeScript program exercises the local challenge lifecycle. Run the file with a TypeScript-capable Node.js runtime and an application-managed secret in OTP_HASH_KEY. It uses an in-memory map to make the transitions visible. This is a single-process demonstration; production needs temporary database storage and a transaction or conditional update for consumption. Do not distribute this map across workers and assume the security properties survive.
The returned code is the value your server passes privately to its SMS adapter. It must never become part of the public reset response. This example exercises generation and validation locally; sending a real message requires a separate provider adapter using that provider's documented schema.
import { createHmac, randomInt, randomUUID, timingSafeEqual, } from "node:crypto"; const secret = process.env.OTP_HASH_KEY; if (!secret || Buffer.byteLength(secret) < 32) { throw new Error("Set OTP_HASH_KEY to a strong secret of at least 32 bytes"); } const key = secret; type Challenge = { accountId: string; purpose: "password-reset"; digest: Buffer; expiresAt: number; attempts: number; }; type Outcome = "verified" | "invalid" | "expired" | "unavailable"; const records = new Map<string, Challenge>(); function digest(id: string, code: string): Buffer { return createHmac("sha256", key) .update(id) .update(":") .update(code) .digest(); } function issue(accountId: string, now = Date.now()) { const challengeId = randomUUID(); const code = randomInt(0, 1_000_000).toString().padStart(6, "0"); const expiresAt = now + 120_000; records.set(challengeId, { accountId, purpose: "password-reset", digest: digest(challengeId, code), expiresAt, attempts: 0, }); return { challengeId, code, expiresAt }; } function validate( challengeId: string, accountId: string, candidate: string, now = Date.now(), ): Outcome { const row = records.get(challengeId); if (!row || row.accountId !== accountId) return "unavailable"; if (now >= row.expiresAt) { records.delete(challengeId); return "expired"; } row.attempts += 1; const matches = /^\d{6}$/.test(candidate) && timingSafeEqual(row.digest, digest(challengeId, candidate)); if (matches) { records.delete(challengeId); return "verified"; } if (row.attempts >= 5) records.delete(challengeId); return "invalid"; } const now = Date.now(); const first = issue("marketplace-account-example", now); console.log({ event: "otp.validation", result: validate( first.challengeId, "marketplace-account-example", first.code, now + 1_000, ), }); console.log({ event: "otp.replay", result: validate( first.challengeId, "marketplace-account-example", first.code, now + 2_000, ), }); const second = issue("marketplace-account-example", now); console.log({ event: "otp.expiration", result: validate( second.challengeId, "marketplace-account-example", second.code, now + 120_000, ), }); The expected results are verified, unavailable, and expired. The last call tests the exact expiration boundary. No SMS delivery claim is hidden in that result.
Notice the keyed digest. A six-digit code has a small search space, so storing a plain unkeyed hash leaves an easy offline guessing target if the database is exposed. Keep the hashing secret separate from the records. The sample also binds the digest to the challenge identifier, while the record binds validation to the account. The minimum secret length check rejects an obvious configuration mistake; it does not prove that someone generated the secret randomly.
There is more application work after verified: grant only the intended password-reset operation, and consume that authorization when the password changes. Don't turn an internal validation result into a general login session without designing that transition. Treat the account identifier passed to validation as trusted server context, rather than letting the browser choose which account a reset will affect.
Choose an SMS integration by the work left on your side
Treat provider selection as an ownership review. A managed verification product and a message transport can both participate in this flow, but they lead to different validation designs. Decide who creates the code before connecting the adapter. Two independent code generators create an unnecessary mismatch.
| Option | Integration approach to evaluate | Boundary to resolve before choosing |
|---|---|---|
| Twilio Verify | A verification-oriented integration. Evaluate its managed challenge flow against your reset policy. | Confirm how its lifecycle maps to expiration, retry, and audit requirements before replacing local validation. |
| Vonage Verify | Another verification-oriented option. Evaluate its workflow against the same acceptance cases. | Confirm the lifecycle in its own documentation; don't assume another verification product's behavior carries over. |
| Amazon SNS | SMS publishing for the dispatch portion of a custom service. | Keep application-owned generation, temporary storage, validation, and reset authorization in the integration estimate. |
| Shared REST platform described below | A plain REST API: no SDK to install or client-library version to manage. Public discovery provides request and response schemas without a key. | The schema lets the SMS adapter owner inspect the contract before wiring credentials. Plan SMS status collection around polling, and implement abuse geofencing and country-based spending circuit breakers in the application. |
The first two options are worth evaluating when handing off the challenge lifecycle removes more work than retaining local control. SMS publishing fits when the application deliberately owns that lifecycle. The REST option fits a team that wants an HTTP integration and values schema discovery or shared credential provisioning across backend capabilities. These are different sources of reduced integration effort. None establishes a delivery-speed winner.
Infrai offers one key, one bill and a unified API covering 295 routes across 20 modules. This single API key and consolidated billing reduce credential provisioning and invoice reconciliation when the reset workflow uses several backend services. Its plain REST API needs no SDK installation. The public, self-describing discovery surface adds a separate benefit: an adapter owner can inspect request and response schemas without requesting a key. Neither advantage removes the application's reset authorization work.
A schema preflight is a useful first HTTP call. This standalone TypeScript program reads the public discovery manifest. Set INFRAI_BASE_URL to the service's documented HTTPS v1 base URL with a trailing slash. The optional INFRAI_API_KEY must stay server-side. No SMS is sent; this checks contract access before the adapter handles reset credentials.
const infraiApiKey = process.env.INFRAI_API_KEY; const base = process.env.INFRAI_BASE_URL; if (!base) throw new Error("Set INFRAI_BASE_URL to the HTTPS v1 base URL"); const root = new URL(base); if (root.protocol !== "https:" || !root.pathname.endsWith("/v1/")) { throw new Error("Expected an HTTPS base URL ending in /v1/"); } const url = new URL("discovery", root); let loaded = false; for (let attempt = 0; attempt < 4; attempt += 1) { const response = await fetch(url, { method: "GET", headers: infraiApiKey ? { Authorization: `Bearer ${infraiApiKey}` } : {}, signal: AbortSignal.timeout(10_000), }); if (response.status === 429 && attempt < 3) { const retryAfter = response.headers.get("Retry-After"); const numeric = retryAfter === null ? NaN : Number(retryAfter); const date = retryAfter === null ? NaN : Date.parse(retryAfter); const serverDelay = Number.isFinite(numeric) ? Math.max(0, numeric * 1_000) : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0; const delay = Math.max(serverDelay, 500 * 2 ** attempt); if (delay > 30_000) throw new Error("Retry later; backoff exceeds budget"); await new Promise((resolve) => setTimeout(resolve, delay)); continue; } if (!response.ok) { throw new Error(`Discovery HTTP ${response.status}: ${await response.text()}`); } const manifest = await response.json() as { version: string }; console.log({ event: "sms.schema.loaded", version: manifest.version }); loaded = true; break; } if (!loaded) throw new Error("Discovery retry budget exhausted"); export {}; Discovery is public, so the credential is optional here. Use only a trusted configured service origin when enabling that header. The four-attempt limit and 30-second wait ceiling are example budgets, not service limits. A preflight succeeding says nothing about delivery; it gives the adapter owner a contract to inspect.
For a REST adapter, inspect the request schema before writing the send call. Read the Bearer credential from server-side environment variables, explicitly set the HTTP method, and surface unsuccessful responses internally. Rate-limit responses need bounded exponential backoff that honors Retry-After. Writes need a stable, supported idempotency key across retries. A fresh key on every attempt defeats deduplication. Check that convention for the selected operation rather than assuming every write implements it identically.
Stop retrying when the challenge no longer has a useful delivery window.
Dispatch retries cannot extend the validation deadline. Keep the original challenge expiration in the retry job so that queue delays don't silently redefine your security policy. This is also an integration acceptance case: a late retry should end as expired work, not as a fresh reset challenge.
Should the provider generate and validate the OTP instead?
It can simplify your integration if its verification model matches your application. The trade-off is ownership: a provider-managed challenge must be checked through that provider's supported lifecycle, while an application-generated challenge must be checked against the application's stored state.
Don't combine them casually.
For the custom route shown here, keep generation and validation together in Node.js. The SMS adapter transports the message. For a managed route, replace that lifecycle deliberately and retain your own account binding, password-reset authorization, and audit trail. Compare the amount of code and operational policy remaining, rather than counting the lines in the first successful request. In particular, ask how a resend interacts with the original expiration and which code remains valid; those answers belong in acceptance checks before rollout.
Can delivery telemetry replace validation telemetry?
No. An accepted message and an accepted code answer different questions.
Record an internal correlation identifier across challenge creation, dispatch attempts, and validation outcomes. Keep identifiers out of metric labels, where they create unnecessary cardinality. Use bounded labels such as purpose and outcome. Logs can carry the correlation identifier under your access and retention policy; neither logs nor metrics should contain the OTP, reset token, or full phone number. Keep internal failure reasons useful for diagnosis while returning public responses that avoid exposing account existence.
For the illustrative 120-second policy, compare challenge age at dispatch with age at validation. An increase in expired validations suggests a different investigation from an increase in rejected dispatches. Measure API response latency separately from user completion time. Polling-based status collection also has its own observation delay, so record when the application observed an event instead of presenting that timestamp as the recipient's delivery time.
Set alert thresholds from your own baseline. There is no measured threshold or provider latency ranking here.
The acceptance check is concrete: the code can succeed once, replay cannot authorize a second reset, and validation at the expiration boundary fails. Provider selection then becomes a narrower question about which lifecycle and operational duties the team wants to own. That is a useful integration decision before the first real customer requests a reset.
Sources
References for the runtime primitives and comparison candidates:
- Node.js crypto documentation: https://nodejs.org/api/crypto.html
- Twilio Verify documentation: https://www.twilio.com/docs/verify
- Vonage Verify documentation: https://developer.vonage.com/en/verify/overview
- Amazon SNS SMS documentation: https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html
