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.

Hosted runs, and optional billing and moderation hooks (all off by default)

Adarsh2814b4d1296b
diff --git a/src/app/api/admin/outputs/[action]/route.ts b/src/app/api/admin/outputs/[action]/route.ts
new file mode 100644
index 00000000..0f626fe2
--- /dev/null
+++ b/src/app/api/admin/outputs/[action]/route.ts
@@ -0,0 +1,22 @@
+import { isOwnerRequest, sessionCookieOf } from "@/server/auth";
+import { hideOutputs, removeOutputs, unhideOutputs, type Targets } from "@/server/takedown";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+const list = (v: unknown): string[] | undefined => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, 500) : undefined);
+
+/**
+ * Take results down (owner only): `hide` (served to no account and by no link; kept), `unhide`, `remove` (deleted;
+ * with `evidence: true`, moved to a locked folder instead). Body: `{ assetIds?, generationIds?, evidence? }`.
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/admin/outputs/[action]">) {
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner can take results down" }, { status: 403, headers: NO_STORE });
+ const { action } = await ctx.params;
+ const body = (await request.json().catch(() => null)) as { assetIds?: unknown; generationIds?: unknown; evidence?: unknown } | null;
+ const t: Targets = { assetIds: list(body?.assetIds), generationIds: list(body?.generationIds) };
+ if (!t.assetIds?.length && !t.generationIds?.length) return Response.json({ error: "Name the results: assetIds or generationIds" }, { status: 400, headers: NO_STORE });
+ if (action === "hide") return Response.json({ hidden: hideOutputs(t) }, { headers: NO_STORE });
+ if (action === "unhide") return Response.json({ shown: unhideOutputs(t) }, { headers: NO_STORE });
+ if (action === "remove") return Response.json({ removed: removeOutputs(t, body?.evidence === true) }, { headers: NO_STORE });
+ return Response.json({ error: "Unknown action" }, { status: 404, headers: NO_STORE });
+}
diff --git a/src/app/api/billing/interest/route.ts b/src/app/api/billing/interest/route.ts
new file mode 100644
index 00000000..c68fb7b2
--- /dev/null
+++ b/src/app/api/billing/interest/route.ts
@@ -0,0 +1,22 @@
+import { requestAccount } from "@/server/auth";
+import { interest } from "@/server/billing";
+import { hit } from "@/server/rate";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * An account's click on an offer the billing service sent ("Tell me when"): passed on to the service
+ * (docs/billing-hook.md, POST /v1/interest). With no billing service set there are no offers: 404.
+ */
+export async function POST(request: Request) {
+ const account = requestAccount(request);
+ if (!account) return Response.json({ error: "Sign in first" }, { status: 401, headers: NO_STORE });
+ const body = (await request.json().catch(() => null)) as { key?: unknown } | null;
+ const key = typeof body?.key === "string" && /^[\w.:-]{1,80}$/.test(body.key) ? body.key : null;
+ if (!key) return Response.json({ error: "Which offer?" }, { status: 400, headers: NO_STORE });
+ const rate = hit(`interest:${account.id}`, 30, 60 * 60_000);
+ if (!rate.ok) return Response.json({ error: "Too many clicks. Try again later." }, { status: 429, headers: { ...NO_STORE, "Retry-After": String(rate.retryAfterS) } });
+ const a = await interest(account.id, key);
+ if (!a) return Response.json({ error: "Not available right now" }, { status: 404, headers: NO_STORE });
+ return Response.json({ ok: true, text: a.text }, { headers: NO_STORE });
+}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 4d600b01..8989645a 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -18,6 +18,11 @@ import { GenerationRequestSchema } from "@/server/request-schema";
import { gateGeneration, GPU_SETUP_HEADER } from "@/server/gpu/gate";
import { gpuTargetFor } from "@/server/gpu/target";
import { connectNeeds } from "@/server/connect-refusal";
+import { billingConfigured } from "@/server/billing";
+import { queueRelease } from "@/server/billing-outbox";
+import { runOnPool } from "@/server/hosted";
+import { decidePlace, moderateRun, poolQuote, readWishes, reservePool, type PlaceDecision, type Refusal } from "@/server/hosted-run";
+import { withRunStamp, type RunStamp } from "@/server/run-stamp";
/**
* List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,
@@ -92,6 +97,12 @@ export async function POST(request: Request) {
const headers: Record<string, string> = r.code === "connect-gpu" ? { [CONNECT_GPU_HEADER]: "1" } : r.code === "add-key" && r.provider ? { [ADD_KEY_HEADER]: r.provider } : {};
return refuse(403, r.error, { code: r.code, ...(r.provider && { provider: r.provider }) }, headers);
};
+ // Beside the request (never in it): the place the client prefers, and the price it showed (hosted runs, billing hook).
+ const { wish, shown } = readWishes(body);
+ const refusedBy = (r: Refusal) => {
+ if (account) unhit(`run:${account.id}`);
+ return refuse(r.status, r.body.error, r.body, r.headers);
+ };
const notes: string[] = [];
if (account && !preview) {
// Room on the server, room in the account's files, and a fair share of runs.
@@ -113,13 +124,40 @@ export async function POST(request: Request) {
}
try {
if (preview) {
+ // Hosted runs: a visitor's run that would go to this install's GPUs is priced there, with the billing service's
+ // quote (its words for Run). Off, or a run on its own GPU or key: priced as before.
+ const pool = viewer.kind !== "owner" ? await poolQuote(account, req, wish) : null;
+ if (pool) {
+ const { model, ...p } = pool.planned;
+ return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op, place: "pool", quote: pool.quote });
+ }
const { model, ...p } = priced(() => previewGeneration(req));
return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op });
}
+ // Hosted runs (FUOBE_HOSTED_RUNS=1): an account's run may go to this install's GPUs. Off: always its own (today).
+ let decision: PlaceDecision = { kind: "own" };
+ if (account) {
+ decision = await decidePlace(account, req, wish);
+ if (decision.kind === "refuse") return refusedBy(decision.refusal);
+ }
+ const onPool = decision.kind === "pool" ? decision : null;
+ if (account && onPool && billingConfigured()) {
+ // The billing service's limits for runs on this install's GPUs (never above the studio's own).
+ const lim = onPool.policy.limits;
+ if (lim.activeRuns > 0 && activeRuns(account.id) >= lim.activeRuns) {
+ unhit(`run:${account.id}`);
+ return refuse(429, ACCOUNT_MESSAGES.activeRuns, {}, { "Retry-After": "30" });
+ }
+ if (lim.outputsPerRun > 0 && (req.params?.numOutputs ?? 1) > lim.outputsPerRun) {
+ req = { ...req, params: { ...req.params, numOutputs: lim.outputsPerRun } };
+ notes.push(ACCOUNT_MESSAGES.outputsCapped);
+ }
+ }
// GPU pre-flight: a ComfyUI run that is sure to fail for something missing stops here with the plan that fixes it
// (src/server/gpu/gate.ts; never when the check is unknown, for graphics memory, or with gpuCheck "skip").
let gpuWarning: string | undefined;
- if (viewer.kind !== "guest") {
+ // (A run on this install's GPUs: its plan was checked by decidePlace; the pre-flight is about the account's own GPU.)
+ if (viewer.kind !== "guest" && !onPool) {
let planned: ReturnType<typeof previewGeneration> | null = null;
try {
planned = onOwn(() => previewGeneration(req));
@@ -155,7 +193,7 @@ export async function POST(request: Request) {
gpuWarning = gate.warning;
}
}
- if (account) {
+ if (account && !onPool) {
// The LoRAs this run adds (and its start frame's step, for an effect that makes one) must be on the account's
// ComfyUI: say which to download before anything is queued.
const fix = await onOwn(() => accountLoraFix(req));
@@ -164,13 +202,34 @@ export async function POST(request: Request) {
return refuse(409, missingFilesMessage(fix), { code: "comfy_missing_model", fix });
}
}
+ // The moderation service's check (none set: nothing checked), before anything is set aside: a refusal costs nothing.
+ // Then, on this install's GPUs, the billing service sets the run's price aside (none set: the run is free).
+ let stamp: RunStamp | null = null;
+ if (account) {
+ const mod = await moderateRun(account, req, onPool?.planned ?? null, onPool ? "pool" : "own");
+ if (!mod.ok) return refusedBy(mod.refusal);
+ if (onPool) {
+ const held = await reservePool(account, req, onPool.planned, shown, mod.checkOutputs);
+ if (!held.ok) return refusedBy(held.refusal);
+ stamp = held.stamp;
+ } else if (mod.checkOutputs) stamp = { checkOutputs: true };
+ }
// Counted again just before the run is stored, with nothing awaited in between: requests that arrived together all
// passed the first count while the checks above waited.
if (account && activeRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) {
unhit(`run:${account.id}`);
+ if (stamp?.hold) queueRelease(stamp.hold);
return refuse(429, ACCOUNT_MESSAGES.activeRuns, {}, { "Retry-After": "30" });
}
- const items = onOwn(() => createGenerations(req));
+ const make = () => createGenerations(req);
+ let items: ReturnType<typeof createGenerations>;
+ try {
+ items = account && onPool ? runOnPool(account.id, () => withRunStamp(stamp ?? { place: "pool" }, make)) : stamp ? onOwn(() => withRunStamp(stamp, make)) : onOwn(make);
+ } catch (e) {
+ // Nothing was made: what was set aside goes back.
+ if (stamp?.hold) queueRelease(stamp.hold);
+ throw e;
+ }
// A script's open-source run while ComfyUI is on the owner's computer: it waits for the owner's Fuobe tab there.
if (viewer.kind === "owner" && token && getSetting("comfyWhere") === "computer" && items.some((g) => g.provider === "comfyui")) notes.push(RUNS_ON_COMPUTER_NOTE);
// What the run leaves out or changes (a model that replaced a retired one, a LoRA that runs only on a GPU, a length the API rounds).
diff --git a/src/app/api/reports/route.ts b/src/app/api/reports/route.ts
new file mode 100644
index 00000000..63026881
--- /dev/null
+++ b/src/app/api/reports/route.ts
@@ -0,0 +1,36 @@
+import { connection } from "next/server";
+import { isOwnerRequest, LoginGuard, requestViewer, sessionCookieOf } from "@/server/auth";
+import { listReports, report, REPORT_CATEGORIES, type ReportCategory } from "@/server/moderation";
+import { hit } from "@/server/rate";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * "Report this result": anyone who can see a result or a shared link may report it. It goes to the install's
+ * moderation service when one is set (FUOBE_MODERATION_URL, docs/moderation-hook.md), else to a list the owner reads
+ * (GET, owner only).
+ */
+export async function POST(request: Request) {
+ const viewer = requestViewer(request);
+ const who = viewer.kind === "account" ? `account:${viewer.account.id}` : viewer.kind === "owner" ? "owner" : `guest:${LoginGuard.clientKey(request.headers)}`;
+ const rate = hit(`report:${who}`, 20, 60 * 60_000);
+ if (!rate.ok) return Response.json({ error: "Too many reports. Try again later." }, { status: 429, headers: { ...NO_STORE, "Retry-After": String(rate.retryAfterS) } });
+ const body = (await request.json().catch(() => null)) as { target?: Record<string, unknown>; category?: unknown; text?: unknown; email?: unknown } | null;
+ const t = body?.target ?? {};
+ const id = (v: unknown) => (typeof v === "string" && /^[\w-]{1,64}$/.test(v) ? v : undefined);
+ const target = { ...(id(t.generationId) && { generationId: id(t.generationId) }), ...(id(t.assetId) && { assetId: id(t.assetId) }), ...(id(t.shareId) && { shareId: id(t.shareId) }) };
+ if (!Object.keys(target).length) return Response.json({ error: "Say what you are reporting" }, { status: 400, headers: NO_STORE });
+ const category = REPORT_CATEGORIES.includes(body?.category as ReportCategory) ? (body!.category as ReportCategory) : null;
+ if (!category) return Response.json({ error: "Pick what is wrong with it" }, { status: 400, headers: NO_STORE });
+ const text = typeof body?.text === "string" ? body.text.slice(0, 2000) : "";
+ const email = viewer.kind === "account" ? viewer.account.email : typeof body?.email === "string" && /^[^\s@]{1,64}@[^\s@]{1,190}$/.test(body.email) ? body.email : null;
+ const a = await report({ target, category, text, reporter: { account: viewer.kind === "account" ? viewer.account.id : null, email } });
+ return Response.json({ ok: true, text: a.text }, { status: 201, headers: NO_STORE });
+}
+
+/** The reports kept here (no moderation service set): the owner only. */
+export async function GET(request: Request) {
+ await connection();
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner sees reports" }, { status: 403, headers: NO_STORE });
+ return Response.json({ items: listReports() }, { headers: NO_STORE });
+}
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
index f4f41392..5778f0c2 100644
--- a/src/app/api/uploads/route.ts
+++ b/src/app/api/uploads/route.ts
@@ -3,6 +3,8 @@ import path from "node:path";
import { nanoid } from "nanoid";
import { CONNECT_GPU_HEADER, CONNECT_GPU_UPLOAD_MESSAGE } from "@/lib/guest-access";
import { accountProviders } from "@/server/account-keys";
+import { policy as billingPolicy } from "@/server/billing";
+import { poolReady } from "@/server/hosted";
import { imageSize } from "@/lib/image-size";
import { sniffMedia, type SniffKind } from "@/lib/sniff";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
@@ -157,8 +159,20 @@ async function ownerUpload(request: Request): Promise<Response> {
// ---------------------------------------------------------------------------
// An account
+/** The kinds of file an account with no GPU or key of its own may add for runs on this install's GPUs (hosted runs). */
+async function hostedUploads(accountId: string): Promise<{ image: boolean; video: boolean; audio: boolean } | null> {
+ if (!poolReady()) return null;
+ const p = await billingPolicy(accountId);
+ if (!p?.hosted || !(p.uploads.image || p.uploads.video || p.uploads.audio)) return null;
+ return p.uploads;
+}
+
async function accountUpload(request: Request, account: Account): Promise<Response> {
- if (!accountGpu(account.id) && !accountProviders(account.id).length) return json(403, { error: CONNECT_GPU_UPLOAD_MESSAGE, code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
+ // No GPU and no key of its own: with hosted runs on, the files a run on this install's GPUs may use (the policy says
+ // which kinds; checked again once the file's kind is known), else nothing.
+ const own = !!accountGpu(account.id) || accountProviders(account.id).length > 0;
+ const hosted = own ? null : await hostedUploads(account.id);
+ if (!own && !hosted) return json(403, { error: CONNECT_GPU_UPLOAD_MESSAGE, code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
if (!diskHasRoom()) return json(503, { error: ACCOUNT_MESSAGES.diskLow });
// A fair share: 60 an hour, 300 a day, 2 at once.
const hour = hit(`up:h:${account.id}`, ACCOUNT_LIMITS.uploadsPerHour, 60 * 60_000);
@@ -175,14 +189,14 @@ async function accountUpload(request: Request, account: Account): Promise<Respon
return json(429, { error: ACCOUNT_MESSAGES.uploadsBusy }, { "Retry-After": "10" });
}
try {
- return await accountUploadBody(request, account);
+ return await accountUploadBody(request, account, hosted);
} finally {
releaseAll();
release();
}
}
-async function accountUploadBody(request: Request, account: Account): Promise<Response> {
+async function accountUploadBody(request: Request, account: Account, hosted: { image: boolean; video: boolean; audio: boolean } | null): Promise<Response> {
const lengthHeader = request.headers.get("content-length");
const length = lengthHeader === null ? NaN : Number(lengthHeader);
if (!Number.isFinite(length) || length < 0) return json(411, { error: ACCOUNT_MESSAGES.lengthNeeded });
@@ -232,6 +246,10 @@ async function accountUploadBody(request: Request, account: Account): Promise<Re
const sniffed = sniffMedia(head, declaredType(declaredFull, name));
if (!sniffed) return drop(415, ACCOUNT_MESSAGES.wrongType);
if (bytes > KIND_CAP[sniffed.kind]) return drop(413, KIND_MESSAGE[sniffed.kind]);
+ if (hosted && !hosted[sniffed.kind as "image" | "video" | "audio"]) {
+ fs.rmSync(dest, { force: true });
+ return json(403, { error: CONNECT_GPU_UPLOAD_MESSAGE, code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });
+ }
if (sniffed.kind === "image") {
const size = imageSize(head);
if (!size) return drop(415, ACCOUNT_MESSAGES.wrongType);
diff --git a/src/app/s/[token]/f/[...path]/route.ts b/src/app/s/[token]/f/[...path]/route.ts
index 4ac2b0f0..eab58ed6 100644
--- a/src/app/s/[token]/f/[...path]/route.ts
+++ b/src/app/s/[token]/f/[...path]/route.ts
@@ -2,6 +2,7 @@ import { shareRoute } from "@/lib/share";
import { fileResponse } from "@/server/file-response";
import { findShare } from "@/server/share-access";
import { shareServesFile } from "@/server/shares";
+import { fileHeld } from "@/server/account-library";
const NOINDEX = { "X-Robots-Tag": "noindex, nofollow, noarchive", "Referrer-Policy": "no-referrer" };
@@ -15,7 +16,8 @@ export async function GET(request: Request, ctx: RouteContext<"/s/[token]/f/[...
const { token, path: parts } = await ctx.params;
const rel = shareRoute(`/s/${token}/f/${parts.join("/")}`)?.file;
const row = rel ? findShare(token) : null;
- if (!rel || !row || !shareServesFile(row, rel)) return new Response("Not found", { status: 404, headers: NOINDEX });
+ // A file hidden by the owner, or held for its check, is never served by a link.
+ if (!rel || !row || !shareServesFile(row, rel) || fileHeld(rel)) return new Response("Not found", { status: 404, headers: NOINDEX });
// Revoking stops new requests at once; a browser may keep what it already has for a few minutes.
return fileResponse(request, rel, { cache: "private, max-age=300", headers: NOINDEX, clean: true });
}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 87b63820..4a49a807 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -886,6 +886,16 @@ export interface GenerationRequest {
* server from the session only (the request schema drops it from what a client sends).
*/
account?: string;
+ /**
+ * Server-only, like `account` (src/server/run-stamp.ts): the run goes to this install's GPUs ("pool", hosted runs);
+ * the billing service's hold for it and the words of its charge; the moderation service sees its outputs first.
+ */
+ place?: "pool";
+ hold?: string;
+ charge?: string;
+ checkOutputs?: boolean;
+ /** How long a run on this install's GPUs may wait in line (ms), when the billing service set it. */
+ waitMs?: number;
feature: string;
presetId?: string;
modelId: string;
@@ -1141,6 +1151,16 @@ export interface Generation {
fix?: GenerationFix | null;
/** Failed or stopped before its paid provider took the job (no external id): the card says "Not billed", not its price. */
notBilled?: true;
+ /** Ran on this install's GPUs (hosted runs), not the account's own. */
+ place?: "pool";
+ /** The billing service's words for what a run on this install's GPUs costs ("7 units"); shown when it succeeded. */
+ charge?: string;
+ /** A run with a billing hold that failed or was stopped: nothing was charged. */
+ notCharged?: true;
+ /** "checking": its outputs wait for the moderation service before they show. */
+ stage?: "checking";
+ /** A run waiting for this install's GPUs: its place in line and the wait, about (GET /api/generations/<id>). */
+ queue?: { place: number; etaSeconds: number | null };
/**
* What the run leaves out or changes, said when it is created (LoRAs a cloud run can't carry, a clip length
* the API rounds). Only on the answer that creates it; not stored.
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 1288c282..abc924ab 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -199,6 +199,8 @@ export function accountMayChange(method: string, pathname: string, search: strin
// Running its own jobs on its own computer.
if (COMPUTER_CHANGES.some(([m, p]) => m === method && p.test(pathname))) return true;
if (method === "POST" && (pathname === "/api/uploads" || pathname === "/api/media/probe")) return true;
+ // "Report this result", and a click on an offer the billing service sent (each route checks the rest).
+ if (method === "POST" && (pathname === "/api/reports" || pathname === "/api/billing/interest")) return true;
// Like, pin or review many of its own runs at once (the route checks each is its own, and refuses the rest).
if (method === "POST" && pathname === "/api/generations/bulk") return true;
return isPriceCheck(method, pathname, search);
@@ -250,6 +252,9 @@ export const LIBRARY_MESSAGE = "Free accounts can't save to this studio's librar
* that key only, with only its own uploaded files (src/app/api/generations/route.ts, generations.ts accountRun). Other
* tools plan with the install's AI helpers or its own ComfyUI, so they stay refused.
*/
+/** A report anyone may send, signed in or not ("Report this result" on a shared link). */
+export const anyoneMayReport = (method: string, pathname: string): boolean => method === "POST" && pathname === "/api/reports";
+
export function ownGpuRun(method: string, pathname: string): boolean {
return method === "POST" && pathname === "/api/generations";
}
diff --git a/src/proxy.ts b/src/proxy.ts
index 1f774b3c..8fe1c6f1 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -11,6 +11,7 @@ import {
liveRoute,
accountMayChange,
accountOwnRead,
+ anyoneMayReport,
ASSIST_OWNER_MESSAGE,
CONNECT_GPU_HEADER,
CONNECT_GPU_OR_KEY_MESSAGE,
@@ -31,6 +32,7 @@ import { fileAccount, generationAccount } from "@/server/account-library";
import { hit } from "@/server/rate";
import { recordExists } from "@/server/records";
import { findShare, shareGuard, shareTargetExists } from "@/server/share-access";
+import { hostedRunsOn } from "@/server/hosted-switch";
/**
* Paths that work signed out: the login page and its API (and share links: openShare). Sign-up and
@@ -171,6 +173,7 @@ function guest(request: NextRequest): NextResponse {
if (method === "GET" || method === "HEAD") return readAsGuest(request, false);
if (isPriceCheck(method, pathname, search)) return priceCheck(request, `guest:${LoginGuard.clientKey(request.headers)}`);
if (isAssistChange(method, pathname)) return assistOwner();
+ if (anyoneMayReport(method, pathname)) return pass(request);
// What an account may send, the library, the owner's settings and the studios' runs: signing up is the next step.
if (!accountMayChange(method, pathname, search) && !isLibraryChange(method, pathname) && !ownerOnly(method, pathname) && !ownGpuRun(method, pathname)) return ownGpuTool();
return NextResponse.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: guestHeaders });
@@ -239,7 +242,9 @@ function account(request: NextRequest, who: Account): NextResponse {
// A tool its own GPU or key wouldn't run says so first: "Connect your GPU" only for what a GPU or a key unlocks.
if (!ownGpuRun(request.method, pathname)) return ownGpuTool();
// Neither its own GPU nor its own key: nothing it could run on. (Which one a run needs, the route says.)
- if (!who.gpu && !hasCloudKey(who)) return NextResponse.json({ error: CONNECT_GPU_OR_KEY_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
+ // With hosted runs on (FUOBE_HOSTED_RUNS=1), a run in the studios may go to this install's GPUs: the route decides.
+ const hosted = hostedRunsOn() && request.method === "POST" && pathname === "/api/generations";
+ if (!who.gpu && !hasCloudKey(who) && !hosted) return NextResponse.json({ error: CONNECT_GPU_OR_KEY_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
return pass(request);
}
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 5bf6fc27..33ff1dc7 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -10,6 +10,8 @@ import { offeredSummary } from "./model-access";
import { PROVIDERS } from "./providers";
import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
+import { balance as billingBalance, OPEN_POLICY, policy as billingPolicy, type Action, type Balance } from "./billing";
+import { poolReady } from "./hosted";
/**
* "Your GPU" (public sign-up): the ComfyUI an account connects, where its runs go. The server calls
@@ -171,6 +173,17 @@ export interface VisitorView {
keys: CloudProvider[];
/** The studio lets accounts run paid models on their own keys (it isn't open-source only). */
paidAllowed: boolean;
+ /**
+ * Hosted runs (FUOBE_HOSTED_RUNS=1): this account (or a guest, once signed up) may run on this install's GPUs, so
+ * connecting a GPU of its own is optional.
+ */
+ hosted?: boolean;
+ /** The billing service's words for the account's balance (billing.ts): the sidebar chip and its menu. */
+ balance?: Balance;
+ /** Extra links the billing service sends for the menu. */
+ links?: Action[];
+ /** A notice to show once per id (the billing service's policy). */
+ notice?: { id: string; text: string; url?: string };
}
/**
@@ -191,6 +204,15 @@ export async function visitorStatus(account: Account | null) {
keys,
paidAllowed: paidAllowed(),
};
+ // Hosted runs and the billing hook: nothing of either with them off.
+ if (poolReady()) {
+ const p = account ? await billingPolicy(account.id) : OPEN_POLICY;
+ if (p?.hosted) viewer.hosted = true;
+ if (account && p?.links?.length) viewer.links = p.links;
+ if (account && p?.notice) viewer.notice = p.notice;
+ const b = account ? await billingBalance(account.id) : null;
+ if (b) viewer.balance = b;
+ }
const configured = (id: string) => (id === "comfyui" ? (gpu ? !!live?.online : true) : isCloudProvider(id) && keys.includes(id));
const access = keys.length ? offeredSummary() : undefined;
return {
diff --git a/src/server/account-library.ts b/src/server/account-library.ts
index fe95fa92..d142e9de 100644
--- a/src/server/account-library.ts
+++ b/src/server/account-library.ts
@@ -20,18 +20,29 @@ export function generationAccount(id: string): string | null | undefined {
* null for the owner, undefined when no file is stored there. A file stamped before the account column existed goes by
* the run that made it.
*/
+/** The owner of a file no account may read yet (held for its check). */
+export const HELD_FILE = "\u0000held";
+
export function fileAccount(rel: string): string | null | undefined {
// Rows store the platform's separator (backslashes on Windows); a URL always has /.
const native = rel.split("/").join(path.sep);
const row = db()
.prepare(
- `SELECT COALESCE(a.account_id, CASE WHEN json_valid(g.request_json) THEN json_extract(g.request_json, '$.account') END) AS account
+ `SELECT COALESCE(a.account_id, CASE WHEN json_valid(g.request_json) THEN json_extract(g.request_json, '$.account') END) AS account, a.held AS held
FROM assets a LEFT JOIN generations g ON g.id = a.generation_id WHERE a.rel_path IN (?, ?) LIMIT 1`,
)
- .get(rel, native) as { account: string | null } | undefined;
+ .get(rel, native) as { account: string | null; held: number | null } | undefined;
+ // A result held for the moderation service's check (output-checks.ts) is nobody's to read until it passes.
+ if (row?.held) return HELD_FILE;
return row ? (row.account ?? null) : undefined;
}
+/** A stored file that is held (hidden, or waiting for its check): served to no account and by no link. */
+export function fileHeld(rel: string): boolean {
+ const native = rel.split("/").join(path.sep);
+ return !!db().prepare("SELECT 1 FROM assets WHERE rel_path IN (?, ?) AND held = 1 LIMIT 1").get(rel, native);
+}
+
/** Whose stored file this asset id is (as fileAccount; undefined when there is no such asset). */
export function assetAccount(id: string): string | null | undefined {
const row = db()
diff --git a/src/server/billing-outbox.ts b/src/server/billing-outbox.ts
new file mode 100644
index 00000000..fede02cc
--- /dev/null
+++ b/src/server/billing-outbox.ts
@@ -0,0 +1,186 @@
+import "server-only";
+import { db } from "./db";
+import { billingConfigured, forgetBalance, sendReport, type RefundReport, type SettleReport } from "./billing";
+
+/**
+ * The billing outbox: every report the billing service must get (settle, refund, release) is written here first, then
+ * sent, and sent again with backoff until the service takes it (for 7 days). A report is known by its key (the run
+ * row's id, or "release:<hold>"), so a row is reported once however often the sweep runs, and a restart in between
+ * loses nothing: the sweep finds every finished row with a hold and no report from what is stored.
+ *
+ * A hold's rows are reported once none of them is still queued or running, each with `rows` (how many rows share the
+ * hold), so the service closes the hold when the last report arrives.
+ */
+
+const BACKOFF_START_MS = 10_000;
+const BACKOFF_MAX_MS = 10 * 60_000;
+const GIVE_UP_MS = 7 * 24 * 3_600_000;
+/** A report that keeps failing this long is logged as an alert. */
+const ALERT_AFTER_MS = 10 * 60_000;
+
+interface DoneRow {
+ id: string;
+ status: "succeeded" | "failed" | "canceled";
+ error: string | null;
+ outputs_json: string;
+ external_id: string | null;
+ cost_usd: number | null;
+ hold: string;
+ started_at: number | null;
+ completed_at: number | null;
+ check_state: string | null;
+}
+
+/** Where a row stands in the output check, for its report: hidden, never checked in time, or nothing to say. */
+function checkStatus(state: string | null): "hidden" | "unchecked" | null {
+ return state === "hidden" ? "hidden" : state === "unchecked" ? "unchecked" : null;
+}
+
+/** Megapixels of a result's largest picture or clip frame, when its size is known. */
+function megapixels(outputs: { width?: number; height?: number }[]): number | null {
+ let best = 0;
+ for (const o of outputs) if (o.width && o.height) best = Math.max(best, (o.width * o.height) / 1e6);
+ return best ? Math.round(best * 100) / 100 : null;
+}
+
+/** Write a report for every finished row of every hold whose rows are all finished. Returns how many were written. */
+export function queueReports(now = Date.now(), limit = 200): number {
+ const d = db();
+ const rows = d
+ .prepare(
+ `SELECT g.id, g.status, g.error, g.outputs_json, g.external_id, g.cost_usd, g.completed_at,
+ json_extract(g.request_json, '$.hold') AS hold, r.started_at AS started_at,
+ (SELECT state FROM output_checks c WHERE c.generation_id = g.id AND c.state IN ('hidden', 'unchecked') LIMIT 1) AS check_state
+ FROM generations g LEFT JOIN generation_runs r ON r.id = g.id
+ WHERE json_extract(g.request_json, '$.hold') IS NOT NULL
+ AND g.status IN ('succeeded', 'failed', 'canceled')
+ AND NOT EXISTS (SELECT 1 FROM billing_outbox o WHERE o.key = g.id)
+ AND NOT EXISTS (SELECT 1 FROM generations h WHERE json_extract(h.request_json, '$.hold') = json_extract(g.request_json, '$.hold') AND h.status IN ('queued', 'running'))
+ ORDER BY g.completed_at LIMIT ?`,
+ )
+ .all(limit) as DoneRow[];
+ if (!rows.length) return 0;
+ const count = d.prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.hold') = ?");
+ const insert = d.prepare("INSERT OR IGNORE INTO billing_outbox (key, kind, hold_id, payload_json, tries, next_at, created_at) VALUES (?, ?, ?, ?, 0, ?, ?)");
+ let written = 0;
+ d.transaction(() => {
+ for (const r of rows) {
+ const n = (count.get(r.hold) as { n: number }).n;
+ const gpuMs = r.started_at && r.completed_at && r.completed_at > r.started_at ? r.completed_at - r.started_at : null;
+ const outputs = (() => {
+ try {
+ return JSON.parse(r.outputs_json) as { width?: number; height?: number }[];
+ } catch {
+ return [];
+ }
+ })();
+ const checked = checkStatus(r.check_state);
+ if (r.status === "succeeded" && !checked) {
+ const report: SettleReport = {
+ holdId: r.hold,
+ generationId: r.id,
+ rows: n,
+ status: "succeeded",
+ final: { outputs: outputs.length, megapixels: megapixels(outputs), seconds: null },
+ providerUsd: r.cost_usd,
+ gpuMs,
+ device: null,
+ reachedProvider: !!r.external_id,
+ };
+ written += insert.run(r.id, "settle", r.hold, JSON.stringify(report), now, now).changes;
+ } else {
+ const report: RefundReport = {
+ holdId: r.hold,
+ generationId: r.id,
+ rows: n,
+ status: checked ?? (r.status === "canceled" ? "canceled" : "failed"),
+ reason: (r.error ?? "").slice(0, 500),
+ reachedProvider: !!r.external_id,
+ gpuMs,
+ device: null,
+ };
+ written += insert.run(r.id, "refund", r.hold, JSON.stringify(report), now, now).changes;
+ }
+ }
+ })();
+ return written;
+}
+
+/** A hold whose rows were never made (createGenerations threw): the whole amount goes back. */
+export function queueRelease(holdId: string, now = Date.now()): void {
+ db()
+ .prepare("INSERT OR IGNORE INTO billing_outbox (key, kind, hold_id, payload_json, tries, next_at, created_at) VALUES (?, 'release', ?, ?, 0, ?, ?)")
+ .run(`release:${holdId}`, holdId, JSON.stringify({ holdId, reason: "not-created" }), now, now);
+ // Sent now, not at the next tick (the runner may not be running yet).
+ void sweepBilling();
+}
+
+interface OutboxRow {
+ key: string;
+ kind: "settle" | "refund" | "release";
+ hold_id: string;
+ payload_json: string;
+ tries: number;
+ created_at: number;
+}
+
+/** Send the reports that are due. Returns how many the service took. */
+export async function drainOutbox(now = Date.now(), limit = 50): Promise<number> {
+ const d = db();
+ const due = d.prepare("SELECT key, kind, hold_id, payload_json, tries, created_at FROM billing_outbox WHERE done_at IS NULL AND next_at <= ? ORDER BY next_at LIMIT ?").all(now, limit) as OutboxRow[];
+ let sent = 0;
+ for (const r of due) {
+ try {
+ await sendReport(r.kind, JSON.parse(r.payload_json));
+ d.prepare("UPDATE billing_outbox SET done_at = ?, tries = tries + 1, last_error = NULL WHERE key = ?").run(Date.now(), r.key);
+ sent++;
+ const account = accountOfHold(r.hold_id);
+ if (account) forgetBalance(account);
+ } catch (e) {
+ const tries = r.tries + 1;
+ const wait = Math.min(BACKOFF_MAX_MS, BACKOFF_START_MS * 2 ** Math.min(tries - 1, 16));
+ const age = now - r.created_at;
+ if (age >= GIVE_UP_MS) {
+ // Kept, marked as given up: the service's own hold sweep releases what it held.
+ d.prepare("UPDATE billing_outbox SET done_at = ?, tries = ?, last_error = ?, gave_up = 1 WHERE key = ?").run(now, tries, (e as Error).message.slice(0, 500), r.key);
+ console.warn(`[fuobe] billing: gave up sending ${r.kind} ${r.key} after 7 days`);
+ continue;
+ }
+ d.prepare("UPDATE billing_outbox SET tries = ?, next_at = ?, last_error = ? WHERE key = ?").run(tries, now + wait, (e as Error).message.slice(0, 500), r.key);
+ if (age >= ALERT_AFTER_MS) console.warn(`[fuobe] billing: ${r.kind} ${r.key} still not sent after ${Math.round(age / 60_000)} min: ${(e as Error).message}`);
+ }
+ }
+ return sent;
+}
+
+/** The account a hold's rows belong to (to read its balance again). */
+function accountOfHold(holdId: string): string | undefined {
+ const r = db().prepare("SELECT json_extract(request_json, '$.account') AS account FROM generations WHERE json_extract(request_json, '$.hold') = ? LIMIT 1").get(holdId) as { account: string | null } | undefined;
+ return r?.account ?? undefined;
+}
+
+declare global {
+ var __fuobeBillingSweep: boolean | undefined;
+}
+
+/** One outbox sweep (the runner's tick): write what is due, send what is due. One at a time. */
+export async function sweepBilling(now = Date.now()): Promise<void> {
+ if (globalThis.__fuobeBillingSweep) return;
+ // Reports wait for a service: with none set, nothing is written (a hold can only exist while one was set).
+ if (!billingConfigured()) return;
+ globalThis.__fuobeBillingSweep = true;
+ try {
+ queueReports(now);
+ await drainOutbox(now);
+ } catch (e) {
+ console.warn(`[fuobe] billing sweep: ${(e as Error).message}`);
+ } finally {
+ globalThis.__fuobeBillingSweep = false;
+ }
+}
+
+/** How many reports wait, and since when (for the admin queue view). */
+export function outboxDepth(): { pending: number; oldestAt: number | null } {
+ const r = db().prepare("SELECT COUNT(*) AS n, MIN(created_at) AS oldest FROM billing_outbox WHERE done_at IS NULL").get() as { n: number; oldest: number | null };
+ return { pending: r.n, oldestAt: r.oldest };
+}
diff --git a/src/server/billing.ts b/src/server/billing.ts
new file mode 100644
index 00000000..7eb6d2b7
--- /dev/null
+++ b/src/server/billing.ts
@@ -0,0 +1,315 @@
+import "server-only";
+import type { Account } from "./auth";
+import { HookDown, hookCall, hookTarget, type HookTarget } from "./hook-client";
+
+/**
+ * The billing hook (docs/billing-hook.md): an install can connect an external billing service at FUOBE_BILLING_URL.
+ * Fuobe sends facts about each run that goes to this install's GPUs (hosted runs, hosted.ts); the service answers with
+ * what the person sees and whether the run may start. With no service set, no call is made and every run is free and
+ * allowed: exactly the studio as it was.
+ *
+ * The service is called only for runs on this install's GPUs ("pool"), plus an account's policy, its balance, account
+ * events and offer clicks. A run on the account's own GPU or its own key never asks it.
+ *
+ * Calls: GET /v1/policy, POST /v1/quote, POST /v1/reserve, POST /v1/release, POST /v1/settle, POST /v1/refund,
+ * GET /v1/balance, POST /v1/account-event, POST /v1/interest. Every call is safe to send twice. Release, settle and
+ * refund go through an outbox (billing-outbox.ts), so they reach the service even after a restart or an outage.
+ */
+
+export type Place = "own-gpu" | "own-key" | "pool" | "install-key";
+
+export interface AccountFacts {
+ id: string;
+ email: string | null;
+ emailVerified: boolean;
+ signIn: "google" | "password";
+ createdAt: number;
+ adultAt: number | null;
+}
+
+export interface RunFacts {
+ place: Place;
+ model: string;
+ op: string | null;
+ app: string | null;
+ preset: string | null;
+ studio: string;
+ kind: "image" | "video" | "audio" | "text" | "model3d";
+ engine: "open" | "cloud";
+ provider: string;
+ jobs: number;
+ outputsPerJob: number;
+ megapixels: number | null;
+ seconds: number | null;
+ fps: number | null;
+ loras: number;
+ inputs: { image: number; video: number; audio: number };
+ lane: string | null;
+ providerUsd: number | null;
+}
+
+export interface QueueFacts {
+ lane: string;
+ ahead: number;
+ etaS: number | null;
+ workersOnline: number;
+ nextOpenAt: number | null;
+ mine: { waiting: number; running: number };
+}
+
+/** A link the service sends; the app opens `url` as given and never builds one. */
+export interface Action {
+ label: string;
+ url: string;
+}
+
+/** An offer the person can ask about; a click sends POST /v1/interest with its key. */
+export interface Offer {
+ key: string;
+ text: string;
+ label: string;
+}
+
+export type RefuseCode = "top-up" | "limit" | "busy" | "not-offered" | "blocked" | "closed" | "paused";
+
+export interface Quote {
+ allowed: boolean;
+ amount: number;
+ priceVersion: string;
+ /** What Run shows, and the line under it. */
+ text: string;
+ sub?: string;
+ code?: RefuseCode;
+ etaS?: number | null;
+ action?: Action;
+ offer?: Offer;
+}
+
+export interface Policy {
+ /** May this account use this install's GPUs at all. */
+ hosted: boolean;
+ /** Which models and apps run on this install's GPUs (never applied to an account's own GPU or key). */
+ pool: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } };
+ /** Which of its own files a run on this install's GPUs may use. */
+ uploads: { image: boolean; video: boolean; audio: boolean };
+ limits: { activeRuns: number; waiting: number; runsPerHour: number; outputsPerRun: number; maxMegapixels: number; maxSeconds: number; keepDays: number; spaceBytes: number };
+ links?: Action[];
+ notice?: { id: string; text: string; url?: string };
+ ttlS: number;
+}
+
+export type ReserveAnswer =
+ | { ok: true; holdId: string; amount: number; boostMs: number; maxWaitMs: number; pools?: string[]; text: string }
+ | { ok: false; code: RefuseCode | "price-changed"; text: string; quote?: Quote; action?: Action; offer?: Offer };
+
+export interface Balance {
+ amount: number;
+ chip: string;
+ text: string;
+ sub?: string;
+ refillAt?: number | null;
+ detail: { label: string; text: string }[];
+ action?: Action;
+ offer?: Offer;
+}
+
+export interface SettleReport {
+ holdId: string;
+ generationId: string;
+ rows: number;
+ status: "succeeded";
+ final: { outputs: number; megapixels: number | null; seconds: number | null };
+ providerUsd: number | null;
+ gpuMs: number | null;
+ device: string | null;
+ reachedProvider: boolean;
+}
+
+export interface RefundReport {
+ holdId: string;
+ generationId: string;
+ rows: number;
+ status: "failed" | "canceled" | "hidden" | "unchecked";
+ reason: string;
+ reachedProvider: boolean;
+ gpuMs: number | null;
+ device: string | null;
+}
+
+/** What a person sees when the billing service doesn't answer: never its address or its error. */
+export const BILLING_PAUSED = "Runs are paused for a moment. Try again soon.";
+
+/** Timeouts per call (ms). */
+export const BILLING_TIMEOUTS = { policy: 1000, quote: 1000, reserve: 2000, balance: 1000, report: 5000, event: 5000 };
+
+const HOOK = "billing service";
+
+/** The service's address, or null when none is set (or it can't be read: then it is logged once and treated as none). */
+function target(): HookTarget | null {
+ const raw = process.env.FUOBE_BILLING_URL ?? "";
+ if (!raw.trim()) return null;
+ const t = hookTarget(raw);
+ if (!t && !globalThis.__fuobeBillingBadUrl) {
+ globalThis.__fuobeBillingBadUrl = true;
+ console.warn("[fuobe] FUOBE_BILLING_URL is not an http(s) or unix: address; the billing hook is off");
+ }
+ return t;
+}
+
+declare global {
+ var __fuobeBillingBadUrl: boolean | undefined;
+ var __fuobeBillingPolicies: Map<string, { at: number; ttlMs: number; policy: Policy }> | undefined;
+ var __fuobeBillingBalances: Map<string, { at: number; balance: Balance }> | undefined;
+}
+
+/** Is a billing service set? */
+export const billingConfigured = (): boolean => target() !== null;
+
+function call<T>(method: "GET" | "POST", path: string, body: unknown, timeoutMs: number): Promise<T> {
+ const t = target();
+ if (!t) return Promise.reject(new HookDown(HOOK, "not configured"));
+ return hookCall<T>({ hook: HOOK, target: t, token: process.env.FUOBE_BILLING_TOKEN || undefined, method, path, body, timeoutMs });
+}
+
+/** Log a transport problem on the server only. */
+function logDown(what: string, e: unknown): void {
+ console.warn(`[fuobe] billing ${what}: ${(e as Error).message}`);
+}
+
+/** An account as the billing service sees it. */
+export function accountFacts(a: Pick<Account, "id" | "email" | "createdAt"> & { signIn?: "google" | "password"; emailVerifiedAt?: number; adultAt?: number }): AccountFacts {
+ return { id: a.id, email: a.email || null, emailVerified: !!a.emailVerifiedAt, signIn: a.signIn ?? "password", createdAt: a.createdAt, adultAt: a.adultAt ?? null };
+}
+
+/** With no billing service: an account may use this install's GPUs (when hosted runs are on) within today's limits. */
+export const OPEN_POLICY: Policy = {
+ hosted: true,
+ pool: {},
+ uploads: { image: true, video: false, audio: false },
+ limits: { activeRuns: 4, waiting: 4, runsPerHour: 60, outputsPerRun: 4, maxMegapixels: 0, maxSeconds: 0, keepDays: 0, spaceBytes: 0 },
+ ttlS: 60,
+};
+
+/**
+ * The account's policy (cached for its `ttlS`). No service: OPEN_POLICY. The service down: null (the caller treats
+ * runs on this install's GPUs as paused).
+ */
+export async function policy(accountId: string): Promise<Policy | null> {
+ if (!billingConfigured()) return OPEN_POLICY;
+ const cache = (globalThis.__fuobeBillingPolicies ??= new Map());
+ const hit = cache.get(accountId);
+ if (hit && Date.now() - hit.at < hit.ttlMs) return hit.policy;
+ try {
+ const p = await call<Policy>("GET", `/v1/policy?account=${encodeURIComponent(accountId)}`, undefined, BILLING_TIMEOUTS.policy);
+ const ttlMs = Math.max(0, Math.min(3600, Number(p.ttlS) || 0)) * 1000;
+ cache.set(accountId, { at: Date.now(), ttlMs, policy: p });
+ if (cache.size > 5000) cache.delete(cache.keys().next().value!);
+ return p;
+ } catch (e) {
+ logDown("policy", e);
+ return hit?.policy ?? null;
+ }
+}
+
+/** A free run's quote (no service set): Run keeps its own words. */
+export const FREE_QUOTE: Quote = { allowed: true, amount: 0, priceVersion: "", text: "" };
+
+/** The quote for a run on this install's GPUs. No service: free. The service down: a refusal with `paused`. */
+export async function quote(account: AccountFacts | null, run: RunFacts, queue: QueueFacts | null): Promise<Quote> {
+ if (!billingConfigured()) return FREE_QUOTE;
+ try {
+ return await call<Quote>("POST", "/v1/quote", { account, run, queue }, BILLING_TIMEOUTS.quote);
+ } catch (e) {
+ logDown("quote", e);
+ return { allowed: false, amount: 0, priceVersion: "", text: BILLING_PAUSED, code: "paused" };
+ }
+}
+
+/**
+ * Set the run's price aside before it is created. No service: null (no hold; the run is free). The service down (one
+ * retry with the same request id): a `paused` refusal. Never throws.
+ */
+export async function reserve(input: { requestId: string; account: AccountFacts; run: RunFacts; queue: QueueFacts | null; shown: { amount: number; priceVersion: string } }): Promise<ReserveAnswer | null> {
+ if (!billingConfigured()) return null;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ const a = await call<ReserveAnswer>("POST", "/v1/reserve", input, BILLING_TIMEOUTS.reserve);
+ if (a.ok && (typeof a.holdId !== "string" || !a.holdId)) throw new HookDown(HOOK, "a reserve answer without a hold id");
+ return a;
+ } catch (e) {
+ logDown(`reserve (try ${attempt + 1})`, e);
+ }
+ }
+ return { ok: false, code: "paused", text: BILLING_PAUSED };
+}
+
+/** The HTTP status and header for a billing refusal (the generations route; docs/billing-hook.md). */
+export function refusalStatus(code: RefuseCode | "price-changed"): number {
+ switch (code) {
+ case "price-changed":
+ return 409;
+ case "top-up":
+ return 402;
+ case "limit":
+ return 429;
+ case "busy":
+ case "paused":
+ return 503;
+ default:
+ return 403;
+ }
+}
+
+export const BILLING_HEADER = "x-fuobe-billing";
+
+/** The account's balance (cached 10 s). No service, or no answer: null (nothing to show). */
+export async function balance(accountId: string): Promise<Balance | null> {
+ if (!billingConfigured()) return null;
+ const cache = (globalThis.__fuobeBillingBalances ??= new Map());
+ const hit = cache.get(accountId);
+ if (hit && Date.now() - hit.at < 10_000) return hit.balance;
+ try {
+ const b = await call<Balance>("GET", `/v1/balance?account=${encodeURIComponent(accountId)}`, undefined, BILLING_TIMEOUTS.balance);
+ cache.set(accountId, { at: Date.now(), balance: b });
+ if (cache.size > 5000) cache.delete(cache.keys().next().value!);
+ return b;
+ } catch (e) {
+ logDown("balance", e);
+ return hit?.balance ?? null;
+ }
+}
+
+/** Forget an account's cached balance (after a run is reserved or reported, the chip reads it again). */
+export function forgetBalance(accountId: string): void {
+ globalThis.__fuobeBillingBalances?.delete(accountId);
+}
+
+/** Tell the service about an account: made, verified, signed in, deleted. Best effort; never fails the caller. */
+export function accountEvent(event: "created" | "verified" | "signed-in" | "deleted", account: AccountFacts): void {
+ if (!billingConfigured()) return;
+ call("POST", "/v1/account-event", { event, account }, BILLING_TIMEOUTS.event).catch((e) => logDown(`account-event ${event}`, e));
+}
+
+/** An account asked about an offer. No service: null. */
+export async function interest(accountId: string, key: string): Promise<{ ok: true; text: string } | null> {
+ if (!billingConfigured()) return null;
+ try {
+ return await call<{ ok: true; text: string }>("POST", "/v1/interest", { account: accountId, key }, BILLING_TIMEOUTS.event);
+ } catch (e) {
+ logDown("interest", e);
+ return null;
+ }
+}
+
+/** Send one outbox report (billing-outbox.ts). Throws HookDown when the service doesn't take it. */
+export async function sendReport(kind: "settle" | "refund" | "release", payload: unknown): Promise<void> {
+ const a = await call<{ ok?: boolean }>("POST", `/v1/${kind}`, payload, BILLING_TIMEOUTS.report);
+ if (a?.ok !== true) throw new HookDown(HOOK, `${kind} wasn't taken`);
+}
+
+/** Forget the cached policies and balances (tests; a changed service). */
+export function resetBillingCache(): void {
+ globalThis.__fuobeBillingPolicies?.clear();
+ globalThis.__fuobeBillingBalances?.clear();
+ globalThis.__fuobeBillingBadUrl = undefined;
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 56acbe02..3c2998a8 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -669,6 +669,56 @@ export const RELAY_TABLES = `CREATE TABLE IF NOT EXISTS relay_runners (
);
CREATE INDEX IF NOT EXISTS relay_inputs_task ON relay_inputs(task_id);`;
+/**
+ * The optional external services' tables (billing.ts, moderation.ts). billing_outbox: every settle, refund and release
+ * the billing service must get, kept until it takes it (billing-outbox.ts). output_checks: each output of a run whose
+ * outputs the moderation service sees first, and where its check is. reports_inbox: "Report this result" when no
+ * moderation service is set, for the owner. Made here rather than as numbered migrations (other branches add those at
+ * the same time). Safe to run on every start; empty and unread while no service is set.
+ */
+export const HOOK_TABLES = `CREATE TABLE IF NOT EXISTS billing_outbox (
+ key TEXT PRIMARY KEY,
+ kind TEXT NOT NULL,
+ hold_id TEXT NOT NULL,
+ payload_json TEXT NOT NULL,
+ tries INTEGER NOT NULL DEFAULT 0,
+ next_at INTEGER NOT NULL,
+ created_at INTEGER NOT NULL,
+ done_at INTEGER,
+ gave_up INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT
+ );
+ CREATE INDEX IF NOT EXISTS billing_outbox_due ON billing_outbox(done_at, next_at);
+ CREATE TABLE IF NOT EXISTS output_checks (
+ asset_id TEXT PRIMARY KEY,
+ generation_id TEXT NOT NULL,
+ state TEXT NOT NULL,
+ asked_at INTEGER NOT NULL,
+ tries INTEGER NOT NULL DEFAULT 0,
+ next_at INTEGER,
+ decided_at INTEGER,
+ text TEXT
+ );
+ CREATE INDEX IF NOT EXISTS output_checks_generation ON output_checks(generation_id);
+ CREATE INDEX IF NOT EXISTS output_checks_due ON output_checks(state, next_at);
+ CREATE TABLE IF NOT EXISTS reports_inbox (
+ id TEXT PRIMARY KEY,
+ target_json TEXT NOT NULL,
+ category TEXT NOT NULL,
+ text TEXT,
+ reporter TEXT,
+ created_at INTEGER NOT NULL,
+ done_at INTEGER
+ );`;
+
+/** Columns the optional services added to existing tables: [table, column, type]. */
+const HOOK_COLUMNS: [string, string, string][] = [
+ // 1: never served to the account (its output check hasn't said "show").
+ ["assets", "held", "INTEGER NOT NULL DEFAULT 0"],
+ // NULL, or "checking" (the tile says "Checking").
+ ["generations", "stage", "TEXT"],
+];
+
/** Columns of the relay tables that came later: [table, column, type]. */
const RELAY_COLUMNS: [string, string, string][] = [
["relay_runners", "comfy", "TEXT NOT NULL DEFAULT 'ok'"],
@@ -731,6 +781,18 @@ function open(): Database.Database {
const has = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column);
if (!has) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
}
+ // The optional billing and moderation services (billing.ts, moderation.ts): their tables and columns.
+ db.exec(HOOK_TABLES);
+ for (const [table, column, type] of HOOK_COLUMNS) {
+ const has = (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).some((c) => c.name === column);
+ if (!has) db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
+ }
+ // A billing hold's rows are found through this index (only rows that have one are in it).
+ try {
+ db.exec("CREATE INDEX IF NOT EXISTS generations_hold ON generations(json_extract(request_json, '$.hold')) WHERE json_extract(request_json, '$.hold') IS NOT NULL");
+ } catch (e) {
+ console.warn(`[fuobe] Couldn't index runs by hold: ${(e as Error).message}`);
+ }
// An account's own runs (its list, its active runs) are found through this index, not by reading every run. Not a
// numbered migration, so branches that add migrations never clash over it; a failure only leaves lists slower.
try {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index b3ace781..20ec92f5 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -79,6 +79,11 @@ import { convertMask, decodePng, encodePng } from "./png";
import { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";
import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";
import { accountSend } from "./account-send";
+import { stamped, stampOf, withRunStamp } from "./run-stamp";
+import { placeInLine, poolWaitMs, runOnPool } from "./hosted";
+import { sweepBilling } from "./billing-outbox";
+import { moderationConfigured } from "./moderation";
+import { holdForCheck, sweepOutputChecks } from "./output-checks";
import { absolutePath, adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir } from "./storage";
interface Row {
@@ -115,6 +120,8 @@ interface Row {
folder_id?: string | null;
/** What a failed ComfyUI run was missing (GenerationFix as JSON). */
fix_json?: string | null;
+ /** NULL, or "checking": its outputs wait for the moderation service (output-checks.ts). */
+ stage?: string | null;
}
/** Trash and folder columns, joined onto every library read. */
@@ -123,7 +130,10 @@ const LIBRARY_JOINS = "LEFT JOIN generation_trash t ON t.generation_id = g.id LE
const LIBRARY_JOIN = `generations g ${LIBRARY_JOINS}`;
export function toGeneration(r: Row): Generation {
- const request = JSON.parse(r.request_json) as GenerationRequest;
+ const stored = JSON.parse(r.request_json) as GenerationRequest;
+ // The billing hold is the server's: never sent to a browser or a script.
+ const { hold, ...request } = stored;
+ const checking = r.stage === "checking";
const model = getModel(r.model_id);
const ar = request.params?.aspectRatio ?? model?.defaults?.aspectRatio;
// Rows read without the library join (the runner's own SELECTs) look the trash and folder up.
@@ -150,7 +160,8 @@ export function toGeneration(r: Row): Generation {
message: r.message,
prompt: r.prompt,
request,
- outputs: JSON.parse(r.outputs_json) as OutputFile[],
+ // Held for the moderation service's check: nothing of it is shown until it passes.
+ outputs: checking ? [] : (JSON.parse(r.outputs_json) as OutputFile[]),
error: r.error,
costUsd: r.cost_usd,
favorite: !!r.favorite,
@@ -169,9 +180,22 @@ export function toGeneration(r: Row): Generation {
...(r.status === "failed" && r.fix_json && { fix: parseFix(r.fix_json) }),
// Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed.
...((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && { notBilled: true as const }),
+ // On this install's GPUs (hosted runs): what it cost, or that it cost nothing.
+ ...(stored.place === "pool" && { place: "pool" as const }),
+ ...(stored.charge && r.status === "succeeded" && { charge: stored.charge }),
+ ...(hold && (r.status === "failed" || r.status === "canceled") && { notCharged: true as const }),
+ ...(checking && { stage: "checking" as const }),
+ // Waiting in line on this install's GPUs: its place and the wait, about.
+ ...(stored.place === "pool" && (r.status === "queued" || r.status === "running") && !checking && poolQueue(r.id)),
};
}
+/** A pool row's place in line, as the Generation field (none once it has started). */
+function poolQueue(id: string): { queue: { place: number; etaSeconds: number | null } } | Record<string, never> {
+ const q = placeInLine(id);
+ return q ? { queue: q } : {};
+}
+
function parseFix(json: string): GenerationFix | null {
try {
const f = JSON.parse(json) as GenerationFix;
@@ -803,12 +827,14 @@ function stampTenant(asked: GenerationRequest, opts: CreateOptions): GenerationR
const who = tenantAccount();
if (!who) {
if (ownGpu()) throw new Error("A run on an account's own GPU must be that account's run.");
- return asked;
+ // The owner's runs carry no place, hold or check of an account's run (run-stamp.ts).
+ return withRunStamp({}, () => stamped(asked));
}
if (asked.account && asked.account !== who) throw new Error("That run belongs to another account.");
const deps = opts.dependsOn === undefined ? [] : Array.isArray(opts.dependsOn) ? opts.dependsOn : [opts.dependsOn];
if (deps.some((d) => generationAccount(d) !== who)) throw new Error("An earlier step of this run isn't yours.");
- return { ...asked, account: who, engine: accountEngineMode(who) === "open" ? "open" : asked.engine };
+ // Where the run goes and its billing hold are the route's decision for this run (run-stamp.ts), never a stored request's.
+ return { ...stamped(asked), account: who, engine: accountEngineMode(who) === "open" ? "open" : asked.engine };
}
export function createGenerations(given: GenerationRequest, opts: CreateOptions = {}): Generation[] {
@@ -1227,7 +1253,8 @@ async function advanceDependents(): Promise<void> {
// An account's step reads its inputs, and is planned, as its run was: as that account, on its own ComfyUI and its own
// keys. submit() then checks the step's own provider (its GPU, or its key for that provider).
const account = stored.account;
- const asRun = <T,>(fn: () => T): T => (account ? asAccount(account, fn) : fn());
+ // A step of a run on this install's GPUs is planned there too, with the run's stamp (its place and hold).
+ const asRun = <T,>(fn: () => T): T => (account ? (stored.place === "pool" ? runOnPool(account, () => withRunStamp(stampOf(stored), fn)) : asAccount(account, fn)) : fn());
try {
// The planned op (r.op), not request.op: a translate whose op was inferred still gets the cue list.
const values = await asRun(() => Promise.all(outputs.map((o, i) => chainValue(pickOutput(o, slots[i]), slots[i], r.op))));
@@ -1300,6 +1327,8 @@ function recordSubmission(id: string, at: number): void {
export const OWN_GPU_ONLY = "Free accounts run only on their own ComfyUI: pick an open-source model.";
export const OPEN_ONLY_RUN = "This studio runs open-source models only, so paid models don't run here. Pick an open-source model.";
export const SWITCHED_OFF_RUN = "This account is switched off, so its runs stopped.";
+/** A run on this install's GPUs that waited past its limit (hosted runs). */
+export const POOL_WAITED = "This studio's GPUs were busy, so it didn't run. Not charged.";
/**
* Everything an account's work runs inside: as the account (tenant.ts: only its own files and runs), on its own ComfyUI
@@ -1421,8 +1450,26 @@ const accountOf = (r: Pick<Row, "request_json">): string | undefined => {
}
};
+/** A row of a run on this install's GPUs (hosted runs). */
+const poolOf = (r: Pick<Row, "request_json">): boolean => {
+ try {
+ return (JSON.parse(r.request_json) as GenerationRequest).place === "pool";
+ } catch {
+ return false;
+ }
+};
+
function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number): Promise<void> {
if (!req.account) return submitNow(id, route, providerId, plan, req, index);
+ // On this install's GPUs (hosted runs): as the account, on this install's ComfyUI server only.
+ if (req.place === "pool") {
+ if (providerId !== "comfyui") {
+ update(id, { status: "failed", error: OWN_GPU_ONLY, completed_at: Date.now(), message: null });
+ submitting().delete(id);
+ return Promise.resolve();
+ }
+ return runOnPool(req.account, () => withRunStamp(stampOf(req), () => submitNow(id, route, providerId, plan, req, index)));
+ }
const own = accountRun(req.account, providerId, "submit");
if ("error" in own) {
update(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
@@ -1448,7 +1495,7 @@ async function submitNow(
// An account's run on its own ComfyUI and keys only (asAccount): outside it, nothing is sent.
const adapter = adapterFor(providerId, req.account);
// An account's run on its own ComfyUI: every LoRA it adds must be there first (nothing is sent before this check).
- if (req.account && providerId === "comfyui") {
+ if (req.account && req.place !== "pool" && providerId === "comfyui") {
const fix = await checkAccountLoras([...plan.loras, ...graphLoras(route.endpoint, plan.params.extra)], route.endpoint, route);
if (fix) throw Object.assign(new Error(missingFilesMessage(fix)), { fix });
}
@@ -1724,8 +1771,10 @@ async function pollGuarded(r: Row): Promise<void> {
update(r.id, { status: "failed", error: "This run's details can't be read, so it was stopped.", completed_at: Date.now(), message: null });
return;
}
- const own = account ? accountRun(account, r.provider, "poll") : undefined;
- if (own && "error" in own) update(r.id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
+ const onPool = account ? poolOf(r) : false;
+ const own = account && !onPool ? accountRun(account, r.provider, "poll") : undefined;
+ if (onPool) await runOnPool(account!, () => pollOne(r));
+ else if (own && "error" in own) update(r.id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });
else if (own) await own.run(() => pollOne(r));
else await pollOne(r);
} catch (e) {
@@ -1744,7 +1793,7 @@ export function rowsToPoll(limit = 100): Row[] {
.prepare(
`SELECT g.* FROM generations g
JOIN (SELECT id, ROW_NUMBER() OVER (PARTITION BY json_extract(request_json, '$.account') ORDER BY created_at) AS turn
- FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL) t ON t.id = g.id
+ FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL AND stage IS NULL) t ON t.id = g.id
ORDER BY ${ACCOUNT_LAST.replace("request_json", "g.request_json")}, t.turn, g.created_at ASC LIMIT ?`,
)
.all(limit) as Row[];
@@ -1761,6 +1810,10 @@ async function tick(): Promise<void> {
const active = rowsToPoll();
for (const r of active) if (accountOf(r)) void pollGuarded(r);
await Promise.all([...active.filter((r) => !accountOf(r)).map(pollGuarded), pollTrainings().catch(() => {}), advanceDependents().catch(() => {})]);
+ // The optional services (billing.ts, moderation.ts): outputs waiting for their check, then reports for the billing
+ // service. Neither does anything while no service is set.
+ if (moderationConfigured()) await sweepOutputChecks();
+ void sweepBilling();
} finally {
state.busy = false;
}
@@ -1773,7 +1826,7 @@ async function fastTick(): Promise<void> {
try {
const rows = db()
.prepare(
- `SELECT g.*, r.started_at AS run_started_at FROM generations g LEFT JOIN generation_runs r ON r.id = g.id WHERE g.status = 'running' AND g.external_id IS NOT NULL AND g.progress IS NOT NULL ORDER BY ${ACCOUNT_LAST.replace("request_json", "g.request_json")}, g.created_at ASC LIMIT 50`,
+ `SELECT g.*, r.started_at AS run_started_at FROM generations g LEFT JOIN generation_runs r ON r.id = g.id WHERE g.status = 'running' AND g.external_id IS NOT NULL AND g.progress IS NOT NULL AND g.stage IS NULL ORDER BY ${ACCOUNT_LAST.replace("request_json", "g.request_json")}, g.created_at ASC LIMIT 50`,
)
.all() as (Row & { run_started_at: number | null })[];
const now = Date.now();
@@ -1833,8 +1886,11 @@ async function pollOne(r: Row): Promise<void> {
pollError = e;
}
// An account's job waits at most 30 minutes in its own ComfyUI's queue (or its provider's).
- const queueMs = account ? ACCOUNT_LIMITS.queueMs : QUEUE_TIMEOUT_MS;
- const where = r.provider === "comfyui" ? "your ComfyUI" : provider(r.provider).label;
+ const stored = JSON.parse(r.request_json) as GenerationRequest;
+ const onPool = !!account && stored.place === "pool";
+ // On this install's GPUs: the wait the billing service set for the run, else FUOBE_POOL_WAIT_MIN.
+ const queueMs = onPool ? poolWaitMs(stored.waitMs) : account ? ACCOUNT_LIMITS.queueMs : QUEUE_TIMEOUT_MS;
+ const where = onPool ? "this studio's GPUs" : r.provider === "comfyui" ? "your ComfyUI" : provider(r.provider).label;
if (!res || res.state === "queued" || res.state === "running") {
// A job on someone's own computer reached their ComfyUI later than it was handed over (it waited for their tab): its
// queue clock starts then.
@@ -1856,7 +1912,9 @@ async function pollOne(r: Row): Promise<void> {
? `Timed out after ${TIMEOUT_MS / 60_000} minutes`
: res?.state === "queued" && res.timeoutError
? res.timeoutError
- : account
+ : onPool
+ ? POOL_WAITED
+ : account
? `Timed out waiting ${queueMs / 60_000} minutes in ${where}'s queue`
: `Timed out waiting ${QUEUE_TIMEOUT_MS / 3_600_000} hours in the provider's queue`,
completed_at: now,
@@ -1941,6 +1999,11 @@ async function pollOne(r: Row): Promise<void> {
resumeFinish({ ...r, outputs_json: JSON.stringify(outputs) });
return;
}
+ // The moderation service asked to see this run's outputs first: they are held, and the row waits ("Checking").
+ if (stored.checkOutputs && moderationConfigured()) {
+ holdForCheck(r.id, outputs);
+ return;
+ }
update(r.id, {
status: "succeeded",
outputs_json: JSON.stringify(outputs),
diff --git a/src/server/hook-client.ts b/src/server/hook-client.ts
new file mode 100644
index 00000000..93cc5618
--- /dev/null
+++ b/src/server/hook-client.ts
@@ -0,0 +1,124 @@
+import "server-only";
+import http from "node:http";
+import https from "node:https";
+
+/**
+ * The transport for an install's optional external services (the billing hook, billing.ts; the moderation hook,
+ * moderation.ts): JSON over HTTPS, HTTP, or a Unix socket on this machine (`unix:/path/to/service.sock`).
+ *
+ * Every call sends `Authorization: Bearer <token>` and waits at most `timeoutMs`. An answer is read up to 1 MB. A
+ * transport error, a timeout, a non-JSON answer or an HTTP status outside 2xx is a HookDown error: its message is
+ * for the server's log only. A browser is told only that runs are paused (the service's address never reaches it).
+ */
+
+export class HookDown extends Error {
+ constructor(
+ readonly hook: string,
+ detail: string,
+ ) {
+ super(`${hook}: ${detail}`);
+ }
+}
+
+/** Where a service is: an http(s) base URL, or a Unix socket path. */
+export type HookTarget = { kind: "url"; base: URL } | { kind: "socket"; path: string };
+
+/** Parse a hook address. `unix:/path.sock` (or `unix:///path.sock`) is a socket; anything else must be an http(s) URL. */
+export function hookTarget(raw: string): HookTarget | null {
+ const v = raw.trim();
+ if (!v) return null;
+ if (v.startsWith("unix:")) {
+ const p = v.slice("unix:".length).replace(/^\/\/(?=\/)/, "");
+ return p ? { kind: "socket", path: p } : null;
+ }
+ try {
+ const base = new URL(v);
+ if (base.protocol !== "http:" && base.protocol !== "https:") return null;
+ return { kind: "url", base };
+ } catch {
+ return null;
+ }
+}
+
+export interface HookCall {
+ hook: string;
+ target: HookTarget;
+ token?: string;
+ method: "GET" | "POST";
+ /** The path under the service's base, with any query: "/v1/quote". */
+ path: string;
+ /** JSON (an object), or raw bytes with `contentType`. */
+ body?: unknown;
+ bytes?: Buffer;
+ contentType?: string;
+ headers?: Record<string, string>;
+ timeoutMs: number;
+}
+
+const MAX_ANSWER = 1024 * 1024;
+
+/** One call to a service. Resolves with the parsed JSON answer; rejects with HookDown. */
+export function hookCall<T>(c: HookCall): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const payload = c.bytes ?? (c.body === undefined ? undefined : Buffer.from(JSON.stringify(c.body)));
+ const headers: Record<string, string> = {
+ Accept: "application/json",
+ ...(c.token && { Authorization: `Bearer ${c.token}` }),
+ ...(payload && { "Content-Type": c.contentType ?? "application/json", "Content-Length": String(payload.length) }),
+ ...c.headers,
+ };
+ let opts: http.RequestOptions;
+ let lib: typeof http | typeof https = http;
+ if (c.target.kind === "socket") {
+ opts = { socketPath: c.target.path, path: c.path, method: c.method, headers: { Host: "localhost", ...headers } };
+ } else {
+ const base = c.target.base;
+ const prefix = base.pathname.replace(/\/+$/, "");
+ lib = base.protocol === "https:" ? https : http;
+ opts = { protocol: base.protocol, hostname: base.hostname, port: base.port || undefined, path: `${prefix}${c.path}`, method: c.method, headers };
+ }
+ let settled = false;
+ // The whole call, connection to last byte, within timeoutMs.
+ const timer = setTimeout(() => {
+ fail(`no answer in ${c.timeoutMs} ms from ${c.method} ${c.path}`);
+ req.destroy();
+ }, c.timeoutMs);
+ const fail = (why: string) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(new HookDown(c.hook, why));
+ };
+ const req = lib.request(opts, (res) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ res.on("data", (d: Buffer) => {
+ size += d.length;
+ if (size > MAX_ANSWER) {
+ req.destroy();
+ fail("the answer was over 1 MB");
+ return;
+ }
+ chunks.push(d);
+ });
+ res.on("end", () => {
+ if (settled) return;
+ const status = res.statusCode ?? 0;
+ if (status < 200 || status > 299) return fail(`HTTP ${status} from ${c.method} ${c.path}`);
+ try {
+ const text = Buffer.concat(chunks).toString("utf8");
+ const value = (text ? JSON.parse(text) : {}) as T;
+ settled = true;
+ clearTimeout(timer);
+ resolve(value);
+ } catch {
+ fail(`an answer that isn't JSON from ${c.method} ${c.path}`);
+ }
+ });
+ res.on("error", (e) => fail(e.message));
+ });
+ req.on("error", (e) => fail(e.message));
+ if (payload) req.write(payload);
+ req.end();
+ });
+}
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
new file mode 100644
index 00000000..bda22ca6
--- /dev/null
+++ b/src/server/hosted-run.ts
@@ -0,0 +1,204 @@
+import "server-only";
+import crypto from "node:crypto";
+import { nanoid } from "nanoid";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
+import { gpuState } from "./account-gpu";
+import { accountGpu, type Account } from "./auth";
+import {
+ accountFacts,
+ BILLING_HEADER,
+ BILLING_PAUSED,
+ billingConfigured,
+ forgetBalance,
+ policy as billingPolicy,
+ quote as billingQuote,
+ refusalStatus,
+ reserve,
+ type Policy,
+ type Quote,
+ type RefuseCode,
+} from "./billing";
+import { outputKind, previewGeneration } from "./generations";
+import { HOSTED_WORDS, inputCounts, poolAllows, poolReady, queueFacts, runFacts, runOnPool } from "./hosted";
+import { hostedRunsOn } from "./hosted-switch";
+import { checkRun, moderationConfigured } from "./moderation";
+import type { RunStamp } from "./run-stamp";
+import { readRef } from "./storage";
+import { runAsTenant } from "./tenant";
+
+/**
+ * The generations route's side of hosted runs (hosted.ts), the billing hook (billing.ts) and the moderation hook
+ * (moderation.ts). With nothing set (no FUOBE_HOSTED_RUNS, no service addresses) none of it changes a run.
+ */
+
+/** What the client asked for: its own GPU, or this install's (a preference the server checks). */
+export type PlaceWish = "own" | "pool" | undefined;
+
+/** The client's preference and the price it showed, read from the body beside the request (never part of it). */
+export function readWishes(body: unknown): { wish: PlaceWish; shown: { amount: number; priceVersion: string } | null } {
+ const b = (body ?? {}) as { place?: unknown; shown?: unknown };
+ const wish = b.place === "own" || b.place === "pool" ? b.place : undefined;
+ const s = b.shown as { amount?: unknown; priceVersion?: unknown } | null | undefined;
+ const shown =
+ s && typeof s === "object" && Number.isFinite(s.amount) && Number(s.amount) >= 0 && typeof s.priceVersion === "string" && s.priceVersion.length <= 200
+ ? { amount: Math.floor(Number(s.amount)), priceVersion: s.priceVersion }
+ : null;
+ return { wish, shown };
+}
+
+/** A refusal the route sends as it is. */
+export interface Refusal {
+ status: number;
+ body: Record<string, unknown> & { error: string };
+ headers: Record<string, string>;
+}
+
+const billingRefusal = (code: RefuseCode | "price-changed", text: string, extra: Record<string, unknown> = {}): Refusal => ({
+ status: refusalStatus(code),
+ body: { error: text, code, ...extra },
+ headers: { [BILLING_HEADER]: code },
+});
+
+type Planned = ReturnType<typeof previewGeneration>;
+
+/** The decision for an account's run: its own GPU or key as today, this install's GPUs, or a refusal. */
+export type PlaceDecision = { kind: "own" } | { kind: "pool"; planned: Planned; policy: Policy } | { kind: "refuse"; refusal: Refusal };
+
+/** Is the account's own GPU there to run now? */
+async function ownGpuOnline(accountId: string): Promise<boolean> {
+ const gpu = accountGpu(accountId);
+ if (!gpu) return false;
+ try {
+ return (await gpuState(accountId, gpu)).online;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Where an account's run goes (hosted.ts has the order). Only with hosted runs on; otherwise always "own" (today).
+ */
+export async function decidePlace(account: Account, req: GenerationRequest, wish: PlaceWish): Promise<PlaceDecision> {
+ if (!hostedRunsOn() || wish === "own" || !poolReady()) return { kind: "own" };
+ let planned: Planned;
+ try {
+ planned = runOnPool(account.id, () => previewGeneration(req));
+ } catch {
+ // A paid model, a model switched off, a request with something wrong: today's path says what.
+ return { kind: "own" };
+ }
+ if (planned.route.provider !== "comfyui") return { kind: "own" };
+ const hasGpu = !!accountGpu(account.id);
+ if (hasGpu && wish !== "pool" && (await ownGpuOnline(account.id))) return { kind: "own" };
+ const p = await billingPolicy(account.id);
+ if (!p) return { kind: "refuse", refusal: billingRefusal("paused", BILLING_PAUSED) };
+ if (!p.hosted) return { kind: "own" };
+ // From here on the run would be this install's: what it can't take there goes to the account's own GPU when it has one.
+ const notHere = (error: string): PlaceDecision => (hasGpu && wish !== "pool" ? { kind: "own" } : { kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });
+ if (outputKind(planned.op, planned.model) === "model3d") return hasGpu && wish !== "pool" ? { kind: "own" } : { kind: "refuse", refusal: { status: 403, body: { error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, headers: {} } };
+ if (!poolAllows(p, planned.model.id, req.presetId)) return notHere(HOSTED_WORDS.notOffered);
+ if (req.loras?.length) return notHere(HOSTED_WORDS.loras);
+ const inputs = inputCounts(req);
+ if ((inputs.image && !p.uploads.image) || (inputs.video && !p.uploads.video) || (inputs.audio && !p.uploads.audio)) return notHere(HOSTED_WORDS.inputs);
+ return { kind: "pool", planned, policy: p };
+}
+
+/** The input files of a request, for the moderation service: their kind and sha256 (pictures' previews: not sent yet). */
+async function inputFacts(accountId: string, req: GenerationRequest): Promise<{ n: number; kind: "image" | "video" | "audio"; sha256: string; preview: null }[]> {
+ const i = req.inputs ?? {};
+ const refs: [string | undefined, "image" | "video" | "audio"][] = [
+ ...(i.images ?? []).map((r) => [r, "image"] as [string, "image"]),
+ [i.endImage, "image"],
+ [i.mask, "image"],
+ [i.sketch, "image"],
+ [i.video, "video"],
+ ...(i.videos ?? []).map((r) => [r, "video"] as [string, "video"]),
+ [i.audio, "audio"],
+ [i.audio2, "audio"],
+ [i.voiceAudio, "audio"],
+ [i.voiceAudio2, "audio"],
+ ...(i.audios ?? []).map((r) => [r, "audio"] as [string, "audio"]),
+ ];
+ const out: { n: number; kind: "image" | "video" | "audio"; sha256: string; preview: null }[] = [];
+ for (const [ref, kind] of refs) {
+ if (!ref) continue;
+ try {
+ const f = await runAsTenant({ kind: "account", id: accountId }, () => readRef(ref));
+ out.push({ n: out.length, kind, sha256: crypto.createHash("sha256").update(f.data).digest("hex"), preview: null });
+ } catch {
+ // A file it can't read: the run says so when it is created.
+ }
+ }
+ return out;
+}
+
+/**
+ * The moderation service's check of an account's run (no service: allowed, nothing to stamp). A refusal costs nothing:
+ * it comes before any hold.
+ */
+export async function moderateRun(account: Account, req: GenerationRequest, planned: Planned | null, place: "pool" | "own"): Promise<{ ok: true; checkOutputs: boolean } | { ok: false; refusal: Refusal }> {
+ if (!moderationConfigured()) return { ok: true, checkOutputs: false };
+ const kind = planned ? outputKind(planned.op, planned.model) : "image";
+ const run = planned
+ ? { ...runFacts(req, planned, kind), place: place === "pool" ? ("pool" as const) : planned.route.provider === "comfyui" ? ("own-gpu" as const) : ("own-key" as const) }
+ : null;
+ const a = await checkRun({
+ requestId: nanoid(16),
+ account: { id: account.id },
+ run: run ?? { ...runFacts(req, { model: { id: req.modelId, kind: "image", engine: "open" }, op: req.op ?? "", jobs: 1, outputs: 1, providerId: "", costUsd: null, loras: { applied: [] } }, "image"), place: "own-gpu" },
+ prompt: req.prompt ?? "",
+ negative: req.negativePrompt ?? null,
+ inputs: await inputFacts(account.id, req),
+ consent: null,
+ });
+ if (a.allowed) return { ok: true, checkOutputs: a.checkOutputs !== false };
+ const status = a.code === "paused" ? 503 : 403;
+ return { ok: false, refusal: { status, body: { error: a.text, code: a.code }, headers: {} } };
+}
+
+/**
+ * Set the run's price aside (no billing service: nothing to set aside; the run is free). Returns the stamp the run's
+ * rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md).
+ */
+export async function reservePool(account: Account, req: GenerationRequest, planned: Planned, shown: { amount: number; priceVersion: string } | null, checkOutputs: boolean): Promise<{ ok: true; stamp: RunStamp } | { ok: false; refusal: Refusal }> {
+ const base: RunStamp = { place: "pool", ...(checkOutputs && { checkOutputs: true }) };
+ if (!billingConfigured()) return { ok: true, stamp: base };
+ const kind = outputKind(planned.op, planned.model);
+ const a = await reserve({
+ requestId: nanoid(16),
+ account: accountFacts(account),
+ run: runFacts(req, planned, kind),
+ queue: queueFacts(account.id),
+ shown: shown ?? { amount: 0, priceVersion: "" },
+ });
+ if (!a) return { ok: true, stamp: base };
+ if (!a.ok) {
+ return { ok: false, refusal: billingRefusal(a.code, a.text, { ...(a.quote && { quote: a.quote }), ...(a.action && { action: a.action }), ...(a.offer && { offer: a.offer }) }) };
+ }
+ forgetBalance(account.id);
+ return { ok: true, stamp: { ...base, hold: a.holdId, ...(a.text && { charge: a.text }), ...(a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }) } };
+}
+
+/**
+ * A price check on this install's GPUs (hosted runs on): the plan there and the billing service's quote (no service:
+ * free, and Run keeps its own words). Null when the run wouldn't go there (its own GPU, its own key, today's answer).
+ */
+export async function poolQuote(account: Account | null, req: GenerationRequest, wish: PlaceWish): Promise<{ planned: Planned; quote: Quote } | null> {
+ if (!hostedRunsOn() || wish === "own" || !poolReady()) return null;
+ let planned: Planned;
+ try {
+ planned = runOnPool(account?.id ?? null, () => previewGeneration(req));
+ } catch {
+ return null;
+ }
+ if (planned.route.provider !== "comfyui") return null;
+ if (account && wish !== "pool" && accountGpu(account.id) && (await ownGpuOnline(account.id))) return null;
+ if (account) {
+ const p = await billingPolicy(account.id);
+ if (p && (!p.hosted || !poolAllows(p, planned.model.id, req.presetId))) return null;
+ }
+ const kind = outputKind(planned.op, planned.model);
+ const q = await billingQuote(account ? accountFacts(account) : null, runFacts(req, planned, kind), queueFacts(account?.id ?? null));
+ return { planned, quote: q };
+}
diff --git a/src/server/hosted-switch.ts b/src/server/hosted-switch.ts
new file mode 100644
index 00000000..f5c70dfc
--- /dev/null
+++ b/src/server/hosted-switch.ts
@@ -0,0 +1,5 @@
+/**
+ * Hosted runs (FUOBE_HOSTED_RUNS=1, docs/public-signup.md "Hosted runs"): accounts with no GPU of their own may run on
+ * this install's GPUs. Off unless set. Read from the environment only, so the sign-in proxy can read it too.
+ */
+export const hostedRunsOn = (): boolean => process.env.FUOBE_HOSTED_RUNS === "1";
diff --git a/src/server/hosted.ts b/src/server/hosted.ts
new file mode 100644
index 00000000..043fe2fd
--- /dev/null
+++ b/src/server/hosted.ts
@@ -0,0 +1,165 @@
+import "server-only";
+import { getModel } from "@/lib/catalog";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { db } from "./db";
+import { hostedRunsOn } from "./hosted-switch";
+import { onInstallComfy } from "./providers/comfyui";
+import { getSetting, withCandidates } from "./settings";
+import { runAsTenant } from "./tenant";
+import type { Policy, QueueFacts, RunFacts } from "./billing";
+
+/**
+ * Hosted runs (FUOBE_HOSTED_RUNS=1; docs/public-signup.md "Hosted runs"): an account with no GPU of its own may run on
+ * this install's GPUs (the "pool" place). With the switch off, nothing here is used and accounts run as before: on
+ * their own GPU or their own key only.
+ *
+ * Where an account's run goes (the generations route):
+ * 1. the account asked for its own GPU, or its own GPU is online and it didn't ask for this install's → its own GPU;
+ * 2. a paid model and its own key → its own key;
+ * 3. hosted runs are on, the model runs on ComfyUI, and the policy allows it → this install's GPUs, with a billing hold
+ * when a billing service is set (billing.ts), free otherwise;
+ * 4. otherwise today's answer ("Connect your GPU", "Add your key").
+ *
+ * This install's GPUs are its own ComfyUI server (Settings → ComfyUI address). An install whose ComfyUI is on the
+ * owner's computer (a browser tab) doesn't offer hosted runs: that computer is the owner's alone.
+ */
+
+export const hostedRuns = hostedRunsOn;
+
+/** Hosted runs are on and this install has a ComfyUI server they can use. */
+export function poolReady(): boolean {
+ if (!hostedRunsOn()) return false;
+ if (getSetting("comfyWhere") === "computer") return false;
+ return !!getSetting("comfyUrl").trim();
+}
+
+/**
+ * Run `fn` as an account's run on this install's GPUs: as the account (its own files and runs only), on this install's
+ * ComfyUI server, the open engine, no demo outputs.
+ */
+export function runOnPool<T>(accountId: string | null, fn: () => T): T {
+ const inside = () => onInstallComfy(() => withCandidates({ engineMode: "open", demoMode: "off" }, fn));
+ return accountId ? runAsTenant({ kind: "account", id: accountId }, inside) : runAsTenant({ kind: "guest" }, inside);
+}
+
+/** Words for runs on this install's GPUs (generic: they fit any install). */
+export const HOSTED_WORDS = {
+ notOffered: "This one runs on your own GPU. Connect one in Settings, or pick another model.",
+ loras: "Extra LoRAs run on your own GPU. Connect one in Settings, or run without them.",
+ inputs: "This kind of file runs on your own GPU. Connect one in Settings, or use a picture.",
+ notHosted: "Runs on this studio's GPUs aren't open to this account. Connect your own GPU in Settings.",
+ waitedTooLong: "This studio's GPUs were busy, so it didn't run. Not charged.",
+};
+
+/** May this model (and app) run on this install's GPUs under this policy? */
+export function poolAllows(p: Pick<Policy, "pool">, modelId: string, presetId?: string | null): boolean {
+ const m = p.pool ?? {};
+ if (m.deny?.includes(modelId)) return false;
+ if (m.allow && !m.allow.includes(modelId)) return false;
+ if (presetId) {
+ if (m.apps?.deny?.includes(presetId)) return false;
+ if (m.apps?.allow && !m.apps.allow.includes(presetId)) return false;
+ }
+ return true;
+}
+
+/** The file kinds a request uses (for the policy's uploads rule and the billing facts). */
+export function inputCounts(req: GenerationRequest): { image: number; video: number; audio: number } {
+ const i = req.inputs ?? {};
+ const image = (i.images?.length ?? 0) + (i.endImage ? 1 : 0) + (i.mask ? 1 : 0) + (i.sketch ? 1 : 0);
+ const video = (i.video ? 1 : 0) + (i.videos?.length ?? 0);
+ const audio = [i.audio, i.audio2, i.voiceAudio, i.voiceAudio2].filter(Boolean).length + (i.audios?.length ?? 0);
+ return { image, video, audio };
+}
+
+/** The pool's one lane while this install's GPUs are its own ComfyUI server. */
+export const POOL_LANE = "comfyui";
+
+/** The pool's rows that wait or run (the route's place-in-line facts). */
+const POOL_ROWS = "json_extract(g.request_json, '$.place') = 'pool' AND g.status IN ('queued', 'running')";
+
+/** How long a run on this install's GPUs may wait in line: the billing service's limit, else FUOBE_POOL_WAIT_MIN (30). */
+export function poolWaitMs(stamped?: number): number {
+ if (stamped && stamped > 0) return stamped;
+ const m = Number(process.env.FUOBE_POOL_WAIT_MIN);
+ return (Number.isFinite(m) && m > 0 ? m : 30) * 60_000;
+}
+
+/** A typical run's time on this install's GPUs (the median of the last 20 that finished), or null before any. */
+function typicalRunMs(): number | null {
+ const rows = db()
+ .prepare(
+ `SELECT g.completed_at - r.started_at AS ms FROM generations g JOIN generation_runs r ON r.id = g.id
+ WHERE json_extract(g.request_json, '$.place') = 'pool' AND g.status = 'succeeded' AND r.started_at IS NOT NULL AND g.completed_at > r.started_at
+ ORDER BY g.completed_at DESC LIMIT 20`,
+ )
+ .all() as { ms: number }[];
+ if (!rows.length) return null;
+ const sorted = rows.map((r) => r.ms).sort((a, b) => a - b);
+ return sorted[Math.floor(sorted.length / 2)];
+}
+
+/** Rows not started yet (no provider start): they wait in line. */
+const WAITING = "NOT EXISTS (SELECT 1 FROM generation_runs r WHERE r.id = g.id AND r.started_at IS NOT NULL)";
+
+/** The line on this install's GPUs right now, for a quote or a reserve (QueueFacts). */
+export function queueFacts(accountId: string | null): QueueFacts {
+ const d = db();
+ const ahead = (d.prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING}`).get() as { n: number }).n;
+ const typical = typicalRunMs();
+ const mine = accountId
+ ? (d
+ .prepare(
+ `SELECT SUM(CASE WHEN ${WAITING} THEN 1 ELSE 0 END) AS waiting, SUM(CASE WHEN ${WAITING} THEN 0 ELSE 1 END) AS running
+ FROM generations g WHERE ${POOL_ROWS} AND json_extract(g.request_json, '$.account') = ?`,
+ )
+ .get(accountId) as { waiting: number | null; running: number | null })
+ : { waiting: 0, running: 0 };
+ return {
+ lane: POOL_LANE,
+ ahead,
+ etaS: typical === null ? null : Math.round(((ahead + 1) * typical) / 1000),
+ workersOnline: poolReady() ? 1 : 0,
+ nextOpenAt: null,
+ mine: { waiting: mine.waiting ?? 0, running: mine.running ?? 0 },
+ };
+}
+
+/** A waiting row's place in line on this install's GPUs (1: next), and the wait, about. Null when it isn't waiting there. */
+export function placeInLine(generationId: string): { place: number; etaSeconds: number | null } | null {
+ const d = db();
+ const row = d.prepare(`SELECT g.created_at FROM generations g WHERE g.id = ? AND ${POOL_ROWS} AND ${WAITING}`).get(generationId) as { created_at: number } | undefined;
+ if (!row) return null;
+ const before = (d.prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING} AND (g.created_at < ? OR (g.created_at = ? AND g.id < ?))`).get(row.created_at, row.created_at, generationId) as { n: number }).n;
+ const typical = typicalRunMs();
+ return { place: before + 1, etaSeconds: typical === null ? null : Math.round(((before + 1) * typical) / 1000) };
+}
+
+/** The facts the billing service prices a run by (from a planned request: previewGeneration's answer). */
+export function runFacts(
+ req: GenerationRequest,
+ p: { model: { id: string; kind: string; engine: "open" | "cloud" }; op: string; jobs: number; outputs: number; providerId: string; costUsd: number | null; loras: { applied: unknown[] } },
+ kind: RunFacts["kind"],
+): RunFacts {
+ const model = getModel(p.model.id);
+ return {
+ place: "pool",
+ model: p.model.id,
+ op: p.op ?? null,
+ app: req.presetId ?? null,
+ preset: req.presetId ?? null,
+ studio: req.feature,
+ kind,
+ engine: p.model.engine,
+ provider: p.providerId,
+ jobs: p.jobs,
+ outputsPerJob: p.jobs > 0 ? Math.max(1, Math.round(p.outputs / p.jobs)) : 1,
+ megapixels: null,
+ seconds: req.params?.duration ?? (kind === "video" ? (model?.defaults?.duration ?? null) : null),
+ fps: req.params?.fps ?? null,
+ loras: p.loras.applied.length,
+ inputs: inputCounts(req),
+ lane: POOL_LANE,
+ providerUsd: p.costUsd,
+ };
+}
diff --git a/src/server/moderation.ts b/src/server/moderation.ts
new file mode 100644
index 00000000..52c459de
--- /dev/null
+++ b/src/server/moderation.ts
@@ -0,0 +1,141 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { db } from "./db";
+import { HookDown, hookCall, hookTarget, type HookTarget } from "./hook-client";
+import type { RunFacts } from "./billing";
+
+/**
+ * The moderation hook (docs/moderation-hook.md): an install can connect an external moderation service at
+ * FUOBE_MODERATION_URL. With none set, nothing is checked (the studio as it was) and "Report this result" goes to a
+ * list the owner reads (reports_inbox).
+ *
+ * - POST /v1/check-run: before a run is created (and before any billing hold). `{ allowed: false }` stops it: nothing
+ * is made and nothing is charged. `checkOutputs` says whether its outputs go to check-output before they show; a
+ * missing field means yes. A service may skip output checks for a run by answering `checkOutputs: false`.
+ * - POST /v1/check-output: one output's bytes; "show", "hide" or "wait".
+ * - POST /v1/report: a person's report of a result or a shared link.
+ */
+
+export type ReportCategory = "intimate" | "minor" | "violence" | "impersonation" | "copyright" | "other";
+export const REPORT_CATEGORIES: ReportCategory[] = ["intimate", "minor", "violence", "impersonation", "copyright", "other"];
+
+export type CheckRunAnswer = { allowed: true; checkOutputs?: boolean } | { allowed: false; code: "blocked" | "consent" | "paused"; text: string };
+export type CheckOutputAnswer = { decision: "show" } | { decision: "hide"; text: string } | { decision: "wait"; retryAfterS: number };
+
+/** What a person sees when the moderation service doesn't answer a run check. */
+export const CHECKS_PAUSED = "Checks are paused for a moment. Try again soon.";
+
+export const MODERATION_TIMEOUTS = { checkRun: 10_000, checkOutput: 30_000, report: 5_000 };
+
+const HOOK = "moderation service";
+
+declare global {
+ var __fuobeModerationBadUrl: boolean | undefined;
+}
+
+function target(): HookTarget | null {
+ const raw = process.env.FUOBE_MODERATION_URL ?? "";
+ if (!raw.trim()) return null;
+ const t = hookTarget(raw);
+ if (!t && !globalThis.__fuobeModerationBadUrl) {
+ globalThis.__fuobeModerationBadUrl = true;
+ console.warn("[fuobe] FUOBE_MODERATION_URL is not an http(s) or unix: address; the moderation hook is off");
+ }
+ return t;
+}
+
+/** Is a moderation service set? */
+export const moderationConfigured = (): boolean => target() !== null;
+
+const token = () => process.env.FUOBE_MODERATION_TOKEN || undefined;
+
+/** How many hours an output may wait for its check before the row fails (and, with a hold, is refunded). */
+export const moderationMaxWaitMs = (): number => {
+ const h = Number(process.env.FUOBE_MODERATION_MAX_WAIT_H);
+ return (Number.isFinite(h) && h > 0 ? h : 24) * 3_600_000;
+};
+
+export interface RunCheckInput {
+ requestId: string;
+ account: { id: string } | null;
+ run: RunFacts;
+ prompt: string;
+ negative: string | null;
+ inputs: { n: number; kind: "image" | "video" | "audio"; sha256: string; preview: string | null }[];
+ consent: boolean | null;
+}
+
+/** Check a run before it is created. No service: allowed, outputs not checked. No answer: refused as paused. */
+export async function checkRun(input: RunCheckInput): Promise<CheckRunAnswer> {
+ const t = target();
+ if (!t) return { allowed: true, checkOutputs: false };
+ try {
+ const a = await hookCall<CheckRunAnswer>({ hook: HOOK, target: t, token: token(), method: "POST", path: "/v1/check-run", body: input, timeoutMs: MODERATION_TIMEOUTS.checkRun });
+ if (a.allowed === true) return { allowed: true, checkOutputs: a.checkOutputs !== false };
+ if (a.allowed === false) return { allowed: false, code: a.code === "consent" ? "consent" : "blocked", text: typeof a.text === "string" && a.text ? a.text : "This request can't be made here." };
+ throw new HookDown(HOOK, "a check-run answer without `allowed`");
+ } catch (e) {
+ console.warn(`[fuobe] moderation check-run: ${(e as Error).message}`);
+ return { allowed: false, code: "paused", text: CHECKS_PAUSED };
+ }
+}
+
+/** Check one output. No service: show. No answer: wait (asked again later). */
+export async function checkOutput(file: { bytes: Buffer; contentType: string; generationId: string; account: string | null; assetId: string; kind: "image" | "video" | "audio"; sha256: string }): Promise<CheckOutputAnswer> {
+ const t = target();
+ if (!t) return { decision: "show" };
+ try {
+ const a = await hookCall<CheckOutputAnswer>({
+ hook: HOOK,
+ target: t,
+ token: token(),
+ method: "POST",
+ path: "/v1/check-output",
+ bytes: file.bytes,
+ contentType: file.contentType,
+ headers: { "X-Fuobe-Generation": file.generationId, "X-Fuobe-Account": file.account ?? "", "X-Fuobe-Asset": file.assetId, "X-Fuobe-Kind": file.kind, "X-Fuobe-Sha256": file.sha256 },
+ timeoutMs: MODERATION_TIMEOUTS.checkOutput,
+ });
+ if (a.decision === "show") return a;
+ if (a.decision === "hide") return { decision: "hide", text: typeof a.text === "string" ? a.text : "" };
+ return { decision: "wait", retryAfterS: Math.max(10, Math.min(3600, Number((a as { retryAfterS?: number }).retryAfterS) || 60)) };
+ } catch (e) {
+ console.warn(`[fuobe] moderation check-output: ${(e as Error).message}`);
+ return { decision: "wait", retryAfterS: 60 };
+ }
+}
+
+export interface ReportInput {
+ target: { generationId?: string; assetId?: string; shareId?: string };
+ category: ReportCategory;
+ text: string;
+ reporter: { account: string | null; email: string | null };
+}
+
+/**
+ * A person's report. To the service when one is set (falling back to the inbox when it doesn't answer, so no report is
+ * lost); else to the owner's inbox.
+ */
+export async function report(r: ReportInput): Promise<{ ok: true; hidden: boolean; text: string }> {
+ const t = target();
+ if (t) {
+ try {
+ const a = await hookCall<{ ok: true; hidden?: boolean; text?: string }>({ hook: HOOK, target: t, token: token(), method: "POST", path: "/v1/report", body: r, timeoutMs: MODERATION_TIMEOUTS.report });
+ return { ok: true, hidden: !!a.hidden, text: typeof a.text === "string" && a.text ? a.text : REPORT_THANKS };
+ } catch (e) {
+ console.warn(`[fuobe] moderation report: ${(e as Error).message}; kept for the owner`);
+ }
+ }
+ db()
+ .prepare("INSERT INTO reports_inbox (id, target_json, category, text, reporter, created_at) VALUES (?, ?, ?, ?, ?, ?)")
+ .run(nanoid(12), JSON.stringify(r.target), r.category, r.text.slice(0, 2000), JSON.stringify(r.reporter), Date.now());
+ return { ok: true, hidden: false, text: REPORT_THANKS };
+}
+
+export const REPORT_THANKS = "Thanks. The studio's owner will look at it.";
+
+/** The owner's list of reports (no moderation service set), newest first. */
+export function listReports(limit = 100): { id: string; target: ReportInput["target"]; category: string; text: string | null; reporter: ReportInput["reporter"]; createdAt: number; doneAt: number | null }[] {
+ const rows = db().prepare("SELECT * FROM reports_inbox ORDER BY created_at DESC LIMIT ?").all(limit) as { id: string; target_json: string; category: string; text: string | null; reporter: string | null; created_at: number; done_at: number | null }[];
+ return rows.map((r) => ({ id: r.id, target: JSON.parse(r.target_json), category: r.category, text: r.text, reporter: r.reporter ? JSON.parse(r.reporter) : { account: null, email: null }, createdAt: r.created_at, doneAt: r.done_at }));
+}
diff --git a/src/server/output-checks.ts b/src/server/output-checks.ts
new file mode 100644
index 00000000..0383a2c3
--- /dev/null
+++ b/src/server/output-checks.ts
@@ -0,0 +1,148 @@
+import "server-only";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import type { OutputFile } from "@/lib/catalog/types";
+import { db } from "./db";
+import { checkOutput, moderationMaxWaitMs } from "./moderation";
+import { absolutePath, deleteAsset, getAsset } from "./storage";
+
+/**
+ * Output checks (moderation.ts): a run whose check-run answer asked to see its outputs (`checkOutputs`) doesn't
+ * succeed when its files are saved. Its files are held (never served to the account), its row stays running with the
+ * stage "checking", and each file goes to check-output:
+ *
+ * - every file "show": the files are served and the row succeeds;
+ * - any file "hide": that file is removed, and the row fails with the service's words (a hold is refunded as "hidden");
+ * - "wait", or no answer: asked again later; past FUOBE_MODERATION_MAX_WAIT_H (24 h) the row fails and its files are
+ * removed (a hold is refunded as "unchecked").
+ */
+
+export const HIDDEN_WORDS = "This result was removed by the studio's checks. Not charged.";
+export const UNCHECKED_WORDS = "This result couldn't be checked in time, so it was removed. Not charged.";
+export const CHECKING_WORDS = "Checking";
+
+/** Hold a finished run's files for their check (the runner calls it instead of marking the row succeeded). */
+export function holdForCheck(generationId: string, outputs: OutputFile[], now = Date.now()): void {
+ const d = db();
+ const ids = outputs.map((o) => o.assetId).filter((x): x is string => !!x);
+ d.transaction(() => {
+ for (const id of ids) {
+ d.prepare("UPDATE assets SET held = 1 WHERE id = ?").run(id);
+ d.prepare("INSERT OR IGNORE INTO output_checks (asset_id, generation_id, state, asked_at, tries, next_at) VALUES (?, ?, 'waiting', ?, 0, ?)").run(id, generationId, now, now);
+ }
+ d.prepare("UPDATE generations SET status = 'running', stage = 'checking', progress = 0.99, message = ?, outputs_json = ?, updated_at = ? WHERE id = ?").run(CHECKING_WORDS, JSON.stringify(outputs), now, generationId);
+ // A run with no saved file (words only) has nothing to check: it succeeds as it is.
+ if (!ids.length) d.prepare("UPDATE generations SET status = 'succeeded', stage = NULL, progress = 1, message = NULL, completed_at = ?, updated_at = ? WHERE id = ?").run(now, now, generationId);
+ })();
+}
+
+type Kind = "image" | "video" | "audio";
+const kindOf = (contentType: string): Kind => (contentType.startsWith("video/") ? "video" : contentType.startsWith("audio/") ? "audio" : "image");
+
+interface CheckRow {
+ asset_id: string;
+ generation_id: string;
+ asked_at: number;
+ tries: number;
+}
+
+/** Decide every run whose files all have an answer (or whose wait ran out). */
+function settleRuns(now: number): void {
+ const d = db();
+ const runs = d
+ .prepare(
+ `SELECT g.id, g.outputs_json, g.status FROM generations g
+ WHERE g.stage = 'checking' AND (
+ NOT EXISTS (SELECT 1 FROM output_checks c WHERE c.generation_id = g.id AND c.state = 'waiting')
+ OR EXISTS (SELECT 1 FROM output_checks c WHERE c.generation_id = g.id AND c.state = 'hidden'))`,
+ )
+ .all() as { id: string; outputs_json: string; status: string }[];
+ for (const r of runs) {
+ const states = d.prepare("SELECT asset_id, state, text FROM output_checks WHERE generation_id = ?").all(r.id) as { asset_id: string; state: string; text: string | null }[];
+ const hidden = states.filter((s) => s.state === "hidden");
+ const unchecked = states.some((s) => s.state === "unchecked");
+ if (r.status !== "running") {
+ // Stopped meanwhile: its held files stay held (never served); the row says what it says.
+ d.prepare("UPDATE generations SET stage = NULL WHERE id = ?").run(r.id);
+ continue;
+ }
+ if (hidden.length || unchecked) {
+ // Hidden or never checked: every held file of the run goes, and the row fails.
+ for (const s of states) if (s.state !== "hidden") removeHeld(s.asset_id);
+ const words = hidden.length ? hidden.find((h) => h.text)?.text || HIDDEN_WORDS : UNCHECKED_WORDS;
+ d.prepare("UPDATE output_checks SET state = CASE WHEN state = 'waiting' THEN 'unchecked' ELSE state END, decided_at = COALESCE(decided_at, ?) WHERE generation_id = ?").run(now, r.id);
+ d.prepare("UPDATE generations SET status = 'failed', stage = NULL, error = ?, message = NULL, outputs_json = '[]', completed_at = ?, updated_at = ? WHERE id = ?").run(words, now, now, r.id);
+ continue;
+ }
+ d.transaction(() => {
+ for (const s of states) d.prepare("UPDATE assets SET held = 0 WHERE id = ?").run(s.asset_id);
+ d.prepare("UPDATE generations SET status = 'succeeded', stage = NULL, progress = 1, message = NULL, completed_at = ?, updated_at = ? WHERE id = ?").run(now, now, r.id);
+ })();
+ }
+}
+
+/** A held file goes for good. */
+function removeHeld(assetId: string): void {
+ try {
+ deleteAsset(assetId);
+ } catch (e) {
+ console.warn(`[fuobe] couldn't remove a held file ${assetId}: ${(e as Error).message}`);
+ }
+}
+
+declare global {
+ var __fuobeOutputChecks: boolean | undefined;
+}
+
+/** One sweep (the runner's tick): ask about each file that is due, then decide the runs that can be decided. */
+export async function sweepOutputChecks(now = Date.now(), limit = 20): Promise<void> {
+ if (globalThis.__fuobeOutputChecks) return;
+ globalThis.__fuobeOutputChecks = true;
+ try {
+ const d = db();
+ const maxWait = moderationMaxWaitMs();
+ // Past the wait: never checked.
+ d.prepare("UPDATE output_checks SET state = 'unchecked', decided_at = ? WHERE state = 'waiting' AND asked_at <= ?").run(now, now - maxWait);
+ const due = d.prepare("SELECT asset_id, generation_id, asked_at, tries FROM output_checks WHERE state = 'waiting' AND next_at <= ? ORDER BY next_at LIMIT ?").all(now, limit) as CheckRow[];
+ for (const c of due) {
+ const asset = getAsset(c.asset_id);
+ if (!asset) {
+ d.prepare("UPDATE output_checks SET state = 'unchecked', decided_at = ? WHERE asset_id = ?").run(now, c.asset_id);
+ continue;
+ }
+ let bytes: Buffer;
+ try {
+ bytes = fs.readFileSync(absolutePath(asset.relPath));
+ } catch {
+ d.prepare("UPDATE output_checks SET state = 'unchecked', decided_at = ? WHERE asset_id = ?").run(now, c.asset_id);
+ continue;
+ }
+ const account = (d.prepare("SELECT json_extract(request_json, '$.account') AS a FROM generations WHERE id = ?").get(c.generation_id) as { a: string | null } | undefined)?.a ?? null;
+ const answer = await checkOutput({
+ bytes,
+ contentType: asset.contentType,
+ generationId: c.generation_id,
+ account,
+ assetId: c.asset_id,
+ kind: kindOf(asset.contentType),
+ sha256: crypto.createHash("sha256").update(bytes).digest("hex"),
+ });
+ if (answer.decision === "show") d.prepare("UPDATE output_checks SET state = 'shown', decided_at = ?, tries = tries + 1 WHERE asset_id = ?").run(now, c.asset_id);
+ else if (answer.decision === "hide") {
+ d.prepare("UPDATE output_checks SET state = 'hidden', decided_at = ?, tries = tries + 1, text = ? WHERE asset_id = ?").run(now, answer.text || null, c.asset_id);
+ removeHeld(c.asset_id);
+ } else d.prepare("UPDATE output_checks SET tries = tries + 1, next_at = ? WHERE asset_id = ?").run(now + answer.retryAfterS * 1000, c.asset_id);
+ }
+ settleRuns(now);
+ } catch (e) {
+ console.warn(`[fuobe] output checks: ${(e as Error).message}`);
+ } finally {
+ globalThis.__fuobeOutputChecks = false;
+ }
+}
+
+/** How many files wait for their check, and since when (the admin queue view). */
+export function checksDepth(): { waiting: number; oldestAt: number | null } {
+ const r = db().prepare("SELECT COUNT(*) AS n, MIN(asked_at) AS oldest FROM output_checks WHERE state = 'waiting'").get() as { n: number; oldest: number | null };
+ return { waiting: r.n, oldestAt: r.oldest };
+}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 2f782cc7..044d4f4c 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -168,6 +168,12 @@ export function computerScope(): Principal | undefined {
/** A run the owner sent to the studio's own ComfyUI before Settings moved ComfyUI to the owner's computer. */
const serverScope = new AsyncLocalStorage<true>();
+/**
+ * Run `fn` on this install's own ComfyUI server (Settings → ComfyUI address), never an account's own GPU and never a
+ * computer's tab: an account's run on this install's GPUs (hosted runs, src/server/hosted.ts).
+ */
+export const onInstallComfy = <T,>(fn: () => T): T => outsideOwnGpu(() => serverScope.run(true, fn));
+
/**
* Whose computer a run sent there belongs to, whatever ComfyUI's place is now: the account's (as its tenant), or the
* owner's.
diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.ts
new file mode 100644
index 00000000..930a24a5
--- /dev/null
+++ b/src/server/run-stamp.ts
@@ -0,0 +1,58 @@
+import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
+import type { GenerationRequest } from "@/lib/catalog/types";
+
+/**
+ * What the server decided about one run before it was created, stamped on every row the run makes (its jobs, and every
+ * step its chains queue), the way `account` is stamped (generations.ts stampTenant). A client never sets these: the
+ * request schema drops them, and stampTenant replaces whatever a stored request carried with the current stamp.
+ *
+ * - `place: "pool"`: the run goes to this install's GPUs (hosted runs, hosted.ts), not the account's own.
+ * - `hold`: the billing service's hold for the run (billing.ts reserve); every row reports to it once (billing-outbox.ts).
+ * - `charge`: the words the billing service gave for the charge ("7 units"), shown on the result.
+ * - `checkOutputs`: the moderation service asked to see this run's outputs before they show (moderation.ts).
+ */
+export interface RunStamp {
+ place?: "pool";
+ hold?: string;
+ charge?: string;
+ checkOutputs?: boolean;
+ /** How long it may wait in line on this install's GPUs (ms), from the billing service. */
+ waitMs?: number;
+}
+
+declare global {
+ var __fuobeRunStamp: AsyncLocalStorage<RunStamp> | undefined;
+}
+
+const store = () => (globalThis.__fuobeRunStamp ??= new AsyncLocalStorage<RunStamp>());
+
+/** Run `fn` with this run's stamp: every row createGenerations makes inside carries it. */
+export const withRunStamp = <T,>(stamp: RunStamp, fn: () => T): T => store().run(stamp, fn);
+
+/** The stamp in scope (none: a run with nothing decided, as every run was before these hooks). */
+export const runStamp = (): RunStamp | undefined => store().getStore();
+
+/** The server-only fields of a request. */
+export const STAMP_FIELDS = ["place", "hold", "charge", "checkOutputs", "waitMs"] as const;
+
+/** A request with the current stamp's fields, and none of a stored request's own. */
+export function stamped(req: GenerationRequest): GenerationRequest {
+ const out = { ...req };
+ for (const k of STAMP_FIELDS) delete out[k];
+ const s = runStamp();
+ if (!s) return out;
+ return {
+ ...out,
+ ...(s.place && { place: s.place }),
+ ...(s.hold && { hold: s.hold }),
+ ...(s.charge && { charge: s.charge }),
+ ...(s.checkOutputs && { checkOutputs: true }),
+ ...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),
+ };
+}
+
+/** A stored request's stamp, to run a later step of it (advanceDependents, polls) as it was decided. */
+export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[number]>): RunStamp {
+ return { ...(req.place === "pool" && { place: "pool" as const }), ...(req.hold && { hold: req.hold }), ...(req.charge && { charge: req.charge }), ...(req.checkOutputs && { checkOutputs: true }), ...(req.waitMs && { waitMs: req.waitMs }) };
+}
diff --git a/src/server/takedown.ts b/src/server/takedown.ts
new file mode 100644
index 00000000..96a32ea7
--- /dev/null
+++ b/src/server/takedown.ts
@@ -0,0 +1,77 @@
+import "server-only";
+import fs from "node:fs";
+import path from "node:path";
+import type { OutputFile } from "@/lib/catalog/types";
+import { DATA_DIR, db } from "./db";
+import { absolutePath, deleteAsset, getAsset } from "./storage";
+
+/**
+ * Take a result down (the owner, POST /api/admin/outputs/{hide,unhide,remove}): by asset id or by run. Hidden files are
+ * held (account-library.ts): served to no account and by no link, kept for the owner. Removed files are deleted, or,
+ * with `evidence`, moved to a locked folder only the server's user can read (`<data>/evidence`, mode 0600).
+ */
+
+export interface Targets {
+ assetIds?: string[];
+ generationIds?: string[];
+}
+
+const ID = /^[\w-]{1,64}$/;
+
+/** The asset ids a request names (its own, and every saved output of the runs it names). */
+export function targetAssets(t: Targets): string[] {
+ const ids = new Set((t.assetIds ?? []).filter((x) => ID.test(x)));
+ for (const g of (t.generationIds ?? []).filter((x) => ID.test(x))) {
+ const rows = db().prepare("SELECT id FROM assets WHERE generation_id = ?").all(g) as { id: string }[];
+ for (const r of rows) ids.add(r.id);
+ }
+ return [...ids].slice(0, 500);
+}
+
+export function hideOutputs(t: Targets): number {
+ let n = 0;
+ for (const id of targetAssets(t)) n += db().prepare("UPDATE assets SET held = 1 WHERE id = ? AND held = 0").run(id).changes;
+ return n;
+}
+
+export function unhideOutputs(t: Targets): number {
+ let n = 0;
+ // A file still waiting for its check stays held.
+ for (const id of targetAssets(t)) n += db().prepare("UPDATE assets SET held = 0 WHERE id = ? AND held = 1 AND NOT EXISTS (SELECT 1 FROM output_checks WHERE asset_id = ? AND state = 'waiting')").run(id, id).changes;
+ return n;
+}
+
+/** The locked folder for evidence. */
+export const evidenceDir = () => path.join(DATA_DIR, "evidence");
+
+export function removeOutputs(t: Targets, evidence: boolean): number {
+ let n = 0;
+ for (const id of targetAssets(t)) {
+ const a = getAsset(id);
+ if (!a) continue;
+ if (evidence) {
+ const dir = evidenceDir();
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
+ const dest = path.join(dir, `${id}${path.extname(a.relPath)}`);
+ try {
+ fs.renameSync(absolutePath(a.relPath), dest);
+ } catch {
+ fs.copyFileSync(absolutePath(a.relPath), dest);
+ }
+ try {
+ fs.chmodSync(dest, 0o600);
+ } catch {}
+ }
+ deleteAsset(id);
+ // The run's result no longer lists it.
+ if (a.generationId) {
+ const r = db().prepare("SELECT outputs_json FROM generations WHERE id = ?").get(a.generationId) as { outputs_json: string } | undefined;
+ if (r) {
+ const left = (JSON.parse(r.outputs_json) as OutputFile[]).filter((o) => o.assetId !== id);
+ db().prepare("UPDATE generations SET outputs_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(left), Date.now(), a.generationId);
+ }
+ }
+ n++;
+ }
+ return n;
+}
diff --git a/tests/billing-hook.test.ts b/tests/billing-hook.test.ts
new file mode 100644
index 00000000..5855ebfc
--- /dev/null
+++ b/tests/billing-hook.test.ts
@@ -0,0 +1,351 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { listenInRange, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+
+// The billing hook (docs/billing-hook.md) and hosted runs, against a stand-in billing service and a stand-in ComfyUI
+// as this install's GPUs. Numbers are arbitrary ("7 units").
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-billing-hook-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// This install's ComfyUI: a stand-in on a free port from 3360 to 3369.
+const probe = http.createServer();
+const comfyPort = await listenInRange(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0 }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const { visitorStatus } = await import("@/server/account-gpu");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const billing = await import("@/server/billing");
+const outbox = await import("@/server/billing-outbox");
+const { hookTarget } = await import("@/server/hook-client");
+
+let fake: FakeBilling;
+let a = "";
+let cookie = "";
+let withGpu = "";
+let gpuCookie = "";
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ globalThis.__fuobeTestGpuPort = comfy.port;
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;
+ withGpu = auth.createAccount("[email protected]", "long enough").id;
+ auth.setAccountGpu(withGpu, { mode: "link", url: comfy.url } as never);
+ gpuCookie = `${auth.SESSION_COOKIE}=${auth.createSession(withGpu).value}`;
+});
+afterAll(async () => {
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ delete process.env.FUOBE_HOSTED_RUNS;
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ await fake.close();
+ await comfy.close();
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const on = () => {
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+};
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ fake.calls.length = 0;
+ fake.down = false;
+ fake.refuse = null;
+ fake.price = { amount: 7, version: "v7" };
+ on();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+const post = (body: unknown, c = cookie, query = "") => {
+ const text = JSON.stringify(body);
+ return generationsRoute.POST(
+ new Request(`http://localhost:3000/api/generations${query}`, { method: "POST", headers: { cookie: c, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }),
+ );
+};
+const run = (extra: Record<string, unknown> = {}) => ({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk", ...extra });
+const holdOf = (id: string) => (db().prepare("SELECT json_extract(request_json, '$.hold') AS h FROM generations WHERE id = ?").get(id) as { h: string | null }).h;
+const statusOf = (id: string) => (db().prepare("SELECT status, error FROM generations WHERE id = ?").get(id) as { status: string; error: string | null });
+
+async function until(fn: () => boolean, ms = 20_000): Promise<void> {
+ const end = Date.now() + ms;
+ while (!fn()) {
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+describe("the billing hook with no service set", () => {
+ it("makes no call and prices a run as before; an account with no GPU is refused as today", async () => {
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_HOSTED_RUNS;
+ const p = await post(run(), cookie, "?preview=1");
+ expect(p.status).toBe(200);
+ const body = (await p.json()) as Record<string, unknown>;
+ expect(body.quote).toBeUndefined();
+ expect(body.place).toBeUndefined();
+ const r = await post(run());
+ expect(r.status).toBe(403);
+ expect(((await r.json()) as { code: string }).code).toBe("connect-gpu");
+ expect(fake.calls).toEqual([]);
+ expect(await billing.policy(a)).toBe(billing.OPEN_POLICY);
+ expect(await billing.reserve({ requestId: "r", account: billing.accountFacts({ id: a, email: "[email protected]", createdAt: 1 }), run: {} as never, queue: null, shown: { amount: 0, priceVersion: "" } })).toBeNull();
+ });
+
+ it("with hosted runs on and no billing service, a run on this install's GPUs is free, with no hold", async () => {
+ delete process.env.FUOBE_BILLING_URL;
+ const r = await post(run());
+ expect(r.status).toBe(201);
+ const { items } = (await r.json()) as { items: { id: string; place?: string }[] };
+ expect(items[0].place).toBe("pool");
+ expect(holdOf(items[0].id)).toBeNull();
+ await until(() => statusOf(items[0].id).status !== "queued" && statusOf(items[0].id).status !== "running");
+ expect(statusOf(items[0].id).status).toBe("succeeded");
+ expect(fake.calls).toEqual([]);
+ });
+});
+
+describe("the billing hook with a service", () => {
+ it("shows the quote's words before Run", async () => {
+ const p = await post(run(), cookie, "?preview=1");
+ const body = (await p.json()) as { place: string; quote: { text: string; amount: number; priceVersion: string } };
+ expect(body.place).toBe("pool");
+ expect(body.quote).toMatchObject({ text: "7 units", amount: 7, priceVersion: "v7" });
+ expect(fake.calls_of("/v1/quote")).toHaveLength(1);
+ // A guest sees the price too.
+ const g = await generationsRoute.POST(new Request("http://localhost:3000/api/generations?preview=1", { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json" }, body: JSON.stringify(run()) }));
+ expect(((await g.json()) as { quote: { text: string } }).quote.text).toBe("7 units");
+ });
+
+ it("reserves before the rows are made, and every row of the run carries the hold; the browser never sees it", async () => {
+ const r = await post({ ...run({ params: { numOutputs: 2 } }), shown: { amount: 7, priceVersion: "v7" } });
+ expect(r.status).toBe(201);
+ const { items } = (await r.json()) as { items: { id: string; request: Record<string, unknown> }[] };
+ expect(items.length).toBe(2);
+ const reserve = fake.calls_of("/v1/reserve");
+ expect(reserve).toHaveLength(1);
+ const hold = [...fake.holds.keys()].at(-1)!;
+ for (const g of items) {
+ expect(holdOf(g.id)).toBe(hold);
+ expect(g.request.hold).toBeUndefined();
+ }
+ const sent = reserve[0].body as { run: { place: string; model: string; jobs: number }; shown: { amount: number }; account: { id: string } };
+ expect(sent.run).toMatchObject({ place: "pool", model: "oss-z-image-turbo" });
+ expect(sent.shown.amount).toBe(7);
+ expect(sent.account.id).toBe(a);
+ // Both rows settle, each once, with rows = 2.
+ await until(() => items.every((g) => fake.reportCount(hold, g.id) === 1));
+ const settles = fake.calls_of("/v1/settle").filter((c) => (c.body as { holdId: string }).holdId === hold);
+ expect(settles.map((c) => (c.body as { rows: number }).rows)).toEqual([2, 2]);
+ expect(items.every((g) => statusOf(g.id).status === "succeeded")).toBe(true);
+ });
+
+ it("never takes the hold, the account or the place's stamp from the client", async () => {
+ const other = auth.createAccount("[email protected]", "long enough").id;
+ const r = await post({ ...run(), hold: "h_evil", account: other, charge: "free", checkOutputs: false, waitMs: 1, shown: { amount: 7, priceVersion: "v7" } });
+ expect(r.status).toBe(201);
+ const { items } = (await r.json()) as { items: { id: string }[] };
+ const stored = JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(items[0].id) as { request_json: string }).request_json) as Record<string, unknown>;
+ expect(stored.hold).not.toBe("h_evil");
+ expect(fake.holds.has(stored.hold as string)).toBe(true);
+ expect(stored.account).toBe(a);
+ expect(stored.charge).toBe("7 units");
+ expect(stored.waitMs).toBe(700_000);
+ });
+
+ it("a higher price at reserve: 409 with the new price, and nothing is made", async () => {
+ fake.price = { amount: 9, version: "v9" };
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const r = await post({ ...run(), shown: { amount: 7, priceVersion: "v7" } });
+ expect(r.status).toBe(409);
+ expect(r.headers.get("x-fuobe-billing")).toBe("price-changed");
+ const body = (await r.json()) as { error: string; code: string; quote: { text: string } };
+ expect(body.code).toBe("price-changed");
+ expect(body.quote.text).toBe("9 units");
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(before);
+ });
+
+ it("maps each refusal to its status and header", async () => {
+ const cases: [string, number][] = [
+ ["top-up", 402],
+ ["limit", 429],
+ ["busy", 503],
+ ["not-offered", 403],
+ ["closed", 403],
+ ];
+ for (const [code, status] of cases) {
+ resetRates();
+ fake.refuse = { code, text: `refused: ${code}` };
+ const r = await post({ ...run(), shown: { amount: 7, priceVersion: "v7" } });
+ expect(r.status).toBe(status);
+ expect(r.headers.get("x-fuobe-billing")).toBe(code);
+ expect(((await r.json()) as { error: string }).error).toBe(`refused: ${code}`);
+ }
+ });
+
+ it("service down: runs on this install's GPUs are paused with plain words, and a run on the account's own GPU still goes", async () => {
+ fake.down = "error";
+ const r = await post({ ...run(), shown: { amount: 7, priceVersion: "v7" } });
+ expect(r.status).toBe(503);
+ const body = (await r.json()) as { error: string };
+ expect(body.error).toBe(billing.BILLING_PAUSED);
+ expect(JSON.stringify(body)).not.toContain(String(fake.port));
+ const p = await post(run(), cookie, "?preview=1");
+ expect(((await p.json()) as { quote: { code: string } }).quote.code).toBe("paused");
+ // Its own GPU online: its own GPU is the place, and the billing service is never asked.
+ fake.calls.length = 0;
+ const own = await post(run(), gpuCookie);
+ expect(own.status).toBe(201);
+ const { items } = (await own.json()) as { items: { id: string; place?: string }[] };
+ expect(items[0].place).toBeUndefined();
+ expect(holdOf(items[0].id)).toBeNull();
+ expect(fake.calls.filter((c) => c.path.startsWith("/v1/reserve") || c.path.startsWith("/v1/quote"))).toEqual([]);
+ });
+
+ it("an account with its own GPU online can still ask for this install's GPUs", async () => {
+ const r = await post({ ...run(), place: "pool", shown: { amount: 7, priceVersion: "v7" } }, gpuCookie);
+ expect(r.status).toBe(201);
+ const { items } = (await r.json()) as { items: { id: string; place?: string }[] };
+ expect(items[0].place).toBe("pool");
+ expect(holdOf(items[0].id)).not.toBeNull();
+ });
+
+ it("the status shows the balance and that hosted runs are open", async () => {
+ const body = await visitorStatus(auth.accountById(a)!);
+ expect(body.viewer.hosted).toBe(true);
+ expect(body.viewer.balance?.chip).toBe("70 units");
+ });
+});
+
+describe("the outbox", () => {
+ const insertRow = (status: string, hold: string, opts: { error?: string } = {}) => {
+ const id = `t${Math.random().toString(36).slice(2, 12)}`;
+ const now = Date.now();
+ db()
+ .prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, error, favorite, created_at, updated_at, completed_at) VALUES (?, 'image', 'oss-z-image-turbo', 'open', 'comfyui', 't2i', 'image', ?, ?, '[]', ?, 0, ?, ?, ?)",
+ )
+ .run(id, status, JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", account: a, place: "pool", hold }), opts.error ?? null, now, now, status === "running" ? null : now);
+ return id;
+ };
+ const newHold = () => {
+ const id = `h_t${Math.random().toString(36).slice(2, 8)}`;
+ fake.holds.set(id, { amount: 7, requestId: id, reports: new Map(), released: false });
+ return id;
+ };
+
+ it("a restart between a row's success and its report: exactly one report per row", async () => {
+ const hold = newHold();
+ const g = insertRow("succeeded", hold);
+ // Nothing was written before the "crash"; the sweep finds it from what is stored, however often it runs.
+ outbox.queueReports();
+ outbox.queueReports();
+ await outbox.drainOutbox();
+ await outbox.drainOutbox();
+ await outbox.sweepBilling();
+ expect(fake.reportCount(hold, g)).toBe(1);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE key = ?").get(g) as { n: number }).n).toBe(1);
+ });
+
+ it("a failed row is refunded within one sweep", async () => {
+ const hold = newHold();
+ const g = insertRow("failed", hold, { error: "The GPU stopped" });
+ await outbox.sweepBilling();
+ expect(fake.holds.get(hold)!.reports.get(g)).toBe("failed");
+ const refund = fake.calls_of("/v1/refund").find((c) => (c.body as { generationId: string }).generationId === g)!.body as { rows: number; reason: string };
+ expect(refund).toMatchObject({ rows: 1, reason: "The GPU stopped" });
+ });
+
+ it("waits until every row of a hold is finished, then reports each with the row count", async () => {
+ const hold = newHold();
+ const one = insertRow("succeeded", hold);
+ const two = insertRow("running", hold);
+ outbox.queueReports();
+ expect((db().prepare("SELECT COUNT(*) AS n FROM billing_outbox WHERE hold_id = ?").get(hold) as { n: number }).n).toBe(0);
+ db().prepare("UPDATE generations SET status = 'canceled', completed_at = ? WHERE id = ?").run(Date.now(), two);
+ await outbox.sweepBilling();
+ expect(fake.holds.get(hold)!.reports.get(one)).toBe("succeeded");
+ expect(fake.holds.get(hold)!.reports.get(two)).toBe("canceled");
+ });
+
+ it("keeps reports while the service is down and sends them when it is back", async () => {
+ const hold = newHold();
+ const g = insertRow("failed", hold);
+ fake.down = "error";
+ await outbox.sweepBilling();
+ const row = db().prepare("SELECT tries, next_at, done_at FROM billing_outbox WHERE key = ?").get(g) as { tries: number; next_at: number; done_at: number | null };
+ expect(row.tries).toBe(1);
+ expect(row.done_at).toBeNull();
+ expect(row.next_at).toBeGreaterThan(Date.now() + 5_000);
+ fake.down = false;
+ // Not before its time, then sent.
+ expect(await outbox.drainOutbox()).toBe(0);
+ expect(await outbox.drainOutbox(Date.now() + 11_000)).toBeGreaterThanOrEqual(1);
+ expect(fake.reportCount(hold, g)).toBe(1);
+ });
+
+ it("a release goes out once", async () => {
+ const hold = newHold();
+ outbox.queueRelease(hold);
+ outbox.queueRelease(hold);
+ await until(() => fake.holds.get(hold)!.released);
+ expect(fake.calls_of("/v1/release").filter((c) => (c.body as { holdId: string }).holdId === hold)).toHaveLength(1);
+ });
+});
+
+describe("the transport", () => {
+ it("reads https, http and unix: addresses, and nothing else", () => {
+ expect(hookTarget("https://billing.example.com/base")).toMatchObject({ kind: "url" });
+ expect(hookTarget("unix:/path/to/billing.sock")).toEqual({ kind: "socket", path: "/path/to/billing.sock" });
+ expect(hookTarget("unix:///path/to/billing.sock")).toEqual({ kind: "socket", path: "/path/to/billing.sock" });
+ expect(hookTarget("ftp://billing.example.com")).toBeNull();
+ expect(hookTarget("")).toBeNull();
+ });
+
+ it("talks to a service on a local socket", async () => {
+ const sock = process.platform === "win32" ? `\\\\.\\pipe\\fuobe-billing-test-${process.pid}` : path.join(dir, "billing.sock");
+ const server = http.createServer((req, res) => {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ ...JSON.parse(JSON.stringify(fake.policy)), links: [{ label: "Help", url: "https://example.com/help" }], seen: req.headers.authorization }));
+ });
+ await new Promise<void>((r) => server.listen(sock, r));
+ try {
+ process.env.FUOBE_BILLING_URL = `unix:${sock}`;
+ billing.resetBillingCache();
+ const p = (await billing.policy(a)) as unknown as { links: unknown[]; seen: string };
+ expect(p.links).toHaveLength(1);
+ expect(p.seen).toBe("Bearer test-billing-token");
+ } finally {
+ await new Promise<void>((r) => server.close(() => r()));
+ }
+ });
+
+ it("gives up on a service that doesn't answer within the call's time", async () => {
+ fake.down = "hang";
+ const t = Date.now();
+ const q = await billing.quote(null, {} as never, null);
+ expect(q.code).toBe("paused");
+ expect(Date.now() - t).toBeLessThan(billing.BILLING_TIMEOUTS.quote + 1500);
+ });
+});
diff --git a/tests/helpers/fake-billing.ts b/tests/helpers/fake-billing.ts
new file mode 100644
index 00000000..05967904
--- /dev/null
+++ b/tests/helpers/fake-billing.ts
@@ -0,0 +1,200 @@
+/**
+ * Stand-ins for an install's optional external services in tests: a billing service (docs/billing-hook.md) and a
+ * moderation service (docs/moderation-hook.md). Each records every call and answers with arbitrary numbers ("7 units").
+ * They listen on 127.0.0.1, on the first free port from 3360 to 3369.
+ */
+import http from "node:http";
+
+export interface Recorded {
+ method: string;
+ path: string;
+ body: unknown;
+ headers: http.IncomingHttpHeaders;
+ bytes?: Buffer;
+}
+
+/** Listen on the first free port from 3360 to 3369. */
+export async function listenInRange(server: http.Server): Promise<number> {
+ for (let port = 3360; port <= 3369; port++) {
+ const ok = await new Promise<boolean>((resolve) => {
+ const onError = () => {
+ server.off("listening", onListening);
+ resolve(false);
+ };
+ const onListening = () => {
+ server.off("error", onError);
+ resolve(true);
+ };
+ server.once("error", onError);
+ server.once("listening", onListening);
+ server.listen(port, "127.0.0.1");
+ });
+ if (ok) return port;
+ }
+ throw new Error("No free port from 3360 to 3369");
+}
+
+function readBody(req: http.IncomingMessage): Promise<Buffer> {
+ return new Promise((resolve) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (c: Buffer) => chunks.push(c));
+ req.on("end", () => resolve(Buffer.concat(chunks)));
+ });
+}
+
+export interface FakeBilling {
+ url: string;
+ port: number;
+ calls: Recorded[];
+ /** What the service charges a run, and the price version. */
+ price: { amount: number; version: string };
+ /** Holds, by id: amount, and the reports each got (by generation id). */
+ holds: Map<string, { amount: number; requestId: string; reports: Map<string, string>; released: boolean }>;
+ /** Answer every call with HTTP 503 (the service "down"), or never answer. */
+ down: false | "error" | "hang";
+ /** Refuse reserves with this code (and words). */
+ refuse: null | { code: string; text: string };
+ /** The policy every account gets. */
+ policy: Record<string, unknown>;
+ /** How many times each (hold, generation) pair was reported. */
+ reportCount: (holdId: string, generationId: string) => number;
+ calls_of: (path: string) => Recorded[];
+ close: () => Promise<void>;
+}
+
+export const FAKE_POLICY = {
+ hosted: true,
+ pool: {},
+ uploads: { image: true, video: false, audio: false },
+ limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, keepDays: 7, spaceBytes: 7_000_000 },
+ ttlS: 0,
+};
+
+export async function startFakeBilling(): Promise<FakeBilling> {
+ let holdN = 0;
+ const reportCounts = new Map<string, number>();
+ const f: Omit<FakeBilling, "url" | "port" | "close"> = {
+ calls: [],
+ price: { amount: 7, version: "v7" },
+ holds: new Map(),
+ down: false,
+ refuse: null,
+ policy: { ...FAKE_POLICY },
+ reportCount: (h, g) => reportCounts.get(`${h} ${g}`) ?? 0,
+ calls_of: (p) => f.calls.filter((c) => c.path.split("?")[0] === p),
+ };
+ const quote = () => ({ allowed: true, amount: f.price.amount, priceVersion: f.price.version, text: `${f.price.amount} units`, sub: "from your test balance", etaS: 7 });
+ const server = http.createServer(async (req, res) => {
+ const raw = await readBody(req);
+ let body: unknown = null;
+ try {
+ body = raw.length ? JSON.parse(raw.toString("utf8")) : null;
+ } catch {}
+ const path = req.url ?? "/";
+ f.calls.push({ method: req.method ?? "GET", path, body, headers: req.headers });
+ if (f.down === "hang") return;
+ const json = (status: number, v: unknown) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(v));
+ };
+ if (f.down === "error") return json(503, { error: "down" });
+ if (req.headers.authorization !== "Bearer test-billing-token") return json(401, { error: "who are you" });
+ const p = path.split("?")[0];
+ const b = (body ?? {}) as Record<string, unknown>;
+ if (p === "/v1/health") return json(200, { ok: true, version: "test" });
+ if (p === "/v1/policy") return json(200, f.policy);
+ if (p === "/v1/quote") return json(200, quote());
+ if (p === "/v1/reserve") {
+ const requestId = String(b.requestId);
+ const again = [...f.holds.entries()].find(([, h]) => h.requestId === requestId);
+ if (again) return json(200, { ok: true, holdId: again[0], amount: again[1].amount, boostMs: 7000, maxWaitMs: 700_000, text: `${again[1].amount} units` });
+ if (f.refuse) return json(200, { ok: false, code: f.refuse.code, text: f.refuse.text });
+ const shown = b.shown as { amount: number; priceVersion: string };
+ if (f.price.amount > shown.amount) return json(200, { ok: false, code: "price-changed", text: `The price is now ${f.price.amount} units.`, quote: quote() });
+ const id = `h_${++holdN}`;
+ f.holds.set(id, { amount: f.price.amount, requestId, reports: new Map(), released: false });
+ return json(200, { ok: true, holdId: id, amount: f.price.amount, boostMs: 7000, maxWaitMs: 700_000, text: `${f.price.amount} units` });
+ }
+ if (p === "/v1/settle" || p === "/v1/refund") {
+ const h = f.holds.get(String(b.holdId));
+ if (!h) return json(404, { error: "no such hold" });
+ const key = `${b.holdId} ${b.generationId}`;
+ reportCounts.set(key, (reportCounts.get(key) ?? 0) + 1);
+ h.reports.set(String(b.generationId), String(b.status));
+ return json(200, p === "/v1/settle" ? { ok: true, charged: h.amount } : { ok: true, text: "Not charged" });
+ }
+ if (p === "/v1/release") {
+ const h = f.holds.get(String(b.holdId));
+ if (h) h.released = true;
+ return json(200, { ok: true });
+ }
+ if (p === "/v1/balance") return json(200, { amount: 70, chip: "70 units", text: "70 units left", refillAt: null, detail: [{ label: "Today", text: "70 units" }] });
+ if (p === "/v1/account-event") return json(200, { ok: true });
+ if (p === "/v1/interest") return json(200, { ok: true, text: "Thanks, noted." });
+ json(404, { error: "not found" });
+ });
+ const port = await listenInRange(server);
+ return Object.assign(f, {
+ port,
+ url: `http://127.0.0.1:${port}`,
+ close: () =>
+ new Promise<void>((done) => {
+ server.closeAllConnections?.();
+ server.close(() => done());
+ }),
+ }) as FakeBilling;
+}
+
+export interface FakeModeration {
+ url: string;
+ port: number;
+ calls: Recorded[];
+ /** The check-run answer. */
+ run: Record<string, unknown>;
+ /** The check-output answer. */
+ output: Record<string, unknown>;
+ down: boolean;
+ calls_of: (path: string) => Recorded[];
+ close: () => Promise<void>;
+}
+
+export async function startFakeModeration(): Promise<FakeModeration> {
+ const f: Omit<FakeModeration, "url" | "port" | "close"> = {
+ calls: [],
+ run: { allowed: true, checkOutputs: false },
+ output: { decision: "show" },
+ down: false,
+ calls_of: (p) => f.calls.filter((c) => c.path.split("?")[0] === p),
+ };
+ const server = http.createServer(async (req, res) => {
+ const raw = await readBody(req);
+ const path = req.url ?? "/";
+ let body: unknown = null;
+ if ((req.headers["content-type"] ?? "").startsWith("application/json")) {
+ try {
+ body = JSON.parse(raw.toString("utf8"));
+ } catch {}
+ }
+ f.calls.push({ method: req.method ?? "GET", path, body, headers: req.headers, bytes: raw });
+ const json = (status: number, v: unknown) => {
+ res.writeHead(status, { "content-type": "application/json" });
+ res.end(JSON.stringify(v));
+ };
+ if (f.down) return json(503, { error: "down" });
+ const p = path.split("?")[0];
+ if (p === "/v1/check-run") return json(200, f.run);
+ if (p === "/v1/check-output") return json(200, f.output);
+ if (p === "/v1/report") return json(200, { ok: true, hidden: false, text: "Report received." });
+ json(404, { error: "not found" });
+ });
+ const port = await listenInRange(server);
+ return Object.assign(f, {
+ port,
+ url: `http://127.0.0.1:${port}`,
+ close: () =>
+ new Promise<void>((done) => {
+ server.closeAllConnections?.();
+ server.close(() => done());
+ }),
+ }) as FakeModeration;
+}