Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Security: safer sign-in limits and redirects after sign-in

Adarshb5f3ab91de6f
diff --git a/docs/public-signup.md b/docs/public-signup.md
index bc94fa4e..f2965b5c 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -45,7 +45,10 @@ it names, and only of the asker's own files: a guest owns none.
- Accounts are stored in `auth.json` in the data folder: the email in lower case, a salted scrypt
hash of the password (the same scheme as the install password), and the creation time.
- Sign-up and log-in attempts are rate limited per visitor (set `FUOBE_TRUST_PROXY=1` behind a
- reverse proxy, so that each visitor gets their own limit).
+ reverse proxy, so that each visitor gets their own limit; an IPv6 address counts by its /64).
+ An email gets 10 log-ins a minute, right or wrong, and after 10 wrong passwords in 15 minutes
+ it is locked for 15 minutes, from any address. Account log-ins and the install password have
+ separate limits, so guessing at one never slows down the other.
An account is signed in, but it sees the owner's studio as a guest does:
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index 58eb309e..14b6e0d1 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -1,45 +1,81 @@
import { cookies } from "next/headers";
import { z } from "zod";
-import { authEnabled, checkAccount, checkPassword, createSession, LoginGuard, publicSignup, recordLogin, SESSION_COOKIE } from "@/server/auth";
+import { authEnabled, createSession, LoginGuard, normalizeEmail, publicSignup, recordLogin, SESSION_COOKIE, verifyAccount, verifyPassword } from "@/server/auth";
+import { hit } from "@/server/rate";
/** The install password alone (the owner), or an account's email and password (public sign-up). */
const Body = z.object({ password: z.string().min(1).max(500), email: z.string().max(254).optional() });
declare global {
var __fuobeLoginGuard: LoginGuard | undefined;
+ var __fuobeAccountLoginGuard: LoginGuard | undefined;
+ var __fuobeEmailLoginGuard: LoginGuard | undefined;
+}
+
+/**
+ * Three budgets, so one kind of guessing never locks the other out:
+ * - the install password (the owner's sign-in): a visitor is locked for a minute after 5 misses, and past 20 misses a
+ * minute from everyone, every try waits a few seconds;
+ * - account log-ins, per visitor: locked for a minute after 5 misses;
+ * - account log-ins, per email: locked for 15 minutes after 10 misses in 15 minutes, from any number of addresses.
+ * Account guessing has no global slowdown: the per-email lock already caps how often one password can be tried.
+ */
+const ownerGuard = () => (globalThis.__fuobeLoginGuard ??= new LoginGuard());
+const accountGuard = () =>
+ (globalThis.__fuobeAccountLoginGuard ??= new LoginGuard({ perClient: 5, global: Infinity, windowMs: 60_000, lockMs: 60_000, throttleMs: 4_000, maxClients: 5000 }));
+const emailGuard = () =>
+ (globalThis.__fuobeEmailLoginGuard ??= new LoginGuard({ perClient: 10, global: Infinity, windowMs: 15 * 60_000, lockMs: 15 * 60_000, throttleMs: 4_000, maxClients: 20_000 }));
+
+/** Every account log-in is counted, a right one too (each one is a slow password check): per visitor, and per email. */
+const PER_CLIENT_A_MINUTE = 30;
+const PER_EMAIL_A_MINUTE = 10;
+
+function tooMany(waitMs: number, key: string) {
+ const secs = Math.max(1, Math.ceil(waitMs / 1000));
+ // Without a trusted proxy every visitor shares one limit (the hint is for whoever runs the server).
+ const hint = key === LoginGuard.DIRECT ? " Behind a reverse proxy? Set FUOBE_TRUST_PROXY=1 so each visitor gets their own limit." : "";
+ return Response.json(
+ { error: `Too many sign-in attempts. Try again in ${secs} second${secs === 1 ? "" : "s"}.${hint}` },
+ { status: 429, headers: { "Retry-After": String(secs) } },
+ );
}
-const guard = (globalThis.__fuobeLoginGuard ??= new LoginGuard());
export async function POST(request: Request) {
if (!authEnabled()) return Response.json({ ok: true });
const key = LoginGuard.clientKey(request.headers);
- const wait = guard.blockedFor(key);
- if (wait > 0) {
- const secs = Math.ceil(wait / 1000);
- // Without a trusted proxy every visitor shares one limit (the hint is for whoever runs the server).
- const hint = key === LoginGuard.DIRECT ? " Behind a reverse proxy? Set FUOBE_TRUST_PROXY=1 so each visitor gets their own limit." : "";
- return Response.json(
- { error: `Too many wrong passwords. Try again in ${secs} second${secs === 1 ? "" : "s"}.${hint}` },
- { status: 429, headers: { "Retry-After": String(secs) } },
- );
- }
const parsed = Body.safeParse(await request.json().catch(() => null));
const email = parsed.success ? parsed.data.email?.trim() : undefined;
let accountId: string | undefined;
if (email) {
- const account = parsed.success && publicSignup(request.headers.get("host")) ? checkAccount(email, parsed.data.password) : null;
+ const emailKey = `email:${normalizeEmail(email) ?? email.toLowerCase()}`;
+ const wait = Math.max(accountGuard().blockedFor(key), emailGuard().blockedFor(emailKey));
+ if (wait > 0) return tooMany(wait, key);
+ // Counted before the password is checked, so a burst can't run more checks than the budget allows.
+ const perEmail = hit(`login:${emailKey}`, PER_EMAIL_A_MINUTE, 60_000);
+ if (!perEmail.ok) return tooMany(perEmail.retryAfterS * 1000, key);
+ // The shared key (no trusted proxy) is every visitor at once: only the per-email budget applies to it.
+ const perClient = key === LoginGuard.DIRECT ? { ok: true, retryAfterS: 0 } : hit(`login:${key}`, PER_CLIENT_A_MINUTE, 60_000);
+ if (!perClient.ok) return tooMany(perClient.retryAfterS * 1000, key);
+ const account = parsed.success && publicSignup(request.headers.get("host")) ? await verifyAccount(email, parsed.data.password) : null;
if (!account) {
- guard.fail(key);
+ accountGuard().fail(key);
+ emailGuard().fail(emailKey);
return Response.json({ error: "Wrong email or password" }, { status: 401 });
}
if (account.disabled) return Response.json({ error: "This account is switched off. Ask the studio's owner." }, { status: 403 });
+ accountGuard().succeed(key);
+ emailGuard().succeed(emailKey);
accountId = account.id;
recordLogin(account.id);
- } else if (!parsed.success || !checkPassword(parsed.data.password)) {
- guard.fail(key);
- return Response.json({ error: "Wrong password" }, { status: 401 });
+ } else {
+ const wait = ownerGuard().blockedFor(key);
+ if (wait > 0) return tooMany(wait, key);
+ if (!parsed.success || !(await verifyPassword(parsed.data.password))) {
+ ownerGuard().fail(key);
+ return Response.json({ error: "Wrong password" }, { status: 401 });
+ }
+ ownerGuard().succeed(key);
}
- guard.succeed(key);
const s = createSession(accountId);
(await cookies()).set(SESSION_COOKIE, s.value, {
httpOnly: true,
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index cec4125b..d24db036 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -1,8 +1,9 @@
import { cookies } from "next/headers";
import { connection } from "next/server";
import { z } from "zod";
-import { authEnabled, checkAccount, deleteAccount, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken } from "@/server/auth";
+import { authEnabled, deleteAccount, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, validToken, verifyAccount } from "@/server/auth";
import { purgeAccount } from "@/server/account-sweep";
+import { hit } from "@/server/rate";
/** Who is looking: the owner, an account, or a guest; and whether sign-up is open. Open to everyone. */
export async function GET(request: Request) {
@@ -22,13 +23,19 @@ export async function GET(request: Request) {
);
}
-/** An account deletes itself (its password again, to be sure). Signs it out. */
+/**
+ * An account deletes itself (its password again, to be sure). Signs it out. Five password checks a minute per account:
+ * each is a slow check on purpose.
+ */
export async function DELETE(request: Request) {
const jar = await cookies();
const session = sessionViewer(sessionCookieOf(request));
if (session?.kind !== "account") return Response.json({ error: "Sign in to the account you want to delete" }, { status: 403 });
const parsed = z.object({ password: z.string().min(1).max(500) }).safeParse(await request.json().catch(() => null));
- if (!parsed.success || !checkAccount(session.account.email, parsed.data.password)) return Response.json({ error: "Wrong password" }, { status: 403 });
+ if (!parsed.success) return Response.json({ error: "Wrong password" }, { status: 403 });
+ const rate = hit(`delete-me:${session.account.id}`, 5, 60_000);
+ if (!rate.ok) return Response.json({ error: "Too many tries. Wait a minute, then try again." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });
+ if (!(await verifyAccount(session.account.email, parsed.data.password))) return Response.json({ error: "Wrong password" }, { status: 403 });
deleteAccount(session.account.id);
jar.delete(SESSION_COOKIE);
// Its runs and files go with it (running ones are stopped first).
diff --git a/src/app/api/auth/signup/route.ts b/src/app/api/auth/signup/route.ts
index e7d51edf..2b0b6c56 100644
--- a/src/app/api/auth/signup/route.ts
+++ b/src/app/api/auth/signup/route.ts
@@ -7,21 +7,24 @@ const Body = z.object({ email: z.string().max(254), password: z.string().max(500
declare global {
var __fuobeSignupGuard: LoginGuard | undefined;
}
-/** Every sign-up counts, made or not: a client makes at most 5 a minute, and everyone slows down past 20. */
-const guard = (globalThis.__fuobeSignupGuard ??= new LoginGuard());
+/**
+ * Every sign-up that could make an account counts, made or not: a client makes at most 5 a minute, and everyone slows
+ * down past 20. A request without an email and a password counts for nothing, so it can't slow anyone else down.
+ */
+const guard = () => (globalThis.__fuobeSignupGuard ??= new LoginGuard());
/** Public sign-up: an account from an email and a password (8+ characters, no verification), signed in at once. */
export async function POST(request: Request) {
if (!publicSignup(request.headers.get("host"))) return Response.json({ error: "Sign-up is off on this studio" }, { status: 404 });
const key = LoginGuard.clientKey(request.headers);
- const wait = guard.blockedFor(key);
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Enter an email and a password" }, { status: 400 });
+ const wait = guard().blockedFor(key);
if (wait > 0) {
const secs = Math.ceil(wait / 1000);
return Response.json({ error: `Too many sign-ups. Try again in ${secs} second${secs === 1 ? "" : "s"}.` }, { status: 429, headers: { "Retry-After": String(secs) } });
}
- guard.fail(key);
- const parsed = Body.safeParse(await request.json().catch(() => null));
- if (!parsed.success) return Response.json({ error: "Enter an email and a password" }, { status: 400 });
+ guard().fail(key);
let account;
try {
account = createAccount(parsed.data.email, parsed.data.password);
diff --git a/src/lib/safe-redirect.ts b/src/lib/safe-redirect.ts
index 99ab374a..d5bf1d5d 100644
--- a/src/lib/safe-redirect.ts
+++ b/src/lib/safe-redirect.ts
@@ -1,13 +1,16 @@
/**
* Where to go after signing in: only a path on this site. "/\evil.example" or "/\t/evil.example"
* look like paths but the URL parser reads them as another host, so the check resolves the URL
- * and compares origins instead of looking at the first characters.
+ * and compares origins instead of looking at the first characters. A path that resolves to
+ * "//evil.example" ("/.//evil.example", "/a/..//evil.example") is refused too: navigating to it
+ * leaves the site.
*/
export function safeNext(next: string | null | undefined, origin: string): string {
if (!next) return "/";
try {
const u = new URL(next, origin);
- return u.origin === new URL(origin).origin ? `${u.pathname}${u.search}${u.hash}` : "/";
+ if (u.origin !== new URL(origin).origin || /^[/\\]{2}/.test(u.pathname)) return "/";
+ return `${u.pathname}${u.search}${u.hash}`;
} catch {
return "/";
}
diff --git a/src/server/auth.ts b/src/server/auth.ts
index 9c176b09..afbb1908 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -124,6 +124,15 @@ function verifyHash(pw: string, stored: string): boolean {
return same(crypto.scryptSync(pw, Buffer.from(salt, "hex"), 32), Buffer.from(hash, "hex"));
}
+/** scrypt off the main thread: the server keeps answering everyone else while a password is checked. */
+const scrypt = (pw: string, salt: Buffer) => new Promise<Buffer>((resolve, reject) => crypto.scrypt(pw, salt, 32, (e, key) => (e ? reject(e) : resolve(key))));
+
+async function verifyHashAsync(pw: string, stored: string): Promise<boolean> {
+ const [salt, hash] = stored.split(":");
+ if (!salt || !hash) return false;
+ return same(await scrypt(pw, Buffer.from(salt, "hex")), Buffer.from(hash, "hex"));
+}
+
export function checkPassword(pw: string): boolean {
const env = envPassword();
if (env) return same(crypto.createHash("sha256").update(pw).digest(), crypto.createHash("sha256").update(env).digest());
@@ -132,6 +141,13 @@ export function checkPassword(pw: string): boolean {
return verifyHash(pw, stored);
}
+/** {@link checkPassword} for a request: the Settings password's scrypt runs off the main thread. */
+export async function verifyPassword(pw: string): Promise<boolean> {
+ if (envPassword()) return checkPassword(pw);
+ const stored = read().password;
+ return !!stored && (await verifyHashAsync(pw, stored));
+}
+
/** Set, change or (with null) remove the UI password. Signs every browser out. */
export function setPassword(pw: string | null): void {
if (envPassword()) throw new Error("The password is set by FUOBE_PASSWORD on the server");
@@ -241,9 +257,30 @@ export function checkAccount(email: string, password: string): Account | null {
return account && ok ? account : null;
}
-/** Remember a log-in (Settings → Accounts shows it). */
+let dummyAsync: Promise<string> | undefined;
+
+/** {@link checkAccount} for a request: scrypt runs off the main thread, and an unknown email costs the same as a known one. */
+export async function verifyAccount(email: string, password: string): Promise<Account | null> {
+ const e = normalizeEmail(email);
+ const account = e ? read().accounts?.find((a) => a.email === e) : undefined;
+ const stored =
+ account?.hash ??
+ (await (dummyAsync ??= (async () => {
+ const salt = crypto.randomBytes(16);
+ return `${salt.toString("hex")}:${(await scrypt(crypto.randomBytes(12).toString("hex"), salt)).toString("hex")}`;
+ })()));
+ const ok = await verifyHashAsync(password, stored);
+ return account && ok ? account : null;
+}
+
+/** How often a log-in is written down: each write rewrites the whole accounts file. */
+const LOGIN_RECORD_MS = 60 * 60_000;
+
+/** Remember a log-in (Settings → Accounts shows it), at most once an hour per account. */
export function recordLogin(id: string): void {
const d = read();
+ const account = d.accounts?.find((a) => a.id === id);
+ if (!account || Date.now() - (account.lastLoginAt ?? 0) < LOGIN_RECORD_MS) return;
write({ ...d, accounts: d.accounts?.map((a) => (a.id === id ? { ...a, lastLoginAt: Date.now() } : a)) });
}
@@ -479,6 +516,22 @@ export function hostAllowed(host: string | null): boolean {
// ---------------------------------------------------------------------------
// Sign-in attempts
+/** A visitor's key from its address: IPv4 as it is, IPv6 by its first 64 bits ("2001:db8:1:2::/64"). */
+function clientOf(address: string): string {
+ const a = address.replace(/^\[(.*)\]$/, "$1").toLowerCase();
+ if (!net.isIPv6(a)) return a;
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(a);
+ if (mapped) return mapped[1];
+ // A trailing dotted IPv4 part is two groups.
+ const v4 = /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(a);
+ const hex = v4 ? a.slice(0, v4.index) + [((+v4[1] << 8) | +v4[2]).toString(16), ((+v4[3] << 8) | +v4[4]).toString(16)].join(":") : a;
+ const [head, tail] = hex.split("::");
+ const left = head ? head.split(":") : [];
+ const right = tail !== undefined && tail ? tail.split(":") : [];
+ const groups = tail === undefined ? left : [...left, ...Array<string>(8 - left.length - right.length).fill("0"), ...right];
+ return `${groups.slice(0, 4).map((g) => (parseInt(g, 16) || 0).toString(16)).join(":")}::/64`;
+}
+
/**
* Wrong-password limits. Route handlers can't see the socket address, and Next keeps any
* X-Forwarded-For a client sends, so that header only identifies a client behind a reverse proxy
@@ -497,11 +550,16 @@ export class LoginGuard {
private readonly o = { perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, throttleMs: 4_000, maxClients: 5000 },
) {}
- /** Who is signing in: the last X-Forwarded-For hop when a trusted proxy sets it, else one shared key. */
+ /**
+ * Who is signing in: the last X-Forwarded-For hop when a trusted proxy sets it, else one shared key. An IPv6 address
+ * counts by its /64 (one home or one server gets a whole /64, so the rest of the address is free to change), and an
+ * IPv4 address written as IPv6 (::ffff:a.b.c.d) as that IPv4 address.
+ */
static clientKey(headers: Headers, trustProxy = process.env.FUOBE_TRUST_PROXY === "1"): string {
if (!trustProxy) return LoginGuard.DIRECT;
const hops = (headers.get("x-forwarded-for") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
- return hops.at(-1) ?? LoginGuard.DIRECT;
+ const last = hops.at(-1);
+ return last ? clientOf(last) : LoginGuard.DIRECT;
}
/** Milliseconds until this client may try again (0 = now). */
diff --git a/tests/sign-in-hardening.test.ts b/tests/sign-in-hardening.test.ts
new file mode 100644
index 00000000..756e3f54
--- /dev/null
+++ b/tests/sign-in-hardening.test.ts
@@ -0,0 +1,144 @@
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+// Route handlers set the session cookie through cookies() (no request scope in a test): a jar that only records.
+const jar = { set: vi.fn(), delete: vi.fn(), get: vi.fn() };
+vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => jar }));
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-sign-in-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+process.env.FUOBE_TRUST_PROXY = "1";
+delete process.env.FUOBE_PASSWORD;
+
+const auth = await import("@/server/auth");
+const { safeNext } = await import("@/lib/safe-redirect");
+const { resetRates } = await import("@/server/rate");
+const login = await import("@/app/api/auth/login/route");
+const signup = await import("@/app/api/auth/signup/route");
+const me = await import("@/app/api/auth/me/route");
+
+const globals = globalThis as Record<string, unknown>;
+/** A fresh start for every limit: guards live on globalThis so a dev server's reloads keep them. */
+function resetGuards() {
+ for (const k of Object.keys(globals)) if (/^__fuobe\w*Guard$/.test(k)) delete globals[k];
+ resetRates();
+}
+
+let ip = 0;
+/** A visitor's address, as Apache passes it on (the last X-Forwarded-For hop). */
+const nextIp = () => `198.51.100.${++ip % 250}`;
+const post = (url: string, body: unknown, from = nextIp(), cookie?: string, method = "POST") =>
+ new Request(`http://localhost:3000${url}`, {
+ method,
+ headers: { "content-type": "application/json", "x-forwarded-for": from, ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) },
+ body: JSON.stringify(body),
+ });
+
+beforeAll(() => {
+ auth.setPassword("install password");
+ auth.createAccount("[email protected]", "member password");
+ auth.createAccount("[email protected]", "other password");
+});
+afterEach(() => {
+ resetGuards();
+ vi.restoreAllMocks();
+});
+afterAll(() => {
+ delete process.env.FUOBE_PUBLIC_SIGNUP;
+ delete process.env.FUOBE_TRUST_PROXY;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+describe("M-1: after sign-in, only pages on this site", () => {
+ const origin = "http://localhost:3000";
+ it("refuses a path that resolves to another host", () => {
+ for (const bad of ["/.//evil.example", "/a/..//evil.example", "/%2e//evil.example", "/./\\evil.example", "http://localhost:3000//evil.example/login?owner=1", "/..//evil.example"]) {
+ expect(safeNext(bad, origin), bad).toBe("/");
+ }
+ });
+
+ it("keeps ordinary paths", () => {
+ expect(safeNext("/video?model=kling-3#x", origin)).toBe("/video?model=kling-3#x");
+ expect(safeNext("/a//b", origin)).toBe("/a//b");
+ expect(safeNext("/library/../settings", origin)).toBe("/settings");
+ });
+});
+
+describe("M-2: password checks are counted and never hold up the server", () => {
+ it("counts a right password too: an email gets 10 log-ins a minute, from any address", async () => {
+ for (let i = 0; i < 10; i++) expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status, `log-in ${i}`).toBe(200);
+ const r = await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }));
+ expect(r.status).toBe(429);
+ expect(r.headers.get("retry-after")).toBeTruthy();
+ // Another email is not affected.
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "other password" }))).status).toBe(200);
+ });
+
+ it("checks a password without the synchronous scrypt", async () => {
+ const sync = vi.spyOn(crypto, "scryptSync");
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "wrong password" }))).status).toBe(401);
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "wrong password" }))).status).toBe(401);
+ expect((await login.POST(post("/api/auth/login", { password: "install password" }))).status).toBe(200);
+ expect(sync).not.toHaveBeenCalled();
+ await expect(auth.verifyAccount("[email protected]", "member password")).resolves.toMatchObject({ email: "[email protected]" });
+ await expect(auth.verifyAccount("[email protected]", "nope nope")).resolves.toBeNull();
+ await expect(auth.verifyPassword("install password")).resolves.toBe(true);
+ await expect(auth.verifyPassword("nope nope")).resolves.toBe(false);
+ });
+
+ it("records a log-in at most once an hour, so log-ins don't rewrite the accounts file", async () => {
+ const file = path.join(dir, "auth.json");
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);
+ const before = fs.readFileSync(file, "utf8");
+ for (let i = 0; i < 3; i++) expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);
+ expect(fs.readFileSync(file, "utf8")).toBe(before);
+ });
+
+ it("an account deleting itself gets 5 password checks a minute", async () => {
+ const a = auth.createAccount("[email protected]", "deleter password");
+ const cookie = auth.createSession(a.id).value;
+ for (let i = 0; i < 5; i++) expect((await me.DELETE(post("/api/auth/me", { password: "wrong password" }, nextIp(), cookie, "DELETE"))).status).toBe(403);
+ expect((await me.DELETE(post("/api/auth/me", { password: "deleter password" }, nextIp(), cookie, "DELETE"))).status).toBe(429);
+ expect(auth.accountById(a.id)).toBeDefined();
+ });
+});
+
+describe("M-4: one visitor's wrong guesses don't lock everyone out", () => {
+ it("treats an IPv6 /64 as one visitor, and an IPv4-mapped address as IPv4", () => {
+ const key = (xff: string) => auth.LoginGuard.clientKey(new Headers({ "x-forwarded-for": xff }), true);
+ expect(key("2001:db8:1:2::1")).toBe(key("2001:db8:1:2:ffff:ffff:ffff:ffff"));
+ expect(key("2001:db8:1:2::1")).toBe(key("2001:0DB8:0001:0002:0000:0000:0000:0042"));
+ expect(key("2001:db8:1:2::1")).not.toBe(key("2001:db8:1:3::1"));
+ expect(key("::ffff:203.0.113.9")).toBe("203.0.113.9");
+ expect(key("203.0.113.9")).toBe("203.0.113.9");
+ });
+
+ it("wrong account passwords from many addresses don't slow the owner's sign-in", async () => {
+ for (let i = 0; i < 30; i++) await login.POST(post("/api/auth/login", { email: `guess${i}@example.com`, password: "wrong password" }));
+ expect((await login.POST(post("/api/auth/login", { password: "install password" }))).status).toBe(200);
+ });
+
+ it("wrong owner passwords from many addresses don't stop accounts from logging in", async () => {
+ for (let i = 0; i < 30; i++) await login.POST(post("/api/auth/login", { password: `wrong ${i}` }));
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);
+ });
+
+ it("locks one email after 10 wrong passwords from any number of addresses, and only that email", async () => {
+ for (let i = 0; i < 10; i++) expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: `wrong ${i}` }))).status).toBe(401);
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "other password" }))).status).toBe(429);
+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);
+ });
+
+ it("counts only sign-ups that could make an account: empty bodies don't slow sign-up for everyone", async () => {
+ for (let i = 0; i < 30; i++) expect((await signup.POST(post("/api/auth/signup", {}))).status).toBe(400);
+ expect((await signup.POST(post("/api/auth/signup", { email: "[email protected]", password: "newcomer password" }))).status).toBe(201);
+ });
+});