Password Reset Flows That Do Not Leak Accounts

· 7 min read ·

A man in a green sweater with a mug watches from a desk while a small white robot in a detective cap hands identical sealed envelopes to a queue of townspeople at a post office counter, with a padlocked door behind

A safe password reset gives the same answer whether or not the email has an account, sends a long random link that works once and expires within an hour, builds that link from your own domain, and signs out every existing session when the password changes. Most “forgot password” code written by an AI tool does one or two of these. The ones it skips are how someone else ends up in your user’s account.

If you use a provider like Supabase Auth, much of this is done for you, and the rest is settings. If your AI wrote the flow by hand, read it against this list. A test file at the end does the reading for you.

1. Does it give the same answer for every email?

Type a made-up address into your own “forgot password” box. If the page says “No account with that email”, you have published a list of who uses your app. OWASP’s Forgot Password cheat sheet calls this the classic user enumeration bug and says to return a consistent message for existing and non-existing accounts. Response time should match too: a fast “no” and a slow “yes” (the slow one sent an email) tells the attacker the same thing. Queue the email in a background job. The reference flow below returns the same body for both but does not test timing, so time both cases by hand.

Supabase handles the message half. Its docs say resetPasswordForEmail() does not reveal whether an account exists. When no user matches, no email is sent, and the call still returns without an error. Your own code on top of it can still undo that, by catching an error and showing “user not found” because the AI wanted helpful messages.

Four properties, and each one is a separate bug when missing:

  • Random and long. From a secure random generator, not a timestamp, a counter, or the user id. OWASP says to store tokens securely, the way you store passwords. The simple version is to keep only a hash, so a leaked database does not hand out working reset links.
  • Single use. The moment it works once, it is dead, and so is every older link for that account.
  • Short lived. Supabase’s production checklist says to make codes and links expire within an hour. The default otp_expiry is 3600 seconds.
  • Tied to one user. The token maps to a single account on the server, not to an id in the URL.

A lot of generated code builds the reset URL from the incoming request’s Host header. An attacker requests a reset for your user with a forged Host, and your server emails the victim a real, valid token on a link to the attacker’s site. One click and the token is theirs. OWASP says to not rely on the Host header when creating reset URLs, and to hard-code the URL or validate it against trusted domains. In Supabase this is the Site URL and redirect allow-list from the auth post.

4. Does the reset kill the old sessions?

People reset a password because they think someone else may have it. If the attacker’s session survives the reset, nothing changed for them. OWASP says to ask the user whether to invalidate existing sessions, or to do it automatically. Do it automatically. On Supabase, signOut({ scope: 'others' }) ends all but the current session. Supabase’s sessions docs say a password change may end sessions “depending on configuration”, so check your project. A JWT can also outlive a reset until it expires: see sessions vs JWT.

5. Does it limit how often someone can ask?

Without a limit, anyone can make your app email a user a thousand reset links, which is harassment with your domain on it. Supabase limits password reset requests to one per user every 60 seconds and sign-in related endpoints to 30 requests per 5 minutes per IP by default. On your own code you add that yourself.

Here is the one that confuses new builders most. Company email security tools open every link in an email to check it for malware. If your reset link is spent the moment it is opened, the scanner uses it up and your user sees “token expired”. Supabase’s troubleshooting article names email prefetching as the most common cause of otp_expired errors. Two fixes: land the link on a page where the user presses a button that submits the token, or send a six-digit code the user types in. In Supabase’s email templates, {{ .Token }} is that code, used instead of {{ .ConfirmationURL }}.

One Supabase detail that costs people an afternoon: the built-in email service is limited to 2 emails per hour for the whole project. Production needs a custom SMTP provider.

Test the behavior, not the code

The checks above are things a user or an attacker can observe, so the tests say only that. They survive a rewrite and fail the day a later “fix” breaks one of them.

Run against a deliberately naive flow (404 for unknown emails, the Host header in the link, a token made from the clock, no expiry, no single use, sessions left alive) in a scratch folder with Node 22 and node --test, seven of the eight fail. This is the naive flow, saved as reset.js:

// NAIVE version: the kind of reset flow an AI tool writes when asked for "forgot password".
function makeApp({ now = () => Date.now() } = {}) {
const users = new Map([["[email protected]", { password: "old-pass-123" }]]);
const tokens = new Map();
const sessions = new Map([["sess-1", "[email protected]"]]);
const outbox = [];
return {
outbox, sessions,
requestReset({ email, host }) {
if (!users.has(email)) return { status: 404, body: "No account with that email" };
const token = now().toString(36); // guessable
tokens.set(token, { email });
outbox.push({ to: email, link: `https://${host}/reset?token=${token}` });
return { status: 200, body: "Check your email" };
},
resetPassword({ token, newPassword }) {
const t = tokens.get(token);
if (!t) return { status: 400 };
users.get(t.email).password = newPassword;
return { status: 200 };
},
isSignedIn(sessionId) { return sessions.has(sessionId); },
login({ email, password }) { return users.get(email)?.password === password; },
};
}
module.exports = { makeApp };

It prints:

not ok 1 - known and unknown emails get the same answer
not ok 2 - the emailed link points at our site even if the Host header lies
not ok 3 - a reset link works once
not ok 4 - a reset link stops working after an hour
not ok 5 - resetting the password signs out existing sessions and changes the login
ok 6 - a reset link still works at 59 minutes
not ok 7 - reset tokens are long, random and unique, even when made at the same instant
not ok 8 - after one reset link is used, an older link for the same account stops working
# pass 1
# fail 7

Test 6 passes on the naive flow only because it has no expiry at all. Against the fixed flow below, all eight pass (# pass 8, # fail 0). Test 8 came from a review that found a real hole: with two reset links outstanding, using one left the other alive. The earlier fixed flow, without the loop that deletes every token for the account, failed only test 8 (# pass 7, # fail 1). Test 8 first checks that two different links exist, so it cannot pass for the wrong reason. Save the tests as reset.test.js:

const test = require("node:test");
const assert = require("node:assert");
const { makeApp } = require("./reset.js");
const tokenFrom = (app) => new URL(app.outbox.at(-1).link).searchParams.get("token");
test("known and unknown emails get the same answer", () => {
const app = makeApp();
const a = app.requestReset({ email: "[email protected]", host: "myapp.com" });
const b = app.requestReset({ email: "[email protected]", host: "myapp.com" });
assert.deepStrictEqual(a, b);
});
test("the emailed link points at our site even if the Host header lies", () => {
const app = makeApp();
app.requestReset({ email: "[email protected]", host: "evil.example" });
assert.ok(app.outbox.at(-1).link.startsWith("https://myapp.com/"));
});
test("a reset link works once", () => {
const app = makeApp();
app.requestReset({ email: "[email protected]", host: "myapp.com" });
const token = tokenFrom(app);
assert.equal(app.resetPassword({ token, newPassword: "new-pass-456" }).status, 200);
assert.notEqual(app.resetPassword({ token, newPassword: "attacker-pass" }).status, 200);
});
test("a reset link stops working after an hour", () => {
let t = 1_000_000;
const app = makeApp({ now: () => t });
app.requestReset({ email: "[email protected]", host: "myapp.com" });
const token = tokenFrom(app);
t += 61 * 60 * 1000;
assert.notEqual(app.resetPassword({ token, newPassword: "new-pass-456" }).status, 200);
});
test("resetting the password signs out existing sessions and changes the login", () => {
const app = makeApp();
assert.equal(app.isSignedIn("sess-1"), true); // sanity: the session exists before the reset
app.requestReset({ email: "[email protected]", host: "myapp.com" });
app.resetPassword({ token: tokenFrom(app), newPassword: "new-pass-456" });
assert.equal(app.isSignedIn("sess-1"), false);
assert.equal(app.login({ email: "[email protected]", password: "old-pass-123" }), false);
assert.equal(app.login({ email: "[email protected]", password: "new-pass-456" }), true);
});
test("a reset link still works at 59 minutes", () => {
let t = 1_000_000;
const app = makeApp({ now: () => t });
app.requestReset({ email: "[email protected]", host: "myapp.com" });
const token = tokenFrom(app);
t += 59 * 60 * 1000;
assert.equal(app.resetPassword({ token, newPassword: "new-pass-456" }).status, 200);
});
test("reset tokens are long, random and unique, even when made at the same instant", () => {
const app = makeApp({ now: () => 1_700_000_000_000 }); // frozen clock
const seen = new Set();
for (let i = 0; i < 100; i++) {
app.requestReset({ email: "[email protected]", host: "myapp.com" });
const token = tokenFrom(app);
assert.ok(token.length >= 43, "32 random bytes encode to 43 characters or more");
seen.add(token);
}
assert.equal(seen.size, 100);
});
test("after one reset link is used, an older link for the same account stops working", () => {
const app = makeApp();
app.requestReset({ email: "[email protected]", host: "myapp.com" });
const first = tokenFrom(app);
app.requestReset({ email: "[email protected]", host: "myapp.com" });
const second = tokenFrom(app);
assert.notEqual(first, second); // sanity: two different links exist
assert.equal(app.resetPassword({ token: second, newPassword: "new-pass-456" }).status, 200);
assert.notEqual(app.resetPassword({ token: first, newPassword: "attacker-pass" }).status, 200);
assert.equal(app.login({ email: "[email protected]", password: "new-pass-456" }), true);
});

Here is the fixed flow it passed against, saved as reset.js. Your app is not shaped like this, so do not paste it in. Ask your AI tool for a small adapter that exposes the same functions on top of your real code, then run the same tests.

const crypto = require("node:crypto");
const SITE_URL = "https://myapp.com";
const TTL_MS = 60 * 60 * 1000;
function makeApp({ now = () => Date.now() } = {}) {
const users = new Map([["[email protected]", { password: "old-pass-123" }]]);
const tokens = new Map(); // store only a hash of the token
const sessions = new Map([["sess-1", "[email protected]"]]);
const outbox = [];
const hash = (t) => crypto.createHash("sha256").update(t).digest("hex");
return {
outbox, sessions,
requestReset({ email }) {
if (users.has(email)) {
const token = crypto.randomBytes(32).toString("base64url");
tokens.set(hash(token), { email, expires: now() + TTL_MS });
outbox.push({ to: email, link: `${SITE_URL}/reset?token=${token}` });
}
return { status: 200, body: "If that email has an account, we sent a reset link" };
},
resetPassword({ token, newPassword }) {
const key = hash(token);
const t = tokens.get(key);
if (!t || t.expires < now()) return { status: 400 };
for (const [k, v] of tokens) if (v.email === t.email) tokens.delete(k); // single use, and every older link for this account dies too
users.get(t.email).password = newPassword;
for (const [id, email] of sessions) if (email === t.email) sessions.delete(id);
return { status: 200 };
},
isSignedIn(sessionId) { return sessions.has(sessionId); },
login({ email, password }) { return users.get(email)?.password === password; },
};
}
module.exports = { makeApp };

The tests run against an in-memory model, so they prove the rules and give your real app a spec to meet. They do not cover response timing, email delivery, or a real mail scanner, and they do not replace one try on the live site with two addresses you own. A plain SHA-256 of the token is fine here because it is 32 random bytes. Passwords need a slow hash; random tokens do not.

A prompt to paste into your AI tool

Read how this app handles “forgot password”. Tell me, with the file and line for each: what the response says for an email with no account, how the reset token is generated and stored, whether it is single use and when it expires, how the reset URL is built (does it use the Host header or request origin?), what happens to existing sessions when the password changes, and whether the reset-request endpoint is rate limited. Do not change any code yet.

The check an engineer does by hand

Request a reset for an address you own, then request one for an address that cannot exist, and compare the two responses side by side: the text, the status code, and roughly how long each takes. Then use the emailed link twice. The second try has to fail.

Reset is one of the places real users find the gaps first, and it belongs on your launch checklist.

The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.

Comments