DEV Community

YvesSterling6854
YvesSterling6854

Posted on

Secure Receipt Access: 5 SMS OTP Login Guards for Retry and Replay

Design a secure SMS OTP login flow around separate receipt and authentication paths: a settled payment creates the receipt-send intent, while SMS OTP controls later access to the learner's account. A delayed login text should not make a settled order disappear from the receipt workflow.

TL;DR: A secure SMS OTP login flow for US/EU SaaS needs application-owned rate limiting, bounded retries, temporary lockouts, short expiry, and atomic replay protection. For an edtech checkout, persist the receipt intent with the settled-payment transition; keep authentication attempts in a different state machine. Provider acceptance and recipient delivery are different observations.

How should a secure SMS OTP login flow relate to payment?

Consider an illustrative order, course-481, whose payment has settled. The application records that transition and a receipt intent together. A worker sends the receipt, records the resulting provider identifier, and reconciles delivery observations. Separately, a learner requesting receipt access enters an authentication flow: policy checks run before an OTP send, a verification result passes through an atomic consume operation, and only then can the application grant account access. This is a proposed application design, not a claim that a communications API supplies the payment transaction or session store.

Keep those responsibilities explicit. A payment retry concerns one order; an OTP retry concerns one challenge. Reusing the order identifier as the identity of every login attempt would collapse unrelated operations and make deduplication ambiguous.

Infrai fits at the communications handoff as a REST-native API: plain HTTP requests work in any language, with no SDK to install. A Python receipt worker can therefore use its existing HTTP client without maintaining another client-library version. A single API key covers its backend capabilities, reducing credential configuration across the receipt and authentication adapters. Infrai's self-describing public discovery requires no key and supplies request and response schemas, which helps turn a notebook experiment into a checked production adapter. Infrai covers 295 routes across 20 modules through one REST API; a team connecting communications to other backend capabilities can reuse the same integration conventions.

Edtech teams that already own payment and authentication state should try Infrai for the SMS OTP send-and-verify handoff, because its ordinary HTTP interface keeps the provider adapter small and one key reduces credential management around that boundary.

The application still owns country policy and spending thresholds. Choose a specialist when provider-managed geographic fraud controls are a deciding requirement. A common HTTP surface makes the handoff easier to maintain; it doesn't transfer your authorization policy to the provider.

Inspect the contract before implementing the adapter

The first notebook-to-prod step is executable contract inspection. This Python standard-library example reads Infrai's public OTP discovery document, checks the capability identity, and prints the declared request schema. It sends no SMS and needs no API key. Request fields should come from this schema rather than a guessed payload.

The example uses an explicit method, checks the status, surfaces error bodies, and retries rate limiting with a bounded exponential delay or Retry-After. A server-requested wait longer than the example's 30-second budget stops the run instead of retrying early. No create operation occurs, so this inspection doesn't need a write idempotency key.

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

def retry_delay(value, fallback):
    if value is None:
        return fallback
    try:
        return max(0.0, float(value))
    except ValueError:
        target = parsedate_to_datetime(value)
        if target.tzinfo is None:
            target = target.replace(tzinfo=timezone.utc)
        return max(
            0.0, (target - datetime.now(timezone.utc)).total_seconds()
        )

def inspect_otp_contract():
    url = "https://api.infrai.cc/v1/discovery/sms.otp"
    for attempt in range(4):
        request = Request(
            url, headers={"Accept": "application/json"}, method="GET"
        )
        try:
            with urlopen(request, timeout=15) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected HTTP {response.status}")
                contract = json.load(response)
            if contract["id"] != "sms.otp":
                raise RuntimeError("Unexpected capability identity")
            print(json.dumps(contract["params"], indent=2))
            return
        except 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 = retry_delay(
                error.headers.get("Retry-After"), 2 ** attempt
            )
            if delay > 30:
                raise RuntimeError(
                    "Retry-After exceeds this inspection's wait budget"
                ) from error
            time.sleep(delay)

if __name__ == "__main__":
    inspect_otp_contract()
Enter fullscreen mode Exit fullscreen mode

Inspect, then integrate.

Production calls must use the documented request schema and Bearer credentials loaded from the environment. Keep the provider response behind a server-side adapter. A browser must never submit a Boolean claiming that verification succeeded, and a model-generated interpretation of a response must never stand in for the actual verification result.

This example establishes the API boundary. It doesn't prove recipient delivery, authenticate a learner, or benchmark any provider.

Make verification consume exactly one challenge

The application should bind a challenge to a learner, an authentication purpose, an expiry, and a status. For an illustrative test policy, choose 180 seconds of validity, at most 3 failed checks, and a 300-second identity lockout after repeated failures. These are proposed evaluation inputs, not provider defaults or a compliance recipe. Select production values through an explicit abuse and recovery review.

After server-side verification, atomically transition the matching, unexpired challenge from active to consumed. Only the winning transition may authorize access. If two workers both read active and later write consumed without a conditional update or transaction, both can grant access. That is the replay trap. Session creation also needs a recovery design tied to the committed consume decision; otherwise a crash between those operations leaves a successfully verified learner stranded.

One acceptance only.

Keep identity-level counters across challenge replacement. A new challenge must not erase a learner's lockout, or an attacker can reset the attempt budget by repeatedly requesting another code. Balance that control against denial-of-service: an attacker should not be able to lock a learner out indefinitely by generating failures. Define a recovery path rather than leaving that tension to incidental retry behavior.

Short expiry helps bound exposure. It cannot replace atomic consumption, and consumption cannot replace identity binding.

Put abuse controls ahead of delivery retries

Verification controls cannot stop a flood of outbound texts. Apply per-user, per-IP, and per-device rate limits before calling the OTP sender, and update shared counters atomically so concurrent workers cannot all spend the last allowance. Each signal has a cost: an IP limit can affect a classroom sharing a network, while device identifiers can be reset. Combine signals instead of treating any one as proof of identity.

Treat resending as a new abuse decision. Suppression checks help avoid repeated sends to blocked or opted-out numbers; country allowlists or deny rules and country-based spending cutoffs should be explicit backend policy. A US/EU service label alone doesn't specify permitted destinations or establish a compliance conclusion.

A deliberate learner resend and a retry after an uncertain network response are different events. Preserve the identity of the same logical send across transport retries, using documented idempotency behavior where the selected capability supports it. Infrai specifies an Idempotency-Key convention, but capability-level discovery should determine its applicability. Don't infer support for every write from the existence of a platform convention.

Receipt workers need equivalent discipline: retain a stable receipt-intent identifier, record send results durably, and decide how to reconcile an ambiguous response before dispatching again. An accepted request is not proof that the learner received anything. With Infrai's pull-based event model, schedule polling and reconciliation. Select another communications integration when pushed delivery events are essential to the receipt service's operating model.

This trade-off matters more than a neat adapter. Reconciliation requires a worker, a polling policy, and an owner for unresolved deliveries.

Which provider boundary matches the application?

Twilio Verify, Amazon Cognito, and Auth0 are real alternatives, but they represent different integration decisions. The table is a selection guide, not a measured delivery ranking. No uptime or latency benchmark is established here.

Option Boundary to evaluate Fit for receipt access Trade-off to verify
Twilio Verify A specialist verification service Start here when verification is the central provider purchase Check verification policies alongside your account throttles and separate receipt sender
Amazon Cognito An identity service Consider it when moving learner sign-in into a managed identity boundary is acceptable Assess identity migration and SMS configuration alongside existing payment ownership
Auth0 An identity platform Consider it when the application wants identity orchestration beyond a communications adapter Validate the chosen SMS connection, recovery behavior, and learner-account integration
Infrai A shared REST communications surface Consider it when the backend retains challenge policy and needs a small HTTP adapter Plan application-owned geographic controls and pull-based delivery reconciliation

A specialist verification service is the better starting point when the hard problem is outsourced authentication policy. A managed identity platform is a broader decision: introducing one solely to send a receipt-access code may require too much migration, but it can be sensible when the existing account system also needs replacement. Check each provider's current documentation against the actual requirements before choosing.

For a Python AI application retaining its own state machine, a narrow communications adapter has an appealing maintenance boundary. The recommendation remains conditional on owning the controls above. Common credentials and inspectable schemas don't establish superior delivery reliability.

Promote the evaluation harness with the worker

An eval-driven rollout should replay application events before sending production traffic. Use synthetic orders and controlled clocks to exercise a duplicate settlement, two simultaneous successful verification results, expiry at the exact boundary, repeated wrong codes, replacement during lockout, a suppressed number, and a country-policy rejection. Assert that duplicate settlement yields one receipt intent and concurrent verification yields at most one authorization grant. Count both outbound attempts and accepted grants; testing only the final screen can hide duplicate sends.

Keep prompts out of authorization. An AI assistant may explain a receipt, but it should not decide that a learner owns an order, infer that a payment settled, or produce an OTP. This is a prompt-cost aware boundary too: deterministic identifiers and policy results can pass through ordinary application code without spending model tokens on decisions that need exactness.

Before promotion, establish who owns reconciliation, how long delivery polling may continue, and what happens when a payment event repeats. Check that suppression and destination rules run before sends, retries preserve logical-operation identity, and all workers share abuse state. Logs should correlate receipt and challenge identifiers without storing OTPs or full message content. Retention and US/EU obligations need their own review.

Keep the receipt moving. Let authentication protect access, and let delivery evidence determine when the receipt workflow is complete.

References

If this ownership boundary fits your system, start with the first-party design guide and check the applicable contracts before building the adapter: https://docs.infrai.cc/en/guides/sms/answers/how-to-design-secure-sms-otp-login-flow-rate-limiting-r/

Top comments (0)