Skip to the code

Lock an account after five wrong passwords

Someone is trying thousands of passwords against Leaf and Kettle's customers. The sign-in form runs signIn(previous, formData), a Server Action in app/actions.ts, through useActionState. Add a lockout: after five wrong passwords in a row, an account can't sign in for 15 minutes.

Read email, trimmed and lowercased, and password, as typed. If either is empty, return { error: "Enter your email and password.", email } and count nothing.

Keep each email's count in kv from @/lib/kv under the key sign-in:<email>, never in a variable: the shop runs on several servers, each with its own memory. kv.get(key) gives back what you stored, or null; kv.set(key, value, { ttlMs }) stores any JSON value, which disappears ttlMs milliseconds later; kv.delete(key) removes it.

While an email is locked, return { error: "Too many failed attempts. Try again in N minutes.", email } without checking the password at all, where N is the minutes left, rounded up (Try again in 1 minute. for the last one).

Otherwise check the password with checkPassword(email, password) from @/lib/users, which returns the user or null. A wrong one adds one to the count and returns { error: "Wrong email or password.", email }, but the fifth in a row locks the email for 15 minutes and returns the locked message, Try again in 15 minutes.. The count starts again from zero when a lock ends, and when 15 minutes pass without a new failure. An email with no account is counted and locked in the same way, so the form never tells anyone which emails have accounts.

The right password clears the count, starts a session with startSession(user.id) from @/lib/sessions, and redirects to /account.

14:00  five wrong passwords for ana@example.com
       → "Wrong email or password." four times, then "Too many failed attempts. Try again in 15 minutes."
14:10  the right password → "Too many failed attempts. Try again in 5 minutes."   (not even checked)
14:15  the right password → redirect("/account")

The app's other files

lib/kv.ts, read-only. Import it as @/lib/kv.

/**
 * A key-value store every server shares, with expiry, like Redis. Values are stored as JSON.
 * A real shop would use a hosted Redis or another shared store, never a variable in one server.
 */
const entries = new Map<string, { json: string; expiresAt: number | null }>();
 
export const kv = {
  /** What's stored under `key`, or null when there's nothing, or it has expired. */
  async get<T = unknown>(key: string): Promise<T | null> {
    const entry = entries.get(key);
    if (!entry) return null;
    if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
      entries.delete(key);
      return null;
    }
    return JSON.parse(entry.json) as T;
  },
  /** Stores `value` under `key`. With `ttlMs`, it disappears that many milliseconds from now. */
  async set(key: string, value: unknown, options: { ttlMs?: number } = {}): Promise<void> {
    entries.set(key, { json: JSON.stringify(value), expiresAt: options.ttlMs ? Date.now() + options.ttlMs : null });
  },
  async delete(key: string): Promise<void> {
    entries.delete(key);
  },
};

lib/users.ts, read-only. Import it as @/lib/users.

export type User = { id: string; name: string };
 
const accounts = [
  { id: "u_ana", name: "Ana", email: "ana@example.com", password: "green-tea-42" },
  { id: "u_ben", name: "Ben", email: "ben@example.com", password: "oolong-at-noon" },
];
 
/** Every email checkPassword was asked about, in order: the tests read it. */
export const passwordChecks: string[] = [];
 
/** The user with this email and password, or null. A real shop compares password hashes. */
export async function checkPassword(email: string, password: string): Promise<User | null> {
  passwordChecks.push(email);
  const account = accounts.find((entry) => entry.email === email);
  if (!account || account.password !== password) return null;
  return { id: account.id, name: account.name };
}

lib/sessions.ts, read-only. Import it as @/lib/sessions.

/** Whose sessions were started, in order: a stand-in for setting the session cookie. */
export const startedSessions: string[] = [];
 
export async function startSession(userId: string) {
  startedSessions.push(userId);
}

What the tests check

  1. signs in with the right password, and clears the count
    const MINUTE = 60 * 1000;
    const initial = { error: null, email: "" };
    const tryPassword = (email, password) => signIn(initial, formData({ email, password }));
    const wrong = (email = "ana@example.com") => tryPassword(email, "matcha");
    const failed = (email) => ({ error: "Wrong email or password.", email });
    const locked = (email, minutes) => ({ error: "Too many failed attempts. Try again in " + minutes + (minutes === 1 ? " minute." : " minutes."), email });
    useFakeTimers();
    expect(await wrong()).toEqual(failed("ana@example.com"));
    expect(await kv.get("sign-in:ana@example.com")).not.toBeNull();
    expect((await redirectOf(() => tryPassword(" Ana@Example.com ", "green-tea-42"))).url).toBe("/account");
    expect(startedSessions).toEqual(["u_ana"]);
    expect(await kv.get("sign-in:ana@example.com")).toBeNull();
    
  2. four wrong passwords say so, and the fifth locks the account
    const MINUTE = 60 * 1000;
    const initial = { error: null, email: "" };
    const tryPassword = (email, password) => signIn(initial, formData({ email, password }));
    const wrong = (email = "ana@example.com") => tryPassword(email, "matcha");
    const failed = (email) => ({ error: "Wrong email or password.", email });
    const locked = (email, minutes) => ({ error: "Too many failed attempts. Try again in " + minutes + (minutes === 1 ? " minute." : " minutes."), email });
    useFakeTimers();
    for (let n = 1; n <= 4; n++) expect(await wrong()).toEqual(failed("ana@example.com"));
    expect(await wrong()).toEqual(locked("ana@example.com", 15));
    
  3. a locked account refuses even the right password, without checking it
    const MINUTE = 60 * 1000;
    const initial = { error: null, email: "" };
    const tryPassword = (email, password) => signIn(initial, formData({ email, password }));
    const wrong = (email = "ana@example.com") => tryPassword(email, "matcha");
    const failed = (email) => ({ error: "Wrong email or password.", email });
    const locked = (email, minutes) => ({ error: "Too many failed attempts. Try again in " + minutes + (minutes === 1 ? " minute." : " minutes."), email });
    const clock = useFakeTimers();
    for (let n = 0; n < 5; n++) await wrong();
    const checks = passwordChecks.length;
    expect(await tryPassword("ana@example.com", "green-tea-42")).toEqual(locked("ana@example.com", 15));
    await clock.advance(10 * MINUTE + 40 * 1000);
    expect(await tryPassword("ana@example.com", "green-tea-42")).toEqual(locked("ana@example.com", 5));
    await clock.advance(4 * MINUTE);
    expect(await wrong()).toEqual(locked("ana@example.com", 1));
    expect(passwordChecks.length).toBe(checks);
    expect(startedSessions).toEqual([]);
    
  4. the lock ends after 15 minutes, with five fresh tries
    const MINUTE = 60 * 1000;
    const initial = { error: null, email: "" };
    const tryPassword = (email, password) => signIn(initial, formData({ email, password }));
    const wrong = (email = "ana@example.com") => tryPassword(email, "matcha");
    const failed = (email) => ({ error: "Wrong email or password.", email });
    const locked = (email, minutes) => ({ error: "Too many failed attempts. Try again in " + minutes + (minutes === 1 ? " minute." : " minutes."), email });
    const clock = useFakeTimers();
    for (let n = 0; n < 5; n++) await wrong();
    await clock.advance(15 * MINUTE);
    for (let n = 1; n <= 4; n++) expect(await wrong()).toEqual(failed("ana@example.com"));
    expect(await wrong()).toEqual(locked("ana@example.com", 15));
    await clock.advance(15 * MINUTE);
    expect((await redirectOf(() => tryPassword("ana@example.com", "green-tea-42"))).url).toBe("/account");
    
  5. the count starts over after a sign-in, and after 15 quiet minutes
    const MINUTE = 60 * 1000;
    const initial = { error: null, email: "" };
    const tryPassword = (email, password) => signIn(initial, formData({ email, password }));
    const wrong = (email = "ana@example.com") => tryPassword(email, "matcha");
    const failed = (email) => ({ error: "Wrong email or password.", email });
    const locked = (email, minutes) => ({ error: "Too many failed attempts. Try again in " + minutes + (minutes === 1 ? " minute." : " minutes."), email });
    const clock = useFakeTimers();
    for (let n = 0; n < 4; n++) await wrong();
    await redirectOf(() => tryPassword("ana@example.com", "green-tea-42"));
    for (let n = 0; n < 4; n++) expect(await wrong()).toEqual(failed("ana@example.com"));
    await clock.advance(15 * MINUTE);
    for (let n = 0; n < 4; n++) expect(await wrong()).toEqual(failed("ana@example.com"));
    expect(await wrong()).toEqual(locked("ana@example.com", 15));
    
  6. counts each email on its own, whatever its case, account or not
    const MINUTE = 60 * 1000;
    const initial = { error: null, email: "" };
    const tryPassword = (email, password) => signIn(initial, formData({ email, password }));
    const wrong = (email = "ana@example.com") => tryPassword(email, "matcha");
    const failed = (email) => ({ error: "Wrong email or password.", email });
    const locked = (email, minutes) => ({ error: "Too many failed attempts. Try again in " + minutes + (minutes === 1 ? " minute." : " minutes."), email });
    useFakeTimers();
    for (const email of ["ana@example.com", "ANA@example.com", " Ana@Example.com", "ana@EXAMPLE.com", "ana@example.com "]) await wrong(email);
    expect(await tryPassword("ana@example.com", "green-tea-42")).toEqual(locked("ana@example.com", 15));
    expect((await redirectOf(() => tryPassword("ben@example.com", "oolong-at-noon"))).url).toBe("/account");
    const answers = [];
    for (let n = 0; n < 5; n++) answers.push(await wrong("zoe@example.com"));
    expect(answers).toEqual([failed("zoe@example.com"), failed("zoe@example.com"), failed("zoe@example.com"), failed("zoe@example.com"), locked("zoe@example.com", 15)]);
    expect(await kv.get("sign-in:zoe@example.com")).not.toBeNull();
    
  7. an empty field counts nothing
    const MINUTE = 60 * 1000;
    const initial = { error: null, email: "" };
    const tryPassword = (email, password) => signIn(initial, formData({ email, password }));
    const wrong = (email = "ana@example.com") => tryPassword(email, "matcha");
    const failed = (email) => ({ error: "Wrong email or password.", email });
    const locked = (email, minutes) => ({ error: "Too many failed attempts. Try again in " + minutes + (minutes === 1 ? " minute." : " minutes."), email });
    useFakeTimers();
    for (let n = 0; n < 6; n++) {
      expect(await tryPassword("Ana@example.com", "")).toEqual({ error: "Enter your email and password.", email: "ana@example.com" });
    }
    expect(await tryPassword("", "matcha")).toEqual({ error: "Enter your email and password.", email: "" });
    expect(await kv.get("sign-in:ana@example.com")).toBeNull();
    expect(passwordChecks).toEqual([]);
    

Learn more

app/actions.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).