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.

WorldCast: every run keeps the still as its front view, big photos are sent at the model's scale, and the worker can ask for a token

Claudeeae553177511
diff --git a/docs/workers/worldcast.md b/docs/workers/worldcast.md
index 3c8e5ab1..1713ed04 100644
--- a/docs/workers/worldcast.md
+++ b/docs/workers/worldcast.md
@@ -46,7 +46,10 @@ One run is a few steps (`src/lib/catalog/worldcast-plan.ts`):
480 × 832 frame from the crop's field of view (Fuobe's default 24 mm lens);
- `render.mp4` and `render_mask.mp4`: the still's point cloud (its MoGe depth) drawn along those poses, 81 frames at
15 fps, H.264; the mask is white (255) where no point landed (a hole) and black (0) where one did;
- - the anchors: the views with WorldCast's names and azimuths (below), each with its SAM 3.1 mask, at their own size;
+ - the anchors: the views with WorldCast's names and azimuths (below), each with its SAM 3.1 mask, brought down to a
+ longest side of 1344 px (the demo's body views are cut from 768 × 1344 frames) and never enlarged. The still is
+ always the `front` anchor when no front view is given: the pipeline drops every anchor, the first frame's
+ included, when it has no body view, and the released checkpoint was never trained that way;
- `anchors_aligned_camera_info.json`: each anchor's camera on a level ring at the subject's distance, looking at
it. This is a guess: the paper aligns real cameras with VGGT-Omega. Without the file WorldCast skips the anchors'
Plücker rays; the quality impact of either is unknown.
@@ -72,6 +75,11 @@ camera goes round to its left, so (`worldcastAnchor`):
All bodies are JSON unless said. Errors answer `{"error": "…"}` with an HTTP status.
+Authentication: when the worker has a `WORLDCAST_TOKEN`, every call (health included) needs
+`Authorization: Bearer <token>`, and answers 401 without it. Fuobe sends its own `WORLDCAST_TOKEN` setting (environment)
+on every call and on the clip's download. A worker without a token must listen on `127.0.0.1` only. `POST /cases` and
+`POST /depth` need a `Content-Length` (411 without one; 413 over 512 MB).
+
### `GET {WORLDCAST_URL}/health`
```json
diff --git a/src/lib/catalog/cinema.ts b/src/lib/catalog/cinema.ts
index 6d5c797a..1e2dc950 100644
--- a/src/lib/catalog/cinema.ts
+++ b/src/lib/catalog/cinema.ts
@@ -13,6 +13,7 @@ import { soulRecipe } from "./soul";
import { planTurnaround, type TurnaroundInput } from "./turnaround";
import { planFlyAround } from "./fly-around";
import { WORLDCAST_AFTER, WORLDCAST_MODELS, WORLDCAST_SECONDS, worldcastFallback, worldcastNote, worldcastSteps } from "./worldcast-plan";
+import { WORLDCAST_RUN } from "@/lib/worldcast";
import { exactDefaults, exactSummary, normalizeExact, takesExact, type ExactOrbit } from "@/lib/exact-orbit";
import { CAST_LOOK } from "./soul-cards";
import type { Engine, GenerationRequest, GenParams, LoraRef, ModelDef, Operation } from "./types";
@@ -2198,8 +2199,10 @@ function planPath(input: CinemaGenerateInput, ctx: CinemaContext = {}): CinemaPl
/** What a filmed path's take remembers: the keys it was planned with (from the photo's pose) and the clip's real length. */
export function pathTake(input: Pick<CinemaGenerateInput, "engine" | "path">, plan: CinemaPlan): CinemaTakeInfo["path"] {
- const params = plan.steps[0]?.request.params;
- const duration = input.engine === "open" ? PATH_FRAMES / PATH_FPS : (params?.duration ?? 5);
+ // WorldCast's plan measures depth and masks first: the film is its last step, 81 frames at 15 fps.
+ const worldcast = plan.model.id === WORLDCAST_MODELS.film;
+ const params = (worldcast ? plan.steps.at(-1) : plan.steps[0])?.request.params;
+ const duration = worldcast ? WORLDCAST_RUN.frames / WORLDCAST_RUN.fps : input.engine === "open" ? PATH_FRAMES / PATH_FPS : (params?.duration ?? 5);
return { keys: params?.cameraPath ?? normalizeKeys(input.path?.keys ?? []), duration, ...(input.path?.preset ? { preset: input.path.preset } : {}) };
}
diff --git a/src/lib/catalog/worldcast-plan.ts b/src/lib/catalog/worldcast-plan.ts
index 8c120fa8..cd7ffa7d 100644
--- a/src/lib/catalog/worldcast-plan.ts
+++ b/src/lib/catalog/worldcast-plan.ts
@@ -36,7 +36,7 @@ export function worldcastNote(views: number, depth: WorldcastDepth = "moge"): st
}
/** Said after the run: what else the clip can go through. */
-export const WORLDCAST_AFTER = "In Upscale, FPS Boost (RIFE) takes the clip to 24 fps and the upscalers enlarge it";
+export const WORLDCAST_AFTER = "Upscale, under the finished clip, opens it in Upscale: FPS Boost (RIFE) takes it to 24 fps and the upscalers enlarge it";
/** A picture of the run: a file, or what an earlier step makes. */
export type WorldcastSource = { url: string } | { key: string };
@@ -84,12 +84,16 @@ const one = (src: WorldcastSource): Pick<WorldcastStep, "after"> & { request: Pi
/** The steps of a WorldCast run, film last (key "main"); numbered as one run. */
export function worldcastSteps(input: WorldcastInput): WorldcastStep[] {
- const layout = worldcastLayout(input.anchors.map((a) => a.side));
- const anchors = layout.anchors.map((a) => input.anchors.find((x) => x.side === a.side)!.src);
+ const still = input.still ?? { url: "/api/files/placeholder.png" };
+ // WorldCast's "front" anchor is the first frame's own camera (the demo's body_views_meta: front = source frame 0). Without a
+ // body view the pipeline drops every anchor, the first frame's included, which the released checkpoint never ran: so the
+ // still is always the front's anchor when no front view is given.
+ const given = input.anchors.some((a) => a.side === "front") ? input.anchors : [{ side: "front" as const, src: still }, ...input.anchors];
+ const layout = worldcastLayout(given.map((a) => a.side));
+ const anchors = layout.anchors.map((a) => given.find((x) => x.side === a.side)!.src);
const stepFeature = input.stepFeature ?? input.feature;
const depth = input.depth ?? "moge";
const steps: WorldcastStep[] = [];
- const still = input.still ?? { url: "/api/files/placeholder.png" };
const pre = (key: string, src: WorldcastSource, request: Omit<GenerationRequest, "inputs" | "chain">): WorldcastStep => {
const o = one(src);
return { key, request: { ...request, ...o.request }, ...(o.after && { after: o.after }) };
diff --git a/src/server/providers/worldcast.ts b/src/server/providers/worldcast.ts
index 68a75122..1f12d05b 100644
--- a/src/server/providers/worldcast.ts
+++ b/src/server/providers/worldcast.ts
@@ -1,7 +1,7 @@
import "server-only";
import { readLayout } from "@/lib/worldcast";
import { buildCase } from "../worldcast-case";
-import { WORKER_DEPTH, cancelJob, jobDepthUrl, jobStatus, jobVideoUrl, submitCase, submitDepth, worldcastBase, worldcastHealth, type WorkerDepth } from "../worldcast";
+import { WORKER_DEPTH, cancelJob, jobDepthUrl, jobStatus, jobVideoUrl, submitCase, submitDepth, worldcastBase, worldcastHeaders, worldcastHealth, type WorkerDepth } from "../worldcast";
import type { ProviderAdapter } from "./types";
import { ProviderError } from "./types";
@@ -11,6 +11,12 @@ import { ProviderError } from "./types";
* the worker when it is done. Open engine, the studio's own GPU only (accountRun refuses an account: not ComfyUI, not a key).
*/
+/** The worker's Bearer header for the clip's download, when a WORLDCAST_TOKEN is set. */
+function auth(): { headers?: Record<string, string> } {
+ const headers = worldcastHeaders();
+ return Object.keys(headers).length ? { headers } : {};
+}
+
const DATA_URI = /^data:([^;,]+);base64,(.*)$/s;
function fileOf(ref: string): Buffer {
@@ -58,8 +64,8 @@ export const worldcastProvider: ProviderAdapter = {
async poll({ externalId, meta }) {
const job = await jobStatus(externalId);
- if (job.status === "succeeded" && typeof meta.depth === "string") return { state: "succeeded", outputs: [{ url: jobDepthUrl(externalId), kind: "image", contentType: "image/png", meta: { role: "depth" } }] };
- if (job.status === "succeeded") return { state: "succeeded", outputs: [{ url: jobVideoUrl(externalId), kind: "video", contentType: "video/mp4", meta: { fps: 15 } }] };
+ if (job.status === "succeeded" && typeof meta.depth === "string") return { state: "succeeded", outputs: [{ url: jobDepthUrl(externalId), kind: "image", contentType: "image/png", ...auth(), meta: { role: "depth" } }] };
+ if (job.status === "succeeded") return { state: "succeeded", outputs: [{ url: jobVideoUrl(externalId), kind: "video", contentType: "video/mp4", ...auth(), meta: { fps: 15 } }] };
if (job.status === "failed") return { state: "failed", error: job.error };
return { state: job.status, ...(job.progress !== undefined && { progress: job.progress }), message: job.message ?? (job.status === "queued" ? "Waiting for the WorldCast worker" : "WorldCast is filming") };
},
diff --git a/src/server/settings.ts b/src/server/settings.ts
index f837df40..21a974a5 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -73,6 +73,8 @@ export const SETTINGS = {
comfyIsolatedUrl: { key: "comfyui.isolatedUrl", env: "COMFYUI_ISOLATED_URL" },
/** The WorldCast worker on the owner's GPU (docs/workers/worldcast.md): an HTTP service outside ComfyUI, usually port 8190. */
worldcastUrl: { key: "worldcast.url", env: "WORLDCAST_URL" },
+ /** The worker's shared secret, sent as a Bearer header on every call (the worker checks its own WORLDCAST_TOKEN). */
+ worldcastToken: { key: "worldcast.token", env: "WORLDCAST_TOKEN", secret: true },
/**
* Where the owner's ComfyUI runs: on this server (its address above), or on the computer the owner uses, reached
* through the owner's own Fuobe tab (a studio on a server, a ComfyUI at home: src/server/computer).
diff --git a/src/server/worldcast-case.ts b/src/server/worldcast-case.ts
index 03dd5f45..ddcaf0e4 100644
--- a/src/server/worldcast-case.ts
+++ b/src/server/worldcast-case.ts
@@ -18,6 +18,12 @@ import { scratchDir } from "./storage";
*/
const MAX_POINTS = 300_000;
+/**
+ * The longest side an anchor picture is sent at. The worker crops each anchor to the person at the size it gets, and
+ * WorldCast encodes that crop at its own size: the demo's body views are cut from 768 × 1344 frames, so a phone photo is
+ * brought down to that scale first (a 4000 × 6000 photo would otherwise add tens of thousands of tokens per anchor).
+ */
+export const ANCHOR_MAX_SIDE = 1344;
export interface CaseInput {
layout: WorldcastLayout;
@@ -83,9 +89,11 @@ export async function buildCase(input: CaseInput): Promise<{ parts: CasePart[];
const anchors = await Promise.all(
input.layout.anchors.map(async (_, i) => {
const pic = input.images[slots.anchor(i)];
- const size = await sizeOf(pic);
+ const full = await sizeOf(pic);
+ const scale = Math.min(1, ANCHOR_MAX_SIDE / Math.max(full.width, full.height));
+ const size = { width: Math.max(1, Math.round(full.width * scale)), height: Math.max(1, Math.round(full.height * scale)) };
return {
- image: await sharp(pic, { failOn: "none" }).rotate().removeAlpha().png().toBuffer(),
+ image: await sharp(pic, { failOn: "none" }).rotate().removeAlpha().resize(size.width, size.height, { fit: "fill" }).png().toBuffer(),
mask: await binaryMask(input.images[slots.anchorMask(i)], size),
};
}),
diff --git a/src/server/worldcast-on.ts b/src/server/worldcast-on.ts
index 535465e5..aabf8270 100644
--- a/src/server/worldcast-on.ts
+++ b/src/server/worldcast-on.ts
@@ -1,5 +1,5 @@
import "server-only";
-import { WORLDCAST_MODELS } from "@/lib/catalog/worldcast-plan";
+import { WORLDCAST_DEPTH, WORLDCAST_MODELS } from "@/lib/catalog/worldcast-plan";
import { isOffered } from "./model-access";
import { ownGpu } from "./providers/comfyui";
import { tenantAccount } from "./tenant";
@@ -9,17 +9,24 @@ import { refreshWorldcast, worldcastAnswers } from "./worldcast";
* What the camera-path planners get for WorldCast (build plan N7-9): true when the studio's worker answers and WorldCast is
* switched on, false when it is on but no worker answers (the run says what it films on instead), undefined for a visitor
* (a guest or an account runs on its own GPU, which has no WorldCast worker: nothing is said about the studio's) or when
- * WorldCast is switched off in Settings → Models & licences.
+ * WorldCast (or a step it needs) is switched off in Settings → Models & licences.
*/
export function worldcastContext(): boolean | undefined {
- if (tenantAccount() || ownGpu()) return undefined;
- if (!isOffered(WORLDCAST_MODELS.film)) return undefined;
+ if (tenantAccount() || ownGpu() || !offered()) return undefined;
return worldcastAnswers();
}
+/**
+ * WorldCast and the steps every run of it needs (the person mask, MoGe 2's depth) are switched on: with any of them off
+ * the buttons keep their Uni3C / Frames run instead of planning a move that is then refused.
+ */
+function offered(): boolean {
+ return isOffered(WORLDCAST_MODELS.film) && isOffered(WORLDCAST_MODELS.mask) && isOffered(WORLDCAST_DEPTH.moge);
+}
+
/** The same, after asking the worker when the last answer is over a minute old (routes call it before they plan). */
export async function worldcastContextNow(): Promise<boolean | undefined> {
- if (tenantAccount() || ownGpu() || !isOffered(WORLDCAST_MODELS.film)) return undefined;
+ if (tenantAccount() || ownGpu() || !offered()) return undefined;
await refreshWorldcast().catch(() => false);
return worldcastAnswers();
}
diff --git a/src/server/worldcast.ts b/src/server/worldcast.ts
index 44b5e0b8..0946d1ce 100644
--- a/src/server/worldcast.ts
+++ b/src/server/worldcast.ts
@@ -37,12 +37,18 @@ function guard(): void {
if (tenantAccount()) throw new ProviderError("WorldCast runs on the studio's own GPU only.");
}
+/** The Bearer header for the worker when a WORLDCAST_TOKEN is set (the reference server then refuses calls without it). */
+export function worldcastHeaders(): Record<string, string> {
+ const t = (getSetting("worldcastToken") ?? "").trim();
+ return t ? { Authorization: `Bearer ${t}` } : {};
+}
+
async function call(path: string, init: RequestInit = {}, timeoutMs = 60_000): Promise<Response> {
guard();
const base = worldcastBase();
if (!base) throw new ProviderError(`No WorldCast worker is set up: add its address in ${WORLDCAST_SETTING} (or WORLDCAST_URL)`);
try {
- return await fetch(`${base}${path}`, { ...init, signal: init.signal ?? AbortSignal.timeout(timeoutMs) });
+ return await fetch(`${base}${path}`, { ...init, headers: { ...worldcastHeaders(), ...(init.headers as Record<string, string> | undefined) }, signal: init.signal ?? AbortSignal.timeout(timeoutMs) });
} catch (e) {
throw new ProviderError(`The WorldCast worker at ${base} doesn't answer (${(e as Error).message}). Start it (workers/worldcast/README.md) or check ${WORLDCAST_SETTING}`);
}
diff --git a/tests/worldcast-plan.test.ts b/tests/worldcast-plan.test.ts
index 2e0e8fcb..6bf9fb99 100644
--- a/tests/worldcast-plan.test.ts
+++ b/tests/worldcast-plan.test.ts
@@ -17,7 +17,7 @@ const { getModel, MODELS } = await import("@/lib/catalog");
const { providerEngine } = await import("@/lib/catalog/engines");
const { planFlyAround } = await import("@/lib/catalog/fly-around");
const { planTurnaround } = await import("@/lib/catalog/turnaround");
-const { planCinema } = await import("@/lib/catalog/cinema");
+const { pathTake, planCinema } = await import("@/lib/catalog/cinema");
const { WORLDCAST_MODELS, worldcastFallback, worldcastSteps } = await import("@/lib/catalog/worldcast-plan");
const { imageSlots, readLayout, worldcastLayout } = await import("@/lib/worldcast");
const { modelLicence } = await import("@/server/model-access");
@@ -70,8 +70,14 @@ describe("the buttons prefer WorldCast when the worker answers", () => {
expect(on.duration).toBe(5.4);
expect(on.costUsd).toBe(0);
expect(on.blocker).toBeUndefined();
- expect(on.steps.map((s) => s.key)).toEqual(["depth", "mask-still", "mask-back", "main"]);
+ // The still is the front's anchor too, so WorldCast always has the first frame's anchor it was trained with.
+ expect(on.steps.map((s) => s.key)).toEqual(["depth", "mask-still", "mask-front", "mask-back", "main"]);
+ expect(readLayout(on.steps.at(-1)!.request.params?.extra?.worldcast).anchors.map((a) => a.view)).toEqual(["front", "back"]);
+ expect(on.steps.at(-1)!.request.inputs?.images).toEqual([image, image, V.back]);
expect(on.notes[0]).toMatch(/the back and sides follow your 1 view/);
+ // With no views named, the still alone is still sent as the front's anchor.
+ const alone = planFlyAround({ engine: "open", image, orbit }, { worldcast: true });
+ expect(readLayout(alone.steps.at(-1)!.request.params?.extra?.worldcast).anchors.map((a) => [a.side, a.view])).toEqual([["front", "front"]]);
expect(on.notes.join(" ")).toMatch(/RIFE/);
const off = planFlyAround({ engine: "open", image, orbit }, { worldcast: false });
@@ -121,6 +127,9 @@ describe("the buttons prefer WorldCast when the worker answers", () => {
expect(on.model.id).toBe("oss-worldcast");
expect(on.blocker).toBeUndefined();
expect(on.steps.at(-1)?.request.feature).toBe("cinema-path");
+ expect(readLayout(on.steps.at(-1)?.request.params?.extra?.worldcast).anchors.map((a) => a.view)).toEqual(["front"]);
+ // The take remembers WorldCast's own length and the keys it filmed.
+ expect(pathTake(input, on)).toEqual({ keys: on.steps.at(-1)?.request.params?.cameraPath, duration: 81 / 15 });
const off = planCinema({ ...input, path: { ...input.path, render: "/api/files/uploads/r.webm" } }, { worldcast: false });
expect(off.model.id).toBe("oss-uni3c-path");
expect(off.notes).toContain(FALLBACK);
@@ -157,13 +166,28 @@ describe("public sign-up", () => {
// The owner, with no worker set: Fly path says what it films on.
expect(worldcastContext()).toBe(false);
});
+
+ it("keeps the Uni3C / Frames run, saying nothing, when a step WorldCast needs is switched off", async () => {
+ const { changeAccess } = await import("@/server/model-access");
+ const { worldcastContext } = await import("@/server/worldcast-on");
+ expect(worldcastContext()).toBe(false);
+ try {
+ for (const id of ["oss-person-mask", "oss-scene-moge", "oss-worldcast"]) {
+ changeAccess([{ kind: "model", id, on: false }]);
+ expect(worldcastContext()).toBeUndefined();
+ changeAccess([{ kind: "reset" }]);
+ }
+ } finally {
+ changeAccess([{ kind: "reset" }]);
+ }
+ });
});
const ffmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;
describe.skipIf(!ffmpeg)("the server's case", async () => {
const sharp = (await import("sharp")).default;
- const { buildCase } = await import("@/server/worldcast-case");
+ const { ANCHOR_MAX_SIDE, buildCase } = await import("@/server/worldcast-case");
it("crops the still to 480 × 832, renders the path and its holes at 81 frames, and keeps each view whole", async () => {
const still = await sharp({ create: { width: 320, height: 240, channels: 3, background: "#2050a0" } }).png().toBuffer();
const mask = await sharp({ create: { width: 320, height: 240, channels: 3, background: "#000" } })
@@ -189,4 +213,19 @@ describe.skipIf(!ffmpeg)("the server's case", async () => {
expect(probe.stdout.trim()).toBe("480,832,15/1,81");
}
}, 60_000);
+
+ it("brings a big view down to the demo's scale before the worker crops it, with its mask the same size", async () => {
+ const still = await sharp({ create: { width: 320, height: 240, channels: 3, background: "#2050a0" } }).png().toBuffer();
+ const mask = await sharp({ create: { width: 320, height: 240, channels: 3, background: "#fff" } }).png().toBuffer();
+ const depth = await sharp({ create: { width: 160, height: 120, channels: 3, background: "#808080" } }).png().toBuffer();
+ const view = await sharp({ create: { width: 2000, height: 3000, channels: 3, background: "#a03020" } }).png().toBuffer();
+ const viewMask = await sharp({ create: { width: 500, height: 750, channels: 3, background: "#fff" } }).png().toBuffer();
+ const layout = worldcastLayout(["back"]);
+ const keys = [{ t: 0, azimuth: 0, elevation: 0, distance: 1 }, { t: 1, azimuth: -90, elevation: 0, distance: 1 }];
+ const { parts } = await buildCase({ layout, images: [still, view, mask, viewMask, depth], keys });
+ const file = (n: string) => (parts.find((p) => p.name === n) as { data: Uint8Array }).data;
+ expect(ANCHOR_MAX_SIDE).toBe(1344);
+ expect(await sharp(file("anchor_back.png")).metadata()).toMatchObject({ width: 896, height: 1344 });
+ expect(await sharp(file("anchor_back_mask.png")).metadata()).toMatchObject({ width: 896, height: 1344 });
+ }, 60_000);
});
diff --git a/tests/worldcast-worker.test.ts b/tests/worldcast-worker.test.ts
index 18128f1f..e857d6ef 100644
--- a/tests/worldcast-worker.test.ts
+++ b/tests/worldcast-worker.test.ts
@@ -9,7 +9,8 @@ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-worldcast-"));
process.env.FUOBE_DATA_DIR = dir;
type Job = { status: string; progress?: number; error?: string };
-const state: { jobs: Map<string, Job>; health: unknown; healthStatus: number; caseStatus: number; fields: string[]; files: string[]; canceled: string[] } = {
+const state: { jobs: Map<string, Job>; health: unknown; healthStatus: number; caseStatus: number; fields: string[]; files: string[]; canceled: string[]; auth: (string | undefined)[] } = {
+ auth: [],
jobs: new Map(),
health: { ok: true, model: "PixCtrol/WorldCast@7ccf2e0", vram_gb: 80, depth: ["depth-pro"] },
healthStatus: 200,
@@ -26,6 +27,7 @@ const server = http.createServer((req, res) => {
res.end(JSON.stringify(body));
};
const url = req.url ?? "";
+ state.auth.push(req.headers.authorization);
if (req.method === "GET" && url === "/health") return send(state.healthStatus, state.health);
if (req.method === "POST" && url === "/cases") {
const chunks: Buffer[] = [];
@@ -81,6 +83,7 @@ afterAll(async () => {
});
beforeEach(() => {
+ state.auth = [];
state.jobs.clear();
state.healthStatus = 200;
state.caseStatus = 200;
@@ -170,6 +173,25 @@ describe("the WorldCast worker's client", () => {
expect(await worldcastProvider.prepareFile(Buffer.from("x"), "image/png", "a.png")).toBe("data:image/png;base64,eA==");
});
+ it("sends the worker's token on every call and on the clip's download when one is set, and nothing without one", async () => {
+ state.jobs.set("job1", { status: "succeeded" });
+ const ctx = { externalId: "job1", meta: {}, route: { op: "camera-path", provider: "worldcast", endpoint: "cases" }, model: {} as never, createdAt: 0 } as const;
+ await wc.jobStatus("job1");
+ expect(state.auth).toEqual([undefined]);
+ process.env.WORLDCAST_TOKEN = "s3cret";
+ try {
+ await wc.worldcastHealth();
+ await wc.submitCase(parts());
+ await wc.jobStatus("job1");
+ await wc.cancelJob("job1");
+ state.jobs.set("job1", { status: "succeeded" });
+ expect(state.auth.slice(1)).toEqual(["Bearer s3cret", "Bearer s3cret", "Bearer s3cret", "Bearer s3cret"]);
+ expect(await worldcastProvider.poll(ctx as never)).toMatchObject({ state: "succeeded", outputs: [{ headers: { Authorization: "Bearer s3cret" } }] });
+ } finally {
+ delete process.env.WORLDCAST_TOKEN;
+ }
+ });
+
it("runs the paper's depth model as a job when asked, and hands its picture on", async () => {
const route = { op: "edit", provider: "worldcast", endpoint: "depth/depth-pro" } as const;
const sub = await worldcastProvider.submit({ generationId: "g", model: {} as never, route: route as never, input: { images: ["data:image/png;base64,eA=="] } as never });
diff --git a/workers/worldcast/README.md b/workers/worldcast/README.md
index 4ccc8755..fc0c7d96 100644
--- a/workers/worldcast/README.md
+++ b/workers/worldcast/README.md
@@ -64,8 +64,10 @@ It loads the weights in the background: `GET /health` answers `"ok": false` unti
in Fuobe, in **Settings → Open-source engine → WorldCast worker URL** (or `WORLDCAST_URL=http://127.0.0.1:8190`), and
press **Save & test**.
-Listen on `127.0.0.1` when Fuobe runs on the same machine. The worker has no login: if Fuobe runs elsewhere, put it
-behind a tunnel or a proxy that only Fuobe's server can reach.
+Listen on `127.0.0.1` (the default) when Fuobe runs on the same machine. If Fuobe runs elsewhere, never leave the worker
+open: set `WORLDCAST_TOKEN` to a long random secret here and the same value as `WORLDCAST_TOKEN` in Fuobe's environment
+(Fuobe sends it as `Authorization: Bearer …` on every call, and the worker answers 401 without it), and put it behind a
+tunnel or a proxy that only Fuobe's server can reach. The server warns when it listens beyond this machine without a token.
| Variable | Default |
|---|---|
@@ -75,6 +77,7 @@ behind a tunnel or a proxy that only Fuobe's server can reach.
| `WORLDCAST_BASE_DIT` | `$WORLDCAST_REPO/checkpoints/base_dit.safetensors` |
| `WORLDCAST_WORK_DIR` | `$WORLDCAST_REPO/fuobe_jobs` (the 50 latest jobs are kept) |
| `WORLDCAST_DEPTH_PRO` | `$WORLDCAST_REPO/checkpoints/depth_pro.pt` |
+| `WORLDCAST_TOKEN` | none: no token asked (keep it on `127.0.0.1` then) |
## Optional: the paper's depth model
diff --git a/workers/worldcast/server.py b/workers/worldcast/server.py
index 8049a4ff..1862266f 100644
--- a/workers/worldcast/server.py
+++ b/workers/worldcast/server.py
@@ -13,6 +13,7 @@ Run it from WorldCast's own clone, in WorldCast's own virtualenv (README.md besi
Nothing here is Fuobe's code at run time: Fuobe only talks to it over HTTP.
"""
import argparse
+import hmac
import io
import json
import os
@@ -38,6 +39,8 @@ DEPTH_PRO_CKPT = os.environ.get("WORLDCAST_DEPTH_PRO", os.path.join(REPO, "check
MODEL_NAME = "PixCtrol/WorldCast@7ccf2e0"
KEEP_JOBS = 50
MAX_UPLOAD = 512 * 2**20
+# A shared secret: when set, every call needs "Authorization: Bearer <token>" (Fuobe sends its WORLDCAST_TOKEN setting).
+TOKEN = os.environ.get("WORLDCAST_TOKEN", "").strip()
VIEWS = ("front", "left_side", "right_side", "back")
FRAMES, FPS, WIDTH, HEIGHT = 81, 15, 480, 832
@@ -304,7 +307,11 @@ def find(jid: str) -> dict:
async def read_form(request: Request):
- if int(request.headers.get("content-length") or 0) > MAX_UPLOAD:
+ # A body without a length (chunked) is refused, so the cap can't be skipped; uvicorn holds a body to its stated length.
+ length = request.headers.get("content-length")
+ if length is None or not length.isdigit():
+ raise HTTPException(411, "send the case with a Content-Length")
+ if int(length) > MAX_UPLOAD:
raise HTTPException(413, "the case is too big")
form = await request.form()
out = {}
@@ -322,6 +329,15 @@ async def http_error(_req, e: HTTPException):
return JSONResponse({"error": str(e.detail)}, status_code=e.status_code)
+async def check_token(request: Request, call_next):
+ if TOKEN:
+ sent = request.headers.get("authorization", "")
+ if not hmac.compare_digest(sent.encode(), f"Bearer {TOKEN}".encode()):
+ return JSONResponse({"error": "this worker needs its token (WORLDCAST_TOKEN)"}, status_code=401)
+ return await call_next(request)
+
+
@app.get("/health")
def health():
vram = None
@@ -425,6 +441,8 @@ def main():
p.add_argument("--host", default="127.0.0.1")
p.add_argument("--port", type=int, default=8190)
args = p.parse_args()
+ if args.host not in ("127.0.0.1", "localhost", "::1") and not TOKEN:
+ print("Warning: listening beyond this machine without WORLDCAST_TOKEN: anyone who reaches it can queue jobs on this GPU", flush=True)
os.makedirs(WORK, exist_ok=True)
threading.Thread(target=load_in_background, daemon=True).start()
threading.Thread(target=runner, daemon=True).start()