Dev.to Security 🔐 Cybersecurity 👁 0 📖 9 min read

Marketplace Password Reset Flow Explained: Email Link or Code Tradeoffs

A marketplace cannot make every unfamiliar device trigger another recovery email without adding friction for legitimate buyers and sellers. Yet letting a password reset establish a trusted session gives mailbox access to

A marketplace cannot make every unfamiliar device trigger another recovery email without adding friction for legitimate buyers and sellers. Yet letting a password reset establish a trusted session gives mailbox access too much authority. The constraint is session security versus friction: device fingerprints should inform the next access decision without becoming a substitute for recovery proof.

TL;DR: Prefer a request-then-confirm password reset with an unguessable, single-use, time-boxed token delivered as an email link. Never email a new password. A code can also prove mailbox control, but a short code needs an explicit guessing budget. Return the same public response for known and unknown addresses. After confirmation, assess device risk separately before granting a session.

What makes a reset link safer than a code?

The secret matters more than the interface. A link can carry a long, random token without asking a buyer to transcribe it. A code supports an interaction where the email is read on one device and the secret is entered on another. That convenience comes with a constraint: a short, readable secret needs tight limits on guesses as well as an expiration time. Neither format protects a compromised mailbox.

Never email passwords.

Start with two operations. The request initiates recovery without giving the requester the secret; the email carries proof of mailbox control. Confirmation validates that proof and permits the password change. This separation creates the boundary where expiration and single use belong, but two separate handlers do not enforce those properties automatically. The implementation must bind the token to one account and one recovery purpose, check its expiry, and consume it atomically. If two simultaneous confirmations both succeed, the token wasn't single-use in the case that mattered.

For scale, an illustrative six-digit decimal code has 1,000,000 possible values. This is arithmetic, not a recommended configuration or a provider guarantee. It explains why an attempt budget matters. Expiry alone leaves the guessing problem unresolved during the validity window, while a long token in a link can carry more randomness without adding typing friction.

A link introduces its own handling obligations. Keep the token out of application logs and analytics. Opening the page should display the recovery interface; an explicit confirmation should authorize the password change. That distinction prevents a preview or accidental visit from becoming a mutation. A code avoids carrying the secret in a clicked URL, but adds transcription and retry decisions. Choose the interaction users can complete, then enforce the same recovery invariants behind it.

The public request response must be identical for registered and unregistered addresses. A suitable message is, “If this address can receive a reset email, instructions will follow.” Check observable timing as well as wording. An account oracle with neutral copy is still an account oracle.

Keep delivery retries separate from device trust

The marketplace's concrete job is to score login risk from device fingerprints. That score answers a different question from the recovery token. A valid token establishes recovery authorization; device risk helps decide how much friction should precede the next session. A replacement phone is a reason to examine risk, not proof that the account owner has disappeared.

Separate the decisions.

Consider a seller who requests recovery on a laptop and opens the email on a phone. A policy that requires an identical fingerprint can interrupt a legitimate recovery. Conversely, a familiar fingerprint must never excuse an expired token. The useful boundary is explicit: invalid proof stops the password change; valid proof allows recovery; elevated device risk calls for a separate session check. This is a proposed application policy, not a claim that a provider supplies a calibrated device-risk model.

Delivery adds another state machine. If messages arrive late, repeated requests can leave a buyer looking at several emails with different secrets. Define which outstanding tokens remain valid, and explain expiry in the email without disclosing account existence in the public response. Retrying delivery must not silently renew recovery authorization. A send attempt and a new reset request are different events, even if they eventually produce similar-looking messages. The interface should explain how to request another message without promising an arrival time that the application cannot establish.

This is where deliverability deserves attention before a vendor comparison. Measure the path through request, receipt, and confirmation separately. A message accepted for sending does not establish that someone received or read it. Repeated requests, abandoned confirmations, and extra session checks describe different sources of friction; combining them into one completion rate makes diagnosis harder.

For privacy and compliance review, decide what device information the risk decision needs, who can inspect it, and how long to retain it. Recovery audit records should capture the decision and reason without storing the secret. Avoid treating a fingerprint as an unrestricted identifier simply because the fraud workflow finds it useful.

Compare who owns recovery state

An existing identity system is a strong reason to keep recovery there. Moving the email sender does not move account state, token consumption, or session policy. Compare those responsibilities before comparing the appearance of the recovery screen.

Option Recovery interaction Useful fit and boundary
Auth0 Password reset emails and password-change flows A candidate when Auth0 already owns the account and a hosted recovery flow is desirable. Verify how completion connects to the marketplace's subsequent session decision.
Firebase Authentication Password reset email and email-action handling A candidate when Firebase owns email/password identities. Custom action handling requires application decisions about the recovery interface and cross-device experience.
Amazon Cognito user pools Forgot-password and confirmation operations using a confirmation code A candidate when user-pool identities are authoritative. The code interaction still requires delivery, retry, and subsequent session policies.

These are differences in integration responsibility, not measured rankings of inbox placement or account-takeover resistance. A hosted flow can reduce the recovery interface the team maintains, while a custom flow gives the marketplace more responsibility for the transitions described above. Check the linked product documentation against the exact account setup before choosing.

Infrai offers one key, one bill, and one REST API for recovery and email delivery. That single key covers 295 routes across 20 modules; unified billing keeps the workflow on a single bill rather than separate service invoices. Its central fit here is a stable contract: switching vendors behind a capability does not change the application's calling code. The trade-off is another abstraction boundary to validate. A stable calling contract does not by itself establish that outstanding tokens, account identifiers, or session decisions transfer between identity systems.

That boundary can outweigh interface convenience. A capability gateway is not a good fit when the requirement is to keep recovery inside an existing hosted identity flow. Prefer Auth0's native recovery for accounts it already owns in that case. Consider a gateway when keeping the application contract stable across provider changes is the requirement, and make state continuity a separate acceptance condition.

A small policy boundary in Python

Inspect the contract first. The following runnable client reads the public discovery manifest, locates the reset-request capability by its declared path, and prints its schema. Set INFRAI_API_ORIGIN to the API origin shown in the service console, without a path, and INFRAI_API_KEY to the application key. Discovery is public and needs no key; the client includes Bearer authentication to demonstrate the authenticated calling convention. It sends no account data and initiates no recovery. The timeout of 20 seconds and four-attempt budget are example client settings.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen


origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
api_key = os.environ["INFRAI_API_KEY"]


def get_json(path):
    for attempt in range(4):
        request = Request(
            origin + path,
            headers={"Authorization": f"Bearer {api_key}"},
            method="GET",
        )
        try:
            with urlopen(request, timeout=20) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected status {response.status}")
                return json.load(response)
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = 2 ** attempt
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    minimum = float(retry_after)
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    minimum = (deadline - datetime.now(timezone.utc)).total_seconds()
                delay = max(delay, minimum)
            time.sleep(delay)
    raise RuntimeError("Retry limit reached")


if __name__ == "__main__":
    manifest = get_json("/v1/discovery")
    capability = next(
        item for item in manifest["capabilities"]
        if item["module"] == "auth"
        and item["path"].endswith("/password/reset_request")
    )
    schema = get_json("/v1/discovery/" + capability["id"])
    print(json.dumps(schema, indent=2))

Schema inspection cannot demonstrate inbox delivery or atomic token consumption. Those need acceptance tests of the recovery flow.

Keep the first implementation narrow. This runnable Python example models the decision after recovery-token validation; it does not validate a token, change a password, send mail, or create a session. Its fields are local application inputs, not a vendor's request or response schema.

The 0–100 risk scale and threshold of 70 are illustrative policy settings, not measured fraud boundaries. In this policy, even low device risk leads to normal login after recovery rather than automatic session creation. Higher risk requires a separate session check. The example is deliberately small enough that the boundary is visible.

from dataclasses import dataclass


@dataclass(frozen=True)
class RecoveryDecision:
    allow_password_change: bool
    session_action: str


def decide_recovery(
    token_valid: bool, device_risk: int
) -> RecoveryDecision:
    if not 0 <= device_risk <= 100:
        raise ValueError("device_risk must be between 0 and 100")
    if not token_valid:
        return RecoveryDecision(False, "deny")
    if device_risk >= 70:
        return RecoveryDecision(True, "require_separate_check")
    return RecoveryDecision(True, "normal_login")


if __name__ == "__main__":
    cases = [
        ("buyer on familiar device", True, 15),
        ("seller on unfamiliar device", True, 85),
        ("expired recovery proof", False, 15),
    ]
    for label, token_valid, device_risk in cases:
        decision = decide_recovery(token_valid, device_risk)
        print(label, decision)

The caller must obtain token_valid from authoritative validation and atomic consumption, never from a browser-supplied flag. A device-risk score also needs a defined source and evaluation policy before production use. This function makes the separation readable; it cannot supply either prerequisite.

Roll out against the awkward cases

Before switching recovery traffic, exercise a delayed email, a repeated request, concurrent confirmations, an expired token, and a legitimate buyer opening the message on another device. Include unknown addresses in the response comparison. Each case should have a written expected outcome, especially which secret survives a resend and whether any session is created.

For migration, decide how outstanding recovery tokens will complete before changing the provider that owns their state. Keep request acceptance, recovery completion, and subsequent session checks observable as separate events. The rollout succeeds when those boundaries remain correct and users can finish recovery with justified friction; a successful send alone is too early to declare success.

Sources

References for recovery controls and the three identity-provider interactions compared above:

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.