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: account uploads can't hold each other up, and sign-ups fit a shared network

Adarsh101bb9834603
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 824d38a8..9318756c 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -174,8 +174,10 @@ multipart form works up to 26 MB). Without a connected GPU it answers 403 with
- 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.
+- Up to 60 uploads an hour, 300 a day and 2 at once (429 with `Retry-After`). An upload sent as a
+ form (older pages, held in memory) also waits for a place among 8 from every account together.
+ An upload ends with 408 when nothing arrives for a minute, or when it takes over 30 minutes.
+ One address (one network) makes at most 20 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 is
deleted.
diff --git a/src/app/api/auth/signup/route.ts b/src/app/api/auth/signup/route.ts
index f83909b7..da6ef0bf 100644
--- a/src/app/api/auth/signup/route.ts
+++ b/src/app/api/auth/signup/route.ts
@@ -13,7 +13,11 @@ 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;
+/**
+ * Accounts a day from one address. One address can be a whole office, class or mobile network, so this is a ceiling
+ * for scripts, not for people: all accounts together keep at most a share of the disk anyway (account-files.ts).
+ */
+const SIGNUPS_A_DAY = 20;
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. */
@@ -28,9 +32,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).
+ // At most 20 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) } });
+ if (today && !today.ok) return Response.json({ error: "Too many new accounts from this network today. Try again tomorrow." }, { status: 429, headers: { "Retry-After": String(today.retryAfterS) } });
let account;
try {
account = createAccount(parsed.data.email, parsed.data.password);
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
index 448eddc3..77e48ab8 100644
--- a/src/app/api/uploads/route.ts
+++ b/src/app/api/uploads/route.ts
@@ -34,6 +34,17 @@ const json = (status: number, body: Record<string, unknown>, headers: Record<str
Response.json(body, { status, headers: { "Cache-Control": "no-store", ...headers } });
class TooBig extends Error {}
+class Stalled extends Error {}
+
+/** One read of a body, or Stalled when nothing arrives within `ms`. */
+function readWithin<T>(reader: ReadableStreamDefaultReader<T>, ms: number): Promise<ReadableStreamReadResult<T>> {
+ if (!Number.isFinite(ms)) return reader.read();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const late = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Stalled()), Math.max(0, ms));
+ });
+ return Promise.race([reader.read(), late]).finally(() => clearTimeout(timer));
+}
/** The file's name as display text only: no folders, no control or path characters, at most 120 characters. */
function displayName(raw: string | null): string | undefined {
@@ -58,14 +69,18 @@ function declaredType(contentType: string | null, name: string | undefined): str
const kindOf = (type: string): SniffKind | null => (/^image\//.test(type) ? "image" : /^video\//.test(type) ? "video" : /^audio\//.test(type) ? "audio" : null);
-/** Stream a request body into `dest`, at most `max` bytes (TooBig past it; no file is left on any failure). */
-async function streamTo(body: ReadableStream<Uint8Array> | null, dest: string, max: number): Promise<number> {
+/**
+ * Stream a request body into `dest`, at most `max` bytes (TooBig past it; no file is left on any failure). With
+ * `idleMs` / `totalMs`: Stalled when nothing arrives for that long, or the whole body takes longer.
+ */
+async function streamTo(body: ReadableStream<Uint8Array> | null, dest: string, max: number, opts: { idleMs?: number; totalMs?: number } = {}): Promise<number> {
const out = fs.createWriteStream(dest);
const reader = body?.getReader();
+ const deadline = Date.now() + (opts.totalMs ?? Infinity);
let bytes = 0;
try {
while (reader) {
- const { done, value } = await reader.read();
+ const { done, value } = await readWithin(reader, Math.min(opts.idleMs ?? Infinity, deadline - Date.now()));
if (done) break;
bytes += value.length;
if (bytes > max) throw new TooBig();
@@ -149,11 +164,13 @@ async function accountUpload(request: Request, account: Account): Promise<Respon
if (!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);
+ // And a few forms at once from every account together: a form is held in memory. A file sent as it is streams to
+ // disk (it holds no memory), so it never waits for other accounts' uploads.
+ const multipart = (request.headers.get("content-type") ?? "").toLowerCase().startsWith("multipart/form-data");
+ const releaseAll = multipart ? enter("up:accounts", ACCOUNT_LIMITS.uploadsAtOnceAll) : () => {};
if (!releaseAll) {
release();
- return json(429, { error: ACCOUNT_MESSAGES.uploadRate }, { "Retry-After": "10" });
+ return json(429, { error: ACCOUNT_MESSAGES.uploadsBusy }, { "Retry-After": "10" });
}
try {
return await accountUploadBody(request, account);
@@ -194,12 +211,13 @@ async function accountUploadBody(request: Request, account: Account): Promise<Re
bytes = file.size;
} else {
declaredFull = request.headers.get("content-type") ?? "";
- // Never more than it said it would send.
- bytes = await streamTo(request.body, dest, Math.min(length, ACCOUNT_LIMITS.videoBytes));
+ // Never more than it said it would send, and never one that stops arriving (it would hold its place for good).
+ bytes = await streamTo(request.body, dest, Math.min(length, ACCOUNT_LIMITS.videoBytes), { idleMs: ACCOUNT_LIMITS.uploadIdleMs, totalMs: ACCOUNT_LIMITS.uploadMaxMs });
}
} catch (e) {
fs.rmSync(dest, { force: true });
if (e instanceof TooBig) return json(413, { error: ACCOUNT_MESSAGES.videoTooBig });
+ if (e instanceof Stalled) return json(408, { error: ACCOUNT_MESSAGES.uploadStalled });
throw e;
}
const drop = (status: number, error: string) => {
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
index 41d19d1a..26ccbf7d 100644
--- a/src/server/account-files.ts
+++ b/src/server/account-files.ts
@@ -33,8 +33,11 @@ export const ACCOUNT_LIMITS = {
uploadsPerHour: 60,
uploadsPerDay: 300,
uploadsAtOnce: 2,
- /** Uploads at once from every account together (a multipart one is held in memory). */
+ /** Form (multipart) uploads at once from every account together: a form is held in memory. A file sent as it is isn't counted. */
uploadsAtOnceAll: 8,
+ /** An upload ends when nothing arrives for this long, or when it takes longer than this in all (95 MB at about 55 KB/s). */
+ uploadIdleMs: 60_000,
+ uploadMaxMs: 30 * 60_000,
/** Retention: uploads (even when a run still names them), and runs with their files. */
uploadDays: 14,
runDays: 30,
diff --git a/tests/account-space-limits.test.ts b/tests/account-space-limits.test.ts
index 5342cec8..0e4b702b 100644
--- a/tests/account-space-limits.test.ts
+++ b/tests/account-space-limits.test.ts
@@ -96,26 +96,83 @@ describe("M-6: accounts can't fill the server's disk", () => {
expect(files.accountsMaxBytes(400 * GB)).toBe(100 * GB);
});
- it("a few uploads at once across every account", async () => {
+ it("a few form uploads (held in memory) at once across every account; a file sent as it is never waits for others", async () => {
+ const multipart = (account: string) => {
+ const body = new FormData();
+ body.set("file", new File([PNG], "a.png", { type: "image/png" }));
+ const probe = new Request("http://localhost:3000/api/uploads", { method: "POST", body });
+ return probe.arrayBuffer().then((buf) =>
+ uploads.POST(
+ new Request("http://localhost:3000/api/uploads", {
+ method: "POST",
+ headers: { cookie: `${auth.SESSION_COOKIE}=${auth.createSession(account).value}`, "content-type": probe.headers.get("content-type")!, "content-length": String(buf.byteLength) },
+ body: buf,
+ }),
+ ),
+ );
+ };
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);
+ const r = await multipart(old);
expect(r.status).toBe(429);
+ expect((await r.json()).error).toBe(files.ACCOUNT_MESSAGES.uploadsBusy);
+ // Streamed to disk, so it holds no memory: other accounts' uploads don't hold it up.
+ expect((await upload(old)).status).toBe(201);
} finally {
for (const release of held) release?.();
}
- expect((await upload(old)).status).toBe(201);
+ expect((await multipart(old)).status).toBe(201);
});
- it("an address makes at most 5 accounts a day", async () => {
+ it("an upload that stops arriving is ended, and frees its place", async () => {
+ const limits = files.ACCOUNT_LIMITS as { uploadIdleMs: number };
+ const idle = limits.uploadIdleMs;
+ limits.uploadIdleMs = 200;
+ try {
+ let sent = false;
+ const body = new ReadableStream<Uint8Array>({
+ pull(c) {
+ if (!sent) {
+ sent = true;
+ c.enqueue(new Uint8Array(PNG.subarray(0, 16)));
+ }
+ // Then nothing more, ever.
+ return new Promise(() => {});
+ },
+ });
+ const r = await uploads.POST(
+ new Request("http://localhost:3000/api/uploads", {
+ method: "POST",
+ headers: { cookie: `${auth.SESSION_COOKIE}=${auth.createSession(old).value}`, "content-type": "image/png", "x-file-name": "a.png", "content-length": String(PNG.length) },
+ body,
+ duplex: "half",
+ } as RequestInit),
+ );
+ expect(r.status).toBe(408);
+ expect((await r.json()).error).toBe(files.ACCOUNT_MESSAGES.uploadStalled);
+ // Its place is free again: two more at once still fit.
+ expect((await Promise.all([upload(old), upload(old)])).map((x) => x.status)).toEqual([201, 201]);
+ } finally {
+ limits.uploadIdleMs = idle;
+ }
+ });
+
+ it("an address (a whole office or class on one network) makes at most 20 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" }) }),
- );
+ const from = (ip: string, email: string) =>
+ signup.POST(new Request("http://localhost:3000/api/auth/signup", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": ip }, body: JSON.stringify({ email, password: "long enough" }) }));
+ // Ten people in one room sign up, a few seconds apart (the per-minute limit is 5).
+ const aMinuteLater = () => delete (globalThis as Record<string, unknown>).__fuobeSignupGuard;
+ for (let i = 0; i < 5; i++) expect((await from("203.0.113.5", `room${i}@example.com`)).status, `person ${i}`).toBe(201);
+ aMinuteLater();
+ for (let i = 5; i < 10; i++) expect((await from("203.0.113.5", `room${i}@example.com`)).status, `person ${i}`).toBe(201);
+ aMinuteLater();
+ for (let i = 10; i < 20; i++) hit("signup-day:203.0.113.5", 20, DAY);
+ const r = await from("203.0.113.5", "[email protected]");
expect(r.status).toBe(429);
- expect((await r.json()).error).toMatch(/today/);
+ // It says what happened: the network, not the person, made the accounts.
+ expect((await r.json()).error).toBe("Too many new accounts from this network today. Try again tomorrow.");
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" }) }),
);