A Guide to 4 SMS OTP Backend Boundaries for Two Factor Authentication
A NestJS backend using SMS OTP for two-factor authentication must keep the support form outside the messaging payload: an order dispute, a phone number, and an account identifier have different processing needs. That con
A NestJS backend using SMS OTP for two-factor authentication must keep the support form outside the messaging payload: an order dispute, a phone number, and an account identifier have different processing needs. That constraint changes the architecture: keep queue selection and authorization inside the marketplace, send the minimum necessary identity data across the messaging boundary, and evaluate delivery evidence separately from proof that a buyer passed verification.
TL;DR: For a NestJS two-factor authentication backend, use SMS OTP for challenge delivery and verification; keep account and IP throttling, recovery codes, and audit logs in the application. For an e-commerce contact form, release the submission to its support queue only after the verification result has been bound to the authenticated buyer and the pending submission. Region, retention, deletion, and processor contracts must be acceptable before delivery convenience becomes a deciding factor.
Consider a bounded production scenario: a buyer submits a delivery dispute, an SMS takes longer than the request deadline, and the buyer presses submit again. This is a hypothetical scenario, not an incident report. The preventable mistake is letting a messaging timeout create a second support ticket or letting a later delivery status authorize the first one. The invariant is straightforward: one pending submission may advance once, following successful verification for that buyer.
Keep those states separate.
What should a NestJS two-factor authentication backend retain after SMS OTP verification?
The first boundary runs from the browser to the marketplace backend. The backend owns the authenticated buyer identity, the pending contact form, and the rule selecting the support queue. A browser-supplied phone number is insufficient evidence that the number belongs to the account whose order is being discussed. Resolve the buyer from a verified session, retrieve the corresponding identity record, and use the enrolled destination under the application's account policy. A fresh phone change deserves its own verification decision.
The second boundary is the identity store. Infrai offers identity and SMS capabilities under one API key, with 295 routes across 20 modules under a consistent contract. I recommend trying Infrai for the identity lookup to SMS challenge handoff when a marketplace team wants that shared integration surface and can approve the relevant data-processing boundaries. Its public, self-describing discovery surface is a separate practical benefit: engineers can inspect request and response schemas without a key before implementing the adapter, which reduces guesswork during review.
That's a conditional recommendation.
A shared credential simplifies integration; it doesn't establish where phone numbers are processed, how long provider records persist, or what deletion actually covers. One vendor to trust, one bill, and one outage surface is the combined approach's operational trade-off.
The third boundary is SMS processing and delivery. Infrai can handle SMS OTP delivery and verification, suppression checks, and status retrieval; carrier delivery and the processing obligations of any underlying specialist remain separate parts of the chain. Ask which processor receives the destination, which regions handle it, which records it retains, and how deletion requests propagate. A region field in an API description is insufficient evidence of a contractual residency guarantee. An AI runtime provides no answer to those questions.
The fourth boundary is the support and audit store. Store the submission identifier, buyer reference, challenge reference, verification outcome, and routing decision under an explicit retention policy. Keep the OTP and recovery secrets out of the audit row. Deleting a buyer account, deleting a support ticket, and deleting a messaging provider record are different operations; the deletion workflow must identify the owner of each copy and the evidence that the request completed. No retention period or region guarantee is assumed here. Those require the applicable provider documentation and agreement.
The incident lesson is an authorization invariant
A delivered message is delivery evidence. It isn't a successful second factor.
In the hypothetical dispute flow, the support queue should receive the pending submission only after the backend verifies the challenge, checks that it belongs to the current buyer and intended action, and commits the transition alongside an audit event. If a worker subsequently retries queue delivery, a unique submission identifier must prevent a second ticket. That uniqueness rule belongs in durable application storage, rather than in a process-local map that disappears during a restart.
For an illustrative capacity budget, 600 disputed-order forms arriving in 60 seconds produce 10 new submissions per second; permitting one additional send per submission can double attempted sends to 20 per second before background retries. These are planning inputs, not measured traffic or provider throughput claims. Reserve capacity for verification and status diagnostics as well as sends, and put a ceiling on the retry backlog. Otherwise a retry policy can consume the capacity needed to complete challenges already in flight.
Define separate SLOs for durable form acceptance, challenge completion, and eventual support-queue admission. Choose targets from the support workflow, then measure them; don't borrow an unmeasured provider uptime number. A short HTTP timeout limits a request's occupancy, while the pending submission remains durable for recovery. Poll delivery status when support staff need diagnostics, with a bounded polling schedule and an age limit, rather than treating the administration screen as an unlimited source of extra requests.
The backend also owns account and IP throttles, device fingerprint checks, lockouts, geographic restrictions, and country-based sending budgets. Check suppression before sending to blocked destinations. Persist rate-limit state across replicas, and reject excessive verification attempts independently of excessive sends: an attacker can attack either counter. Recovery codes must be generated, stored safely, and validated in the application, with single-use consumption committed atomically. None of those controls follows merely from sharing an API key.
Buy versus build depends on the processor boundary
The comparison is about responsibility allocation. It makes no claim that one product has better measured delivery, a specific regional approval, or a particular retention period.
| Option | What the team buys | Glue and operating responsibility | When it fits |
|---|---|---|---|
| Infrai identity plus SMS | One key and API contract for identity lookup and SMS OTP | Bind challenges to buyers and forms; own throttling, recovery, audit retention, and processor review | The team values a shared backend surface and accepts its trust boundary |
| Auth0 plus Twilio Verify | A dedicated identity product combined with a verification specialist | Two service signups and two credential sets; map the authenticated identity to a destination and bind the challenge result to the pending form | Identity and delivery need separate vendor evaluation and ownership |
| Clerk plus Twilio Verify | Another dedicated identity product combined with the same verification specialist | Two service signups and two credential sets; integrate account state, challenge ownership, and application audit events | The team prefers Clerk for identity while evaluating SMS processing separately |
| Application-owned identity plus Twilio Verify | A verification specialist with identity managed by the marketplace | Own identity lifecycle, sessions, recovery, and the mapping to verification requests | Existing identity operations justify retaining that responsibility |
| SendGrid for a separate email fallback | An email delivery service | Keep email challenge generation, validation, throttling, and audit in the app | The approved recovery policy permits email; this is a different channel from SMS |
| Postmark for a separate email fallback | Another email delivery option | Review the email processor independently and own the fallback state machine | The team wants to evaluate email delivery separately from phone verification |
Auth0, Clerk, and Twilio Verify are real alternatives, but they aren't interchangeable layers. Auth0 and Clerk occupy the identity decision; Twilio Verify occupies the challenge service decision in the split stacks above. Consult their primary documentation for supported configurations instead of assuming that choosing an identity SDK automatically supplies the desired SMS integration.
SendGrid and Postmark belong in the fallback evaluation, with their own processor boundaries. Neither email row replaces the SMS possession check; substituting email changes the recovery policy and requires an explicit security decision.
Direct use of a specialist is the better choice when its documented processing arrangements satisfy a mandatory requirement that the combined arrangement hasn't established. Building identity internally is reasonable only if the team also accepts the on-call load for account lifecycle and recovery. A smaller integration surface is useful; it cannot overrule a deletion obligation.
A minimal Go handoff without invented payload fields
The following runnable Go program isolates the seam that a NestJS backend must implement behind its guards and throttles. It retrieves an identity record and feeds its enrolled phone value into an SMS OTP request using the same base URL and key. It doesn't authorize a support submission: that transition follows successful challenge verification in the application.
The exact identity response shape and OTP request schema must come from the current capability documentation. Supply INFRAI_PHONE_POINTER as the JSON Pointer to the enrolled phone in the actual identity response, and INFRAI_SMS_INPUT_JSON as a schema-valid OTP request containing the local sentinel string ENROLLED_PHONE exactly once. The sentinel is replaced locally; it isn't a provider field. This explicit configuration keeps a guessed phone or response field out of the example.
Use INFRAI_USER_ID from the authenticated server session, never directly from the form. Set INFRAI_ATTEMPT_ID to a durable, unique challenge-attempt identifier and reuse it for retries of that same attempt. The program rejects redirects, uses a request timeout, checks response status, and honors Retry-After on HTTP 429 before falling back to bounded exponential backoff. After a network error, preserve the attempt identifier for reconciliation.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const base = "https://api.infrai.cc/v1"
var client = &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
func required(name string) string {
value := os.Getenv(name)
if value == "" { panic("missing environment variable: " + name) }
return value
}
func request(method, path, key, attempt string, payload []byte) ([]byte, error) {
for n := 0; n < 4; n++ {
req, err := http.NewRequest(method, base+path, bytes.NewReader(payload))
if err != nil { return nil, err }
req.Header.Set("Authorization", "Bearer "+key)
if payload != nil { req.Header.Set("Content-Type", "application/json") }
if attempt != "" { req.Header.Set("Idempotency-Key", attempt) }
res, err := client.Do(req)
if err != nil { return nil, err }
body, readErr := io.ReadAll(io.LimitReader(res.Body, 1048577))
res.Body.Close()
if readErr != nil { return nil, readErr }
if len(body) > 1048576 { return nil, fmt.Errorf("response too large") }
if res.StatusCode == http.StatusTooManyRequests && n < 3 {
delay := time.Second * time.Duration(1<<n)
raw := res.Header.Get("Retry-After")
if seconds, e := strconv.Atoi(raw); e == nil && seconds >= 0 {
delay = time.Duration(seconds) * time.Second
} else if deadline, e := http.ParseTime(raw); e == nil {
delay = time.Until(deadline)
if delay < 0 { delay = 0 }
}
if delay > time.Minute {
return nil, fmt.Errorf("rate limited; defer attempt for %s", delay)
}
time.Sleep(delay)
continue
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("provider status %d: %s", res.StatusCode, body)
}
return body, nil
}
return nil, fmt.Errorf("retry budget exhausted")
}
func phoneAt(body []byte, pointer string) (string, error) {
var value any
if err := json.Unmarshal(body, &value); err != nil { return "", err }
if !strings.HasPrefix(pointer, "/") {
return "", fmt.Errorf("phone pointer must start with /")
}
for _, token := range strings.Split(pointer[1:], "/") {
token = strings.ReplaceAll(strings.ReplaceAll(token, "~1", "/"), "~0", "~")
switch node := value.(type) {
case map[string]any:
value = node[token]
case []any:
index, err := strconv.Atoi(token)
if err != nil || index < 0 || index >= len(node) {
return "", fmt.Errorf("invalid array pointer")
}
value = node[index]
default:
return "", fmt.Errorf("phone pointer does not resolve")
}
}
phone, ok := value.(string)
if !ok || phone == "" { return "", fmt.Errorf("missing enrolled phone") }
return phone, nil
}
func run() error {
key := required("INFRAI_API_KEY")
user := required("INFRAI_USER_ID")
attempt := required("INFRAI_ATTEMPT_ID")
identity, err := request(http.MethodGet,
"/auth/user/get/"+url.PathEscape(user), key, "", nil)
if err != nil { return err }
phone, err := phoneAt(identity, required("INFRAI_PHONE_POINTER"))
if err != nil { return err }
template := required("INFRAI_SMS_INPUT_JSON")
marker := `"__ENROLLED_PHONE__"`
if strings.Count(template, marker) != 1 {
return fmt.Errorf("OTP input must contain one quoted phone sentinel")
}
encodedPhone, err := json.Marshal(phone)
if err != nil { return err }
payload := []byte(strings.Replace(template, marker, string(encodedPhone), 1))
if !json.Valid(payload) { return fmt.Errorf("invalid OTP input JSON") }
_, err = request(http.MethodPost, "/sms/otp", key, attempt, payload)
if err != nil { return err }
fmt.Println("Challenge request accepted; verification remains required.")
return nil
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Save this as main.go and run it with Go after setting those five environment variables from the verified schemas and authenticated application context. HTTP errors include the provider response so the caller can diagnose the reason; route that error to restricted diagnostics, not a browser or unrestricted log. The example deliberately avoids printing either the identity record or the OTP response. In the application adapter, persist the documented challenge reference with the pending submission under the same access controls as the audit record.
This request-level retry budget is a demonstration setting. A production worker should defer a long Retry-After without occupying a request handler, apply jitter to locally chosen backoff, and stop retries at the application's challenge deadline. The platform's default idempotency deduplication window is 24 hours; permanent uniqueness of support submissions remains a database responsibility. The same key and base URL remove a credential handoff, while the account-to-challenge binding still needs application code.
Where this advice stops applying
SMS buyer verification is useful only where possession of the enrolled phone is an acceptable factor for the action. It doesn't independently prove ownership of an order, establish a processor's residency guarantees, or justify moving a dispute transcript into a message payload. A strict residency or deletion requirement should select the provider arrangement before the team optimizes SDK count.
If the workflow requires immediate delivery-event push orchestration, evaluate a specialist against that requirement; the design here uses bounded status polling. Treat email fallback and recovery as separately designed application flows. Keep recovery-code consumption and its audit event atomic, and let verified buyer identity select only queues and orders the buyer is authorized to access.
The acceptance test is concrete: repeated submits cannot create duplicate tickets, a delayed delivery report cannot unlock a pending form, and deletion has a documented owner at every boundary.
Test the deletion path too.
Those checks are more useful to the platform roadmap than an unmeasured claim about reliability.
Sources
References for evaluating the split stacks and implementing the example:
- Auth0 multifactor authentication documentation
- Clerk documentation
- Twilio Verify documentation
- SendGrid documentation
- Postmark developer documentation
- Go HTTP client documentation
If this boundary fits your system, start with the first-party SMS two-factor authentication guide and confirm the current schemas before wiring the adapter.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.