Secure Password Reset Flow Explained — Email Token Expiry and Observability
Secure Password Reset Flow Explained — Email Token Expiry and Observability A secure password reset flow needs evidence at the point where the password changes. An email delivery event cannot supply it. TL;DR: generate
Secure Password Reset Flow Explained — Email Token Expiry and Observability
A secure password reset flow needs evidence at the point where the password changes. An email delivery event cannot supply it. TL;DR: generate a random token, store its hash with an expiry, and consume it in the same database transaction that updates the password. Rate-limit requests and redemption attempts. Keep tokens out of logs.
Consider a B2B SaaS application that sends an order receipt after payment settles. A buyer who cannot sign in may request a password reset while waiting for that receipt. Both messages depend on email delivery, but their success conditions differ: the receipt communicates a settled payment; the recovery link grants permission to replace a credential. Treating both as “email sent” hides the security boundary that matters.
The useful teaching model starts with two pictures. Before: request → email accepted → success counter. After: request → queued recovery work → email transport → explicit password submission → atomic credential change. Delivery signals explain part of that journey. The final database commit establishes that recovery completed. That's the boundary.
This guide uses Node.js and Express to make those controls concrete, with observability as the acceptance test: can an operator explain a failed recovery without collecting the credential that would let someone complete it?
How do you build a secure password reset flow with email tokens?
It proves that a valid recovery token authorized a password change under the application's rules. It does not prove that the intended person read a particular email, and a transport acceptance response does not prove that the password changed. Keep those assertions separate in dashboards and in support language. The OWASP Forgot Password Cheat Sheet recommends cryptographically secure random tokens, secure storage, expiration, single use, and consistent responses for existing and nonexistent accounts.
For the receipt scenario, use distinct event families for payment settlement, receipt delivery, and credential recovery. A shared mail worker can report transport outcomes, but it should not label an accepted reset message as a successful recovery. Otherwise, a backlog can look healthy while users are still unable to regain access.
Start with a small event vocabulary: recovery requested, transport accepted, transport failed, and password changed. Add invalid-or-expired redemption counts where they help detect abuse. Use an opaque request identifier to connect internal events. Do not derive that identifier from an email address or token. Keep account identifiers in access-controlled audit records only where the investigation actually needs them; keep metric labels bounded, such as operation and outcome.
Count outcomes. Protect evidence.
The trade-off is deliberate: a combined invalid-or-expired outcome reveals less detail to the client and gives the public endpoint a smaller information surface, while an internal expiry measurement can still explain why users need another link. It should measure age or an aggregate outcome, never retain the presented secret.
OWASP's Logging Cheat Sheet provides the broader rule: access tokens and other authentication secrets belong outside ordinary application logs.
Build the transaction around the credential change
Here is a minimal TypeScript module for the sensitive portion of the flow. The storage and rate-limit interfaces are application adapters, not built-in Express features. Their comments are implementation requirements. In particular, the transaction must roll back token deletion if the password update or session revocation fails. A read followed by an unconditional delete does not satisfy the contract.
The example uses 32 random bytes and a 15-minute lifetime as explicit application choices, not universal requirements. Choose the lifetime against your measured queue and delivery delays. A shorter window reduces the period during which a stolen link is useful, but leaves less time for a legitimate user to act.
Store the token hash, not the bearer token.
Passwords need a dedicated password-hashing function; SHA-256 here is only for the high-entropy reset token.
import { createHash, randomBytes } from "node:crypto";
import { Router, type RequestHandler } from "express";
const ttlMs = 15 * 60 * 1000;
const digest = (token: string) =>
createHash("sha256").update(token, "utf8").digest("hex");
type Transaction = {
// Atomically delete and return one matching row only when
// expires_at > database current time. Concurrent claims serialize.
consumeUnexpired(hash: string): Promise<{ userId: string } | null>;
setPassword(userId: string, encodedHash: string): Promise<void>;
revokeSessions(userId: string): Promise<void>;
};
type Dependencies = {
// Persist before dispatch. Store no raw token in this table.
insertToken(row: {
userId: string;
tokenHash: string;
expiresAt: Date;
}): Promise<void>;
// Commit all changes together, or roll them all back on error.
transaction<T>(work: (tx: Transaction) => Promise<T>): Promise<T>;
// Apply application password policy and a dedicated password hash.
// Throw on rejection; never log the input.
hashPassword(password: string): Promise<string>;
// Shared, atomic limiter across application instances.
allowRedemption(clientKey: string): Promise<boolean>;
// Derive from trusted connection/proxy configuration, not raw headers.
clientKey(req: Parameters<RequestHandler>[0]): string;
};
export function createRecovery(deps: Dependencies, publicOrigin: string) {
const origin = new URL(publicOrigin);
if (origin.protocol !== "https:") throw new Error("HTTPS required");
// Call only from the account lookup worker, after request throttling.
async function issue(userId: string): Promise<URL> {
const token = randomBytes(32).toString("hex");
await deps.insertToken({
userId,
tokenHash: digest(token),
expiresAt: new Date(Date.now() + ttlMs),
});
const link = new URL("/reset-password", origin.origin);
link.hash = new URLSearchParams({ token }).toString();
return link; // Pass directly to private delivery work, never logs.
}
const router = Router();
const complete: RequestHandler = (req, res, next) => {
void (async () => {
res.setHeader("Cache-Control", "no-store");
if (!(await deps.allowRedemption(deps.clientKey(req)))) {
res.status(429).json({ message: "Try again later." });
return;
}
const { token, password } = req.body ?? {};
if (
typeof token !== "string" || !/^[a-f0-9]{64}$/.test(token) ||
typeof password !== "string"
) {
res.status(400).json({ message: "Invalid reset submission." });
return;
}
const encodedHash = await deps.hashPassword(password);
const changed = await deps.transaction(async (tx) => {
const row = await tx.consumeUnexpired(digest(token));
if (!row) return false;
await tx.setPassword(row.userId, encodedHash);
await tx.revokeSessions(row.userId);
return true;
});
if (!changed) {
res.status(400).json({ message: "Invalid or expired reset link." });
return;
}
res.status(204).end();
})().catch(next);
};
router.post("/password-reset/complete", complete);
return { issue, router };
}
Mount the router behind a size-limited JSON parser and an error handler that redacts request bodies. The password adapter must enforce a maximum input size before running its expensive hash, apply the application's password policy, and return safe validation errors. OWASP recommends modern password-hashing algorithms such as Argon2id. Use the adapter to keep those settings explicit and reviewable. Hashing before the transaction avoids holding database locks during the expensive work, but also means invalid token submissions can consume hashing resources. Redemption throttling matters for that reason too.
The issuance endpoint needs its own controls. Return the same acknowledgement for existing and nonexistent accounts, and queue account lookup so the response path does not branch on account existence. Apply a shared per-client limit and a per-account issuance limit inside the private worker. Use the application's established account lookup rules; do not invent email normalization that changes which account an address identifies. Rate-limit keys containing identity data also need restricted access and bounded retention. Do not lock an account merely because someone requested recovery for it.
For example data, keep the separation visible: order order_demo_4821 is settled, its receipt is queued, and recovery request recovery_demo_73 is pending. Those are illustrative identifiers. Neither the payment state nor the receipt state authorizes setPassword. Only a valid token claim does.
The browser page must read the token from the URL fragment, remove it from the address bar, and submit it in a request body only after the user chooses a new password. URL fragments are not sent to the server as part of an HTTP request. That reduces one exposure path, but scripts on the page can still read them. Serve the page over HTTPS, exclude third-party scripts, set a restrictive referrer policy, and redact request bodies across proxies, tracing, and application logging. Build the public origin from trusted configuration, never the incoming Host header.
Keep link opening harmless.
A GET must not consume the token: mail security scanners can visit links before the recipient acts. Consumption belongs with the explicit password submission. For queued delivery, the raw link is still a secret; protect the payload, restrict worker access, and expire retained delivery data. If dispatch fails, preserve the hashed record's expiry and let the user request another message.
Do not extend the authorization window silently on retries.
Test the evidence before shipping the dashboard
The most useful test sends two completion requests with the same valid token concurrently. Exactly one should change the password. The other must fail. Then inject a password-write failure after the token claim and confirm that the transaction restores the token. These tests check the storage adapter's behavior, which a TypeScript interface cannot enforce. Also test expiry at the boundary: a row whose expiry equals the database's current time is invalid under the strict comparison above. Synchronize application and database clocks because issuance computes the expiry in the application. Open the email link without submitting the form and confirm that the token remains usable. Exercise the request endpoint with existing and nonexistent accounts, inspect responses and timing under load, and verify that throttling works across multiple application instances. A process-local counter cannot enforce a shared limit.
Finally, send a synthetic token through a staging flow and inspect every telemetry destination for it, including error events, traces, mail job failures, and reverse-proxy logs.
The acceptance condition is absence.
A clean application logger is insufficient if a tracing integration records the POST body.
Deployment changes deserve the same attention. Roll out the database contract before application code depends on it, preserve outstanding token validation across a rolling release, and exercise rollback while an unexpired link exists. For monitoring, compare request volume, transport outcomes, completion counts, and recovery age without attaching email addresses or tokens as metric labels. Alert thresholds should come from your service objectives and normal traffic; no universal completion ratio distinguishes an outage from recipients who never intended to finish.
Can delivery events tell us enough?
They can narrow an investigation. A growing queue points to dispatch delay; transport failures point to another part of the path. Neither observation establishes that a credential changed. A completion counter should follow a committed password update, with an audit mechanism that preserves the event if the process stops immediately after commit. A transactional outbox is one way to connect that commit to durable audit delivery.
SPF has a narrower role still: RFC 7208 defines authorization of sending hosts for an envelope domain. It does not validate your reset token, enforce expiry, or prove that a human received the message. Keep email authentication checks in the delivery workflow and token checks in the recovery workflow. This distinction also helps support teams explain why an accepted message and an incomplete recovery can coexist.
Does all this make recovery too complicated?
It adds storage contracts, worker discipline, and tests. Those are real maintenance costs. A small application can keep the implementation compact, but it still needs atomic consumption, bounded token lifetime, secure password storage, and abuse controls. Deferring those controls makes the recovery endpoint a weaker route into the same account.
The useful simplification is operational: one authorization boundary, one transaction, and evidence that avoids collecting secrets. After a successful reset, send a password-change notification and require a normal sign-in, as OWASP recommends. In the B2B receipt scenario, the settled order remains a payment fact; recovered access becomes a separate, auditable credential fact. That gives operators something precise to teach, test, and troubleshoot.
References
The recovery, logging, and password-storage guidance below supports the security controls. The runtime and URL references explain the primitives used in the example; the mail standard establishes the narrower scope of sender authorization.
Further reading
- OWASP Forgot Password Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
- OWASP Password Storage Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
- Node.js cryptography API: https://nodejs.org/api/crypto.html
- Express API reference: https://expressjs.com/en/4x/api.html
- MDN URL fragment reference: https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Fragment
- RFC 7208, Sender Policy Framework: https://datatracker.ietf.org/doc/html/rfc7208
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.