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: an account's finished pictures count against its space and limits

Adarsha75069ac9999
diff --git a/src/app/api/generations/[id]/finish/route.ts b/src/app/api/generations/[id]/finish/route.ts
index 42a7bcfb..123b071f 100644
--- a/src/app/api/generations/[id]/finish/route.ts
+++ b/src/app/api/generations/[id]/finish/route.ts
@@ -1,6 +1,8 @@
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountUsage, diskHasRoom } from "@/server/account-files";
import { requestAccount } from "@/server/auth";
import { gateAsProxy } from "@/server/direct-gate";
import { FinishError, finishOutput } from "@/server/generations";
+import { hit, unhit } from "@/server/rate";
const MAX_BYTES = 64 * 1024 * 1024;
/** An account's finished picture (its own result: the proxy checks): smaller. */
@@ -10,14 +12,16 @@ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
/**
* Fuobe Soul's finished picture (the look's grade and overlay, made in the browser): it replaces the raw output,
* which stays as meta.original. Form fields: file (PNG), index (the output's place). An account's file is stored as
- * its own (through the generation).
+ * its own (through the generation), and counts as its uploads and results do: room on the server, room in its files,
+ * and an hourly limit.
*/
export async function POST(request: Request, ctx: RouteContext<"/api/generations/[id]/finish">) {
// The proxy doesn't run on this route (a big form): its checks run here (an account: only its own run).
const denied = gateAsProxy(request);
if (denied) return denied;
const { id } = await ctx.params;
- const max = requestAccount(request) ? ACCOUNT_MAX_BYTES : MAX_BYTES;
+ const account = requestAccount(request);
+ const max = account ? ACCOUNT_MAX_BYTES : MAX_BYTES;
if (Number(request.headers.get("content-length") ?? 0) > max + 64 * 1024) return Response.json({ error: `That picture is too large (${max / 2 ** 20} MB max)` }, { status: 413 });
const form = await request.formData().catch(() => null);
const file = form?.get("file");
@@ -26,9 +30,17 @@ export async function POST(request: Request, ctx: RouteContext<"/api/generations
if (file.size > max) return Response.json({ error: `That picture is too large (${max / 2 ** 20} MB max)` }, { status: 413 });
const data = Buffer.from(await file.arrayBuffer());
if (file.type !== "image/png" || !data.subarray(0, 8).equals(PNG_MAGIC)) return Response.json({ error: "Finished pictures are PNG images" }, { status: 415 });
+ if (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);
+ 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) });
+ }
try {
return Response.json(finishOutput(id, index, data));
} catch (e) {
+ if (account) unhit(`finish:${account.id}`);
if (e instanceof FinishError) return Response.json({ error: e.message }, { status: e.status });
throw e;
}
diff --git a/src/server/account-files.ts b/src/server/account-files.ts
index 4d1936c9..330775da 100644
--- a/src/server/account-files.ts
+++ b/src/server/account-files.ts
@@ -47,6 +47,8 @@ export const ACCOUNT_LIMITS = {
queueMs: 30 * 60_000,
/** GPU address checks and saves, per minute. */
gpuChecksPerMinute: 10,
+ /** Fuobe Soul's finished pictures (the look's grade made in the browser) stored per hour: a run's 4 outputs, 60 runs. */
+ finishesPerHour: 240,
} as const;
export const RETENTION_MS = { upload: ACCOUNT_LIMITS.uploadDays * DAY, run: ACCOUNT_LIMITS.runDays * DAY };
@@ -64,6 +66,7 @@ export const ACCOUNT_MESSAGES = {
diskLow: "The studio is short of space right now. Try again later.",
activeRuns: "You have 4 runs going. Start the next one when one finishes.",
runRate: "That's a lot of runs this hour. Try again later.",
+ finishRate: "That's a lot of finished pictures this hour. Try again later.",
outputsCapped: "Runs on your GPU make up to 4 at a time.",
bodyTooBig: "That request is too large.",
gpuChecks: "Too many checks. Wait a minute.",
diff --git a/tests/account-finish-limits.test.ts b/tests/account-finish-limits.test.ts
new file mode 100644
index 00000000..8ec663c3
--- /dev/null
+++ b/tests/account-finish-limits.test.ts
@@ -0,0 +1,99 @@
+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";
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-finish-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;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const auth = await import("@/server/auth");
+const { db } = await import("@/server/db");
+const { createGenerations } = await import("@/server/generations");
+const { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } = await import("@/server/account-files");
+const { saveFile } = await import("@/server/storage");
+const { hit, resetRates } = await import("@/server/rate");
+const finish = await import("@/app/api/generations/[id]/finish/route");
+
+let a = "";
+let cookie = "";
+let owner = "";
+beforeAll(() => {
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(a, { url: "https://gpu.example.com" });
+ cookie = auth.createSession(a).value;
+ owner = auth.createSession().value;
+});
+afterEach(() => {
+ globalThis.__fuobeTestDiskFree = 1e13;
+ resetRates();
+});
+afterAll(() => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const PNG = Buffer.concat([Buffer.from("89504e470d0a1a0a0000000d49484452", "hex"), Buffer.alloc(64)]);
+
+/** A finished Fuobe Soul run with a graded picture to finish, made by `account` (or the owner). */
+function soulRun(account?: string): string {
+ const [g] = createGenerations({ feature: "image", modelId: "fuobe-soul", prompt: "a fox", engine: "open", presetId: "v1-90s-grain" });
+ const raw = { url: "/api/files/outputs/raw.png", kind: "image", meta: { look: "v1-90s-grain", grade: "portra" } };
+ db()
+ .prepare("UPDATE generations SET status = 'succeeded', outputs_json = ?, request_json = CASE WHEN ? IS NULL THEN request_json ELSE json_set(request_json, '$.account', ?) END WHERE id = ?")
+ .run(JSON.stringify([raw]), account ?? null, account ?? null, g.id);
+ return g.id;
+}
+
+function post(id: string, session: string) {
+ const body = new FormData();
+ body.set("file", new File([PNG], "finished.png", { type: "image/png" }));
+ body.set("index", "0");
+ return finish.POST(new Request(`http://localhost:3000/api/generations/${id}/finish`, { method: "POST", headers: { cookie: `${auth.SESSION_COOKIE}=${session}` }, body }), {
+ params: Promise.resolve({ id }),
+ } as never);
+}
+
+describe("M-5: an account's finished pictures count like its other files", () => {
+ it("finishes its own run's picture, stored as its own", async () => {
+ const r = await post(soulRun(a), cookie);
+ expect(r.status).toBe(200);
+ const url = (await r.json()).outputs[0].url as string;
+ expect(db().prepare("SELECT account_id FROM assets WHERE rel_path = ?").get(url.slice("/api/files/".length).replaceAll("/", path.sep))).toEqual({ account_id: a });
+ });
+
+ it("refuses when the server is short of space, as an upload would be", async () => {
+ globalThis.__fuobeTestDiskFree = 0;
+ const r = await post(soulRun(a), cookie);
+ expect(r.status).toBe(503);
+ expect((await r.json()).error).toBe(ACCOUNT_MESSAGES.diskLow);
+ // The owner's own finish doesn't depend on the accounts' floor.
+ expect((await post(soulRun(), owner)).status).toBe(200);
+ });
+
+ 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);
+ try {
+ const r = await post(soulRun(a), cookie);
+ expect(r.status).toBe(413);
+ expect((await r.json()).error).toBe(ACCOUNT_MESSAGES.filesFull);
+ } finally {
+ db().prepare("DELETE FROM assets WHERE id = ?").run(big.id);
+ }
+ });
+
+ it("has an hourly limit", async () => {
+ for (let i = 0; i < ACCOUNT_LIMITS.finishesPerHour; i++) hit(`finish:${a}`, ACCOUNT_LIMITS.finishesPerHour, 60 * 60_000);
+ const r = await post(soulRun(a), cookie);
+ expect(r.status).toBe(429);
+ expect(r.headers.get("retry-after")).toBeTruthy();
+ });
+});