Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Security: price checks read only the asker's own file headers, and are rate-limited

Adarshdce0019facfd
diff --git a/docs/public-signup.md b/docs/public-signup.md
index bf298137..bc94fa4e 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -30,7 +30,9 @@ it (files, uploads, projects, settings values, tokens) answer 401 "Sign up to se
Every change a guest sends (generate, upload, save a setting, create a project…) answers 401. The
studio shows a "Create a free account to run this" card with **Sign up** and **Log in**. Price
checks (the estimate routes, and `?preview=1` on the run routes that support it) stay open, so the
-studios can show prices.
+studios can show prices. A guest may send 120 price checks a minute (per visitor behind a trusted
+reverse proxy; see below), and so may each account. A price check reads only the header of a file
+it names, and only of the asker's own files: a guest owns none.
## Accounts
diff --git a/src/app/api/ads/creatives/[id]/save/route.ts b/src/app/api/ads/creatives/[id]/save/route.ts
index 11de5945..5ef853a0 100644
--- a/src/app/api/ads/creatives/[id]/save/route.ts
+++ b/src/app/api/ads/creatives/[id]/save/route.ts
@@ -2,7 +2,7 @@ import { z } from "zod";
import { saveComposite } from "@/server/ads";
import { failure, readBody } from "@/server/marketing";
-const Body = z.object({ url: z.string().startsWith("/api/files/"), ratio: z.enum(["1:1", "4:5", "9:16"]) });
+const Body = z.object({ url: z.string().startsWith("/api/files/").max(500), ratio: z.enum(["1:1", "4:5", "9:16"]) });
/** Record a creative composited in the browser (an uploaded PNG) in the Library. */
export async function POST(request: Request, ctx: RouteContext<"/api/ads/creatives/[id]/save">) {
diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.ts
index 60ffef47..cc2fd354 100644
--- a/src/app/api/dub/route.ts
+++ b/src/app/api/dub/route.ts
@@ -7,7 +7,7 @@ import { priceAs } from "@/server/visitor";
const Body = z.object({
engine: z.enum(["cloud", "open"]),
mode: z.enum(["oneshot", "steps"]),
- video: z.string().startsWith("/api/files/"),
+ video: z.string().startsWith("/api/files/").max(500),
title: z.string().max(200).optional(),
source: z.string().max(12).optional(),
targets: z.array(z.string().min(2).max(12)).min(1).max(8),
diff --git a/src/app/api/generations/local/route.ts b/src/app/api/generations/local/route.ts
index 4387fa3e..2a8e4ea1 100644
--- a/src/app/api/generations/local/route.ts
+++ b/src/app/api/generations/local/route.ts
@@ -8,7 +8,7 @@ const Body = z.object({
prompt: z.string().max(2000),
inputs: z.object({ images: z.array(z.string()).max(1).optional(), video: z.string().optional() }),
params: z.object({ extra: z.record(z.string(), z.unknown()).optional() }).optional(),
- output: z.object({ url: z.string().startsWith("/api/files/"), kind: z.enum(["image", "video"]), contentType: z.string().optional() }),
+ output: z.object({ url: z.string().startsWith("/api/files/").max(500), kind: z.enum(["image", "video"]), contentType: z.string().optional() }),
});
/** Record a result rendered in the browser (e.g. a colour grade) so it shows up in the library. */
diff --git a/src/app/api/marketing/runs/[id]/compose/route.ts b/src/app/api/marketing/runs/[id]/compose/route.ts
index 252a7c5c..392caa2d 100644
--- a/src/app/api/marketing/runs/[id]/compose/route.ts
+++ b/src/app/api/marketing/runs/[id]/compose/route.ts
@@ -2,7 +2,7 @@ import { z } from "zod";
import { failure, readBody, saveRunComposite } from "@/server/marketing";
const Body = z.object({
- url: z.string().startsWith("/api/files/"),
+ url: z.string().startsWith("/api/files/").max(500),
ratio: z.string().regex(/^\d+:\d+$/),
text: z.string().max(1000).default(""),
/** The words as set (kept on the run, so "Edit text" opens with them). */
diff --git a/src/app/api/palettes/route.ts b/src/app/api/palettes/route.ts
index 627ec9a0..958becca 100644
--- a/src/app/api/palettes/route.ts
+++ b/src/app/api/palettes/route.ts
@@ -8,7 +8,7 @@ const Body = z.object({
colors: z.array(z.string().max(9)).min(1).max(12),
background: z.string().max(9).nullable().optional(),
source: z.enum(["manual", "images"]).default("manual"),
- thumb: z.string().startsWith("/api/files/").nullable().optional(),
+ thumb: z.string().startsWith("/api/files/").max(500).nullable().optional(),
});
/** Your colour signatures and the 50 built-in palettes, plus which models take a palette natively. */
diff --git a/src/app/api/photodump/fashion/route.ts b/src/app/api/photodump/fashion/route.ts
index ebeebd7d..431712dd 100644
--- a/src/app/api/photodump/fashion/route.ts
+++ b/src/app/api/photodump/fashion/route.ts
@@ -1,7 +1,7 @@
import { z } from "zod";
import { createFashion, previewFashion, type FashionRun } from "@/server/photodump";
-const File = z.string().startsWith("/api/files/");
+const File = z.string().startsWith("/api/files/").max(500);
const Engine = z.enum(["cloud", "open"]);
const Body = z.discriminatedUnion("step", [
diff --git a/src/app/api/photodump/route.ts b/src/app/api/photodump/route.ts
index 5ca3d5a9..6b2e2c88 100644
--- a/src/app/api/photodump/route.ts
+++ b/src/app/api/photodump/route.ts
@@ -7,7 +7,7 @@ const Body = z
packId: z.string().min(1).max(80),
engine: z.enum(["cloud", "open"]),
elementId: z.string().max(40).optional(),
- selfie: z.string().startsWith("/api/files/").optional(),
+ selfie: z.string().startsWith("/api/files/").max(500).optional(),
aspectRatio: z.string().max(10).optional(),
modelId: z.string().max(80).optional(),
})
diff --git a/src/lib/media-probe.ts b/src/lib/media-probe.ts
index ae542713..0d94f5bc 100644
--- a/src/lib/media-probe.ts
+++ b/src/lib/media-probe.ts
@@ -24,13 +24,18 @@ export interface MediaInfo {
const fourcc = (b: Uint8Array, o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]);
-export function probeMedia(data: Uint8Array): MediaInfo | null {
+/**
+ * `size`: the whole file's length when `data` is only its first bytes (a WAV's sound data and a constant-rate MP3's
+ * length are read from it). Leave it out when `data` is the whole file.
+ */
+export function probeMedia(data: Uint8Array, size = data.length): MediaInfo | null {
try {
if (data.length < 12) return null;
- if (fourcc(data, 0) === "RIFF" && fourcc(data, 8) === "WAVE") return probeWav(data);
+ const total = Math.max(size, data.length);
+ if (fourcc(data, 0) === "RIFF" && fourcc(data, 8) === "WAVE") return probeWav(data, total);
if (fourcc(data, 0) === "fLaC") return probeFlac(data);
if (fourcc(data, 4) === "ftyp" || ["moov", "mdat", "free", "wide", "skip"].includes(fourcc(data, 4))) return probeIsoBmff(data);
- return probeMp3(data);
+ return probeMp3(data, total);
} catch {
return null;
}
@@ -80,6 +85,43 @@ export async function probeMediaRanges(read: ReadRange, size: number): Promise<M
}
}
+/** Reads the bytes [start, end) of a file at once (a file on this computer's disk). */
+export type ReadRangeSync = (start: number, end: number) => Uint8Array;
+
+/**
+ * {@link probeMediaRanges} for a file read at once (on the server's own disk), never all of it: an MP4 / MOV's moov box
+ * (none over `maxMoov`), or the first `headBytes` of anything else, which is enough for a WAV, FLAC or MP3 with the
+ * file's size.
+ */
+export function probeMediaRangesSync(read: ReadRangeSync, size: number, opts: { headBytes?: number; maxMoov?: number } = {}): MediaInfo | null {
+ const maxMoov = opts.maxMoov ?? MAX_MOOV_BYTES;
+ try {
+ const head = read(0, Math.min(size, opts.headBytes ?? HEAD_BYTES));
+ if (head.length < 12) return null;
+ if (!ISO_TOP.includes(fourcc(head, 4))) return probeMedia(head, size);
+ for (let o = 0; o + 8 <= size; ) {
+ const h = o + 16 <= head.length ? head.subarray(o, o + 16) : read(o, Math.min(size, o + 16));
+ if (h.length < 8) return null;
+ const d = new DataView(h.buffer, h.byteOffset, h.byteLength);
+ let len = d.getUint32(0);
+ if (len === 1) {
+ if (h.length < 16) return null;
+ len = Number(d.getBigUint64(8));
+ } else if (len === 0) len = size - o;
+ if (len < 8) return null;
+ if (fourcc(h, 4) === "moov") {
+ if (len > maxMoov) return null;
+ const end = Math.min(size, o + len);
+ return probeMedia(end <= head.length ? head.subarray(o, end) : read(o, end));
+ }
+ o += len;
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
/** Probe a dropped file (a File or Blob) by reading only the parts that say what it is. */
export function probeBlob(blob: Blob): Promise<MediaInfo | null> {
return probeMediaRanges(async (start, end) => new Uint8Array(await blob.slice(start, end).arrayBuffer()), blob.size);
@@ -198,7 +240,7 @@ function probeIsoBmff(data: Uint8Array): MediaInfo | null {
// ---------------------------------------------------------------------------
// WAV, FLAC, MP3
-function probeWav(data: Uint8Array): MediaInfo | null {
+function probeWav(data: Uint8Array, total = data.length): MediaInfo | null {
const d = new DataView(data.buffer, data.byteOffset, data.byteLength);
let byteRate = 0;
for (let o = 12; o + 8 <= data.length; ) {
@@ -206,7 +248,7 @@ function probeWav(data: Uint8Array): MediaInfo | null {
let size = d.getUint32(o + 4, true);
if (id === "fmt ") byteRate = d.getUint32(o + 16, true);
if (id === "data") {
- if (!size || size === 0xffffffff || o + 8 + size > data.length) size = data.length - o - 8; // streamed header
+ if (!size || size === 0xffffffff || o + 8 + size > total) size = total - o - 8; // streamed header
return byteRate ? { container: "wav", duration: size / byteRate, hasVideo: false, hasAudio: true } : null;
}
o += 8 + size + (size % 2);
@@ -229,7 +271,7 @@ const MP3_BITRATES: Record<string, number[]> = {
};
const MP3_RATES: Record<number, number[]> = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] };
-function probeMp3(data: Uint8Array): MediaInfo | null {
+function probeMp3(data: Uint8Array, total = data.length): MediaInfo | null {
let o = 0;
if (fourcc(data, 0).startsWith("ID3")) o = 10 + ((data[6] & 0x7f) << 21) + ((data[7] & 0x7f) << 14) + ((data[8] & 0x7f) << 7) + (data[9] & 0x7f);
// The first frame header within a few KB of the tag.
@@ -251,5 +293,5 @@ function probeMp3(data: Uint8Array): MediaInfo | null {
return { container: "mp3", duration: (frames * samplesPerFrame) / rate, hasVideo: false, hasAudio: true };
}
if (!bitrate) return null;
- return { container: "mp3", duration: ((data.length - o) * 8) / bitrate, hasVideo: false, hasAudio: true };
+ return { container: "mp3", duration: ((total - o) * 8) / bitrate, hasVideo: false, hasAudio: true };
}
diff --git a/src/proxy.ts b/src/proxy.ts
index fd064cd4..4fedea36 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -22,6 +22,7 @@ import {
} from "@/lib/guest-access";
import { authEnabled, crossSite, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
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";
@@ -66,6 +67,16 @@ function viewerOf(request: NextRequest, open: boolean): Viewer | null {
const guestHeaders = { [GUEST_HEADER]: "1", "Cache-Control": "no-store" };
+/** Price checks a guest (per address) or an account may send a minute: free, but each one plans a run. A page sends far fewer. */
+const PRICE_CHECKS_PER_MINUTE = 120;
+
+/** A guest's or an account's price check, within its budget (the owner's are never counted). */
+function priceCheck(request: NextRequest, who: string): NextResponse {
+ const r = hit(`price:${who}`, PRICE_CHECKS_PER_MINUTE, 60_000);
+ if (r.ok) return pass(request);
+ return NextResponse.json({ error: "Too many price checks. Try again in a minute." }, { status: 429, headers: { "Retry-After": String(r.retryAfterS), "Cache-Control": "no-store" } });
+}
+
/**
* A guest (public sign-up on, signed out): every page and the catalog reads, the owner's lists
* empty, the rest of the library 401, and every change 401 (the client offers to sign up).
@@ -73,7 +84,7 @@ const guestHeaders = { [GUEST_HEADER]: "1", "Cache-Control": "no-store" };
function guest(request: NextRequest): NextResponse {
const { pathname, search } = request.nextUrl;
if (request.method === "GET" || request.method === "HEAD") return readAsGuest(request, false);
- if (isPriceCheck(request.method, pathname, search)) return pass(request);
+ if (isPriceCheck(request.method, pathname, search)) return priceCheck(request, `guest:${LoginGuard.clientKey(request.headers)}`);
return NextResponse.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: guestHeaders });
}
@@ -116,6 +127,7 @@ function account(request: NextRequest, who: Account): NextResponse {
const file = request.method === "GET" || request.method === "HEAD" ? /^\/api\/files\/(.+)$/.exec(pathname)?.[1] : undefined;
if (file !== undefined) return fileAccount(safeDecode(file)) === who.id ? pass(request) : notYours();
if (request.method === "GET" || request.method === "HEAD") return accountOwnRead(pathname) ? pass(request) : readAsGuest(request, true);
+ if (isPriceCheck(request.method, pathname, search)) return priceCheck(request, `account:${who.id}`);
if (accountMayChange(request.method, pathname, search)) return pass(request);
if (isLibraryChange(request.method, pathname)) return NextResponse.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
if (!who.gpu) return NextResponse.json({ error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
diff --git a/src/server/audio-tools.ts b/src/server/audio-tools.ts
index d719ad61..90449750 100644
--- a/src/server/audio-tools.ts
+++ b/src/server/audio-tools.ts
@@ -1,13 +1,11 @@
import "server-only";
-import fs from "node:fs/promises";
import { z } from "zod";
import { planJoin, planLoop, CROSSFADE_MAX, JOIN_MAX_CLIPS, LOOP_MAX_SECONDS, type AudioToolPreview, type ToolPlan } from "@/lib/av/audio-tools";
import type { Engine, Generation } from "@/lib/catalog/types";
-import { probeMedia } from "@/lib/media-probe";
import { createPipeline } from "./chains";
import { previewChained } from "./generations";
import { engineMode } from "./settings";
-import { absolutePath } from "./storage";
+import { storedMedia } from "./storage";
/**
* The Audio hub's Loop / extend and Join tools on the server: each clip's length is read from its own header
@@ -45,40 +43,16 @@ export type AudioToolRequest = z.infer<typeof AudioToolBody>;
export class AudioToolError extends Error {}
-declare global {
- var __fuobeAudioLengths: Map<string, number | null> | undefined;
-}
/**
- * Lengths already read, by file and version (path, size, modified time): the page asks for a price after
- * every settled change, and a Join of big WAVs would read every file again each time.
+ * A clip's length from its header (WAV, FLAC, MP3, M4A), else the browser's. Only the header is read, once per file
+ * (storedMedia caches it: the page asks for a price after every settled change). A visitor's price check reads only its
+ * own files: another's answers like one that is gone.
*/
-const lengths = (globalThis.__fuobeAudioLengths ??= new Map<string, number | null>());
-const LENGTHS_KEPT = 500;
-
-/** A clip's length from its header (WAV, FLAC, MP3, M4A), else the browser's. Read without blocking the server. */
-async function lengthOf(url: string, given?: number): Promise<number | undefined> {
- let file: string;
- let key: string;
- try {
- file = absolutePath(decodeURIComponent(url.slice("/api/files/".length)));
- const st = await fs.stat(file);
- if (!st.isFile()) throw new Error("not a file");
- key = `${file}:${st.size}:${st.mtimeMs}`;
- } catch {
- throw new AudioToolError("That audio file is gone — add it again");
- }
- if (!lengths.has(key)) {
- let data: Buffer;
- try {
- data = await fs.readFile(file);
- } catch {
- throw new AudioToolError("That audio file is gone — add it again");
- }
- const info = probeMedia(data);
- if (lengths.size >= LENGTHS_KEPT) lengths.delete(lengths.keys().next().value!);
- lengths.set(key, info?.duration && info.duration > 0 ? Math.round(info.duration * 1000) / 1000 : null);
- }
- return lengths.get(key) ?? given;
+function lengthOf(url: string, given?: number): number | undefined {
+ const found = storedMedia(url);
+ if (!found) throw new AudioToolError("That audio file is gone — add it again");
+ const d = found.info?.duration;
+ return d && d > 0 ? Math.round(d * 1000) / 1000 : given;
}
async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine }> {
@@ -86,10 +60,10 @@ async function plan(body: AudioToolRequest): Promise<ToolPlan & { engine: Engine
if (mode !== "both" && body.engine !== mode) throw new AudioToolError(mode === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");
try {
if (body.tool === "loop") {
- const sourceDuration = await lengthOf(body.audio, body.sourceDuration);
+ const sourceDuration = lengthOf(body.audio, body.sourceDuration);
return { engine: body.engine, ...planLoop({ ...body, sourceDuration: sourceDuration ?? 0 }) };
}
- const clips = await Promise.all(body.clips.map(async (c) => ({ ...c, duration: await lengthOf(c.url, c.duration) })));
+ const clips = body.clips.map((c) => ({ ...c, duration: lengthOf(c.url, c.duration) }));
return { engine: body.engine, ...planJoin({ ...body, clips }) };
} catch (e) {
throw e instanceof AudioToolError ? e : new AudioToolError((e as Error).message);
diff --git a/src/server/cinema-schemas.ts b/src/server/cinema-schemas.ts
index 9c2f2005..2d1b1899 100644
--- a/src/server/cinema-schemas.ts
+++ b/src/server/cinema-schemas.ts
@@ -6,7 +6,7 @@ import { CinemaError } from "./cinema";
/** Request bodies of /api/cinema/** (zod drops unknown keys). */
const Hex = z.string().regex(/^#[0-9a-fA-F]{6}$/);
-const FileRef = z.string().startsWith("/api/files/");
+const FileRef = z.string().startsWith("/api/files/").max(500);
const Slug = z.string().max(80).nullable().optional();
export const DirectorSchema = z.object({
diff --git a/src/server/dub.ts b/src/server/dub.ts
index 3aa2a741..8cb96e2a 100644
--- a/src/server/dub.ts
+++ b/src/server/dub.ts
@@ -1,5 +1,4 @@
import "server-only";
-import fs from "node:fs";
import { nanoid } from "nanoid";
import { z } from "zod";
import type { Cue } from "@/lib/cues";
@@ -20,11 +19,10 @@ import {
import { normalizeCues } from "@/lib/av/cue-edit";
import { getModel } from "@/lib/catalog";
import type { Engine, Generation } from "@/lib/catalog/types";
-import { probeMedia } from "@/lib/media-probe";
import { createPipeline } from "./chains";
import { db } from "./db";
import { cancelGeneration, createGenerations, getGeneration, previewChained } from "./generations";
-import { absolutePath } from "./storage";
+import { storedMedia } from "./storage";
/**
* Translate & dub sessions. A session remembers the source video, the languages and which generations
@@ -97,36 +95,15 @@ export interface CreateDubInput {
}
/**
- * Lengths read from stored files, by path, size and time: a dub (or an Assist call) is checked, priced
- * and started, each asking for the length, and reading a 200 MB upload each time would block the server.
+ * The source's length: its MP4/MOV header, else what the browser measured. The dubbed voice track is this long. Only
+ * the header is read, once per file (a dub is checked, priced and started, each asking for the length), and a visitor's
+ * price check reads only its own file (storedMedia). Gone, another's, or a header Fuobe can't read (WebM): what the
+ * browser measured.
*/
-const lengths = new Map<string, number | null>();
-
-/** The source's length: its MP4/MOV header, else what the browser measured. The dubbed voice track is this long. */
export function videoLength(ref: string, measured?: number): number | undefined {
- try {
- if (ref.startsWith("/api/files/")) {
- const abs = absolutePath(decodeURIComponent(ref.slice("/api/files/".length)));
- const st = fs.statSync(abs);
- const key = `${abs}|${st.size}|${st.mtimeMs}`;
- if (!lengths.has(key)) {
- let d: number | null = null;
- try {
- const info = probeMedia(fs.readFileSync(abs));
- const v = info?.videoDuration ?? info?.duration;
- d = v && v > 0 ? v : null;
- } catch {
- // An unreadable header (WebM): what the browser measured.
- }
- lengths.set(key, d);
- if (lengths.size > 64) lengths.delete(lengths.keys().next().value!);
- }
- const d = lengths.get(key);
- if (d) return d;
- }
- } catch {
- // Gone: what the browser measured.
- }
+ const info = storedMedia(ref)?.info;
+ const v = info?.videoDuration ?? info?.duration;
+ if (v && v > 0) return v;
return measured && measured > 0 ? measured : undefined;
}
diff --git a/src/server/katana.ts b/src/server/katana.ts
index f2b4b5c9..4ec7b564 100644
--- a/src/server/katana.ts
+++ b/src/server/katana.ts
@@ -5,14 +5,12 @@ import type { PlannedJob } from "@/lib/assist";
import { finalKey, KATANA_FEATURE, KATANA_LIMITS, katanaSteps, katanaStage, motionModel, MOTION_MODELS, planSegments, currentMotionModel, stepsToRedo, type KatanaInput, type KatanaJob, type KatanaJobView, type Segment } from "@/lib/av/katana";
import { getModel } from "@/lib/catalog";
import type { Engine, Generation } from "@/lib/catalog/types";
-import { probeMedia } from "@/lib/media-probe";
import { createPipeline } from "./chains";
import { db } from "./db";
import { cancelGeneration, createGenerations, getGeneration, previewChained } from "./generations";
import { firstOn } from "./model-access";
import { engineMode } from "./settings";
-import fs from "node:fs";
-import { absolutePath } from "./storage";
+import { storedMedia } from "./storage";
/**
* Katana jobs: a reference edit rebuilt with your subject (src/lib/av/katana.ts plans it). The steps
@@ -132,8 +130,8 @@ const Seg = z.object({ start: z.number().min(0).max(KATANA_LIMITS.maxReference),
export const KatanaBody = z.object({
engine: z.enum(["cloud", "open"]),
- reference: z.string().startsWith("/api/files/"),
- photos: z.array(z.string().startsWith("/api/files/")).min(1).max(KATANA_LIMITS.maxPhotos),
+ reference: z.string().startsWith("/api/files/").max(500),
+ photos: z.array(z.string().startsWith("/api/files/").max(500)).min(1).max(KATANA_LIMITS.maxPhotos),
instructions: z.string().max(KATANA_LIMITS.maxInstructions).optional(),
/** Segments chosen in the studio (scene cuts); without them the clip is cut every `length` seconds. */
segments: z.array(Seg).max(KATANA_LIMITS.maxSegments).optional(),
@@ -146,16 +144,14 @@ export const KatanaBody = z.object({
});
export type KatanaRequest = z.infer<typeof KatanaBody>;
-/** The reference's length: what the browser measured, else the file's header (MP4, MOV). */
+/**
+ * The reference's length: what the browser measured, else the file's header (MP4, MOV). Only the header is read; a
+ * visitor's price check reads only its own file (storedMedia).
+ */
function referenceLength(ref: string, given?: number): number {
if (given) return given;
- let d: number | undefined;
- try {
- const info = probeMedia(fs.readFileSync(absolutePath(decodeURIComponent(ref.slice("/api/files/".length)))));
- d = info?.videoDuration ?? info?.duration;
- } catch {
- d = undefined;
- }
+ const info = storedMedia(ref)?.info;
+ const d = info?.videoDuration ?? info?.duration;
if (!d) throw new Error("Couldn't read how long the reference is — try an MP4");
return d;
}
diff --git a/src/server/marketing.ts b/src/server/marketing.ts
index e5d1b056..9922cc05 100644
--- a/src/server/marketing.ts
+++ b/src/server/marketing.ts
@@ -46,7 +46,6 @@ import {
} from "@/lib/catalog/marketing";
import { dualEngine } from "@/lib/catalog/engines";
import { routesFor } from "@/lib/catalog/plan";
-import { probeMedia } from "@/lib/media-probe";
import { themeFrom } from "@/components/ads/layout";
import type { ChainSlot, Engine, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";
import { getBrand, getProduct } from "./brand";
@@ -58,7 +57,7 @@ import { isOffered } from "./model-access";
import { keepOffered } from "@/lib/model-access";
import { engineMode } from "./settings";
import { encodePng } from "./png";
-import { readRef, saveFile } from "./storage";
+import { saveFile, storedMedia } from "./storage";
/**
* Marketing Studio (templates → product shots, posters, ads, product motion, UGC presenters),
@@ -68,7 +67,7 @@ import { readRef, saveFile } from "./storage";
* over open-engine posters). Both engines; demo mode runs every step on the mock provider.
*/
-const FILE = z.string().startsWith("/api/files/");
+const FILE = z.string().startsWith("/api/files/").max(500);
// ---------------------------------------------------------------------------
// Inputs
@@ -1201,26 +1200,15 @@ export async function runClickToAd(input: ClickToAdInput): Promise<{ run: Market
return { run: launch(plan, { ...input, script }), script };
}
-declare global {
- var __fuobeClipFacts: Map<string, { sound: boolean | null; aspect?: string }> | undefined;
-}
-const clipFacts = () => (globalThis.__fuobeClipFacts ??= new Map());
-
-/** Whether a stored clip has a soundtrack, and its shape, from the file's own header (cached per file). */
+/**
+ * Whether a stored clip has a soundtrack, and its shape, from the file's own header: only the header is read, cached by
+ * the file itself (not by the text of the request), and a visitor's price check reads only its own clip (storedMedia).
+ * Not readable here: unknown, and the plan falls back to what works without knowing.
+ */
export async function referenceFacts(ref: string): Promise<{ sound: boolean | null; aspect?: string }> {
- const cache = clipFacts();
- const hit = cache.get(ref);
- if (hit) return hit;
- let facts: { sound: boolean | null; aspect?: string } = { sound: null };
- try {
- const info = probeMedia(new Uint8Array((await readRef(ref)).data));
- if (info?.hasVideo) facts = { sound: info.hasAudio, aspect: info.width && info.height ? nearestAspect(`${info.width}:${info.height}`, ["9:16", "4:5", "3:4", "1:1", "4:3", "16:9", "21:9"]) : undefined };
- } catch {
- // Not readable here: the plan falls back to what works without knowing.
- }
- if (cache.size > 200) cache.clear();
- cache.set(ref, facts);
- return facts;
+ const info = storedMedia(ref)?.info;
+ if (!info?.hasVideo) return { sound: null };
+ return { sound: info.hasAudio, aspect: info.width && info.height ? nearestAspect(`${info.width}:${info.height}`, ["9:16", "4:5", "3:4", "1:1", "4:3", "16:9", "21:9"]) : undefined };
}
async function multiplierContext(input: MultiplierInput): Promise<MultiplierContext> {
diff --git a/src/server/storage.ts b/src/server/storage.ts
index 00fa2656..1e2ac18d 100644
--- a/src/server/storage.ts
+++ b/src/server/storage.ts
@@ -4,6 +4,7 @@ import path from "node:path";
import { nanoid } from "nanoid";
import { DATA_DIR, db } from "./db";
import type { MediaKind } from "@/lib/catalog/types";
+import { probeMediaRangesSync, type MediaInfo } from "@/lib/media-probe";
import { fetchRemote } from "./remote-fetch";
import { tenant, tenantAccount } from "./tenant";
import { accountInputLimit } from "./account-files";
@@ -374,6 +375,61 @@ export function guardRef(ref: string): void {
if (!tenantAccount() || owner !== tenantAccount()) throw new RefError(NOT_YOURS_MESSAGE, 403);
}
+declare global {
+ var __fuobeStoredFacts: Map<string, MediaInfo | null> | undefined;
+}
+const STORED_FACTS_KEPT = 500;
+/** The most read of a file's start for its header, and of an MP4's index (moov) inside a tenant and outside. */
+const STORED_HEAD_BYTES = 1024 * 1024;
+const TENANT_MOOV_BYTES = 8 * 1024 * 1024;
+const OWNER_MOOV_BYTES = 64 * 1024 * 1024;
+
+/**
+ * What a stored file's header says (length, size, tracks), for a price check or a plan: only the header (and an MP4's
+ * index) is read, never the whole file, at once and cached by the file's own path, size and time.
+ *
+ * - null: no such file here, as far as this asker may know. Inside a tenant (a visitor's price check, an account's run)
+ * that is also another's file: it answers like one that is gone, before any cache is looked at.
+ * - { info: null }: a file the asker may use whose header says nothing Fuobe reads (WebM…), or, inside a tenant, one
+ * bigger than an upload of its kind may be (never read: the run itself says it is too big).
+ */
+export function storedMedia(ref: string): { info: MediaInfo | null } | null {
+ const rel = filesRel(ref);
+ if (rel === null) return null;
+ if (tenant() && !ownsRef(ref, rel)) return null;
+ let abs: string;
+ let st: fs.Stats;
+ try {
+ abs = absolutePath(rel);
+ st = fs.statSync(abs);
+ } catch {
+ return null;
+ }
+ if (!st.isFile()) return null;
+ if (tenant() && st.size > accountInputLimit(contentTypeFor(rel)).bytes) return { info: null };
+ const cache = (globalThis.__fuobeStoredFacts ??= new Map());
+ const key = `${rel}:${st.size}:${st.mtimeMs}`;
+ if (cache.has(key)) return { info: cache.get(key) ?? null };
+ let info: MediaInfo | null = null;
+ try {
+ const fd = fs.openSync(abs, "r");
+ try {
+ const read = (start: number, end: number) => {
+ const buf = Buffer.alloc(Math.max(0, end - start));
+ return buf.subarray(0, fs.readSync(fd, buf, 0, buf.length, start));
+ };
+ info = probeMediaRangesSync(read, st.size, { headBytes: STORED_HEAD_BYTES, maxMoov: tenant() ? TENANT_MOOV_BYTES : OWNER_MOOV_BYTES });
+ } finally {
+ fs.closeSync(fd);
+ }
+ } catch {
+ return null;
+ }
+ if (cache.size >= STORED_FACTS_KEPT) cache.delete(cache.keys().next().value!);
+ cache.set(key, info);
+ return { info };
+}
+
export function toDataUri(data: Buffer, contentType: string): string {
return `data:${contentType};base64,${data.toString("base64")}`;
}
diff --git a/tests/assist-studio-routes.test.ts b/tests/assist-studio-routes.test.ts
index 48b6222f..3813c8a6 100644
--- a/tests/assist-studio-routes.test.ts
+++ b/tests/assist-studio-routes.test.ts
@@ -260,7 +260,8 @@ describe("Translate & dub", () => {
it("reads a video's length once, however often a call is checked and priced", () => {
const fresh = saveFile({ data: fs.readFileSync(fixture), contentType: "video/mp4", source: "upload", name: "read once.mp4" }).url;
- const spy = vi.spyOn(fs, "readFileSync");
+ // Its header only (storage.ts storedMedia opens it and reads the start and the index), and only the first time.
+ const spy = vi.spyOn(fs, "openSync");
try {
for (let k = 0; k < 3; k++) {
expect(plan("dub_video", { video: fresh, languages: ["German"] }, "open").studio).toBe("Translate & dub");
diff --git a/tests/price-check-reads.test.ts b/tests/price-check-reads.test.ts
new file mode 100644
index 00000000..b9cf6de2
--- /dev/null
+++ b/tests/price-check-reads.test.ts
@@ -0,0 +1,194 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-price-reads-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_TRUST_PROXY;
+
+const auth = await import("@/server/auth");
+const { saveFile } = await import("@/server/storage");
+const { runAsTenant } = await import("@/server/tenant");
+const { asVisitor } = await import("@/server/generations");
+const { previewAudioTool } = await import("@/server/audio-tools");
+const { MultiplierBody, MarketingBody, ClickToAdBody, referenceFacts } = await import("@/server/marketing");
+const { KatanaBody, planKatana } = await import("@/server/katana");
+const { videoLength } = await import("@/server/dub");
+const { resetRates } = await import("@/server/rate");
+const { proxy } = await import("@/proxy");
+const dubRoute = await import("@/app/api/dub/route");
+
+const MP4 = fs.readFileSync(path.join(import.meta.dirname, "fixtures", "shorts-12s.mp4"));
+
+let a = "";
+let b = "";
+beforeAll(() => {
+ auth.setPassword("install password");
+ a = auth.createAccount("[email protected]", "long enough").id;
+ b = auth.createAccount("[email protected]", "long enough").id;
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ resetRates();
+});
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+/** A mono 16-bit WAV, `seconds` long. */
+function wav(seconds: number): Buffer {
+ const rate = 8000;
+ const n = Math.round(seconds * rate);
+ const buf = Buffer.alloc(44 + n * 2);
+ buf.write("RIFF", 0);
+ buf.writeUInt32LE(36 + n * 2, 4);
+ buf.write("WAVEfmt ", 8);
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20);
+ buf.writeUInt16LE(1, 22);
+ buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * 2, 28);
+ buf.writeUInt16LE(2, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36);
+ buf.writeUInt32LE(n * 2, 40);
+ return buf;
+}
+
+/** A price check as the proxy and priceAs run it: as that visitor, on its own GPU (none here). */
+const asA = <T,>(fn: () => T) => asVisitor(null, fn, a);
+const asGuest = <T,>(fn: () => T) => asVisitor(null, fn);
+/** Every whole-file read the server could make. */
+function wholeReads() {
+ return [vi.spyOn(fs.promises, "readFile"), vi.spyOn(fs, "readFileSync")];
+}
+const called = (spies: ReturnType<typeof wholeReads>, file: string) => spies.some((s) => s.mock.calls.some((c) => String(c[0]).includes(path.basename(file))));
+
+describe("H-3: price checks read only the header of the asker's own files", () => {
+ it("audio Join and Loop: never another's file, and it answers like a file that is gone", async () => {
+ const owners = saveFile({ data: wav(30), contentType: "audio/wav", source: "upload" }).url;
+ const others = saveFile({ data: wav(30), contentType: "audio/wav", source: "upload", accountId: b }).url;
+ for (const url of [owners, others]) {
+ await expect(asA(() => previewAudioTool({ tool: "loop", engine: "open", audio: url, duration: 60 }))).rejects.toThrow(/gone/);
+ await expect(asGuest(() => previewAudioTool({ tool: "loop", engine: "open", audio: url, duration: 60 }))).rejects.toThrow(/gone/);
+ }
+ // The owner still prices with any file.
+ expect((await previewAudioTool({ tool: "loop", engine: "open", audio: owners, duration: 60 })).summary).toMatch(/Loops it/);
+ });
+
+ it("audio Join: ten copies of its own file read its header, not the whole file", async () => {
+ const mine = saveFile({ data: wav(20), contentType: "audio/wav", source: "upload", accountId: a }).url;
+ const spies = wholeReads();
+ const p = await asA(() => previewAudioTool({ tool: "join", engine: "open", clips: Array.from({ length: 10 }, () => ({ url: mine })), crossfade: 0 }));
+ expect(p.length).toBeGreaterThan(190);
+ expect(called(spies, mine)).toBe(false);
+ });
+
+ it("audio: an own file bigger than an upload may be is never read; the browser's length is used", async () => {
+ const mine = saveFile({ data: wav(5), contentType: "audio/wav", source: "upload", accountId: a });
+ // Its result grew past what an upload of sound may be (50 MB).
+ fs.truncateSync(path.join(dir, "files", mine.relPath), 51 * 2 ** 20);
+ const opened = vi.spyOn(fs, "openSync");
+ const spies = wholeReads();
+ const p = await asA(() => previewAudioTool({ tool: "loop", engine: "open", audio: mine.url, sourceDuration: 7, duration: 60 }));
+ expect(p.summary).toMatch(/Loops it/);
+ expect(opened.mock.calls.some((c) => String(c[0]).includes(path.basename(mine.relPath)))).toBe(false);
+ expect(called(spies, mine.relPath)).toBe(false);
+ });
+
+ it("Katana: another's clip is never read, and an own clip is read by its header", () => {
+ const owners = saveFile({ data: MP4, contentType: "video/mp4", source: "upload" }).url;
+ const mine = saveFile({ data: MP4, contentType: "video/mp4", source: "upload", accountId: a }).url;
+ const body = (reference: string) => KatanaBody.parse({ engine: "open", reference, photos: [reference] });
+ expect(() => asA(() => planKatana(body(owners)))).toThrow(/how long the reference is/);
+ const spies = wholeReads();
+ expect(asA(() => planKatana(body(mine))).input.segments.at(-1)?.end).toBeCloseTo(12, 0);
+ expect(called(spies, mine)).toBe(false);
+ });
+
+ it("Dub: another's video gives what the browser measured, never the file's length", () => {
+ const owners = saveFile({ data: MP4, contentType: "video/mp4", source: "upload" }).url;
+ expect(asA(() => videoLength(owners, 3))).toBe(3);
+ expect(asGuest(() => videoLength(owners))).toBeUndefined();
+ expect(videoLength(owners)).toBeCloseTo(12, 0);
+ const mine = saveFile({ data: MP4, contentType: "video/mp4", source: "upload", accountId: a }).url;
+ const spies = wholeReads();
+ expect(asA(() => videoLength(mine))).toBeCloseTo(12, 0);
+ expect(called(spies, mine)).toBe(false);
+ });
+});
+
+describe("H-2: the ad multiplier's price check keeps nothing a request sends", () => {
+ it("refuses a file path over 500 characters, in every studio body that takes one", () => {
+ const long = `/api/files/${"a".repeat(600)}`;
+ expect(MultiplierBody.safeParse({ engine: "open", video: long, duration: 10, mode: "prompt", quality: "720p" }).success).toBe(false);
+ expect(KatanaBody.safeParse({ engine: "open", reference: long, photos: ["/api/files/x.png"] }).success).toBe(false);
+ expect(KatanaBody.safeParse({ engine: "open", reference: "/api/files/x.mp4", photos: [long] }).success).toBe(false);
+ expect(MarketingBody.shape.reference.safeParse(long).success).toBe(false);
+ expect(ClickToAdBody.shape.avatar.safeParse(long).success).toBe(false);
+ });
+
+ it("the Dub price check refuses a long path too", async () => {
+ const r = await dubRoute.POST(
+ new Request("http://localhost/api/dub?preview=1", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ engine: "open", mode: "steps", video: `/api/files/${"a".repeat(600)}`, targets: ["es"] }) }),
+ );
+ expect(r.status).toBe(400);
+ });
+
+ it("caches a clip's facts by the file, not by the text of the request, and never a failed read", async () => {
+ const mine = saveFile({ data: MP4, contentType: "video/mp4", source: "upload", accountId: a }).url;
+ const spies = wholeReads();
+ const first = await asA(() => referenceFacts(mine));
+ expect(first.aspect).toBeDefined();
+ expect(called(spies, mine)).toBe(false);
+ // The same file under other names (?1, ?2…) is one entry; a read that failed adds none.
+ const sizeOf = () => (globalThis as { __fuobeStoredFacts?: Map<unknown, unknown> }).__fuobeStoredFacts?.size ?? 0;
+ const before = sizeOf();
+ for (let i = 0; i < 20; i++) await asA(() => referenceFacts(`${mine}?${i}`));
+ for (let i = 0; i < 20; i++) await asGuest(() => referenceFacts(`/api/files/uploads/nope/${i}.mp4`));
+ expect(sizeOf()).toBe(before);
+ });
+
+ it("L-11: another's clip answers 'unknown', even after its owner's check filled the cache", async () => {
+ const owners = saveFile({ data: MP4, contentType: "video/mp4", source: "upload" }).url;
+ expect((await referenceFacts(owners)).aspect).toBeDefined();
+ expect(await asGuest(() => referenceFacts(owners))).toEqual({ sound: null });
+ expect(await runAsTenant({ kind: "account", id: b }, () => referenceFacts(owners))).toEqual({ sound: null });
+ });
+});
+
+describe("H-2 / H-3: price checks are rate-limited per visitor", () => {
+ const post = (url: string, cookie?: string, ip = "203.0.113.7") =>
+ new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": ip, ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) }, body: "{}" });
+ const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+
+ it("a guest gets 120 a minute, then a plain 429; another visitor is not affected", async () => {
+ process.env.FUOBE_TRUST_PROXY = "1";
+ try {
+ for (let i = 0; i < 120; i++) expect(passed(proxy(post("/api/ads/multiplier/estimate"))), `check ${i}`).toBe(true);
+ const r = proxy(post("/api/audio-tools?preview=1"));
+ expect(r.status).toBe(429);
+ expect(r.headers.get("retry-after")).toBeTruthy();
+ expect((await r.json()).error).toMatch(/Too many price checks/);
+ expect(passed(proxy(post("/api/katana?preview=1", undefined, "198.51.100.9")))).toBe(true);
+ } finally {
+ delete process.env.FUOBE_TRUST_PROXY;
+ }
+ });
+
+ it("an account gets its own budget; the owner is never limited", () => {
+ const account = auth.createSession(a).value;
+ for (let i = 0; i < 120; i++) expect(passed(proxy(post("/api/dub?preview=1", account)))).toBe(true);
+ expect(proxy(post("/api/dub?preview=1", account)).status).toBe(429);
+ const owner = auth.createSession().value;
+ for (let i = 0; i < 200; i++) expect(passed(proxy(post("/api/dub?preview=1", owner)))).toBe(true);
+ });
+});