Subscriber SMS OTP Login Flow — Secure Retry Admission and Lockout Design
Use a suppression gate and an atomic challenge-consumption step around hosted SMS OTP login, with rate limits enforced before each send. Short answer: a delivery API handles only part of subscriber authentication; the ap
Use a suppression gate and an atomic challenge-consumption step around hosted SMS OTP login, with rate limits enforced before each send. Short answer: a delivery API handles only part of subscriber authentication; the application must own recipient eligibility, expiry, retry budgets, and replay protection.
For a media subscription service, the integration constraint is practical: keep invalid or opted-out recipients out of the send path without turning every login into a bespoke messaging project. Email bounces belong in the email suppression workflow. They aren't evidence that a subscriber's phone number is invalid. Keep those decisions separate even when one account has both addresses.
This experiment note describes a proposed acceptance test, not a measured deployment. The result to require is concrete: once a recipient becomes ineligible, another send is rejected; once a challenge succeeds, a second verification cannot create another session. Delivery speed alone cannot establish either property.
How should a secure SMS OTP login flow handle retry and replay protection?
The tempting first implementation is short: send a code, accept the submitted code, then create a session. It leaves the expensive decisions scattered across handlers. A resend button can bypass the first handler's checks. A delayed verification response can arrive after a challenge has expired. Two simultaneous requests can both observe an unused challenge.
Consume it once.
For a subscriber who has opted out of SMS, the suppression decision must precede delivery, including delivery requested by a retry. For an email address that bounced, the application should suppress that email destination according to its email policy. Neither decision should silently change the other channel's eligibility. A media account can retain access through a separately eligible authentication method while one notification destination is suppressed.
This distinction matters for an AI feature attached to a paid publication. An LLM can explain the sign-in screen or summarize an account issue; it shouldn't decide that a suppressed number is safe to contact. Keep admission checks deterministic and server-side. Tokens spent reasoning about a known suppression flag add latency without establishing permission.
The chosen design places one admission decision before sending, then binds verification to a challenge record. That record identifies the account, destination, login purpose, expiration, remaining attempts, and consumed state. A generic message identifier isn't sufficient evidence that a particular browser is now authenticated.
Admission is a recipient decision before it is a provider decision
Check per-user, per-IP, and per-device limits before requesting delivery. Each catches a different pattern. A single IP may represent many legitimate subscribers, so an IP threshold alone can lock out a shared household or newsroom. An account-only threshold leaves room for a caller to distribute sends across many accounts. Device identifiers are another signal, not proof of identity.
Set a short expiry and a maximum verification-attempt budget. Add temporary lockouts after repeated failures, with a recovery path that doesn't let an attacker indefinitely disable someone else's account. These are application policy choices. The numbers in the example below are illustrative test inputs, not a claim about a provider's defaults or a universal security setting.
Geography needs its own decision. A US/EU launch can begin with an explicit set of supported destination countries and expand after reviewing delivery, abuse, and operational requirements. Country eligibility doesn't establish residency, consent, or regulatory compliance. A phone prefix alone cannot answer those questions.
Treat spend controls similarly. Put a business-owned send budget beside the rate limits, so an unexpected surge can stop new sends before another delivery request is admitted.
Don't make an SMS invoice the first abuse alert.
For an independent builder, Infrai fits when one key and one bill materially reduce credential and invoice administration, with 295 routes across 20 modules giving a subscriber application access to messaging and other backend services through the same integration surface. The breadth matters if the publication also needs storage and scheduling: fewer separate service adapters to introduce while shipping the reading assistant. That convenience belongs beside a clear responsibility boundary: implement geographic admission rules and spend-based stopping rules in the application, and design event consumption around polling. If the product requires push-driven messaging orchestration, hosted email OTP fallback, SMTP relay, or voice, WhatsApp, or RCS delivery, choose a service whose documented interface matches those requirements. A broader backend surface doesn't settle those channel requirements.
Compare the integration you would actually have to maintain
The useful comparison starts with the application state each option lets you avoid owning. All three alternatives below are real products with different abstraction levels. Their documentation is the place to check the exact supported flow before implementation; this note makes no latency or delivery-rate ranking.
| Option | Integration focus | Trade-off for a subscriber login |
|---|---|---|
| Twilio Verify | Managed verification service | A natural candidate when verification is the core requirement. Evaluate its verification lifecycle and controls before reproducing them in application code; the subscriber's suppression policy still needs an explicit owner. |
| Amazon SNS SMS | SMS publishing within an AWS messaging service | Suitable when the application already owns the authentication challenge. Budget integration work for code generation, verification state, expiry, and consumption rather than treating SMS publishing as an authentication result. |
| Firebase Authentication phone sign-in | Phone authentication through Firebase's authentication flow | Suitable when the app wants an integrated identity flow. Evaluate the client and identity integration as part of the adoption cost, especially if the subscriber account system already lives elsewhere. |
Start with Verify when managing a verification lifecycle is the immediate job. Start with SNS when owning that lifecycle is an intentional architectural choice. Examine Firebase when identity integration is itself useful, rather than an extra dependency introduced just to send a text.
There isn't a fair winner without that context.
A solo founder shipping an AI reading assistant may prefer fewer service credentials, but an established publication with an existing identity system can reasonably prioritize compatibility with that system. Count the adapters, polling work, account mappings, and recovery screens. Unit delivery prices won't capture that maintenance burden.
A focused example: one challenge, two verification requests
The TypeScript below includes a read-only contract inspection and a local policy check. Configure INFRAI_DISCOVERY_URL with the public discovery URL for the sms.otp capability from your deployment configuration, and INFRAI_API_KEY with your server-side key. The contract inspection prints the request schema instead of guessing send fields. Public discovery does not require authentication; this server-side example includes the configured credential to illustrate the adapter's Bearer convention. It sends no SMS and makes no authentication decision from a delivery receipt.
The synthetic subscriber is already suppressed in the first case. In the second, two callers try to consume the same challenge. Exactly one succeeds.
async function inspectOtpContract(): Promise<void> {
const discoveryUrl = process.env.INFRAI_DISCOVERY_URL;
const key = process.env.INFRAI_API_KEY;
if (!discoveryUrl || !key) {
throw new Error("Set INFRAI_DISCOVERY_URL and INFRAI_API_KEY");
}
const target = new URL(discoveryUrl);
if (target.protocol !== "https:") {
throw new Error("Discovery requires HTTPS");
}
for (let attempt = 0; attempt < 3; attempt += 1) {
const response = await fetch(target, {
method: "GET",
headers: { Authorization: `Bearer ${key}` },
signal: AbortSignal.timeout(10_000)
});
if (response.status === 429 && attempt < 2) {
const retryAfter = response.headers.get("Retry-After");
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const date = retryAfter === null ? NaN : Date.parse(retryAfter);
const delay = Number.isFinite(seconds)
? Math.max(0, seconds * 1000)
: Number.isFinite(date)
? Math.max(0, date - Date.now())
: 500 * 2 ** attempt;
if (delay > 30_000) throw new Error("Retry later");
await response.body?.cancel();
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (!response.ok) {
throw new Error(`Discovery HTTP ${response.status}: ${await response.text()}`);
}
const contract = await response.json() as Record<string, unknown>;
if (contract.id !== "sms.otp" || !contract.params) {
throw new Error("Unexpected discovery contract");
}
console.log(JSON.stringify(contract.params, null, 2));
return;
}
throw new Error("Discovery retry budget exhausted");
}
inspectOtpContract().catch(error => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
type Challenge = {
accountId: string;
expiresAt: number;
attemptsLeft: number;
consumed: boolean;
};
type Decision =
| "suppressed"
| "expired"
| "locked"
| "replayed"
| "invalid"
| "accepted";
function consume(
challenge: Challenge,
suppressed: boolean,
verified: boolean,
now: number
): Decision {
if (suppressed) return "suppressed";
if (challenge.consumed) return "replayed";
if (now >= challenge.expiresAt) return "expired";
if (challenge.attemptsLeft <= 0) return "locked";
challenge.attemptsLeft -= 1;
if (!verified) return "invalid";
challenge.consumed = true;
return "accepted";
}
function assertEqual(actual: Decision, expected: Decision): void {
if (actual !== expected) {
throw new Error(`Expected ${expected}, received ${actual}`);
}
}
const now = Date.now();
const challenge: Challenge = {
accountId: "subscriber-42",
expiresAt: now + 120_000,
attemptsLeft: 3,
consumed: false
};
assertEqual(consume(challenge, true, true, now), "suppressed");
assertEqual(consume(challenge, false, false, now), "invalid");
assertEqual(consume(challenge, false, true, now), "accepted");
assertEqual(consume(challenge, false, true, now), "replayed");
const expired: Challenge = {
accountId: "subscriber-43",
expiresAt: now,
attemptsLeft: 3,
consumed: false
};
assertEqual(consume(expired, false, true, now), "expired");
console.log("Local challenge policy checks passed.");
Run the sample in a TypeScript-capable runtime. Its synchronous mutation only demonstrates the state transition within one process. In production, reserve verification attempts atomically before calling the verifier, so concurrent wrong submissions cannot exceed the budget while external requests are in flight. After a successful result, recheck eligibility and expiration, then consume the challenge with a database transaction or conditional write that permits only one winner.
That final check matters.
A provider's successful response might arrive after the application deadline, or after a suppression change. The application must evaluate its current state before authorizing a session. Bind the challenge to the intended account and login operation, and make session issuance recoverable through the same logical operation so a network retry cannot mint independent sessions.
A resend also needs a defined policy. Decide which challenge remains valid and how the shared attempt budget behaves; document the rule in the adapter contract. Don't silently reset a lockout each time a subscriber presses resend. For delivery requests, honor rate-limit responses with bounded exponential backoff and Retry-After where present, and use a documented idempotency mechanism before retrying a write. A timeout isn't evidence that the first send failed.
What should be measured before shipping?
Begin with synthetic recipients and controlled concurrent requests. Measure rejected sends to suppressed destinations, attempts admitted beyond the configured budget, and successful consumes per challenge. The expected acceptance criteria are zero, zero, and at most one, respectively. Those are test targets, not production measurements.
Then measure the integration cost: how quickly suppression changes reach the admission gate, how much polling is needed, and how long a legitimate subscriber waits after requesting a code. Record provider response time separately from application checks and session creation. Otherwise a single end-to-end number hides the component that needs work.
Keep OTPs out of logs and model prompts. Correlate decisions with an internal challenge identifier and record why admission was rejected without retaining the code. Test a suppressed phone, an expired challenge, an exhausted attempt budget, a repeated successful verification, and simultaneous submissions. Include a bounced email paired with an eligible phone to verify that channel-specific suppression stays channel-specific.
Ship when those properties hold and recovery is understandable. Expand the provider abstraction only when a second integration exposes a real difference worth supporting. For this media workflow, the smallest useful boundary is a deterministic subscriber-admission policy plus an atomic authentication transition. Everything else should earn its place.
References
- NIST SP 800-63B, Digital Identity Guidelines: https://pages.nist.gov/800-63-3/sp800-63b.html
- Twilio Verify documentation: https://www.twilio.com/docs/verify
- Amazon SNS SMS documentation: https://docs.aws.amazon.com/sns/latest/dg/sns-mobile-phone-number-as-subscriber.html
- Firebase Authentication phone sign-in documentation: https://firebase.google.com/docs/auth/web/phone-auth
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.