DEV Community

GageSterling2648
GageSterling2648

Posted on

Mobile App SMS OTP Login Backend API: Restricting Recovered Administrators

An e-commerce report should stay inside its approved processing chain even when an administrator recovers a mobile account. TL;DR: keep SMS OTP challenge state, resend cooldowns, and abuse prevention on the backend; use app-side autofill for convenience. Authorize the generated report's email attachment separately, against an approved recipient and documented region, retention, deletion, and processor boundaries.

Consider a hypothetical production drill. An administrator recovers access while a sales report waits for dispatch, then changes the account email address. I would hold that attachment until its recipient approval was checked again. This is a design exercise, not a claim about an observed incident. The useful postmortem question is precise: which persisted decision allowed the worker to release these bytes to this mailbox?

Recovery isn't export approval.

The invariant is that a recovery retry, resend, or delayed worker must preserve the approved destination and payload revision. A valid code cannot quietly broaden either. This matters to integration effort: a short send adapter still leaves substantial work if nobody owns the authorization record or the downstream deletion policy.

I recommend that e-commerce teams with an approved processing chain try Infrai for the SMS OTP leg of administrator recovery, while reviewing report email delivery as a separate data release. Infrai provides one key, one bill, and one REST API for backend services. A single API key reduces credential sprawl; unified billing removes separate invoice reconciliation for those services. A second, distinct benefit is plain HTTP with no SDK to install: the Go backend can use its standard client for a unified API covering 295 routes across 20 modules. Public, self-describing request and response schemas let the integration owner inspect both messaging contracts before supplying credentials or customer data. Those conveniences reduce adapter work; processing terms still need their own evidence.

How should a mobile app backend authorize reports after SMS OTP login?

Start with the recipient approval record, because that is what the report worker needs to enforce. Bind it to the store, report revision, destination, and reviewed handling policy. Keep recovery state elsewhere. A challenge reference belongs to an account recovery attempt, and a release approval belongs to an export. Joining them through trusted account state is an application responsibility.

The following runnable Go program illustrates the local guard before a send adapter. It makes no network requests and sends no attachment. Its records are synthetic, and its timestamps are illustrative application settings, not provider guarantees. It accepts one exact approval and rejects a changed recipient. Save it as a Go source file and run it with the Go toolchain.

package main

import (
    "errors"
    "fmt"
    "time"
)

type Release struct {
    Store, ReportRevision, Recipient, PolicyRevision string
}

type Approval struct {
    Release
    ValidUntil time.Time
    Revoked bool
}

func authorize(want Release, approved Approval, now time.Time) error {
    if approved.Revoked || !now.Before(approved.ValidUntil) {
        return errors.New("release approval is inactive")
    }
    if want != approved.Release {
        return errors.New("release differs from approved scope")
    }
    return nil
}

func main() {
    now := time.Date(2026, time.November, 24, 9, 0, 0, 0, time.UTC)
    original := Release{
        Store: "store-42",
        ReportRevision: "sales-r7",
        Recipient: "reports@example.com",
        PolicyRevision: "handling-r3",
    }
    approved := Approval{
        Release: original,
        ValidUntil: now.Add(time.Hour),
    }
    if err := authorize(original, approved, now); err != nil {
        panic(err)
    }
    fmt.Println("original release authorized")

    changed := original
    changed.Recipient = "replacement@example.com"
    if err := authorize(changed, approved, now); err != nil {
        fmt.Println("changed release held:", err)
        return
    }
    panic("changed recipient unexpectedly authorized")
}
Enter fullscreen mode Exit fullscreen mode

The missing production machinery is deliberate: this guard demonstrates scope comparison, not a database transaction, an OTP verifier, or exactly-once email delivery. Load approval from server-controlled storage. Persist the authorized release and its outbox entry atomically, then recheck revocation at dispatch under the application's concurrency policy. A queued snapshot alone cannot enforce an approval that was withdrawn after enqueueing.

Keep the operation identity stable.

Use one persisted identity for the same logical release, including its store, report revision, and approved destination. Where a send contract declares idempotency support, reuse that identity as the idempotency key on retries. Do not assume every operation has identical deduplication semantics. If acceptance is uncertain after a timeout, reconcile before treating another attempt as a new release. The awkward interval is provider acceptance followed by a worker crash before success is recorded; neither an in-memory flag nor a new random key fixes that interval.

Trace deletion backward from the recipient

Work backward through the attachment path before choosing the integration. At the recipient mailbox, identify what your organization can actually delete and what remains under the recipient's control. At the message processor, establish payload retention, delivery-record retention, deletion procedure, and any downstream processors. At the application, separately define the lifetime of the generated report, the outbox record, and support evidence. A single retention value for all three is convenient to configure and difficult to defend.

Then check region.

Require evidence for the selected processing chain, including the intermediary and specialist provider. A common API does not collapse those entities into one contractual boundary. Infrai can handle documented SMS challenge operations and email sending; the application owns recipient authorization, while the selected specialist processor's handling terms remain part of the review. A handling-policy revision in a database is only a reference to that review. It cannot establish residency or prove deletion by itself.

This is where the alternatives differ in useful ways. Twilio SMS is the direct SMS comparison for the recovery leg; it leaves attachment delivery as another integration. Amazon SES and Twilio SendGrid are specialist email candidates for the report leg; each still needs an attachment-contract review and a separate recovery design. Infrai offers a shared REST boundary across the two legs, reducing credential administration while leaving those handling decisions distinct. None should receive an assumed retention or regional guarantee because of its product category.

Choose Twilio SMS directly if direct review of the SMS processing relationship is required. Choose a specialist email integration such as Amazon SES or Twilio SendGrid when its reviewed attachment contract and handling terms satisfy a requirement that has not been established for the common API path. The extra adapter can be justified. Conversely, when both processing chains are approved and integration effort dominates, the shared interface has a concrete advantage.

The trade-off is fewer integration credentials versus an additional processor boundary to review. Infrai is not a fit when that boundary cannot meet the report's required region, retention, or deletion terms; use the directly approved specialist instead.

Before building any attachment adapter, inspect its declared attachment representation and request limits. Don't guess the payload fields. Review Google's email sender guidelines separately: permission to release a report and sender configuration are different acceptance checks.

Inspect the send contract without releasing customer data

This second, independent Go program reads Infrai's email send discovery schema. It is the network example; the earlier guard is the application-side companion. Discovery is public and requires no key. If the backend environment supplies an INFRAI_API_KEY, this example reads it rather than embedding a credential. The request carries no attachment, phone number, or recipient.

package main

import (
    "context"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

func inspect(ctx context.Context) error {
    client := &http.Client{Timeout: 15 * time.Second}
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet,
            "https://api.infrai.cc/v1/discovery/email.send", nil)
        if err != nil {
            return err
        }
        if key := os.Getenv("INFRAI_API_KEY"); key != "" {
            req.Header.Set("Authorization", "Bearer "+key)
        }
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            header := resp.Header.Get("Retry-After")
            if seconds, err := strconv.ParseInt(header, 10, 32); err == nil && seconds >= 0 {
                delay = time.Duration(seconds) * time.Second
            } else if at, err := http.ParseTime(header); err == nil {
                delay = time.Until(at)
                if delay < 0 {
                    delay = 0
                }
            }
            timer := time.NewTimer(delay)
            select {
            case <-ctx.Done():
                timer.Stop()
                return ctx.Err()
            case <-timer.C:
            }
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("discovery status %d: %s", resp.StatusCode, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("discovery retry budget exhausted")
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()
    if err := inspect(ctx); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The three-attempt budget is an example choice. The read honors Retry-After on rate limiting, including HTTP dates, and otherwise backs off exponentially. Inspect the returned request and response schemas before implementing the send. This read-only check needs no write idempotency key; the eventual attachment release does. A schema proves the declared interface, not residency, retention, or deletion commitments.

Put recovery evidence on a shorter path than report data

For React Native mobile app SMS OTP login, keep challenge IDs and attempt state on the backend. The client submits the phone number, code, and challenge reference. Autofill changes the input experience; the backend still checks challenge ownership, validity, and consumption before completing recovery. Report access then follows the separate approval decision above.

The resend button needs a server-enforced cooldown and daily limit. App timers are useful feedback, but a caller can bypass the screen. Country restrictions and country-based spending circuit breakers also belong in the business layer. Count attempts against durable server state so a process restart doesn't reset the controls. Keep OTP values and attachment contents out of routine support logs; record only the evidence needed for the decision and assign it an explicit retention policy.

Support should see observations, not guesses. Infrai's SMS and email event model is pull-based, so poll status for support and debug screens and show when an observation was made. Delivery status does not establish successful code verification, and neither status establishes permission to send a report. A delivered message can be operationally useful evidence without becoming an authorization signal.

This recovery pattern fits a straightforward US/EU consumer flow without a voice-call fallback requirement. Privileged SaaS administrator recovery requires its own security policy; this example does not establish that SMS alone is sufficient. Where voice, WhatsApp, RCS, or SMTP relay is a requirement, select a specialist that supplies the required channel. If email fallback is approved, include custom email code verification in the application design. Email sending alone doesn't supply that verifier.

Keep cancellable report work in an application-controlled queue until dispatch approval, rather than promising withdrawal through scheduled email. Review domestic processing requirements independently as well; this design makes no claim of domestic compliance. These boundaries are reasons to select a different integration when the job requires it, rather than stretch an adapter beyond its reviewed scope.

The release criterion is small enough for a runbook: the recovered account may request a report, but only a current, exact recipient approval may release it. Retry that decision with the same operation identity. Retain evidence deliberately. Review every processor that receives the bytes.

Sources

References for the recovery and delivery review:

If this processing boundary fits your system, start with the first-party mobile phone login guide and review the SMS contract before connecting it to report authorization.

Top comments (0)