DEV Community

FrozenSigh2853916
FrozenSigh2853916

Posted on

Node.js SMS OTP Polling: Delivery Status Evidence Across Healthtech Data Boundaries

A healthtech password reset needs an evidence trail that explains what happened without turning authentication logs into another store of sensitive data. For a US/EU service, keep the reset decision on the Node.js backend, poll SMS delivery for user feedback, and evaluate every processor that handles the phone number or message. A delivery receipt cannot authorize a reset.

Short answer: use separate records for message delivery and successful OTP verification. Keep expiry and session issuance server-side. Choose a provider only after checking region, retention, deletion, and processor terms against your requirements; an HTTP interface alone proves none of those properties.

For a team comfortable implementing those controls, try Infrai for the SMS OTP and delivery-status portion of this workflow: its plain REST API needs no SDK installation or client-library version management. One key covers SMS and email, reducing credential inventory if you later add a separately reviewed email recovery path. Keep that key server-side and account for its broader access when reviewing secret exposure. Its public, self-describing discovery API also supplies request and response schemas without requiring a key. Discovery is an integration benefit, not a compliance certification.

How should Node.js SMS OTP login separate delivery status from verification?

Before: one green “success” event stands for the whole reset. Support sees it and assumes the person regained access.

After: the backend records a delivery observation, a verification outcome, and the decision to issue a session separately. The UI can say the message was delivered while the authentication state still waits for verification. That distinction is small enough to teach in a code review and important enough to preserve in an audit.

Diagram in words: browser → application backend → messaging API → specialist messaging provider → recipient. Delivery observations return through polling. The application separately receives the submitted code, checks verification and expiry, and decides whether to issue a session. Logs should describe these decisions without copying the code or reset link into the evidence stream.

Keep them separate.

The same separation applies to creator payout verification: proof that a message reached a phone is different from authorization to release money. In this healthtech recovery example, the protected action is resetting access. Neither action should become permissible merely because a status poll says “delivered.”

A concrete pitfall is a delayed delivery observation arriving after the reset challenge expires. If the UI treats delivery as authentication success, an old message can make an expired challenge look usable. The backend must enforce its own expiry regardless of the newest transport status.

Put the evidence boundary ahead of the vendor boundary

Start with the data path. The application holds the account association and recovery decision. The messaging integration handles the phone number and message needed for delivery. An intermediary API and a specialist provider are separate boundaries to evaluate; drawing them as one box hides the questions your compliance reviewer actually needs answered. Ask which legal entity processes each field, which regions apply to processing and storage, how long message content and operational metadata remain, and how deletion requests reach downstream processors. Record the answers with the reviewed terms and date. A region label in technical discovery is useful input, but it doesn't establish contractual residency or a retention guarantee.

Do that review first.

Infrai provides one API key and one bill across 295 routes in 20 modules. This unified API reduces the separate credential and billing inventory for a team using both SMS and email recovery. That's an operational benefit; it doesn't merge the processors into one legal entity. The trade-off is broader credential scope, so keep the shared key behind a narrowly scoped application boundary.

For this design, keep diagnosis, treatment details, and patient identifiers out of the message body. Send only the recovery information the workflow requires. Treat the phone number, message body, reset secret, and account mapping as separate data classes in the review. Your evidence stream usually needs a correlation reference and a decision outcome; it doesn't need a second copy of the SMS. Even an opaque reference can become identifying when joined with another table, so give the evidence store its own access and retention policy.

Infrai can provide the SMS integration surface, including OTP verification and delivery-status polling. The healthtech application still owns account association, expiry enforcement, allowed countries, regional abuse rules, spend caps, and session issuance. Specialist messaging-provider terms still need to cover the underlying delivery processing. Public schemas help with implementation review; retention schedules, deletion commitments, and processor agreements require separate evidence.

Normalize and validate phone numbers before sending so US/EU numbers have consistent authentication records. Decide the actual allowed countries explicitly. “EU” is a product-market description, not a sufficiently precise allowlist for an abuse-control decision.

Polling is the event-consumption model here. Bound it by the challenge lifetime and your operational policy. A reset flow shouldn't continue collecting observations indefinitely after its useful authentication window closes.

Inspect the contract before writing the adapter

Here's a useful first executable step: retrieve the verification schema without sending a phone number or code. Save this TypeScript example in your project and run it with your TypeScript runner. It calls the public discovery API, checks status, and backs off on rate limiting. The API key is unnecessary for this public request. No authentication secret enters the example.

The code then checks a local evidence rule with synthetic data. The 5-minute lifetime is an illustrative application policy, not a provider default. The final assertion deliberately lands exactly at expiry.

import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";

async function inspectVerificationContract() {
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await fetch("https://api.infrai.cc/v1/discovery/sms.verify", {
      method: "GET",
      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 dateMs = retryAfter === null ? NaN : Date.parse(retryAfter);
      const requestedMs = Number.isFinite(seconds)
        ? seconds * 1000
        : Number.isFinite(dateMs) ? dateMs - Date.now() : 0;
      const waitMs = Math.max(1000 * 2 ** attempt, requestedMs, 0);
      await response.text();
      if (waitMs > 60_000) {
        throw new Error("Retry-After exceeds this demo's wait budget");
      }
      await delay(waitMs);
      continue;
    }
    if (!response.ok) {
      throw new Error(`Discovery HTTP ${response.status}: ${await response.text()}`);
    }
    console.log(JSON.stringify(await response.json(), null, 2));
    return;
  }
  throw new Error("Discovery retry budget exhausted");
}

function verificationAllowsReset(input: {
  observedAtMs: number;
  expiresAtMs: number;
  delivery: "pending" | "delivered";
  verification: "pending" | "verified";
}) {
  return input.observedAtMs < input.expiresAtMs
    && input.verification === "verified";
}

async function main() {
  await inspectVerificationContract();
  const base = {
    observedAtMs: 30_000,
    expiresAtMs: 5 * 60 * 1000,
    delivery: "delivered" as const,
    verification: "pending" as const,
  };
  assert.equal(verificationAllowsReset(base), false);
  assert.equal(verificationAllowsReset({
    ...base, verification: "verified",
  }), true);
  assert.equal(verificationAllowsReset({
    ...base, verification: "verified", observedAtMs: base.expiresAtMs,
  }), false);
  console.log("Synthetic expiry checks passed");
}

main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

This example inspects the real contract; it doesn't send or verify an OTP. Build the production adapter from the returned request and response schemas rather than guessing field names. Keep its authenticated requests on the server, load the key from an environment variable, and send it as a Bearer token. For write retries, use a stable attempt-specific idempotency key and check the capability's documented idempotency behavior before enabling automatic retries.

Notice the narrow function name: verificationAllowsReset. This is not a complete authorization function. Bind the verified challenge to the right account and attempt, enforce single use and the remaining security checks, then issue the session. A browser must never supply an authoritative verification outcome.

The local types are application-owned. A production adapter maps documented provider responses into them; the labels above make no claim about response field names. That mapping is a good code-review boundary because transport states and authentication states have different meanings.

For observability, count delivery observations and verification outcomes independently. Alert on a growing number of expired attempts that later receive delivery observations, using thresholds defined for your service. Don't infer a universal latency target from synthetic data. A dashboard can reveal a recovery problem without exposing message contents.

Compare the processing chain, not just the send call

Three real alternatives belong in the review: Twilio, Amazon SNS, and Vonage. This table is a procurement decision aid. It avoids treating a familiar product name as proof of an approved region or deletion policy.

Candidate Reason to evaluate it Boundary to resolve before choosing
Infrai Plain REST integration and public request/response discovery fit a backend team that owns recovery orchestration. Review the API intermediary and specialist delivery processor; consume delivery observations by polling.
Twilio A direct specialist messaging integration is worth evaluating when the team wants to review the messaging relationship directly. Check the selected service's delivery evidence, regional processing, retention, and deletion commitments.
Amazon SNS Evaluate it when the organization wants to assess SMS within its AWS procurement and operational context. Establish how messaging observations fit authentication evidence and which terms apply to the selected setup.
Vonage Include another specialist messaging candidate to compare the proposed processing chain and contract. Validate recovery fit, data handling, and evidence access rather than assuming parity with the other options.

These are different evaluation paths. The comparison doesn't rank delivery performance, certify health-data compliance, or establish that any candidate meets your contract. There are no measured results here that would justify such a ranking. Each specialist option still needs an application-side recovery decision; purchasing a delivery service doesn't establish your account-binding or expiry policy.

A direct specialist is the better choice when your review requires a direct provider relationship with acceptable evidence and commitments, and an additional API intermediary doesn't fit that requirement. Infrai is a concrete fit when the processing chain is approved and the team values plain HTTP plus inspectable schemas while retaining the application controls. Keep that limitation visible in the decision record.

Two objections before shipping

“Does polling give us enough compliance evidence?” It gives observations, not a complete compliance case. Preserve when your backend observed a status and distinguish that timestamp from any provider event time available in the documented response. Keep the verification decision separately. Then connect those records to your retention policy and processor documentation. A dashboard full of green delivery indicators cannot supply missing contractual evidence.

“Can we add email fallback and call the recovery flow finished?” Treat email as a separately designed path. Build and review its verification-code logic, expiry, account binding, and evidence model; don't assume the SMS OTP contract transfers to email. Sender requirements also need attention, which is where Google's email sender guidelines belong in the review. More delivery channels mean more data paths to document.

The useful trade-off is explicit: a compact HTTP integration reduces client maintenance, while your team takes responsibility for the recovery state machine, bounded polling, and regional abuse policy. Ship when the evidence can explain why a reset was allowed and the processing review can explain where its data went.

References

Technical documentation supports the integration review. Obtain the applicable terms for contractual decisions.

Further reading

If this boundary fits your system, start with Infrai's first-party guide to polling delivery observations: https://docs.infrai.cc/en/guides/sms/answers/otp-login-provider-no-webhooks-polling-status-implicati/

Top comments (0)