import { beforeEach, describe, expect, it } from "vitest"; import { cache } from "~/utils/cache.server"; import { clearFailedLogins, getFailedLoginCount, LOGIN_CAPTCHA_AFTER_FAILURES, loginRequiresCaptcha, recordFailedLogin, } from "./login-captcha-gate.server"; function req() { return new Request("https://example.test/login"); } describe("login-captcha-gate", () => { beforeEach(() => { cache.clear(); }); it("starts at zero and increments per recorded failure", () => { const request = req(); expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(0); expect(recordFailedLogin({ request, identifier: "ada@example.test" })).toBe(1); expect(recordFailedLogin({ request, identifier: "ada@example.test" })).toBe(2); expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(2); }); it("requires a captcha only from the configured failure threshold", () => { expect(loginRequiresCaptcha(0)).toBe(false); expect(loginRequiresCaptcha(LOGIN_CAPTCHA_AFTER_FAILURES - 1)).toBe(false); expect(loginRequiresCaptcha(LOGIN_CAPTCHA_AFTER_FAILURES)).toBe(true); expect(loginRequiresCaptcha(LOGIN_CAPTCHA_AFTER_FAILURES + 2)).toBe(true); }); it("clears the counter on a successful login", () => { const request = req(); recordFailedLogin({ request, identifier: "ada@example.test" }); recordFailedLogin({ request, identifier: "ada@example.test" }); clearFailedLogins({ request, identifier: "ada@example.test" }); expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(0); }); it("keys per identifier so a different email does not inherit the captcha gate", () => { const request = req(); recordFailedLogin({ request, identifier: "ada@example.test" }); recordFailedLogin({ request, identifier: "ada@example.test" }); recordFailedLogin({ request, identifier: "ada@example.test" }); expect(loginRequiresCaptcha(getFailedLoginCount({ request, identifier: "ada@example.test" }))).toBe(true); expect(getFailedLoginCount({ request, identifier: "mallory@example.test" })).toBe(0); expect(loginRequiresCaptcha(getFailedLoginCount({ request, identifier: "mallory@example.test" }))).toBe(false); }); });