Gate logistics phone login on suppression status, resend cooldowns, and server-owned attempt limits, then log why each SMS OTP request was admitted or blocked. A dispatch desk needs to distinguish an invalid recipient from a courier who tapped “resend” too soon. Those conditions need different responses.
TL;DR: For passwordless phone login in Express and Node.js, keep send-code, verify-code, resend-code, and lockout states in your backend. Check suppression before delivery. Apply increasing cooldowns and daily caps across phone, IP, and device. Measure policy decisions separately from delivery evidence. An accepted request isn't proof of a completed login.
The useful unit is a login challenge, tied to a delivery attempt. A shipment identifier can provide business context, but it must not become an authentication credential. This walkthrough uses fictional dispatch data.
How should passwordless phone login handle SMS OTP resend attempts?
Before: a resend button produces another request, and the dashboard counts sends. The count rises. The courier still cannot enter the dispatch portal.
After: the backend records a reason for every decision. Suppression stops attempts to a blocked number. A cooldown rejects an impatient repeat. Delivery submission gets its own identifier, while verification retains a separate outcome. Now an operator can ask: did the request reach delivery, or did policy stop it first?
Here is the diagram in words: dispatch login → backend policy → suppression check → delivery submission → status polling → verification outcome. A denial exits before submission. A resend returns through policy.
Keep the distinctions.
Bounce handling for emailed dispatch notices and SMS suppression belong in the same operational conversation, but they are different channel signals. An email bounce doesn't establish that a phone number is invalid. Use the suppression decision for the destination and channel you're about to contact.
Build one executable policy walkthrough
Start with an inspectable contract. Infrai pairs a plain REST API with unified billing and a single key across 295 routes in 20 modules, so a dispatch backend can keep email and SMS credential handling together without installing an SDK. Its public, self-describing discovery supplies request and response schemas without requiring a key. The operational benefit here is one credential boundary for both channels; it does not merge their suppression decisions.
The following TypeScript file reads the OTP capability schema, then runs a local admission-policy exercise. It sends no SMS and grants no session. Save it as otp-policy.ts and run node otp-policy.ts on Node.js v24. Configure INFRAI_BASE_URL with the documented v1 base URL, including a trailing slash, and supply INFRAI_API_KEY through the environment. The authenticated GET illustrates the same explicit authentication pattern used for protected calls; discovery itself is public.
There are three policy steps: reserve a send, carry the same limits into a resend, and record verification lockout. The 30/60/120-second cooldowns, three-send daily cap, five-attempt maximum, and five-minute expiry below are illustrative application settings. They aren't provider defaults.
import assert from "node:assert/strict"; const baseURL = process.env.INFRAI_BASE_URL; const apiKey = process.env.INFRAI_API_KEY; if (!baseURL || !apiKey || !baseURL.endsWith("/")) { throw new Error("Set INFRAI_BASE_URL with a trailing slash and INFRAI_API_KEY"); } const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); async function inspectContract(): Promise<void> { const url = new URL("discovery/sms.otp", baseURL); for (let attempt = 0; attempt < 4; attempt += 1) { const response = await fetch(url, { method: "GET", headers: { Authorization: `Bearer ${apiKey}` }, signal: AbortSignal.timeout(15_000), }); if (response.status === 429 && attempt < 3) { const retryAfter = response.headers.get("Retry-After"); const seconds = retryAfter === null ? NaN : Number(retryAfter); const date = retryAfter === null ? NaN : Date.parse(retryAfter); const requested = Number.isFinite(seconds) ? seconds * 1_000 : Number.isFinite(date) ? date - Date.now() : 0; await response.body?.cancel(); await pause(Math.max(1_000 * 2 ** attempt, requested, 0)); continue; } if (!response.ok) { throw new Error(`Discovery ${response.status}: ${await response.text()}`); } const schema = await response.json(); console.log(JSON.stringify({ capability: schema.id, method: schema.method, path: schema.path, params: schema.params, })); return; } } await inspectContract(); type Context = { phoneKey: string; ipKey: string; deviceKey: string }; type Challenge = { state: "sent" | "locked" | "verified"; attempts: number; sends: number; nextSendAt: number; expiresAt: number; }; const cooldowns = [30_000, 60_000, 120_000]; const dailyCap = 3; const maxAttempts = 5; const daily = new Map<string, number>(); const events: { action: string; reason: string }[] = []; function record(action: string, reason: string): string { events.push({ action, reason }); console.log(JSON.stringify({ action, reason })); return reason; } function reserveSend( context: Context, challenge: Challenge | undefined, suppressed: boolean, now: number ): string { const action = challenge ? "resend-code" : "send-code"; if (suppressed) return record(action, "suppressed"); if (challenge?.state === "locked") return record(action, "locked"); if (challenge?.state === "verified") return record(action, "completed"); if (challenge && now >= challenge.expiresAt) { return record(action, "expired"); } if (challenge && now < challenge.nextSendAt) { return record(action, "cooldown"); } const day = Math.floor(now / 86_400_000); const keys = [ `phone:${context.phoneKey}:${day}`, `ip:${context.ipKey}:${day}`, `device:${context.deviceKey}:${day}`, ]; if (keys.some((key) => (daily.get(key) ?? 0) >= dailyCap)) { return record(action, "daily-cap"); } for (const key of keys) daily.set(key, (daily.get(key) ?? 0) + 1); return record(action, "admitted"); } function noteSubmission(challenge: Challenge, now: number): void { const index = Math.min(challenge.sends, cooldowns.length - 1); challenge.sends += 1; challenge.nextSendAt = now + cooldowns[index]; } function verificationResult( challenge: Challenge, trustedProviderMatch: boolean, now: number ): string { if (challenge.state !== "sent") return record("verify-code", challenge.state); if (now >= challenge.expiresAt) return record("verify-code", "expired"); challenge.attempts += 1; if (trustedProviderMatch) { challenge.state = "verified"; return record("verify-code", "verified"); } if (challenge.attempts >= maxAttempts) { challenge.state = "locked"; return record("verify-code", "locked"); } return record("verify-code", "mismatch"); } const context: Context = { phoneKey: "courier-phone-token", ipKey: "dispatch-network-token", deviceKey: "handheld-token", }; const startedAt = Date.UTC(2026, 10, 24, 8); const challenge: Challenge = { state: "sent", attempts: 0, sends: 0, nextSendAt: startedAt, expiresAt: startedAt + 300_000, }; // Step 1: suppression wins before a send reservation is consumed. assert.equal(reserveSend(context, undefined, true, startedAt), "suppressed"); assert.equal(reserveSend(context, undefined, false, startedAt), "admitted"); noteSubmission(challenge, startedAt); // Step 2: a resend keeps its challenge and admission history. assert.equal(reserveSend(context, challenge, false, startedAt + 1_000), "cooldown"); assert.equal(reserveSend(context, challenge, false, startedAt + 30_000), "admitted"); noteSubmission(challenge, startedAt + 30_000); assert.equal(reserveSend(context, challenge, false, startedAt + 89_000), "cooldown"); assert.equal(reserveSend(context, challenge, false, startedAt + 90_000), "admitted"); noteSubmission(challenge, startedAt + 90_000); assert.equal(reserveSend(context, challenge, false, startedAt + 210_000), "daily-cap"); // Step 3: failed verification consumes the original attempt budget. for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { const expected = attempt === maxAttempts ? "locked" : "mismatch"; assert.equal(verificationResult(challenge, false, startedAt + 220_000), expected); } assert.equal(verificationResult(challenge, true, startedAt + 221_000), "locked"); assert.equal(reserveSend(context, challenge, false, startedAt + 222_000), "locked"); assert.equal(events.filter((event) => event.reason === "admitted").length, 3); Read the assertions.
The first checks suppression before consuming a send slot. The middle checks distinguish cooldown from daily cap. The last catches a specific pitfall: treating a resend as a new guessing budget. A resend must preserve both the attempt counter and the expiry window.
The map is process-local. In a production Express service, persist this state in your database and make check-and-reserve atomic across all three scopes. Otherwise, two workers can both read the last available slot and both send. Reserve verification attempts atomically before calling the verifier, then apply its result to the same challenge under concurrency control. The boolean in the exercise stands for a trusted verification result; never accept it from an HTTP request body. Bind access to the challenge on the server. Derive the IP through a configured trust boundary. Treat a client-supplied device identifier as one imperfect signal, since a device label alone cannot establish identity. Finally, expire old daily buckets and decide how a new challenge interacts with an existing lockout: creating a new identifier must not erase a recipient's limits.
That's the boundary.
Connect delivery evidence to the decision log
Move admission policy into a service called by your send, resend, and verify handlers. Read request fields from the current delivery schema. The discovery call deliberately inspects that contract rather than guessing an OTP payload.
Log an internal challenge identifier, operation identifier, admission reason, and provider request identifier when available. Keep codes and raw phone numbers out of logs. Record submission latency separately from the time until verification.
Then count admitted sends, suppression denials, cooldown denials, cap denials, verification mismatches, and lockouts. Put identifiers in logs and low-cardinality reasons in metrics. Alert thresholds need your traffic baseline; a universal percentage would be invented.
The trade-off is status freshness: collect delivery and event evidence by polling, with an interval chosen for the dispatch workflow. This approach is not a fit for a design that requires immediate pushed delivery events. Geographic restrictions and country-based spend circuit breakers remain application responsibilities. An email fallback needs its own verification flow. Keep scheduled email outside a workflow that depends on cancellation, and keep SMTP relay, voice, WhatsApp, and RCS requirements outside this integration's scope. These are selection boundaries, not reasons to weaken authentication checks.
A transport retry and a user resend are different operations. Reuse the same idempotency key when retrying one write; give a newly admitted resend a new operation identifier. Back off on HTTP 429 and honor Retry-After, as the read-only contract example demonstrates. Check response statuses and retain actionable backend errors.
Never reset limits.
Would another delivery service change the policy?
The admission rules survive a provider change. Selection still matters, especially when dispatch notices and login messages share an operations team.
| Option | Useful comparison point | Boundary for this workflow |
|---|---|---|
| Twilio | Its SMS documentation explains GSM-7 and UCS-2 segmentation, useful when reviewing message content. | Segmentation guidance doesn't define your cooldowns or verification attempt budget. |
| Amazon SNS | Its SMS documentation offers a phone-messaging alternative to evaluate. | Validate the specific delivery workflow; don't assume a messaging interface owns the complete login state machine. |
| Amazon SES | Its email documentation is relevant to dispatch notices and email recovery. | Email delivery doesn't implement phone login. Keep channel-specific suppression and authentication state explicit. |
These are scope comparisons, not measured rankings. Evaluate delivery options against recipient destinations, suppression handling, status collection, and the evidence support can retain. Choose an email service for an email workflow; don't treat it as an equivalent SMS verifier.
Can cooldowns strand legitimate couriers?
Yes. A shared dispatch network makes the trade-off concrete: an IP cap can affect several legitimate couriers even when each phone is below its own cap. Keep all three scopes visible internally. The limitation of an IP-only policy is that it cannot distinguish those users reliably, so tune the scopes together rather than relying on one identifier.
Return a useful cooldown hint to the client. Calculate eligibility again on the server.
A disabled button helps the user; the database decides eligibility. Suppression also needs an explicit support or recovery path. Repeated resends cannot repair an invalid destination, and email recovery shouldn't silently inherit an SMS identity decision. The acceptance criterion is practical: every send has a reason, every retry preserves its operation identity, and every lockout has evidence support can interpret.

