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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Security: nobody can lock a chosen account out of logging in
Adarshd1338ef7a08d
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex dac6d7d4..824d38a8 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -46,9 +46,12 @@ it names, and only of the asker's own files: a guest owns none.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 areverse 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.+ A visitor gets 30 account log-ins a minute, right or wrong, and 10 a minute for one email. After+ 5 wrong passwords for one email, that visitor is locked out of it for 15 minutes. After 10 wrong+ passwords for one email from any number of addresses, the email is locked for 15 minutes, but+ only for the addresses that got it wrong twice or more. The person whose account it is still+ gets in from anywhere else, so nobody can lock a chosen account out. 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.tsindex 14b6e0d1..3268fd42 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -1,7 +1,7 @@import { cookies } from "next/headers";import { z } from "zod";import { authEnabled, createSession, LoginGuard, normalizeEmail, publicSignup, recordLogin, SESSION_COOKIE, verifyAccount, verifyPassword } from "@/server/auth";-import { hit } from "@/server/rate";+import { enter, 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() });@@ -10,25 +10,41 @@ declare global {var __fuobeLoginGuard: LoginGuard | undefined;var __fuobeAccountLoginGuard: LoginGuard | undefined;var __fuobeEmailLoginGuard: LoginGuard | undefined;+ var __fuobePairLoginGuard: LoginGuard | undefined;}+const PAIR_SEPARATOR = "|";+/**- * Three budgets, so one kind of guessing never locks the other out:+ * Separate budgets, so one kind of guessing never locks the other out, and nobody can lock a chosen account 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.+ * - one email from one visitor: locked for 15 minutes after 5 misses;+ * - one email from many visitors: after 10 misses in 15 minutes the email is locked for 15 minutes, but only for the+ * visitors that got it wrong twice or more. Anyone else still gets in with the right password (2 tries each), so the+ * person whose account it is can't be locked out on purpose.+ * Every miss is counted before the password is checked, so requests sent all at once can't run more checks than this.*/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 }));+/** One email from one visitor. Without a trusted proxy every visitor is the shared key: that pair slows down, never locks. */+const pairGuard = () =>+ (globalThis.__fuobePairLoginGuard ??= new LoginGuard(+ { perClient: 5, global: Infinity, windowMs: 15 * 60_000, lockMs: 15 * 60_000, throttleMs: 4_000, maxClients: 20_000 },+ (key) => key.endsWith(`${PAIR_SEPARATOR}${LoginGuard.DIRECT}`),+ ));-/** Every account log-in is counted, a right one too (each one is a slow password check): per visitor, and per email. */+/** Every account log-in is counted, a right one too (each one is a slow password check): per visitor, and per email from it. */const PER_CLIENT_A_MINUTE = 30;const PER_EMAIL_A_MINUTE = 10;+/** Tries a visitor still gets at an email many visitors got wrong. */+const TRIES_AT_A_LOCKED_EMAIL = 2;+/** Owner password checks at once (a Settings password's check is slow, and shares the server's worker threads). */+const OWNER_CHECKS_AT_ONCE = 2;function tooMany(waitMs: number, key: string) {const secs = Math.max(1, Math.ceil(waitMs / 1000));@@ -47,33 +63,53 @@ export async function POST(request: Request) {const email = parsed.success ? parsed.data.email?.trim() : undefined;let accountId: string | undefined;if (email) {- const emailKey = `email:${normalizeEmail(email) ?? email.toLowerCase()}`;- const wait = Math.max(accountGuard().blockedFor(key), emailGuard().blockedFor(emailKey));+ // Only an address that could be an account's is counted per email: made-up text adds nothing to remember.+ const emailKey = normalizeEmail(email);+ const pair = emailKey ? `${emailKey}${PAIR_SEPARATOR}${key}` : undefined;+ // The visitor's own budget first: a request it refuses adds no key at all.+ let wait = accountGuard().blockedFor(key);+ if (pair && emailKey) {+ wait = Math.max(wait, pairGuard().blockedFor(pair));+ if (key !== LoginGuard.DIRECT && pairGuard().misses(pair) >= TRIES_AT_A_LOCKED_EMAIL) wait = Math.max(wait, emailGuard().blockedFor(`email:${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) {- accountGuard().fail(key);- emailGuard().fail(emailKey);- return Response.json({ error: "Wrong email or password" }, { status: 401 });+ if (pair) {+ const perEmail = hit(`login:${pair}`, PER_EMAIL_A_MINUTE, 60_000);+ if (!perEmail.ok) return tooMany(perEmail.retryAfterS * 1000, key);}- if (account.disabled) return Response.json({ error: "This account is switched off. Ask the studio's owner." }, { status: 403 });+ // A miss until the password proves right: requests sent together are each counted before any check ends.+ accountGuard().fail(key);+ if (pair && emailKey) {+ pairGuard().fail(pair);+ emailGuard().fail(`email:${emailKey}`);+ }+ const account = emailKey && parsed.success && publicSignup(request.headers.get("host")) ? await verifyAccount(emailKey, parsed.data.password) : null;+ if (!account) return Response.json({ error: "Wrong email or password" }, { status: 401 });accountGuard().succeed(key);- emailGuard().succeed(emailKey);+ if (pair && emailKey) {+ pairGuard().succeed(pair);+ emailGuard().succeed(`email:${emailKey}`);+ }+ if (account.disabled) return Response.json({ error: "This account is switched off. Ask the studio's owner." }, { status: 403 });accountId = account.id;recordLogin(account.id);} 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 });+ const checking = enter("owner-login", OWNER_CHECKS_AT_ONCE);+ if (!checking) return tooMany(1000, key);+ // A miss until the password proves right (a Settings password's check takes a while: guesses sent together all count).+ ownerGuard().fail(key);+ let ok: boolean;+ try {+ ok = parsed.success && (await verifyPassword(parsed.data.password));+ } finally {+ checking();}+ if (!ok) return Response.json({ error: "Wrong password" }, { status: 401 });ownerGuard().succeed(key);}const s = createSession(accountId);diff --git a/src/server/auth.ts b/src/server/auth.tsindex 82cbcd06..ec26f3de 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -569,10 +569,21 @@ export class LoginGuard {private failures = new Map<string, { n: number; first: number; until: number }>();private recent: number[] = [];+ /**+ * `shared`: keys that stand for every visitor at once (no trusted proxy), which are slowed down past their budget,+ * never locked. By default the shared key itself.+ */constructor(private readonly o = { perClient: 5, global: 20, windowMs: 60_000, lockMs: 60_000, throttleMs: 4_000, maxClients: 5000 },+ private readonly shared: (key: string) => boolean = (key) => key === LoginGuard.DIRECT,) {}+ /** This key's misses in its window (0 once the window has passed). */+ misses(key: string, now = Date.now()): number {+ const f = this.failures.get(key);+ return f && now - f.first <= this.o.windowMs ? f.n : 0;+ }+/*** 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@@ -590,7 +601,7 @@ export class LoginGuard {this.recent = this.recent.filter((t) => now - t < this.o.windowMs);const f = this.failures.get(key);const own = f && f.until > now ? f.until - now : 0;- const shared = key === LoginGuard.DIRECT && !!f && now - f.first <= this.o.windowMs && f.n >= this.o.perClient;+ const shared = this.shared(key) && !!f && now - f.first <= this.o.windowMs && f.n >= this.o.perClient;const last = this.recent.at(-1);const throttle = (shared || this.recent.length >= this.o.global) && last !== undefined ? Math.max(0, last + this.o.throttleMs - now) : 0;return Math.max(own, throttle);@@ -603,7 +614,7 @@ export class LoginGuard {const n = fresh ? 1 : f.n + 1;this.failures.delete(key);// The shared key is throttled (blockedFor), never locked.- const locks = key !== LoginGuard.DIRECT && n >= this.o.perClient;+ const locks = !this.shared(key) && n >= this.o.perClient;this.failures.set(key, { n, first: fresh ? now : f.first, until: locks ? now + this.o.lockMs : 0 });// Forget old entries; never let the map grow without bound.for (const [k, v] of this.failures) {diff --git a/src/server/rate.ts b/src/server/rate.tsindex b8a03026..2f480bf5 100644--- a/src/server/rate.ts+++ b/src/server/rate.ts@@ -6,40 +6,65 @@ import "server-only";* limits that only keep one account from crowding out the others.*/+/** A key's recent hits, and when the last of them leaves its window (then the key can go). */+interface Entry {+ times: number[];+ until: number;+}+declare global {- var __fuobeRate: Map<string, number[]> | undefined;+ var __fuobeRates: Map<string, Entry> | undefined;+ var __fuobeRatesSwept: number | undefined;var __fuobeRateBusy: Map<string, number> | undefined;}-const hits = (): Map<string, number[]> => (globalThis.__fuobeRate ??= new Map());+/** The most keys kept: past it the least recently used go first. Keys whose window has passed go anyway (sweep). */+export const MAX_RATE_KEYS = 100_000;+/** How often the expired keys are looked for (a walk over every key: not on every hit). */+const SWEEP_MS = 5_000;++const hits = (): Map<string, Entry> => (globalThis.__fuobeRates ??= new Map());++function sweep(map: Map<string, Entry>, now: number): void {+ if (now - (globalThis.__fuobeRatesSwept ?? 0) >= SWEEP_MS) {+ globalThis.__fuobeRatesSwept = now;+ for (const [k, e] of map) if (e.until <= now) map.delete(k);+ }+ // Still too many: the least recently used go (a key moves to the end of the map on each hit), one step each.+ while (map.size > MAX_RATE_KEYS) map.delete(map.keys().next().value!);+}++const retryAfter = (times: number[], limit: number, windowMs: number, now: number) => Math.max(1, Math.ceil((times[times.length - limit] + windowMs - now) / 1000));/** What a key's hits look like now: ok when another fits; retryAfterS when it doesn't. */export function peek(key: string, limit: number, windowMs: number, now = Date.now()): { ok: boolean; retryAfterS: number } {- const list = (hits().get(key) ?? []).filter((t) => t > now - windowMs);- if (list.length < limit) return { ok: true, retryAfterS: 0 };- return { ok: false, retryAfterS: Math.max(1, Math.ceil((list[list.length - limit] + windowMs - now) / 1000)) };+ const times = (hits().get(key)?.times ?? []).filter((t) => t > now - windowMs);+ if (times.length < limit) return { ok: true, retryAfterS: 0 };+ return { ok: false, retryAfterS: retryAfter(times, limit, windowMs, now) };}/** Count a hit when it fits under `limit` in `windowMs`; else refuse it, with the seconds until one fits. */export function hit(key: string, limit: number, windowMs: number, now = Date.now()): { ok: boolean; retryAfterS: number } {const map = hits();- const list = (map.get(key) ?? []).filter((t) => t > now - windowMs);- if (list.length >= limit) {- map.set(key, list);- return { ok: false, retryAfterS: Math.max(1, Math.ceil((list[list.length - limit] + windowMs - now) / 1000)) };- }- list.push(now);- map.set(key, list);- // Keys nobody uses any more go (a rough sweep, so the map can't grow without end).- if (map.size > 20_000) for (const [k, v] of map) if (!v.length || v[v.length - 1] < now - 24 * 60 * 60_000) map.delete(k);- return { ok: true, retryAfterS: 0 };+ const times = (map.get(key)?.times ?? []).filter((t) => t > now - windowMs);+ const ok = times.length < limit;+ if (ok) times.push(now);+ if (times.length) {+ map.delete(key);+ map.set(key, { times, until: times[times.length - 1] + windowMs });+ } else map.delete(key);+ sweep(map, now);+ return ok ? { ok, retryAfterS: 0 } : { ok, retryAfterS: retryAfter(times, limit, windowMs, now) };}/** Take back the last hit of a key (a request refused for another reason after it was counted). */export function unhit(key: string): void {- hits().get(key)?.pop();+ hits().get(key)?.times.pop();}+/** How many keys the limiter holds (tests: it must not grow without end). */+export const rateKeyCount = () => hits().size;+/** At most `limit` at once for a key: returns a release function, or null when the key is full. */export function enter(key: string, limit: number): (() => void) | null {const busy = (globalThis.__fuobeRateBusy ??= new Map());@@ -58,6 +83,7 @@ export function enter(key: string, limit: number): (() => void) | null {/** Tests: forget every count. */export function resetRates(): void {- globalThis.__fuobeRate?.clear();+ globalThis.__fuobeRates?.clear();+ globalThis.__fuobeRatesSwept = undefined;globalThis.__fuobeRateBusy?.clear();}diff --git a/tests/sign-in-hardening.test.ts b/tests/sign-in-hardening.test.tsindex b30d133d..2dbf6b74 100644--- a/tests/sign-in-hardening.test.ts+++ b/tests/sign-in-hardening.test.ts@@ -72,13 +72,21 @@ describe("M-1: after sign-in, only pages on this site", () => {});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" }));+ it("counts a right password too: one address gets 10 log-ins a minute to one email", async () => {+ const from = nextIp();+ for (let i = 0; i < 10; i++) expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }, from))).status, `log-in ${i}`).toBe(200);+ const r = await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }, from));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);+ // Another email, and the same email from another address, are not affected.+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "other password" }, from))).status).toBe(200);+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }))).status).toBe(200);+ });++ it("one address gets 30 account log-ins a minute in all", async () => {+ const from = nextIp();+ for (let i = 0; i < 30; i++) await login.POST(post("/api/auth/login", { email: i % 2 ? "[email protected]" : "[email protected]", password: i % 2 ? "member password" : "other password" }, from));+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }, from))).status).toBe(429);});it("checks a password without the synchronous scrypt", async () => {@@ -111,6 +119,34 @@ describe("M-2: password checks are counted and never hold up the server", () =>});});+describe("guests can't grow the rate limiter's memory", () => {+ it("a log-in refused by the visitor's own budget, or with a made-up email, adds no key", async () => {+ const { rateKeyCount } = await import("@/server/rate");+ const from = nextIp();+ for (let i = 0; i < 30; i++) await login.POST(post("/api/auth/login", { email: `spent${i}@example.com`, password: "wrong password" }, from));+ const before = rateKeyCount();+ for (let i = 0; i < 50; i++) expect((await login.POST(post("/api/auth/login", { email: `random${i}-${"a".repeat(200)}@example.com`, password: "x" }, from))).status).toBe(429);+ expect(rateKeyCount()).toBe(before);+ // Text that isn't an email address: no key for it, only the visitor's own.+ const other = nextIp();+ expect((await login.POST(post("/api/auth/login", { email: "z".repeat(250), password: "x" }, other))).status).toBe(401);+ expect(rateKeyCount()).toBe(before + 1);+ });++ it("drops a key once its window has passed, and never keeps more than its cap", async () => {+ const { hit, rateKeyCount, MAX_RATE_KEYS } = await import("@/server/rate");+ const t = Date.now();+ for (let i = 0; i < 1000; i++) hit(`short:${i}`, 5, 1000, t);+ expect(rateKeyCount()).toBe(1000);+ hit("later", 5, 1000, t + 10_000);+ expect(rateKeyCount()).toBe(1);+ for (let i = 0; i < MAX_RATE_KEYS + 50; i++) hit(`long:${i}`, 5, 60 * 60_000, t + 20_000);+ expect(rateKeyCount()).toBeLessThanOrEqual(MAX_RATE_KEYS);+ // The newest keys are the ones kept.+ expect(hit(`long:${MAX_RATE_KEYS + 49}`, 1, 60 * 60_000, t + 20_001).ok).toBe(false);+ });+});+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);@@ -131,10 +167,44 @@ describe("M-4: one visitor's wrong guesses don't lock everyone out", () => {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("after 10 wrong passwords to one email from many addresses, only the addresses that got it wrong are locked out of it", async () => {+ const guesser = nextIp();+ for (let i = 0; i < 2; i++) expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: `wrong ${i}` }, guesser))).status).toBe(401);+ for (let i = 2; i < 10; i++) expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: `wrong ${i}` }))).status).toBe(401);+ // An address that guessed wrong twice: locked out of this email, even with the right password.+ const r = await login.POST(post("/api/auth/login", { email: "[email protected]", password: "other password" }, guesser));+ expect(r.status).toBe(429);+ expect(Number(r.headers.get("retry-after"))).toBeGreaterThan(60);+ // The person whose account it is, from any other address: in at once, so nobody can lock them out on purpose.+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "other password" }))).status).toBe(200);+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "member password" }, guesser))).status).toBe(200);+ });++ it("an address gets 2 tries at an email many addresses got wrong", async () => {+ for (let i = 0; i < 10; i++) await login.POST(post("/api/auth/login", { email: "[email protected]", password: `wrong ${i}` }));+ const late = nextIp();+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "wrong again" }, late))).status).toBe(401);+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "wrong once more" }, late))).status).toBe(401);+ expect((await login.POST(post("/api/auth/login", { email: "[email protected]", password: "other password" }, late))).status).toBe(429);+ });++ it("counts owner guesses sent all at once before any is checked (a Settings password's check takes a while)", async () => {+ const from = nextIp();+ const answers = await Promise.all(Array.from({ length: 40 }, (_, i) => login.POST(post("/api/auth/login", { password: `wrong ${i}` }, from))));+ const statuses = answers.map((r) => r.status);+ expect(statuses.filter((s) => s === 401).length).toBeLessThanOrEqual(5);+ expect(statuses.filter((s) => s === 429).length).toBeGreaterThanOrEqual(35);+ });++ it("checks at most a few owner passwords at once", async () => {+ const { enter } = await import("@/server/rate");+ const held = [enter("owner-login", 2), enter("owner-login", 2)];+ try {+ expect((await login.POST(post("/api/auth/login", { password: "install password" }))).status).toBe(429);+ } finally {+ for (const release of held) release?.();+ }+ expect((await login.POST(post("/api/auth/login", { password: "install password" }))).status).toBe(200);});it("counts only sign-ups that could make an account: empty bodies don't slow sign-up for everyone", async () => {