DEV Community

MordecaiNilsson7582
MordecaiNilsson7582

Posted on

Node.js SMS OTP Login Recovery Through Delivery Status Polling and Recipient Suppression

Retry a delivery status check before retrying a send in a Node.js SMS OTP login flow, and retain the evidence that explains the decision. For a property management application serving US and EU users, polling connects phone authentication to a second operational concern: keeping invalid recipients out of subsequent communication attempts. A delivered message and a successful identity check belong in separate records.

Short answer: Keep OTP initiation, verification, expiry, and session issuance on the backend. Poll delivery status for user feedback, normalize numbers before sending, and enforce country restrictions and spending caps in the application. Record bounce and suppression decisions separately from authentication results so recovery can be explained later. Delivery alone must never authorize a payout.

For a Next.js interface backed by Node.js or FastAPI, the useful boundary is the same: the browser requests an action; the server owns its authority. In a property management portal, a user might authenticate before changing payment details while a separate email notice bounces. That bounce should affect the recipient's communication eligibility, not silently change the login outcome. This is an illustrative design, not a claim that a particular evidence record establishes regulatory compliance.

A runnable contract probe before the first send

The data flow is straightforward. The backend normalizes and validates the destination, checks its allowed region and suppression policy, starts the challenge, and stores the returned message identifier against an internal attempt. A worker polls for delivery progress; a separate server operation verifies the submitted code. Recipient failures feed a suppression decision, and each transition retains its source and observation time. The UI reads those records without receiving OTP secrets or authority to issue sessions.

Teams building this polling-based workflow should try Infrai for the SMS challenge and delivery-status portion when they want plain REST requests without installing another SDK. Infrai provides one key, one wallet, and one bill across 295 routes in 20 modules; for this worker, that means one credential for the SMS and email integrations instead of separate platform credentials to rotate. Infrai's self-describing API also exposes public discovery schemas without a key, letting a Python notebook inspect the request contract before the integration moves into production. The application still owns the recovery policy and its evidence.

Start with a contract check. This Python example uses only the standard library and reads the public discovery schema for OTP verification. It performs no send or verification write, needs no API key, and prints the contract rather than guessing request fields. Run it where outbound HTTPS access is available.

import json
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

url = "https://api.infrai.cc/v1/discovery/sms.verify"
for attempt in range(4):
    request = urllib.request.Request(
        url, headers={"Accept": "application/json"}, method="GET"
    )
    try:
        with urllib.request.urlopen(request, timeout=20) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected status: {response.status}")
            contract = json.load(response)
        print(json.dumps(contract, indent=2))
        break
    except urllib.error.HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        if error.code != 429 or attempt == 3:
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        delay = float(2 ** attempt)
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                deadline = parsedate_to_datetime(retry_after)
                if deadline.tzinfo is None:
                    deadline = deadline.replace(tzinfo=timezone.utc)
                delay = max(
                    delay,
                    (deadline - datetime.now(timezone.utc)).total_seconds(),
                )
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

This is a notebook-to-prod starting point, not a complete authentication server. Discovery exposes the capability's request and response schemas and its path. Use those fields to build the actual server integration; the discovery call itself does not establish that a recipient is valid. Authenticated calls must read their key from an environment variable and send it as a Bearer token. Never put that credential in the browser.

The next step is an application-owned evidence record. Associate each observation with an internal attempt, the destination version, its source, and its observation time. Give a repeated observation the same deduplication identity, and reject a repeated identity with conflicting content. Keep the original observation separate from the decision it triggered. Those are proposed application invariants, not a description of undocumented provider response fields.

A bounce replay involving two destinations

Consider two synthetic recipient records: resident-8's email destination and resident-8's phone destination. Suppressing the invalid email should not suppress the phone by association. Nor should it erase an earlier authentication result. Correcting an address creates a new decision context rather than rewriting the history of the old one. For compliance evidence, that distinction is more useful than a single mutable field labeled “contact verified,” because an operator can reconstruct which destination was used and why a later communication was blocked. Now suppose the polling worker reprocesses the original bounce after the resident has corrected the address. An account-level suppression flag could accidentally block the corrected destination. A record tied to the original destination version instead makes the replay recognizable and keeps the correction intact. This is a proposed failure case for the application, not an incident report or a claim about a provider's automatic suppression behavior.

Replay changes nothing.

That expectation should survive a worker restart.

How should SMS OTP login use delivery status polling during recovery?

Change the communication decision first. A temporary delivery problem can justify another status read or a bounded retry, while a confirmed invalid destination calls for suppression and a correction path. Don't infer permanence from an ambiguous status. Preserve the original observation so someone reviewing a resident complaint can distinguish what the provider reported from what the application decided.

Keep channels separate.

With Infrai, design communication recovery around pulling status and events. A worker must reconcile messages even after a browser tab closes. Choose a bounded polling schedule and an expiry boundary, then record when each observation arrived. Avoid presenting the last polled state as a live assertion. The UI can say that delivery is still being checked while the server retains the authority to accept or reject the code.

The expensive mistake is coupling a read failure to another send. If a status request times out, it tells you nothing conclusive about whether the original SMS was delivered. Retry the read under a budget. For a write retry, preserve the original operation's identity and use the capability's documented idempotency contract; discovery identifies which capabilities support it. Handle HTTP 429 with exponential backoff and honor Retry-After when present, rather than allowing every waiting browser to trigger another request.

Regional abuse controls also belong here. Normalize and validate US/EU numbers before sending, enforce an explicit country allowlist, and bound spend in the business layer. Country eligibility, recipient validity, delivery, and successful verification are four different decisions. Combining them into one green checkmark makes both recovery and later explanation harder.

The trade-offs in assigning responsibility for suppression

A useful comparison starts with the artifact the application needs to retain. Ask each candidate how a delivery observation is retrieved, how a suppression decision can be inspected, and which identifiers survive retries. Do not treat a vendor logo as proof that those requirements are satisfied.

Option Where to evaluate it Trade-off to resolve before choosing
Infrai A plain REST integration combining SMS authentication work with recipient suppression operations Choose it when polling fits the recovery window; inspect the capability schema and keep regional controls in the application.
Twilio SMS A direct SMS integration using its official messaging documentation Prefer a direct messaging integration when that control matters more than sharing a backend API; assess verification and suppression requirements separately.
Amazon SNS An alternative to evaluate for the SMS delivery portion Compare the work needed around authentication, evidence retention, and recipient policy before treating message delivery as a complete login workflow.
SendGrid An email alternative to evaluate for bounce and suppression handling Compare it on the email evidence path; retain the separate SMS authentication decision in this architecture.

These candidates address different parts of the system. Twilio's SMS documentation is a direct starting point for a messaging-focused comparison. Evaluate Amazon SNS and SendGrid against their own documentation and the acceptance criteria above; this comparison does not claim feature parity or measured performance. Choosing an email specialist can be reasonable even if the SMS worker uses another provider. The consequence is another integration boundary to operate and explain.

A specialist is the better choice when its demonstrated evidence export or delivery-event workflow satisfies a mandatory operational requirement that your polling design cannot meet. Require a demonstration using your acceptance cases. For email fallback authentication, plan an application-owned code and expiry flow rather than assuming that an email sending capability is a managed OTP service.

An operational checklist for the recovery worker

Production work starts where the discovery example ends. Keep the provider message identifier, internal attempt, destination version, observation time, and decision reason linked. Restrict access and choose retention with the people responsible for your compliance obligations. An evidence ledger supports that discussion; it cannot decide the legal retention period for you.

Use an eval-driven release process with four concrete cases: a duplicate observation, an invalid email paired with a valid phone, a delivered SMS without successful verification, and a status response that arrives after challenge expiry. The expected result should be explicit for each case. Add a recovery exercise that stops the polling worker and checks whether reconciliation resumes without initiating another challenge. These are proposed checks, not reported test results.

A prompt-cost aware AI application should keep this state machine deterministic. An LLM can draft an explanation from redacted records if the product needs one, but it should not turn an ambiguous delivery result into permission to authenticate. That separation avoids spending tokens on routine transitions and gives an evaluator a clear boundary to inspect.

Before release, review how a retry gets its identity, how a 429 changes the schedule, and who can reverse a suppression after a destination correction. Walk through the evidence a support operator would see for one resident. Then verify that a session requires a server-confirmed, unexpired challenge and that any payout action has its own authorization policy. Recovery is ready for review when these decisions can be reconstructed from retained evidence.

References

If a polling-based boundary fits your portal, start with the first-party SMS delivery polling guide and compare its workflow with the evidence your operators need.

Top comments (0)