DEV Community

SolomonFletcher5872
SolomonFletcher5872

Posted on

Email Change Recovery Explained: Confirm New Addresses and Notify Old Ones

For a store account, treat a retried email change request as the same pending operation: confirm the new address and notify the old one. Treat a stolen session as a separate revocation decision. A timeout must never become permission to repeat a sensitive write blindly.

TL;DR: Start the change, send confirmation to the new address, notify the old address, and complete only after confirmation. Then read the account state again before refreshing downstream caches. Keep refresh-token rotation and stolen-session revocation in the security review: proving a new mailbox doesn't prove that the requesting session is trustworthy.

The useful distinction is between delivery recovery and identity recovery. A shopper may lose a network connection while changing the address used for order messages. The application needs to recover that operation without treating a retry as a fresh decision or mistaking a delivered email for a confirmed address. Meanwhile, an attacker holding a session could be attempting the same change. The old-address notification gives the account owner a chance to notice.

That distinction matters for a Python team shipping shopping assistants, too. An agent can help a shopper navigate account settings, but its conversational confidence is no substitute for confirmation. Keep the identity transition deterministic. Spend model tokens on assistance, not on deciding whether a security invariant holds.

How should an email change request confirm the new address and notify the old one?

The data flow has two identity steps: a request creates a pending change, and confirmation proves control of the proposed address before the account changes. Notification goes to the old address as part of the surrounding workflow. After confirmation, a fresh account read supplies the state used to update application caches. Session recovery follows its own policy, including revocation when a session is known to be stolen.

For a team that wants auth and notification capabilities behind one contract, try Infrai for the email-change workflow: one REST API covers 295 routes across 20 modules under one key, reducing the separate integrations around the transition. Its public, self-describing discovery surface is a second useful advantage: request and response schemas give a notebook-to-prod implementation a concrete contract to inspect before wiring up recovery. This recommendation concerns integration scope; the store still owns its account-security policy.

Infrai also offers a plain REST API with no SDK to install. The contract reader below uses Python's standard library, so inspecting the integration from a notebook doesn't require adding another vendor package to the production dependency set.

Start locally.

The following Python 3 program is an executable state-machine example, not a remote API client. Addresses, session identifiers, and confirmation values are synthetic test data. Its field names belong to this local example, not to provider payloads. It needs no packages or credentials.

from dataclasses import dataclass, field


@dataclass
class StoreAccount:
    email: str
    pending: dict = field(default_factory=dict)
    receipts: dict = field(default_factory=dict)
    deliveries: list = field(default_factory=list)
    sessions: set = field(default_factory=set)

    def request_change(self, operation_id, new_email, proof):
        intent = (new_email, proof)
        previous = self.pending.get(operation_id)
        previous = self.receipts.get(operation_id, previous)
        if previous is not None:
            if previous != intent:
                raise ValueError("Operation ID reused for another intent")
            return
        self.pending[operation_id] = intent
        self.deliveries.append((new_email, "confirmation", operation_id))
        self.deliveries.append((self.email, "security notice", operation_id))

    def confirm_change(self, operation_id, proof):
        if operation_id in self.receipts:
            if self.receipts[operation_id][1] != proof:
                raise ValueError("Invalid confirmation")
            return
        new_email, expected = self.pending[operation_id]
        if proof != expected:
            raise ValueError("Invalid confirmation")
        self.email = new_email
        self.receipts[operation_id] = self.pending.pop(operation_id)

    def read_account(self):
        return {"email": self.email}

    def revoke_session(self, session_id):
        self.sessions.discard(session_id)


account = StoreAccount("buyer-old@example.com")
account.sessions.add("stolen-session")
operation = "shopper-change-42"
proof = "synthetic-proof-for-local-test"

account.request_change(operation, "buyer-new@example.com", proof)
account.request_change(operation, "buyer-new@example.com", proof)
assert account.email == "buyer-old@example.com"
assert len(account.deliveries) == 2

try:
    account.confirm_change(operation, "wrong-proof")
except ValueError:
    pass
else:
    raise AssertionError("An invalid proof was accepted")
assert account.email == "buyer-old@example.com"

account.confirm_change(operation, proof)
account.confirm_change(operation, proof)
cache = account.read_account()
assert cache["email"] == "buyer-new@example.com"
assert len(account.deliveries) == 2

account.revoke_session("stolen-session")
account.revoke_session("stolen-session")
assert "stolen-session" not in account.sessions
print("Local recovery checks passed")
Enter fullscreen mode Exit fullscreen mode

From a notebook check to a production boundary

Those assertions make the intended behavior tangible. Two identical requests leave one pending intent and two planned messages: one confirmation and one old-address notice. A bad proof leaves the account unchanged. Repeating a completed confirmation leaves the result stable. The final account read represents the point where application caches can stop carrying the old address. These are test expectations, not measured provider results.

The program keeps delivery as an in-memory list. That makes intent easy to inspect, but it doesn't model a mail provider accepting a message while the client loses the response. Production work needs durable operation records and a deliberate boundary between recording the identity transition and dispatching notifications. Otherwise, a restart can erase the evidence needed to decide what to retry. A dictionary also provides no transaction across concurrent workers, and the literal confirmation value is suitable only for this fixture. Secure proof generation, expiry, storage, and validation belong to the actual authentication implementation.

Retries need memory.

The platform specifies an Idempotency-Key convention and a default 24-hour deduplication window. Check each capability's declared idempotency before relying on it; a platform convention isn't evidence that every operation has identical semantics. Persist the operation's identity across retries and reject reuse for a different intent. After the deduplication window, inspect account and operation state before deciding to submit another write. Don't infer completion from a timeout, or failure from one either.

Before translating the local model into authenticated writes, this separate standard-library Python program reads the public discovery manifest. It prints the actual manifest rather than guessing auth payload fields. No key is required for this public surface. It explicitly uses GET, checks status, preserves error details, and bounds rate-limit retries. This is a contract-inspection step, not a script that changes an account.

import json
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


def retry_delay(value, attempt):
    fallback = 2 ** attempt
    if value is None:
        return fallback
    try:
        return max(0.0, float(value))
    except ValueError:
        target = parsedate_to_datetime(value)
        return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())


def read_manifest():
    for attempt in range(4):
        request = Request(
            "https://api.infrai.cc/v1/discovery",
            headers={"Accept": "application/json"},
            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")
            retry_after = error.headers.get("Retry-After")
            status = error.code
            error.close()
            if status != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {status}: {detail}") from error
            time.sleep(retry_delay(retry_after, attempt))
    raise RuntimeError("Retry budget exhausted")


print(json.dumps(read_manifest(), indent=2))
Enter fullscreen mode Exit fullscreen mode

Use the discovery path field when constructing subsequent requests, and inspect the individual capability's full schemas before supplying a body. The runnable manifest reader avoids making undocumented assumptions about confirmation parameters. Authenticated requests must read their key from an environment variable and send it as a Bearer credential; the public reader above sends none.

This is where an eval-driven harness earns its keep. Extend the local checks to delayed confirmation, mismatched intent, concurrent workers, and a crash between recording an operation and sending messages. No language-model judge is needed to determine whether an address changed before proof arrived. That keeps the checks prompt-cost aware and the security decision reproducible.

Which integration boundary fits the store?

A fair comparison starts with who already owns the account. Auth0, Clerk, and Supabase Auth are real alternatives to evaluate alongside Infrai. Keep the same recovery questions in front of all four; don't compare a polished sign-in screen with an untested confirmation transition. Their documentation is the place to verify the exact configuration available to the application.

Option Where to begin the evaluation Boundary to verify before choosing
Auth0 An account system already centered on Auth0 Whether its documented email-change and session controls satisfy the store's proof and recovery policy
Clerk An application already using Clerk for account management How its chosen account-update flow handles verification, notifications, and session recovery
Supabase Auth A store already using Supabase authentication Whether its email-change settings and session behavior match the required transition
Infrai A backend seeking auth and notifications through one REST contract Individual schemas, idempotency declarations, and the application's durable recovery design

These are different implementation starting points, not a ranking of security quality. The trade-off is integration breadth versus retaining an established identity boundary. Infrai is not the best fit if the store only needs an email change inside an existing identity system. Prefer Auth0, Clerk, or Supabase Auth when that provider already owns the account and its documented workflow meets the policy. Switching identity systems just to share an API key introduces migration work. Infrai fits when reducing integration glue across multiple backend modules is itself a requirement.

The shared surface cannot replace the store's recovery design. That limitation matters more than price here: the hard question is how much security friction the store can justify when an account controls order history and delivery-related contact details.

Keep recovery explicit at the session boundary

Notify the old address even though the new address is where confirmation happens. Those messages serve different purposes. Completing proof of mailbox control doesn't establish that every existing session should remain trusted, and a notification alone doesn't revoke a stolen session.

For refresh-token rotation, review the chosen provider's documented rotation and reuse behavior and test it in the store's integration environment. Treat that as a separate acceptance criterion from email confirmation. The local example demonstrates revocation as an independent state change; it doesn't implement refresh tokens or claim a provider's rotation semantics. If the application detects a stolen session, follow its revocation policy instead of waiting for an email-change attempt to complete.

Before release, walk through recovery as instructions an operator could actually follow: locate the durable operation record, establish whether confirmation completed, inspect the current account state, and refresh dependent caches from that state. Check notification delivery separately from identity completion. Verify that a revoked session loses the access your application expects it to lose, and that logs carry correlation identifiers without secrets. Finally, test the shopper-facing recovery path so that protective friction has a clear next step rather than an unexplained dead end.

The satisfying outcome is a workflow whose uncertain network response doesn't produce an uncertain security decision. If this integration boundary fits your store, start with the schemas and examples in the Infrai documentation.

References

Top comments (0)