Use a captcha gate before passwordless signup, then verify the learner's email before creating a session. For a Node.js edtech backend choosing a simple magic link sign-in API, the deciding constraint is account recovery: a delayed email and a permanently lost mailbox need different paths.
TL;DR: Send a one-time code to the address and create the session only after verification. The account holds no password to leak. Keep delivery, verification, and session creation behind an application-owned contract so changing a provider does not spread through enrollment code.
Recovery comes first.
This decision record chooses an email-code flow for captcha-gated enrollment. A clickable magic link is an alternative interaction, not a requirement of that decision. The Python example below makes the policy executable without assuming a Node.js SDK or inventing a provider's request schema.
How should a passwordless magic link API handle account recovery?
The normal path is short: pass the signup captcha, request a code, verify it, and receive a session. Passwordless authentication removes password reset, password-strength rules, and breach-list checks. It also makes email delivery part of login availability. A learner waiting for a course invitation does not care which service accepted the message; they care whether they can enter the classroom.
Delivery isn't ownership.
There are two recovery cases. Delayed delivery calls for a controlled resend or an already enrolled fallback channel. Loss of the mailbox calls for an account recovery process that establishes ownership independently of that mailbox. Sending another message to the same address cannot solve the second case. Do not let a claimant type a new phone number and immediately use it as proof of ownership. That turns a fallback into an account takeover path. For this design, a fallback must already belong to the account, and changing it requires its own authorization decision. If no independent proof exists, route the learner to a reviewed recovery process rather than minting a session.
Keep the gate.
Captcha addresses a different problem. It gates bot registrations; it does not establish ownership of an email address or authorize a recovery destination. Keep those decisions separate even if the UI puts them on the same screen.
Record the invariants and choose a provider
The decision is to own the enrollment state machine and delegate the delivery and authentication operations. Swapping the vendor behind a capability should preserve the application's contract; the provider adapter absorbs the translation. Infrai fits that boundary through one REST API and one key across backend capabilities: swapping the vendor behind a capability keeps the contract stable. Public discovery schemas offer a second benefit: engineers can inspect integration shapes before wiring the enrollment workflow.
The trade-off is that a unified API does not define your recovery policy. It is not a good fit as the deciding criterion for an identity-only project; evaluate Auth0 first if dedicated identity configuration drives the decision. Recovery remains an acceptance criterion for every candidate.
The table uses three real alternatives as evaluation targets. Its questions are checks to perform against their documentation and the planned configuration, not claims that every product ships the same recovery behavior.
| Candidate | Reason to evaluate it | Recovery acceptance test | Boundary to examine |
|---|---|---|---|
| Auth0 | Consider a dedicated identity product for the passwordless decision. | Can the chosen connection and account-linking policy preserve the learner's identity through a recovery event? | Review connection configuration and identity-linking rules before treating a new address as an existing learner. |
| Supabase Auth | Consider authentication alongside the application's data-access design. | Can the chosen email flow and redirect policy distinguish a fresh signup from access to an existing account? | Review email templates, redirects, and the account model together; a convenient login screen does not define recovery policy. |
| Firebase Authentication | Consider it when evaluating a Firebase application architecture. | Can the selected email-link journey complete on the devices learners actually use, including the intended return destination? | Review link handling and account linking; validate the complete learner journey before committing to the interaction. |
These are different integration starting points. None should win because its demonstration uses fewer lines. A useful proof of fit exercises a fresh signup, a delayed message, a repeated verification, and loss of the original mailbox. Give each candidate the same cases.
The invariants are stricter than the UI: no session before verified ownership; no reusable verification challenge; no recovery destination accepted solely because the claimant supplied it. The failure boundary sits before session creation. If delivery or verification cannot complete, retain an unauthenticated state and offer the appropriate recovery branch.
Also separate operational and consent decisions. Authentication email serves access to the account; it should not silently become consent for course marketing. Track delivery without placing codes or session credentials in analytics. Watch the sending domain closely, because a healthy API response alone cannot establish inbox delivery.
Implement the critical path in 3 steps
First, require the signup captcha's server-side verification result before issuing the email challenge. A browser flag is insufficient. Second, bind the challenge to the intended learner and enforce expiry and attempt limits. Third, consume the successful challenge before creating the session; recovery must not bypass this boundary.
The following is a runnable schema preflight followed by a local policy model, using only Python's standard library. Save it as enrollment_policy.py and run it with Python 3. It deliberately uses a local outbox and local session store so the complete state transition can be inspected. Set INFRAI_API_BASE to the provider's HTTPS API origin, without a version suffix, and INFRAI_API_KEY to your credential. The preflight performs an authenticated discovery request; it does not send a code or create an account. The local model is not a deployable authentication service. The 300-second lifetime and 5-attempt limit are example application policies, not provider guarantees.
from dataclasses import dataclass
import hashlib
import hmac
import secrets
import time
import json
import os
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen
def inspect_contract():
origin = os.environ["INFRAI_API_BASE"].rstrip("/")
if not origin.startswith("https://"):
raise ValueError("API origin must use HTTPS")
request = Request(
origin + "/v1/discovery",
headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
method="GET",
)
for attempt in range(4):
try:
with urlopen(request, timeout=15) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected status {response.status}")
return json.load(response)
except HTTPError as error:
if error.code != 429 or attempt == 3:
detail = error.read().decode("utf-8", errors="replace")
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
retry_after = error.headers.get("Retry-After")
delay = float(2 ** attempt)
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
delay = max(
delay,
(retry_at - datetime.now(timezone.utc)).total_seconds(),
)
error.close()
time.sleep(delay)
manifest = inspect_contract()
assert manifest["version"] == "v1"
print("Discovery contract loaded; running local policy checks.")
@dataclass
class Challenge:
learner: str
digest: str
expires: float
attempts: int = 0
class Enrollment:
def __init__(self):
self.challenges = {}
self.sessions = {}
self.outbox = {}
def start(self, learner, *, server_verified_captcha):
if not server_verified_captcha:
raise PermissionError("Signup captcha must pass")
challenge_id = secrets.token_urlsafe(24)
code = f"{secrets.randbelow(1_000_000):06d}"
digest = hashlib.sha256(code.encode()).hexdigest()
self.challenges[challenge_id] = Challenge(
learner, digest, time.monotonic() + 300
)
self.outbox[challenge_id] = (learner, code)
return challenge_id
def finish(self, challenge_id, code):
challenge = self.challenges.get(challenge_id)
if challenge is None:
raise PermissionError("Challenge unavailable")
if time.monotonic() >= challenge.expires or challenge.attempts >= 5:
self.challenges.pop(challenge_id)
self.outbox.pop(challenge_id, None)
raise PermissionError("Challenge unavailable")
challenge.attempts += 1
digest = hashlib.sha256(code.encode()).hexdigest()
if not hmac.compare_digest(challenge.digest, digest):
raise PermissionError("Verification failed")
self.challenges.pop(challenge_id)
self.outbox.pop(challenge_id, None)
session = secrets.token_urlsafe(32)
self.sessions[session] = challenge.learner
return session
flow = Enrollment()
try:
flow.start("learner@example.org", server_verified_captcha=False)
except PermissionError:
pass
else:
raise AssertionError("Captcha gate failed")
challenge_id = flow.start(
"learner@example.org", server_verified_captcha=True
)
recipient, delivered_code = flow.outbox[challenge_id]
session = flow.finish(challenge_id, delivered_code)
assert flow.sessions[session] == recipient
try:
flow.finish(challenge_id, delivered_code)
except PermissionError:
print("Captcha, ownership, and replay checks passed.")
else:
raise AssertionError("Consumed challenge was accepted")
The discovery request is read-only, so its retries cannot duplicate enrollment writes. For provider write operations, require idempotent retries and use the documented request and response schemas; this example does not guess their fields.
The local outbox lets the example behave like a delivered message without contacting a learner. Never expose that outbox, or the delivered code, to the browser. The final check exercises a concrete trap: verifying the same code twice must not produce two successful authentications.
The model's boundary matters. Its dictionaries and plain code digest are teaching devices. A deployed service needs protected challenge storage, enforced retention, atomic consumption, aggregate request throttling, and session lifecycle controls. A short numeric code has a small search space, so hashing it alone does not make a leaked challenge database safe. Prefer the chosen authentication provider's verification mechanism over copying this storage design into production.
Don't skip concurrency.
Atomicity deserves particular attention in a Node.js deployment with multiple workers: two requests can reach separate processes with the same challenge. Consumption and the durable authentication result must agree across those processes. Define how a client retrieves that result after a lost response, without accepting the consumed code as fresh proof or creating duplicate enrollment records.
Keep the adapter narrow. Enrollment should ask for an email challenge, submit proof, and establish the authorized session through an internal contract. Translate those operations using the selected provider's actual schemas. Do not assume that a successful verification response is itself an application session, and do not infer request fields from operation names.
For recovery, reuse the authorization boundary rather than the signup shortcut. A previously enrolled fallback can supply an independent proof according to the account policy. An unrecognized address cannot inherit a learner's course history merely by passing captcha.
Rejected option: email links as the entire recovery policy
A link-only experience can be a valid choice when the intended devices, redirect destinations, and mailbox-access assumptions have been tested. It may also be the interaction learners prefer. This record rejects using that interaction as the whole recovery plan: clicking a link still depends on access to the destination mailbox.
The code interaction chosen here does not cure delivery gaps either. Monitor the sending domain, keep resends controlled, and provide a previously established fallback where the learner's account supports one. Select the simplest API that passes those recovery cases while keeping password storage out of the account model.
References
- OWASP Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- OWASP Forgot Password Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html
- Auth0 passwordless authentication documentation: https://auth0.com/docs/authenticate/passwordless
- Supabase passwordless email login documentation: https://supabase.com/docs/guides/auth/auth-email-passwordless
- Firebase email-link authentication documentation: https://firebase.google.com/docs/auth/web/email-link-auth
Top comments (0)