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: accounts can't fill the server's disk or memory with sign-ups
Adarsh9c6e0cdb7f41
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex f2965b5c..dac6d7d4 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -166,9 +166,13 @@ multipart form works up to 26 MB). Without a connected GPU it answers 403 with- The type is read from the file's first bytes. A file that isn't one of these answers 415.- `Content-Length` is required (411), and a file over its size answers 413 before it is read.-- An account keeps up to 1 GB of uploads and 3 GB of files in all (uploads and results). Past that,- uploads and runs answer 413: delete some runs to make room.-- Up to 60 uploads an hour, 300 a day and 2 at once (429 with `Retry-After`).+- An account keeps up to 1 GB of uploads and 3 GB of files in all (uploads and results); in its+ first 7 days, 1 GB in all. Past that, uploads and runs answer 413: delete some runs to make room.+- All accounts together keep at most a quarter of the data disk (`FUOBE_ACCOUNTS_DISK_GB` sets+ it), and the disk always keeps its free floor (`FUOBE_ACCOUNT_DISK_FREE_GB`). Past either,+ account uploads and runs answer 503 "short of space"; the owner's work is not affected.+- Up to 60 uploads an hour, 300 a day and 2 at once (429 with `Retry-After`), and 8 at once from+ every account together. One address makes at most 5 accounts a day.- **How long files stay.** Uploads are removed after 14 days, even when a run still uses them.Runs and their results are removed after 30 days. Everything goes at once when the account isdeleted.diff --git a/src/app/api/auth/signup/route.ts b/src/app/api/auth/signup/route.tsindex 2b0b6c56..f83909b7 100644--- a/src/app/api/auth/signup/route.ts+++ b/src/app/api/auth/signup/route.ts@@ -1,6 +1,7 @@import { cookies } from "next/headers";import { z } from "zod";import { AccountError, createAccount, createSession, LoginGuard, publicSignup, SESSION_COOKIE } from "@/server/auth";+import { hit, peek } from "@/server/rate";const Body = z.object({ email: z.string().max(254), password: z.string().max(500) });@@ -12,6 +13,8 @@ declare global {* 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());+const SIGNUPS_A_DAY = 5;+const DAY = 24 * 60 * 60_000;/** 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) {@@ -25,6 +28,9 @@ export async function POST(request: Request) {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);+ // At most 5 accounts a day from one address (the shared key, without a trusted proxy, is everyone: not capped here).+ const today = key === LoginGuard.DIRECT ? null : peek(`signup-day:${key}`, SIGNUPS_A_DAY, DAY);+ if (today && !today.ok) return Response.json({ error: "You've made enough accounts for today. Try again tomorrow." }, { status: 429, headers: { "Retry-After": String(today.retryAfterS) } });let account;try {account = createAccount(parsed.data.email, parsed.data.password);@@ -32,6 +38,7 @@ export async function POST(request: Request) {if (e instanceof AccountError) return Response.json({ error: e.message }, { status: e.status });throw e;}+ if (key !== LoginGuard.DIRECT) hit(`signup-day:${key}`, SIGNUPS_A_DAY, DAY);const s = createSession(account.id);(await cookies()).set(SESSION_COOKIE, s.value, {httpOnly: true,diff --git a/src/app/api/generations/[id]/finish/route.ts b/src/app/api/generations/[id]/finish/route.tsindex 123b071f..dfa612eb 100644--- a/src/app/api/generations/[id]/finish/route.ts+++ b/src/app/api/generations/[id]/finish/route.ts@@ -1,4 +1,4 @@-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "@/server/account-files";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { requestAccount } from "@/server/auth";import { gateAsProxy } from "@/server/direct-gate";import { FinishError, finishOutput } from "@/server/generations";@@ -33,7 +33,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/generationsif (account) {const refuse = (status: number, error: string, headers: Record<string, string> = {}) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store", ...headers } });if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);- if (accountUsage(account.id).total + data.length > ACCOUNT_LIMITS.totalBytes) return refuse(413, ACCOUNT_MESSAGES.filesFull);+ if (accountUsage(account.id).total + data.length > accountTotalBytes(account.id)) return refuse(413, filesFullMessage(account.id));const rate = hit(`finish:${account.id}`, ACCOUNT_LIMITS.finishesPerHour, 60 * 60_000);if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.finishRate, { "Retry-After": String(rate.retryAfterS) });}diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 67847c72..cbc6767d 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -3,7 +3,7 @@ import { CONNECT_GPU_HEADER, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/limport { missingFilesMessage } from "@/lib/missing-files";import { accountGpu, requestViewer } from "@/server/auth";import { OPERATION_LABELS } from "@/lib/catalog/types";-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "@/server/account-files";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { accountInputProblem } from "@/server/account-inputs";import { db } from "@/server/db";import { accountLoraFix, accountRun, asVisitor, createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";@@ -84,7 +84,7 @@ export async function POST(request: Request) {if (account && !preview) {// Room on the server, room in the account's files, and a fair share of runs.if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);- if (accountUsage(account.id).total >= ACCOUNT_LIMITS.totalBytes) return refuse(413, ACCOUNT_MESSAGES.filesFull);+ if (accountUsage(account.id).total >= accountTotalBytes(account.id)) return refuse(413, filesFullMessage(account.id));if (activeRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, {}, { "Retry-After": "30" });const rate = hit(`run:${account.id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.tsindex 015d0f59..448eddc3 100644--- a/src/app/api/uploads/route.ts+++ b/src/app/api/uploads/route.ts@@ -4,7 +4,7 @@ import { nanoid } from "nanoid";import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE } from "@/lib/guest-access";import { imageSize } from "@/lib/image-size";import { sniffMedia, type SniffKind } from "@/lib/sniff";-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "@/server/account-files";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";import { accountGpu, type Account } from "@/server/auth";import { gateDirect } from "@/server/direct-gate";import { enter, hit } from "@/server/rate";@@ -149,9 +149,16 @@ async function accountUpload(request: Request, account: Account): Promise<Responif (!hour.ok || !day.ok) return json(429, { error: ACCOUNT_MESSAGES.uploadRate }, { "Retry-After": String(Math.max(hour.retryAfterS, day.retryAfterS)) });const release = enter(`up:${account.id}`, ACCOUNT_LIMITS.uploadsAtOnce);if (!release) return json(429, { error: ACCOUNT_MESSAGES.uploadRate }, { "Retry-After": "10" });+ // And a few at once from every account together.+ const releaseAll = enter("up:accounts", ACCOUNT_LIMITS.uploadsAtOnceAll);+ if (!releaseAll) {+ release();+ return json(429, { error: ACCOUNT_MESSAGES.uploadRate }, { "Retry-After": "10" });+ }try {return await accountUploadBody(request, account);} finally {+ releaseAll();release();}}@@ -170,7 +177,7 @@ async function accountUploadBody(request: Request, account: Account): Promise<Reif (length > ACCOUNT_LIMITS.videoBytes) return json(413, { error: ACCOUNT_MESSAGES.videoTooBig });const usage = accountUsage(account.id);if (usage.uploads + length > ACCOUNT_LIMITS.uploadsBytes) return json(413, { error: ACCOUNT_MESSAGES.uploadsFull });- if (usage.total + length > ACCOUNT_LIMITS.totalBytes) return json(413, { error: ACCOUNT_MESSAGES.filesFull });+ if (usage.total + length > accountTotalBytes(account.id)) return json(413, { error: filesFullMessage(account.id) });const dest = tempFile();let bytes: number;diff --git a/src/server/account-files.ts b/src/server/account-files.tsindex 330775da..7eb0662e 100644--- a/src/server/account-files.ts+++ b/src/server/account-files.ts@@ -1,5 +1,6 @@import "server-only";import fs from "node:fs";+import { accountById } from "./auth";import { DATA_DIR, db } from "./db";/**@@ -25,10 +26,15 @@ export const ACCOUNT_LIMITS = {/** Live uploads per account, and all its files (uploads and results). */uploadsBytes: 1 * GB,totalBytes: 3 * GB,+ /** All its files in its first days: accounts made in bulk can't fill the disk fast. */+ newAccountBytes: 1 * GB,+ newAccountDays: 7,/** Uploads: per hour, per day, and at once. */uploadsPerHour: 60,uploadsPerDay: 300,uploadsAtOnce: 2,+ /** Uploads at once from every account together (a multipart one is held in memory). */+ uploadsAtOnceAll: 8,/** Retention: uploads (even when a run still names them), and runs with their files. */uploadDays: 14,runDays: 30,@@ -75,6 +81,19 @@ export const ACCOUNT_MESSAGES = {lengthNeeded: "Send the file with its size (Content-Length).",} as const;+/** What an account may keep in all: 3 GB, or 1 GB in its first 7 days. */+export function accountTotalBytes(id: string): number {+ const created = accountById(id)?.createdAt ?? 0;+ return Date.now() - created < ACCOUNT_LIMITS.newAccountDays * DAY ? ACCOUNT_LIMITS.newAccountBytes : ACCOUNT_LIMITS.totalBytes;+}++/** What an account is told when its files are full. */+export function filesFullMessage(id: string): string {+ return accountTotalBytes(id) < ACCOUNT_LIMITS.totalBytes+ ? "Your files have reached 1 GB. A new account keeps up to 1 GB in its first 7 days, then 3 GB. Delete some runs to make room."+ : ACCOUNT_MESSAGES.filesFull;+}+/** What an account stores: all its files, its uploads, and how many uploads. */export function accountUsage(id: string): { total: number; uploads: number; uploadCount: number } {const r = db()@@ -119,14 +138,39 @@ export function diskFloorBytes(size = diskSpace().size): number {return Math.max(2 * GB, Math.min(ACCOUNT_LIMITS.diskFreeBytes, size / 10));}-/** Whether the server has room for an account's upload or run. When it hasn't, the server log says so once an hour. */+/**+ * What all accounts together may keep: FUOBE_ACCOUNTS_DISK_GB when it is set, else a quarter of the data disk. The rest+ * stays the owner's (and the other sites' on a shared server), however many accounts sign up.+ */+export function accountsMaxBytes(size = diskSpace().size): number {+ const set = process.env.FUOBE_ACCOUNTS_DISK_GB?.trim();+ if (set && Number.isFinite(Number(set)) && Number(set) >= 0) return Number(set) * GB;+ return size / 4;+}++/** What every account's files weigh together. */+function accountsBytes(): number {+ const r = db().prepare("SELECT COALESCE(SUM(size), 0) AS n FROM assets WHERE account_id IS NOT NULL").get() as { n: number };+ return Number(r.n);+}++/**+ * Whether the server has room for an account's upload or run: the disk keeps its free floor, and all accounts together+ * stay under their share (accountsMaxBytes). When it hasn't, the server log says so once an hour.+ */export function diskHasRoom(): boolean {const { free, size } = diskSpace();const floor = diskFloorBytes(size);- if (free >= floor) return true;+ const max = accountsMaxBytes(size);+ const used = accountsBytes();+ if (free >= floor && used < max) return true;if (Date.now() - (globalThis.__fuobeDiskLowWarned ?? 0) > 60 * 60_000) {globalThis.__fuobeDiskLowWarned = Date.now();- console.warn(`[fuobe] Accounts can't upload or run now: the data disk has ${(free / GB).toFixed(1)} GB free, and ${(floor / GB).toFixed(1)} GB is kept free (FUOBE_ACCOUNT_DISK_FREE_GB sets it).`);+ console.warn(+ free < floor+ ? `[fuobe] Accounts can't upload or run now: the data disk has ${(free / GB).toFixed(1)} GB free, and ${(floor / GB).toFixed(1)} GB is kept free (FUOBE_ACCOUNT_DISK_FREE_GB sets it).`+ : `[fuobe] Accounts can't upload or run now: their files take ${(used / GB).toFixed(1)} GB, their share of the disk (FUOBE_ACCOUNTS_DISK_GB sets it).`,+ );}return false;}diff --git a/src/server/generations.ts b/src/server/generations.tsindex 9578b2c4..7cdd3b91 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -56,7 +56,7 @@ import { accountGpu } from "./auth";import { CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";import { outsideTenant, runAsTenant, tenant, tenantAccount } from "./tenant";import { generationAccount } from "./account-library";-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "./account-files";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "./account-files";import { checkAccountLoras } from "./account-loras";import { missingFilesMessage, type MissingFiles } from "@/lib/missing-files";import { Readable } from "node:stream";@@ -1904,7 +1904,7 @@ function relinkMain(meta: Record<string, unknown> | undefined, from: string, to:/** The most one file of an account's run may weigh (a result, or a file it links to). */const ACCOUNT_LIMITS_FILE_BYTES = 2 ** 30;-/** An account's files are full (ACCOUNT_LIMITS.totalBytes): the job fails with this message. */+/** An account's files are full (accountTotalBytes): the job fails with this message. */class AccountFilesFull extends Error {}/** Types an account's result is stored as; any other is stored as application/octet-stream (.bin), never served as a page. */@@ -1935,11 +1935,11 @@ const accountType = (t: string) => {return ACCOUNT_OUTPUT_TYPES.has(bare) ? bare : "application/octet-stream";};-/** Before an account's file is kept: refuse it (and remove `file`, when given) when its files would pass 3 GB. */+/** Before an account's file is kept: refuse it (and remove `file`, when given) when its files would pass its total (3 GB; 1 GB while new). */function roomFor(account: string, bytes: number, file?: string): void {- if (accountUsage(account).total + bytes <= ACCOUNT_LIMITS.totalBytes) return;+ if (accountUsage(account).total + bytes <= accountTotalBytes(account)) return;if (file) fs.rmSync(file, { force: true });- throw new AccountFilesFull(ACCOUNT_MESSAGES.filesFull);+ throw new AccountFilesFull(filesFullMessage(account));}/**@@ -1948,12 +1948,12 @@ function roomFor(account: string, bytes: number, file?: string): void {* server is short of space. A download that fails leaves no file behind.*/async function persistAccountOutput(o: RichOutput, generationId: string, account: string, linked: Record<string, unknown> | undefined): Promise<OutputFile> {- const left = ACCOUNT_LIMITS.totalBytes - accountUsage(account).total;- if (left <= 0) throw new AccountFilesFull(ACCOUNT_MESSAGES.filesFull);+ const left = accountTotalBytes(account) - accountUsage(account).total;+ if (left <= 0) throw new AccountFilesFull(filesFullMessage(account));if (!diskHasRoom()) throw new Error(ACCOUNT_MESSAGES.diskLow);const quotaCapped = left < OWN_OUTPUT_LIMITS.maxBytes;// A result over what the account has room for says so, not the size of one answer.- const full = (e: unknown) => (quotaCapped && e instanceof RemoteFetchError && /^The answer was over/.test(e.message) ? new AccountFilesFull(ACCOUNT_MESSAGES.filesFull) : e);+ const full = (e: unknown) => (quotaCapped && e instanceof RemoteFetchError && /^The answer was over/.test(e.message) ? new AccountFilesFull(filesFullMessage(account)) : e);let res: Response;try {res = await outputFetch(o.url, { headers: o.headers }, { maxBytes: left });diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 3ce9bbc6..dc23bdaa 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -63,7 +63,7 @@ import { adoptFile, readRef, scratchDir } from "../storage";import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";import { zipToFile } from "../zip";-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "../account-files";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";import { accountSend } from "../account-send";import { tenantAccount } from "../tenant";import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";@@ -510,13 +510,13 @@ async function bundleFrames(outputs: ComfyOutput[], generationId: string): Promiif (account) {if (frames.length > ACCOUNT_LIMITS.framesPerJob) throw new ProviderError(`Your ComfyUI made ${frames.length} EXR frames. A run on your GPU keeps up to ${ACCOUNT_LIMITS.framesPerJob}: export a shorter clip.`);if (!diskHasRoom()) throw new ProviderError(ACCOUNT_MESSAGES.diskLow);- budget = ACCOUNT_LIMITS.totalBytes - accountUsage(account).total;- if (budget <= 0) throw new ProviderError(ACCOUNT_MESSAGES.filesFull);+ budget = accountTotalBytes(account) - accountUsage(account).total;+ if (budget <= 0) throw new ProviderError(filesFullMessage(account));}const dest = path.join(scratchDir(), `${generationId || nanoid(8)}-${nanoid(6)}.zip`);let total = 0;// Past what the account's files have room for: say that, not the size of one answer.- const full = (e: unknown) => (account && budget - total < OWN_FRAME_MAX_BYTES && e instanceof RemoteFetchError && /^The answer was over/.test(e.message) ? new ProviderError(ACCOUNT_MESSAGES.filesFull) : e);+ const full = (e: unknown) => (account && budget - total < OWN_FRAME_MAX_BYTES && e instanceof RemoteFetchError && /^The answer was over/.test(e.message) ? new ProviderError(filesFullMessage(account)) : e);async function* files() {for (const [i, f] of frames.entries()) {let data: Buffer;diff --git a/tests/account-finish-limits.test.ts b/tests/account-finish-limits.test.tsindex 8ec663c3..db8d8910 100644--- a/tests/account-finish-limits.test.ts+++ b/tests/account-finish-limits.test.ts@@ -80,11 +80,11 @@ describe("M-5: an account's finished pictures count like its other files", () =>it("refuses when the account's files are full", async () => {const big = saveFile({ data: Buffer.from("x"), contentType: "image/png", source: "upload", accountId: a });- db().prepare("UPDATE assets SET size = ? WHERE id = ?").run(ACCOUNT_LIMITS.totalBytes, big.id);+ db().prepare("UPDATE assets SET size = ? WHERE id = ?").run(ACCOUNT_LIMITS.newAccountBytes, big.id);try {const r = await post(soulRun(a), cookie);expect(r.status).toBe(413);- expect((await r.json()).error).toBe(ACCOUNT_MESSAGES.filesFull);+ expect((await r.json()).error).toMatch(/Your files have reached 1 GB/);} finally {db().prepare("DELETE FROM assets WHERE id = ?").run(big.id);}diff --git a/tests/account-review-fixes.test.ts b/tests/account-review-fixes.test.tsindex 91ded560..88bc4b84 100644--- a/tests/account-review-fixes.test.ts+++ b/tests/account-review-fixes.test.ts@@ -52,6 +52,13 @@ beforeAll(async () => {b = auth.createAccount("[email protected]", "long enough").id;auth.setAccountGpu(a, { url: fake.url });cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+ // Accounts past their first week, so their files may reach 3 GB (a new account keeps 1 GB).+ const authFile = path.join(dir, "auth.json");+ const data = JSON.parse(fs.readFileSync(authFile, "utf8")) as { accounts: { createdAt: number }[] };+ for (const x of data.accounts) x.createdAt -= 8 * 24 * 60 * 60_000;+ fs.writeFileSync(authFile, JSON.stringify(data));+ // A new modified time, so the auth module reads the file again (it caches by that time).+ fs.utimesSync(authFile, new Date(), new Date(Date.now() + 5000));});afterAll(async () => {globalThis.fetch = realFetch;diff --git a/tests/account-space-limits.test.ts b/tests/account-space-limits.test.tsnew file mode 100644index 00000000..5342cec8--- /dev/null+++ b/tests/account-space-limits.test.ts@@ -0,0 +1,124 @@+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";+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-space-limits-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ACCOUNTS_DISK_GB;+globalThis.__fuobeTestDiskFree = 1e13;++const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const files = await import("@/server/account-files");+const { saveFile } = await import("@/server/storage");+const { enter, hit, resetRates } = await import("@/server/rate");+const uploads = await import("@/app/api/uploads/route");+const signup = await import("@/app/api/auth/signup/route");++const GB = 2 ** 30;+const DAY = 24 * 60 * 60_000;+const PNG = Buffer.concat([Buffer.from("89504e470d0a1a0a0000000d4948445200000010000000100806000000", "hex"), Buffer.alloc(64)]);++let fresh = "";+let old = "";+beforeAll(() => {+ auth.setPassword("install password");+ fresh = auth.createAccount("[email protected]", "long enough").id;+ old = auth.createAccount("[email protected]", "long enough").id;+ for (const id of [fresh, old]) auth.setAccountGpu(id, { url: "https://gpu.example.com" });+ // An account made 8 days ago (auth.json is the accounts' store).+ const file = path.join(dir, "auth.json");+ const data = JSON.parse(fs.readFileSync(file, "utf8")) as { accounts: { id: string; createdAt: number }[] };+ for (const a of data.accounts) if (a.id === old) a.createdAt = Date.now() - 8 * DAY;+ fs.writeFileSync(file, JSON.stringify(data));+ // A new modified time, so the auth module reads the file again (it caches by that time).+ fs.utimesSync(file, new Date(), new Date(Date.now() + 5000));+});+afterEach(() => {+ delete process.env.FUOBE_ACCOUNTS_DISK_GB;+ delete process.env.FUOBE_TRUST_PROXY;+ resetRates();+ db().prepare("DELETE FROM assets WHERE account_id IS NOT NULL").run();+});+afterAll(() => {+ globalThis.__fuobeTestDiskFree = undefined;+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++/** A result of `account` that weighs `bytes` (only its row says so). */+function weigh(account: string, bytes: number) {+ const a = saveFile({ data: Buffer.from("x"), contentType: "image/png", source: "generation", accountId: account });+ db().prepare("UPDATE assets SET size = ? WHERE id = ?").run(bytes, a.id);+}++const upload = (account: string) =>+ uploads.POST(+ new Request("http://localhost:3000/api/uploads", {+ method: "POST",+ headers: { cookie: `${auth.SESSION_COOKIE}=${auth.createSession(account).value}`, "content-type": "image/png", "x-file-name": "a.png", "content-length": String(PNG.length) },+ body: PNG,+ }),+ );++describe("M-6: accounts can't fill the server's disk", () => {+ it("a new account keeps 1 GB in its first 7 days, then 3 GB", async () => {+ expect(files.accountTotalBytes(fresh)).toBe(1 * GB);+ expect(files.accountTotalBytes(old)).toBe(files.ACCOUNT_LIMITS.totalBytes);+ weigh(fresh, 1 * GB - 10);+ const r = await upload(fresh);+ expect(r.status).toBe(413);+ expect((await r.json()).error).toMatch(/1 GB.*first 7 days/);+ weigh(old, 1 * GB - 10);+ expect((await upload(old)).status).toBe(201);+ });++ it("all accounts together keep at most a share of the disk (FUOBE_ACCOUNTS_DISK_GB)", async () => {+ process.env.FUOBE_ACCOUNTS_DISK_GB = "2";+ weigh(old, 1.5 * GB);+ expect(files.diskHasRoom()).toBe(true);+ weigh(fresh, 0.6 * GB);+ expect(files.diskHasRoom()).toBe(false);+ const r = await upload(old);+ expect(r.status).toBe(503);+ expect((await r.json()).error).toBe(files.ACCOUNT_MESSAGES.diskLow);+ });++ it("by default, all accounts together keep at most a quarter of the disk", () => {+ expect(files.accountsMaxBytes(400 * GB)).toBe(100 * GB);+ });++ it("a few uploads at once across every account", async () => {+ const held = Array.from({ length: files.ACCOUNT_LIMITS.uploadsAtOnceAll }, () => enter("up:accounts", files.ACCOUNT_LIMITS.uploadsAtOnceAll));+ try {+ expect(held.every(Boolean)).toBe(true);+ const r = await upload(old);+ expect(r.status).toBe(429);+ } finally {+ for (const release of held) release?.();+ }+ expect((await upload(old)).status).toBe(201);+ });++ it("an address makes at most 5 accounts a day", async () => {+ process.env.FUOBE_TRUST_PROXY = "1";+ for (let i = 0; i < 5; i++) hit("signup-day:203.0.113.5", 5, DAY);+ const r = await signup.POST(+ new Request("http://localhost:3000/api/auth/signup", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.5" }, body: JSON.stringify({ email: "[email protected]", password: "long enough" }) }),+ );+ expect(r.status).toBe(429);+ expect((await r.json()).error).toMatch(/today/);+ const ok = await signup.POST(+ new Request("http://localhost:3000/api/auth/signup", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.6" }, body: JSON.stringify({ email: "[email protected]", password: "long enough" }) }),+ );+ expect(ok.status).toBe(201);+ });+});