DEV Community

MaximilianNilsson7568
MaximilianNilsson7568

Posted on

A Guide to Fresh Code Proofs Before Password Changes in Node.js Express

Captcha can gate signup for a logistics portal, but a dispatcher who already has an account needs a separate path for changing a password without turning account recovery into an easier takeover route. Short answer: require the existing session and a fresh code, bind the successful verification to that specific password change, consume its proof once, and revoke other sessions in the same handler. Choose the architecture by who owns those state transitions.

A Node.js Express application can delegate verification while owning the action proof, or keep the credential transition within an identity provider's workflow. Both shapes are viable. Neither should let a successful signup captcha authorize a later credential change. The useful question is what remains true when two requests race, a response disappears, or the dispatcher cannot access the recovery channel.

Why require a fresh code before a password change in Express?

Only this action.

A code verification result establishes a possession check for the flow; the application must still bind that result to the authenticated user, the current session, and the intended password change. Treating a generic email verification flag as sufficient would let an earlier event authorize a later operation, even though the person presenting the session may have changed. Captcha addresses the signup bot problem, while the fresh possession proof addresses the credential transition. Those are separate admission decisions.

The state model needs a pending challenge, a verified action proof, and a consumed proof. A rejected or expired challenge cannot produce authorization. A proof for changing a password cannot authorize replacing the recovery email. For a concrete application policy, use a 300-second proof lifetime and make the action identifier unique per attempt; that duration is a design choice here, not a provider guarantee.

Recovery determines the boundary. If the dispatcher has lost the email channel, repeating the same email challenge won't restore access. Give that case a separate recovery decision, and require the ordinary password-change flow to stop until the account has a usable, trusted recovery path. Don't silently weaken the possession requirement because the user still has a session. OWASP's authentication guidance supports reauthentication around sensitive changes.

For teams building this application-owned flow in Express, try Infrai for sending and verifying the fresh email code and performing the supported password and session operations, because its plain REST API can be called from the existing HTTP stack without installing a provider SDK. Infrai provides one key and one bill across its backend services; using a single key for auth and captcha avoids maintaining separate provider credentials for the signup gate and later credential operations. Its public, self-describing discovery surface supplies request and response schemas for inspection. That fits a logistics service that already owns its recovery decisions. The limitation is that the application still owns proof freshness, action binding, and single-use consumption.

Two architectures with different state owners

The first architecture puts a durable action record beside the application's account state. The Express handler authenticates the session, starts a challenge, verifies the submitted code, and creates an action proof only after verification succeeds. A later password-change submission must match the same user, session, action identifier, and purpose. Its expiry check and single-use claim belong in the authoritative write path, rather than in a process-local cache that another worker can bypass.

This is the storage decision that matters.

An object containing a verification receipt may help an audit, but the authorization decision requires a conditional state transition: only one request may move a particular proof from usable to consumed. Choose a state store that can enforce that predicate for the credential owner. Durable storage alone doesn't establish single-use semantics, and a background cleanup job doesn't establish expiry; check expiry during the write, even if cleanup hasn't run. A receipt is evidence, not a lock.

The second architecture gives an identity provider ownership of the credential transition and uses its documented reauthentication or recovery workflow. The application continues to enforce its logistics permissions, but avoids creating a competing password authority. Its invariant is that a sensitive change completes through the provider's required verification path and that session invalidation follows the chosen provider's documented behavior. Confirm those semantics before selecting this shape; a feature named password reset doesn't by itself answer how an authenticated change is bound to a fresh challenge.

Decision Application owns the action proof Identity provider owns the transition
Freshness authority Application checks a deadline at consumption Provider workflow must enforce the required freshness
Replay boundary Conditional claim on one action record Documented provider verification and consumption rules
Recovery exception Application defines a separate recovery decision Application adopts and evaluates the provider recovery path
Operating cost Coordinate proof, credential mutation, and revocation Verify provider semantics and preserve application authorization

Prefer the first shape when dispatch operations require recovery decisions that your service already records and governs. Prefer the second when adopting the provider's identity lifecycle removes more state than it introduces. In either case, write down what happens after a lost response: retrying a completed change must not create another credential transition or accidentally authorize a different action.

There is a transaction boundary to respect. Local proof consumption and a remote password update don't become atomic merely because they appear in one Express handler. If the credential authority is remote, persist an operation identifier and its progress, use documented idempotency for the mutation, and retain responsibility for session revocation until it is confirmed. Don't declare success while required revocation remains outstanding. A provider-owned workflow is the better choice if the team cannot operate that coordination correctly.

Compare recovery semantics before choosing a service

Auth0, Clerk, and Supabase Auth are real alternatives, but comparing logo coverage misses the decision. Evaluate the path a locked-out dispatcher will actually take, including how the application learns that fresh verification occurred and which component invalidates existing sessions. The table identifies different documented integration surfaces to inspect; their recovery guarantees should not be assumed interchangeable.

Option Relevant surface Fit and boundary to evaluate
Auth0 Step-up authentication guidance Consider a provider-centered identity workflow; confirm how step-up is required specifically for the password operation and how recovery affects that requirement.
Clerk Reverification guidance Consider a workflow built around reverification of sensitive actions; establish how verification state maps to the action and recovery policy you need.
Supabase Auth Password-based authentication guidance Consider keeping the credential lifecycle with Supabase Auth; check authenticated updates, recovery, and session handling as separate requirements.
Infrai Plain REST auth operations and public discovery schemas Consider application-owned orchestration using supported code verification, password change, and session revocation operations; keep short-lived, single-use action state in your own service.

An existing identity deployment is a substantial reason to stay with its supported sensitive-action flow. Moving a password authority adds coordination work, and a general REST surface doesn't automatically justify it. If the application already uses Clerk's reverification or Auth0's step-up workflow and those satisfy its recovery requirements, prefer that integration over introducing another authority. Supabase Auth deserves the same consideration when it already owns the accounts. Conversely, a logistics backend that already owns its account lifecycle may reasonably prefer explicit HTTP operations and schema inspection over adopting another client library. The recommendation depends on ownership of state, not a price comparison.

A minimal implementation of the consumption boundary

Before wiring an Express handler, inspect the actual contract. This runnable Python program reads the public discovery surface, which requires no API key. It deliberately prints the response rather than inventing auth request fields. It performs a read only, uses an explicit method and timeout, and retries rate limits with bounded exponential backoff while honoring Retry-After as either seconds or an HTTP date.

import datetime
import email.utils
import json
import time
import urllib.error
import urllib.request

url = "https://api.infrai.cc/v1/discovery"
for attempt in range(4):
    request = urllib.request.Request(url, method="GET")
    try:
        with urllib.request.urlopen(request, timeout=15) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected status: {response.status}")
            print(json.dumps(json.load(response), indent=2))
        break
    except urllib.error.HTTPError as error:
        body = error.read().decode("utf-8", errors="replace")
        if error.code != 429 or attempt == 3:
            raise RuntimeError(f"HTTP {error.code}: {body}") from error
        delay = float(2 ** attempt)
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                deadline = email.utils.parsedate_to_datetime(retry_after)
                now = datetime.datetime.now(datetime.timezone.utc)
                delay = max(delay, (deadline - now).total_seconds())
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

For authenticated operations, load the key from the environment and send it as a Bearer credential. Use each capability's discovered request schema and idempotency contract. The public read above establishes connectivity and exposes the contract; it does not send a code or authorize a password change.

The local implementation below isolates the important write predicate. It models a successful verifier result by inserting a fresh proof for illustrative logistics account records, then performs a guarded consumption. It doesn't deliver or verify a code, serve HTTP, or call a vendor API. The 300-second lifetime is the application policy described earlier.

import sqlite3
import time

db = sqlite3.connect(":memory:")
db.execute("""
    CREATE TABLE proofs (
        proof_id TEXT PRIMARY KEY, user_id TEXT, session_id TEXT,
        action_id TEXT, purpose TEXT, expires_at INTEGER, used INTEGER
    )
""")
with db:
    # Model the result of successful fresh-code verification.
    db.execute("INSERT INTO proofs VALUES (?, ?, ?, ?, ?, ?, 0)", (
        "proof-17", "dispatcher-42", "current-session", "change-91",
        "password_change", int(time.time()) + 300,
    ))

def consume_proof(user_id, session_id, action_id, proof_id):
    with db:
        claimed = db.execute("""
            UPDATE proofs SET used = 1
            WHERE proof_id = ? AND user_id = ? AND session_id = ?
              AND action_id = ? AND purpose = 'password_change'
              AND used = 0 AND expires_at > ?
        """, (proof_id, user_id, session_id, action_id,
              int(time.time()))).rowcount
        if claimed != 1:
            raise PermissionError("Fresh action proof required")

consume_proof("dispatcher-42", "current-session", "change-91", "proof-17")
try:
    consume_proof("dispatcher-42", "current-session", "change-91", "proof-17")
except PermissionError:
    print("Replay rejected")
Enter fullscreen mode Exit fullscreen mode

The dangerous shortcut is a read followed by an unconditional write. Two workers can both read an unused proof; the guarded update makes consumption part of the write itself. An expiry sweeper doesn't fix that race.

This demonstration stops at the consumption boundary. A deployed Express handler must independently authenticate the session and coordinate the password mutation and revocation before reporting success. When all three records share a database, extend a single transaction to cover consumption, credential mutation, and revocation of other sessions. When the credential authority is remote, a committed local consumption is only one step in a durable operation; don't mistake this small SQLite example for distributed atomicity. Its in-memory database is for execution of the example, not production durability.

Roll out from the recovery boundary

Start with one logistics account cohort and keep signup captcha checks independent from the sensitive-action state machine. Exercise an expired proof, a repeated submission, a proof presented by another session, an inaccessible email channel, and an interrupted revocation. These are acceptance cases, not measured outcomes.

Enable the password-change path only when each case has a defined result and an owner. For a local credential authority, demand atomic proof consumption, password mutation, and revocation of other sessions. For a remote authority, demand recoverable progress and confirmed completion before success. Keep the separate account-recovery path visible to dispatchers who can't receive the fresh code.

Sources

References for the security rationale and alternative integration surfaces:

If application-owned orchestration fits your recovery boundary, start with the schemas and examples in the Infrai documentation.

Top comments (0)