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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Worker: never run InstantHMR's live capture node, and refuse its routes
Adarsh290634ae382c
diff --git a/bin/lib/worker/checks.mjs b/bin/lib/worker/checks.mjsindex 0b020555..bfdabcaf 100644--- a/bin/lib/worker/checks.mjs+++ b/bin/lib/worker/checks.mjs@@ -13,10 +13,18 @@ import { inputProblem, verifiedIndex } from "./rules.mjs";const here = path.dirname(fileURLToPath(import.meta.url));-export function allowedNodes(extraFile) {- const built = JSON.parse(fs.readFileSync(path.join(here, "dist", "allowed-nodes.json"), "utf8")).nodes;+/**+ * Node types this worker never runs, whatever the allowlist or the PC owner's file says (the build leaves them out too:+ * scripts/lib/worker-catalog.mjs). InstantHMRLiveCapture: ComfyUI-InstantHMR's live capture, which reads recordings and+ * 3D files from the input folder and goes with a websocket that writes files and can send UDP. The pack the worker+ * installs doesn't register it; this refuses it again if a full copy loads (comfy_guard.py blocks its routes).+ */+export const DENIED_NODES = new Set(["InstantHMRLiveCapture"]);++export function allowedNodes(extraFile, builtFile = path.join(here, "dist", "allowed-nodes.json")) {+ const built = JSON.parse(fs.readFileSync(builtFile, "utf8")).nodes;const extra = extraFile ? JSON.parse(fs.readFileSync(extraFile, "utf8")) : [];- return new Set([...built, ...(Array.isArray(extra) ? extra : (extra.nodes ?? []))]);+ return new Set([...built, ...(Array.isArray(extra) ? extra : (extra.nodes ?? []))].filter((c) => !DENIED_NODES.has(c)));}/** The input rules built into this worker. Throws when they aren't built: the worker never runs without them. */@@ -33,7 +41,7 @@ export function inputRules(file = path.join(here, "dist", "input-rules.json")) {*/export function graphCheck(graph, allowed, verified, o = {}) {for (const [id, node] of Object.entries(graph ?? {})) {- if (!node || typeof node.class_type !== "string" || !allowed.has(node.class_type)) return { reason: "unknown-node", node: id, cls: typeof node?.class_type === "string" ? node.class_type : null, input: null };+ if (!node || typeof node.class_type !== "string" || DENIED_NODES.has(node.class_type) || !allowed.has(node.class_type)) return { reason: "unknown-node", node: id, cls: typeof node?.class_type === "string" ? node.class_type : null, input: null };}const ctx = { rules: o.rules ?? null, staged: o.staged ?? [], byName: verifiedIndex(verified) };let unverified = null;diff --git a/bin/lib/worker/comfy_guard.py b/bin/lib/worker/comfy_guard.pyindex 675282d5..b1f5fb84 100644--- a/bin/lib/worker/comfy_guard.py+++ b/bin/lib/worker/comfy_guard.py@@ -10,6 +10,9 @@ answers 403 to any request whose Host is not exactly 127.0.0.1:<port>, or that dX-Fuobe-Worker-Key. A web page that points its own name at 127.0.0.1 (DNS rebinding) sends neither, so it reachesnothing.+Some routes answer 403 to every request, with the key or without (BLOCKED_ROUTES): routes a node pack can add that the+worker never uses, refused under ComfyUI's /api prefix too.+One request needs no key: GET /fuobe-worker/hello with X-Fuobe-Worker-Challenge (16 to 128 hex digits). The answer isthe challenge signed with the key (HMAC-SHA-256), this process's id and its parent's (a venv's python.exe on Windowsstarts the real Python as a child of its own). The worker checks both before it sends the key, so a program that took@@ -29,12 +32,23 @@ import osimport reimport runpyimport sys+from urllib.parse import unquoteKEY_ENV = "FUOBE_WORKER_GUARD_KEY"KEY_HEADER = "X-Fuobe-Worker-Key"CHALLENGE_HEADER = "X-Fuobe-Worker-Challenge"HELLO_PATH = "/fuobe-worker/hello"CHALLENGE = re.compile(r"^[0-9a-f]{16,128}$")+# Routes no request reaches. ComfyUI-InstantHMR's live capture (/instanthmr/*: a websocket with no login that writes+# recordings and can send UDP) is left out of the pack the worker installs; this refuses it again if a full copy loads.+BLOCKED_ROUTES = ("/instanthmr",)+++def blocked(path: str) -> bool:+ """The path is a blocked route or under one, also under /api (ComfyUI serves every route there too), in any case+ and with any doubled slash or "." step."""+ p = "/" + "/".join(s for s in unquote(path.split("?", 1)[0]).replace("\\", "/").split("/") if s not in ("", ".")).lower()+ return any(p == b or p.startswith(b + "/") for r in BLOCKED_ROUTES for b in (r, "/api" + r))def _bytes(text: str) -> bytes:@@ -58,6 +72,8 @@ def make_middleware(web, key: str, host: str):async def fuobe_worker_guard(request, handler):if request.headers.get("Host", "") != host:return web.Response(status=403)+ if blocked(request.path) or blocked(request.raw_path):+ return web.Response(status=403)if request.method == "GET" and request.path == HELLO_PATH and KEY_HEADER not in request.headers:challenge = request.headers.get(CHALLENGE_HEADER, "")if not CHALLENGE.match(challenge):diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex c696108d..766806ad 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -240,6 +240,9 @@ ComfyUI:rebinding) sends its own name, so it is refused.- The request must carry the key in `X-Fuobe-Worker-Key`. The worker sends it with every request and with the livesocket. Without it, the answer is 403.+- Some routes are refused with 403 even with the key (`BLOCKED_ROUTES`), under ComfyUI's `/api` prefix too and in+ any spelling: `/instanthmr/*`, the live capture routes of the full ComfyUI-InstantHMR. The pack that workers install+ leaves them out; the guard refuses them again.Before the worker sends the key, the process on the port must prove two things. It signs a random challenge with thekey (`GET /fuobe-worker/hello`, HMAC-SHA-256), and it names its process id and its parent's. One of them must be the@@ -619,6 +622,8 @@ a workflow or a node pack that workers run, follow [Adding a model, a workflow o1. Every node type is on the allowlist that is built into the worker (`bin/lib/worker/dist/allowed-nodes.json`, madeby `scripts/build-worker.mjs` from the catalog's workflows and the graph builders). For your own workflows, passa file with `allowNodesFile` in `worker.json`. The studio can never send a file like that.+ Some node types are never allowed, whatever the allowlist or that file says (`DENIED_NODES` in+ `bin/lib/worker/checks.mjs`): `InstantHMRLiveCapture`.2. Every file that the graph reads was sent with the job, under the name the studio gave it.3. Every input keeps to its rule (`bin/lib/worker/dist/input-rules.json`). The build gives a rule to each input thatcould name a file, a folder, a download or code, from the values in the catalog's own workflows:diff --git a/scripts/lib/worker-catalog.mjs b/scripts/lib/worker-catalog.mjsindex eb15939e..cf40fc33 100644--- a/scripts/lib/worker-catalog.mjs+++ b/scripts/lib/worker-catalog.mjs@@ -9,6 +9,7 @@import fs from "node:fs";import path from "node:path";import { jsonStrings, loaderInput, MODEL_EXT, pathNamed, TEXT_NAME, textPathProblem, valueProblem } from "../../bin/lib/worker/rules.mjs";+import { DENIED_NODES } from "../../bin/lib/worker/checks.mjs";import { builderSources } from "../../bin/lib/worker/stamp.mjs";const SKIP = new Set(["requirements.json", "manifest.json", "model-pins.json", "first-run-files.json"]);@@ -41,7 +42,8 @@ const nodesOf = (graph) => Object.entries(graph ?? {}).filter(([, n]) => n && ty/*** The node allowlist: the catalog's node types, the ones the graph builders add (builderSources: they add nodes of- * their own, such as LoRA loaders, joins and overlays), and the LoRA loaders.+ * their own, such as LoRA loaders, joins and overlays), and the LoRA loaders. Never a node the worker denies+ * (DENIED_NODES in bin/lib/worker/checks.mjs).*/export function allowedNodeList(root, catalog = readCatalog(root)) {const nodes = new Set();@@ -52,7 +54,7 @@ export function allowedNodeList(root, catalog = readCatalog(root)) {for (const g of Object.values(catalog.graphs)) for (const [, n] of nodesOf(g)) nodes.add(n.class_type);for (const file of builderSources(root)) for (const m of fs.readFileSync(file, "utf8").matchAll(/class_type: "([^"]+)"/g)) nodes.add(m[1]);for (const extra of ["LoraLoader", "LoraLoaderModelOnly"]) nodes.add(extra);- return [...nodes].sort();+ return [...nodes].filter((c) => !DENIED_NODES.has(c)).sort();}// ---------------------------------------------------------------------------diff --git a/tests/worker-guard.test.ts b/tests/worker-guard.test.tsindex ffd4f24e..a185902e 100644--- a/tests/worker-guard.test.ts+++ b/tests/worker-guard.test.ts@@ -99,6 +99,11 @@ if __name__ == "__main__":app.router.add_get("/system_stats", stats)app.router.add_get("/env", env)app.router.add_get("/ws", ws)+ # A pack's own routes, as ComfyUI serves them: as the pack names them and again under /api.+ for base in ("", "/api"):+ app.router.add_get(base + "/instanthmr/ws", ws)+ app.router.add_get(base + "/instanthmr", files)+ app.router.add_get(base + "/instanthmr_other", files)app.add_subapp("/internal", internal)web.run_app(app, host=args.listen, port=args.port, print=None)`;@@ -178,6 +183,28 @@ describe.skipIf(!python)("the guard in front of a stand-in ComfyUI (Python)", ()expect(c.headers()[GUARD.key]).not.toBe(oldKey);expect((await raw(c.port!, "/system_stats", { Host: `127.0.0.1:${c.port}`, [GUARD.key]: oldKey })).status).toBe(403);});++ it("refuses the blocked routes (ComfyUI-InstantHMR's live capture) even with the key, in every spelling", async () => {+ const comfyDir = tempDir("fuobe-guard-blocked-comfy-");+ const workDir = tempDir("fuobe-guard-blocked-work-");+ fs.writeFileSync(path.join(comfyDir, "main.py"), STAND_IN_MAIN);+ const c = new OwnComfy({ comfyDir, workDir, python, modelDirs: [] });+ started.push(c);+ await c.start();+ const port = c.port!;+ const host = `127.0.0.1:${port}`;+ const key = { [GUARD.key]: c.headers()[GUARD.key] };+ for (const p of ["/instanthmr", "/instanthmr/ws", "/api/instanthmr/ws", "/api/instanthmr", "/InstantHMR/ws", "/API/InstantHMR/ws", "//instanthmr/ws", "/./instanthmr/ws", "/%69nstanthmr/ws", "/instanthmr/ws?x=1"]) {+ expect((await raw(port, p, { Host: host, ...key })).status, p).toBe(403);+ }+ expect((await c.fetch(`${c.base}/instanthmr/ws`)).status).toBe(403);+ expect(await wsOpens(`ws://${host}/instanthmr/ws`, key)).toBe(false);+ expect(await wsOpens(`ws://${host}/api/instanthmr/ws`, key)).toBe(false);+ // Only that route and what is under it: a route that merely starts with the same letters, and the rest, answer.+ expect((await c.fetch(`${c.base}/instanthmr_other`)).status).toBe(200);+ expect((await c.fetch(`${c.base}/system_stats`)).status).toBe(200);+ expect(await wsOpens(`ws://${host}/ws`, key)).toBe(true);+ });});describe.skipIf(!venv)("the guard started through a venv's Python", () => {diff --git a/tests/worker-input-rules.test.ts b/tests/worker-input-rules.test.tsindex 0ddbc595..d6bd2453 100644--- a/tests/worker-input-rules.test.ts+++ b/tests/worker-input-rules.test.ts@@ -1,6 +1,7 @@+import fs from "node:fs";import path from "node:path";import { describe, expect, it } from "vitest";-import { graphCheck, vetGraph } from "../bin/lib/worker/checks.mjs";+import { allowedNodes, DENIED_NODES, graphCheck, vetGraph } from "../bin/lib/worker/checks.mjs";import { inputProblem, loaderInput, pathProblem, ruleProblem, textPathProblem, verifiedIndex } from "../bin/lib/worker/rules.mjs";import { allowedNodeList, filePins, inputRules, missingRules, readCatalog, UNPINNED_FILES, unpinnedFiles } from "../scripts/lib/worker-catalog.mjs";import { tempDir } from "./helpers/temp-dir";@@ -433,3 +434,44 @@ describe("graphs as the studio builds them", () => {expect(prepared).toBe(runs.length);}, 120_000);});++describe("nodes the worker denies", () => {+ // ComfyUI-InstantHMR's live capture: the pack the worker installs doesn't register it; refused again whatever a list says.+ const live = {+ class_type: "InstantHMRLiveCapture",+ inputs: { recording: "instanthmr_live/a.mp4", model: "instanthmr_medium.safetensors", detector: "rt_detr_v4-x-hgnet_fp16.safetensors", camera: "This device", character: "MHR body", vmc: "127.0.0.1:39539" },+ };++ it("are never on the built allowlist, though a catalog workflow named one", () => {+ expect(DENIED_NODES.has("InstantHMRLiveCapture")).toBe(true);+ expect(allowed.has("InstantHMRLiveCapture")).toBe(false);+ // Body Double's own InstantHMR nodes stay allowed.+ expect(allowed.has("InstantHMRLoader")).toBe(true);+ expect(allowed.has("InstantHMRPredict")).toBe(true);+ const named = {+ ...catalog,+ requirements: { ...catalog.requirements, workflows: { live: { core: ["SaveVideo"], packs: { "ComfyUI-InstantHMR": ["InstantHMRLoader", "InstantHMRLiveCapture"] } } } },+ graphs: { "live.json": { "1": live } },+ };+ const list = allowedNodeList(root, named as unknown as Parameters<typeof allowedNodeList>[1]);+ expect(list).toContain("InstantHMRLoader");+ expect(list).not.toContain("InstantHMRLiveCapture");+ });++ it("are left out of the PC owner's own list too", () => {+ const dir = tempDir("fuobe-worker-denied-");+ const built = path.join(dir, "allowed-nodes.json");+ const extra = path.join(dir, "allow-nodes.json");+ fs.writeFileSync(built, JSON.stringify({ nodes: ["LoadImage", "InstantHMRLiveCapture"] }));+ fs.writeFileSync(extra, JSON.stringify({ nodes: ["InstantHMRLiveCapture", "MyOwnNode"] }));+ expect([...allowedNodes(extra, built)].sort()).toEqual(["LoadImage", "MyOwnNode"]);+ fs.writeFileSync(extra, JSON.stringify(["InstantHMRLiveCapture"]));+ expect([...allowedNodes(extra, built)]).toEqual(["LoadImage"]);+ });++ it("refuse a graph with one, even when the set it is checked against holds it", () => {+ const withLive = new Set([...allowed, "InstantHMRLiveCapture"]);+ expect(graphCheck({ "1": live }, withLive, verified, { rules, staged: SENT })).toMatchObject({ reason: "unknown-node", node: "1", cls: "InstantHMRLiveCapture" });+ expect(vetGraph({ "1": live }, allowed, verified, { rules, staged: SENT })).toBe("unknown-node");+ });+});