Adding a verification link to resident signup reduces typing, but gives the application another credential to protect. Resolve that trade-off by making the link and the SMS code alternate inputs to one pending signup, with one expiry and one failed-attempt budget. TL;DR: passwordless phone login needs a server-enforced resend cooldown, cumulative maximum attempts, and admission controls that survive a fresh signup request. Keep those decisions outside the message transport. That keeps integration effort focused on a small, testable state transition.
The concrete job is delivering a verification link during property-management account signup. A resident can follow that link or enter an SMS OTP. The state contract applies at the request boundary of an Express or Node.js application. The runnable example uses Python for notebook-to-prod checks. The angle is credential exposure: every resend changes what a resident can present, what a worker can deliver, and what a log must exclude.
The data flow is short. Admission checks create a pending signup bound to a destination; a send operation reserves a delivery and supplies a code and link token to the message adapter; a confirmation operation checks either credential against that signup and consumes it once. A resend replaces both credentials without resetting failed guesses or extending the original deadline.
Exercise credential replacement before wiring delivery
Start with the transition that is easiest to hide behind an SDK: replacing credentials while keeping the abuse budget. This standard-library script uses synthetic resident data and an in-memory delivery callback. Its 30-second cooldown, 300-second lifetime, five-failure cap, and three-send cap are illustrative application policy, not service requirements or measured recommendations.
from dataclasses import dataclass
from hashlib import sha256
import hmac
import secrets
from threading import Lock
from urllib.parse import urlencode
@dataclass
class PendingSignup:
destination: str
deadline: float
next_send: float = 0
sends: int = 0
failures: int = 0
consumed: bool = False
code_digest: str = ""
link_digest: str = ""
class Verification:
def __init__(self, clock, deliver):
self.clock = clock
self.deliver = deliver
self.key = secrets.token_bytes(32)
self.rows = {}
self.lock = Lock()
def digest(self, signup, kind, value):
data = f"{signup}:{kind}:{value}".encode()
return hmac.new(self.key, data, sha256).hexdigest()
def begin(self, destination):
# The caller must first enforce admission controls.
signup = secrets.token_urlsafe(16)
with self.lock:
self.rows[signup] = PendingSignup(
destination, self.clock() + 300
)
return signup
def send(self, signup):
with self.lock:
row = self.rows.get(signup)
now = self.clock()
if row is None or row.consumed or now >= row.deadline:
return "closed"
if row.failures >= 5 or row.sends >= 3:
return "limited"
if now < row.next_send:
return "cooldown"
code = f"{secrets.randbelow(1_000_000):06d}"
token = secrets.token_urlsafe(32)
row.code_digest = self.digest(signup, "code", code)
row.link_digest = self.digest(signup, "link", token)
row.sends += 1
row.next_send = now + 30
query = urlencode({"signup": signup, "token": token})
message = {
"destination": row.destination,
"code": code,
"link": "https://signup.example/verify?" + query,
}
self.deliver(message)
return "accepted"
def confirm(self, signup, kind, value):
with self.lock:
row = self.rows.get(signup)
if row is None or row.consumed or self.clock() >= row.deadline:
return False
if row.failures >= 5 or row.sends == 0:
return False
if kind not in ("code", "link"):
return False
expected = row.code_digest if kind == "code" else row.link_digest
if not hmac.compare_digest(
expected, self.digest(signup, kind, value)
):
row.failures += 1
return False
row.consumed = True
return True
clock = [0.0]
messages = []
flow = Verification(lambda: clock[0], messages.append)
signup = flow.begin("+12025550123")
assert flow.send(signup) == "accepted"
old_link_digest = flow.rows[signup].link_digest
assert flow.send(signup) == "cooldown"
assert not flow.confirm(signup, "code", "wrong")
clock[0] = 30.0
assert flow.send(signup) == "accepted"
assert flow.rows[signup].failures == 1
assert flow.rows[signup].link_digest != old_link_digest
assert flow.confirm(signup, "code", messages[-1]["code"])
assert not flow.confirm(signup, "code", messages[-1]["code"])
One budget survives.
The callback receives plaintext credentials because it must construct the message. The stored record receives keyed digests instead. Code and link inputs have separate digest domains, and the signup identifier participates in each digest. These are properties of this example, not claims about a messaging service. Keeping the callback small also lets an eval harness collect messages without sending anything to a resident.
This script deliberately ends at a process boundary. Its dictionary, lock, and generated key live in one process; restarting loses the records, and another worker cannot coordinate through that lock. A production implementation needs shared persistent state, atomic transitions, and securely managed key material. Also notice the ordering: a delivery reservation is consumed before the callback runs. If the callback raises, the reservation remains consumed. Make that behavior explicit before replacing the callback with a network call.
What should SMS OTP prove during passwordless phone login?
For this design, it proves only that the submitted credential matches the pending signup's configured verification condition. It must not independently grant access to an apartment, lease, or another resident's account. Those authorization decisions need separate records and checks. Keeping that boundary explicit avoids making a convenient signup feature carry property-access meaning it was never designed to establish.
Treat the URL as a credential.
Use a landing page with an explicit confirmation action before consumption, and include automated link fetching in the test cases. Do not let an initial page fetch mark an account verified. Keep the token out of analytics, request logs, and page resources that could receive the URL; redaction needs to cover the complete delivery path, including exception reporting. A replacement link should invalidate its predecessor, and the signup screen should explain that only the latest message works. This chooses fewer outstanding credentials at the expense of friction when messages arrive late.
Changing the destination also changes the verification context. Bind the new context server-side and apply admission limits again; a credential delivered to the previous phone number must not verify the replacement destination. Conversely, simply creating another pending signup cannot be allowed to restore an unlimited guessing or sending allowance. The per-signup state machine is useful precisely because its boundary is clear. It isn't the entire abuse defense.
Compare the work introduced by each signup path
The useful comparison is between application behaviors, with integration effort measured in the state and UI responsibilities the team must own. These are design choices, not product rankings.
| Signup path | Application connection | Integration work | Suitable interaction | Main constraint |
|---|---|---|---|---|
| Typed SMS code | Send adapter plus code confirmation | Code entry, resend feedback, shared attempt counter | Resident copies a code into the signup screen | Guess limits must remain effective across resends |
| Verification link | Send adapter plus confirmation page | Token redaction, explicit confirmation, replacement handling | Resident opens a link from the message | Automated fetching must not consume the credential |
| Both inputs for one signup | Both confirmations call one consumption operation | Reconcile credentials, deadline, and failure budget once | Resident chooses the available interaction | Resending must replace both inputs consistently |
Don't hide this work in the transport wrapper. A send acceptance is an observation about submission, not evidence that the resident received or confirmed anything. Name events accordingly. If the message adapter accepts a request but the signup remains pending, that state should be intelligible to both the UI and the operator.
SMS message construction deserves its own fixture. The character-limit reference below explains segmentation and the distinction between GSM-7 and UCS-2 encoding. Evaluate the actual rendered message, including the complete verification URL and representative localized text. Testing a short template without its token-bearing URL misses the thing the resident receives. This is a content and integration check; no changing unit price is needed to justify it.
For an AI application, keep the authentication decision deterministic. A model can help draft explanatory signup copy, but it has no role in deciding whether a token matches a stored digest. Passing resident destinations or credentials into that prompt adds sensitive inputs and prompt cost without helping the comparison. Use separate evals: copy quality belongs in the language workflow; single-use consumption belongs in state-transition checks. That's a useful notebook-to-prod boundary to preserve.
Release by checking exposure and budget invariants
Before deployment, make the eval harness challenge the boundaries rather than merely reproduce a successful signup. At 29 seconds the illustrative cooldown still blocks a resend; at 30 it permits one if the other budgets remain available. At 300 seconds the challenge is closed. Exercise five failed submissions distributed across multiple sends, then try the correct credential. Race two successful confirmations and check that exactly one consumes the pending signup. These are proposed checks derived from the example policy, not benchmark results.
Test delayed delivery too.
When moving the example into persistent storage, update the challenge and enqueue its delivery job in one transaction. Give the job a stable identity and a bounded retry policy, and decide whether the send budget counts logical sends or transport submissions. Associate queued work with the credential generation so a delayed worker can identify superseded work before submission. Once a message is in flight, ordering remains outside the verification endpoint's authority; the endpoint must reject superseded credentials regardless of arrival order. Successful consumption and the account's verification update also belong in one transaction. Otherwise, consuming a credential and failing to update the account leaves the resident stuck between two states.
Finish the release check by examining the information that crosses each boundary. Confirm that logs contain outcomes and correlation identifiers rather than codes, tokens, or full resident destinations. Apply admission and request controls across signup creation, sends, and verification, considering destination and source network rather than relying on a single pending record. Use generic external responses where revealing account existence would be inappropriate. Then verify that a resident can understand an expired message and retry within the configured policy.
The integration decision is ready when those checks describe one coherent signup contract: delivery can be retried, credentials can be replaced, and neither action silently restores the guessing budget. Keep that contract small enough to run in a notebook and strict enough to enforce across production workers.
Sources
References: the SMS character-limit documentation supports the message-encoding and segmentation discussion. The code and numerical thresholds above are an illustrative application design, not provider defaults.
Top comments (0)