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
Fuobe Connect: every node ComfyUI runs is one it validates, and a 3D view holds only numbers
Adarshfcc0b906a22c
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 47af7268..e16fc0c1 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -40,7 +40,15 @@ Connect checks each request it lets through in Python, whatever the studio's pag`true`, `false`, a number with a point or `-1` as an output; the pack sees those as links too, and refuses them;- `VHS_VideoCombine` takes only a plain format name and plain-word settings (they go into ffmpeg's arguments), anda link only for its pictures, sound, batch, VAE and frame rate;- - every loader reads a Fuobe input (`fuobe_<id>.<ext>`), and no node gets a JSON object except a 3D view's entries;+ - every loader reads a Fuobe input (`fuobe_<id>.<ext>`). A written value is a text, a number, `true`, `false` or+ `null`: never a list (ComfyUI reads one as a link) and never a JSON object, except a 3D view's entries in the exact+ form of ComfyUI's 3D nodes (the camera and the models' placements are numbers only). No object holds `"__value__"`+ at any depth (ComfyUI unwraps it, so a link inside would skip ComfyUI's check), and a node holds only `class_type`,+ `inputs` and `_meta` (ComfyUI reads `is_changed`, `_loop_body` and `_loop_end` as its own);+ - inside ComfyUI, every node that ComfyUI runs is one it checks first: a link goes only into an input the node lists+ (worked out the way ComfyUI does it for dynamic inputs), no input names a hidden one, a node type ComfyUI would swap+ before its check is refused, and a graph with a loop holds only nodes that lead to an output. A 3D node's camera and+ placements in a run's history never count as one of its files;- an upload goes only into the input folder, under a Fuobe input name, as a picture, clip, sound, 3D scene, array orsubtitle file (never `.json`, `.txt`, `.csv` or a file of no known type);- the studio sees, cancels, stops and downloads only its own prompts and their results; a prompt is its own only oncediff --git a/integrations/fuobe-connect/README.md b/integrations/fuobe-connect/README.mdindex 579a44ef..c571c829 100644--- a/integrations/fuobe-connect/README.md+++ b/integrations/fuobe-connect/README.md@@ -66,7 +66,17 @@ Its page can:Fuobe Connect sees each of these as a link, and refuses it;- `VHS_VideoCombine` puts its format's settings into ffmpeg's arguments, so each setting must be one plain word(`yuv420p`, `hq`), and it takes a link only for its pictures, sound, batch, VAE and frame rate;- - the workflow may not give a node a JSON object (ComfyUI passes one on unchecked), except a 3D view's entries.+ - a value written in the workflow is one plain thing: a text, a number, `true`, `false` or `null`. Never a list+ (ComfyUI reads a list as a link) and never a JSON object (ComfyUI passes one on unchecked), except a 3D view's+ entries, which must have the exact form of ComfyUI's own 3D nodes: the camera and the models' placements are+ numbers only. No object anywhere may hold a `"__value__"` key: ComfyUI takes the value out of one, so a link+ inside it would run a node that ComfyUI never checked;+ - a node holds only its type, its inputs and its title. ComfyUI reads other keys as its own (`is_changed`,+ `_loop_body`, `_loop_end`);+ - every node that ComfyUI runs must be one that ComfyUI checks first. A link goes only into an input that the node+ lists (ComfyUI runs a node linked from any other input name but never checks it), no input may name one of the+ node's hidden inputs, a node type that ComfyUI would swap for another before it checks the workflow is refused, and+ a workflow with a loop (`StartLoop`, `EndLoop`) may hold only nodes that lead to one of its outputs.A workflow that uses an installed node from the list can still do what that node does in ComfyUI's own folders: forexample, save into your output folder, or keep a node pack's own cache. These checks follow what the listed nodes dodiff --git a/integrations/fuobe-connect/fuobe_connect/graph.py b/integrations/fuobe-connect/fuobe_connect/graph.pyindex c51d3e3f..497189ab 100644--- a/integrations/fuobe-connect/fuobe_connect/graph.py+++ b/integrations/fuobe-connect/fuobe_connect/graph.py@@ -19,15 +19,33 @@ A graph from a studio (a trusted page in direct mode, or the paired studio in pavalue another node works out would reach a dropdown, or any other input, unchecked;- a node that puts its inputs into a program's arguments (ARG_NODES: VHS_VideoCombine and ffmpeg) takes a link onlyinto its media inputs, and its other text only as one plain word;-- a value the graph writes is never a JSON object, except a 3D view's entries: ComfyUI hands an object to a node- unchecked, and some nodes read a file's path from one;+- a value the graph writes is one plain thing: a text, a number (never NaN or infinity), true, false or null. Never a+ list: ComfyUI reads a list as a link. Never a JSON object: ComfyUI hands an object to a node unchecked, and some nodes+ read a file's path from one. The one exception is a 3D view's entries (OBJECT_INPUTS), each in the exact form+ ComfyUI's own 3D nodes use: numbers for the camera and the models' placements, nothing else;+- no object anywhere holds a "__value__" key, at any depth: ComfyUI's validate_inputs takes the value out of+ {"__value__": x} in place, so {"__value__": ["4", 0]} becomes a link to a node it never validated;+- a node holds only "class_type", "inputs" and "_meta" (its title). ComfyUI reads other keys as its own state:+ "is_changed" stands in for the node's IS_CHANGED, and Start Loop reads "_loop_body" and "_loop_end";- a link names its node's output with a whole number from 0 (["4", 0]). ComfyUI also takes true, false, a number witha point (0.0) or -1 as an output. is_link here sees every link that ComfyUI sees, and a link in any of those formsis refused;- a few inputs take only a link from one node type, or text of one shape (LINK_INPUTS, TEXT_INPUTS).-A result is downloaded only when this run's own history lists it. A model name the graph writes is checked by ComfyUI-itself, against the files in your model folders.+Inside ComfyUI, where the node classes can say what they take (NodeKinds), also:++- a link goes only into an input that ComfyUI validates on that node: one the node lists as required or optional (a v3+ node's dynamic inputs worked out from the node's own values, the way validate_inputs does it). ComfyUI runs a node+ linked from any other input name but never validates it;+- no input names one of the node's hidden inputs: ComfyUI hands some of those to the node as written, unchecked;+- a node type that isn't installed but that ComfyUI would swap for another (its node replacements) is refused: the swap+ happens after this check, with other inputs;+- a graph with a loop (Start Loop, End Loop) has only nodes ComfyUI validates (each one reached from an output node):+ the loop runs nodes downstream of an output, and its body, without validating them.++A result is downloaded only when this run's own history lists it (never from what a 3D node echoes there as data: its+camera and the models' placements). A model name the graph writes is checked by ComfyUI itself, against the files in+your model folders.Pure, so the tests run it alone."""@@ -35,8 +53,10 @@ Pure, so the tests run it alone.from __future__ import annotationsimport json+import mathimport osimport re+import sys# The names Fuobe gives the files it sends (src/server/computer/tasks.ts stageInput).INPUT_NAME = re.compile(r"^fuobe_[A-Za-z0-9_-]{8,24}\.[a-z0-9]{1,5}$")@@ -188,8 +208,112 @@ TEXT_INPUTS: dict[str, dict] = {"StringFormat": {"f_string": lambda s: not _FIELD_ACCESS.search(s)},}-# The only inputs that take a JSON object the graph writes: a 3D view's entries (Load3D's are checked below).-OBJECT_INPUTS = frozenset({("Load3D", "image"), ("Save3DAdvanced", "viewport_state")})+# ---------------------------------------------------------------------------+# The objects a graph may write: a 3D view's entries+#+# ComfyUI hands an object to a node unchecked. Load3D reads its picture entries as files (checked in graph_problem) and+# passes the camera and the models' placements on; Save3DAdvanced reads only those two and shows both in the run's+# history (Saved3DModels). So each takes exactly the form of ComfyUI's own Load3DCamera.CameraInfo and+# Load3DModelInfo.Model3DTransform (comfy_api/latest/_io.py): numbers, no other key.+++def _number(x) -> bool:+ return type(x) in (int, float) and math.isfinite(x)+++def _vector(v, names: tuple) -> bool:+ """{"x": 1, "y": 2, "z": 3} (or a list of as many numbers): numbers only, under these names only."""+ if isinstance(v, dict):+ return len(v) <= len(names) and all(k in names and _number(x) for k, x in v.items())+ return isinstance(v, list) and len(v) <= len(names) and all(_number(x) for x in v)+++_XYZ = ("x", "y", "z")+_XYZW = ("x", "y", "z", "w")+_CAMERA_NUMBERS = frozenset({"zoom", "fov", "aspect", "near", "far"})+_CAMERA_VECTORS = {"position": _XYZ, "target": _XYZ, "quaternion": _XYZW, "frustum": ("left", "right", "top", "bottom")}+_PLACEMENT = {"position": _XYZ, "quaternion": _XYZW, "scale": _XYZ}+# Load3D's picture entries: files it opens (each one of this run's inputs, or "").+_VIEW_FILES = frozenset({"image", "mask", "normal", "recording"})+++def camera_ok(v) -> bool:+ """A camera as ComfyUI's 3D nodes write it, or null."""+ if v is None:+ return True+ if not isinstance(v, dict) or len(v) > 12:+ return False+ for k, x in v.items():+ if k in _CAMERA_NUMBERS:+ ok = _number(x)+ elif k in _CAMERA_VECTORS:+ ok = _vector(x, _CAMERA_VECTORS[k])+ elif k == "cameraType":+ ok = x in ("perspective", "orthographic")+ elif k == "useCustomUp":+ ok = isinstance(x, bool)+ else:+ ok = False+ if not ok:+ return False+ return True+++def placements_ok(v) -> bool:+ """The models' placements: a short list of {position, quaternion, scale}, numbers only."""+ return isinstance(v, list) and len(v) <= 64 and all(isinstance(p, dict) and all(k in _PLACEMENT and _vector(x, _PLACEMENT[k]) for k, x in p.items()) for p in v)+++def _view_ok(v, files) -> bool:+ if not isinstance(v, dict):+ return False+ for k, x in v.items():+ if k in _VIEW_FILES:+ ok = files(x)+ elif k == "camera_info":+ ok = camera_ok(x)+ elif k == "model_3d_info":+ ok = placements_ok(x)+ else:+ ok = False+ if not ok:+ return False+ return True+++# The only inputs that take a JSON object the graph writes, each with its one form. Load3D's picture entries are texts+# (graph_problem checks each names one of this run's inputs); Save3DAdvanced reads none of them, so they stay empty.+OBJECT_INPUTS = {+ ("Load3D", "image"): lambda v: _view_ok(v, lambda x: isinstance(x, str)),+ ("Save3DAdvanced", "viewport_state"): lambda v: _view_ok(v, lambda x: x == ""),+}++# The keys a node may hold. ComfyUI reads others as its own state: "is_changed" stands in for the node's own IS_CHANGED+# (execution.py IsChangedCache), and Start Loop reads "_loop_body" and "_loop_end" (comfy_extras/nodes_loop.py).+NODE_KEYS = frozenset({"class_type", "inputs", "_meta"})+++def node_keys_ok(node: dict) -> bool:+ """Only the keys above, and a title (with the pack's name and version, as ComfyUI's page writes them) as _meta."""+ if not set(node) <= NODE_KEYS:+ return False+ meta = node.get("_meta")+ return meta is None or (isinstance(meta, dict) and len(meta) <= 8 and all(isinstance(k, str) and isinstance(x, str) and len(x) <= 1024 for k, x in meta.items()))+++def has_value_key(v) -> bool:+ """An object, at any depth, with a "__value__" key: ComfyUI's validate_inputs takes the value out of it in place, so+ a list inside one becomes a link to a node it never validated."""+ stack = [v]+ while stack:+ x = stack.pop()+ if isinstance(x, dict):+ if "__value__" in x:+ return True+ stack.extend(x.values())+ elif isinstance(x, list):+ stack.extend(x)+ return False# Nodes that take inputs under any name and put the values into a program's arguments. VHS_VideoCombine hands its# format's settings to ffmpeg, one inside a filter (the GIF format's dither), and ComfyUI checks neither their type nor@@ -237,69 +361,242 @@ LOOSE_LINKS: frozenset = frozenset()+# A type no node has: an output type that says it equals this one says it equals every type.+_NO_TYPE = "\x00FUOBE_CONNECT_NO_SUCH_TYPE"++def loose_type(t) -> bool:- """An output type that ComfyUI matches to any input: "*", a match type, a dropdown, a list of options, or a text- type of a node pack's own that says it equals every other type."""- if type(t) is not str:+ """An output type that ComfyUI matches to any input (validate_node_input): one that says it equals every other type+ (`not t != other`: a node pack's own "any", ComfyUI's IO.ANY), "*", a match type, a dropdown, or a list of options.+ ComfyUI's own IO types (IO.CONDITIONING, IO.IMAGE ...) are texts that compare by their names, like any text."""+ if isinstance(t, (list, tuple)):return True- return any(p.strip() in _LOOSE_TYPES for p in t.split(","))+ try:+ if not (t != _NO_TYPE):+ return True+ except Exception:+ return True+ if not isinstance(t, str):+ return False # ComfyUI matches a type that isn't text to no input+ return any(p.strip() in _LOOSE_TYPES for p in str.__str__(t).split(","))def dropdown_spec(spec) -> bool:"""An input spec ComfyUI shows as a dropdown: a list of options, COMBO, or a dynamic dropdown."""t = spec[0] if isinstance(spec, (list, tuple)) and spec else spec- return isinstance(t, (list, tuple)) or (isinstance(t, str) and t in _DROPDOWN_TYPES)+ return isinstance(t, (list, tuple)) or (isinstance(t, str) and str.__str__(t) in _DROPDOWN_TYPES)+++def _input_names(inputs) -> frozenset:+ """The inputs ComfyUI's validate_inputs goes through on a node: its required and optional ones (only the names the+ dicts hold: a node pack's dict that claims to hold every name still lists only its own)."""+ inputs = inputs if isinstance(inputs, dict) else {}+ return frozenset(inputs.get("required") or {}) | frozenset(inputs.get("optional") or {})+++_MISSING = {"found": False}class NodeKinds:- """What the node classes themselves say, inside ComfyUI: which outputs ComfyUI doesn't type-check and which inputs- are dropdowns. It covers every node, your own listed ones too. `lookup(class_type)` gives (INPUT_TYPES(),- RETURN_TYPES) or None. A node's kinds are read once (a class that fails to say is asked again next time: ComfyUI- refuses a graph with it anyway)."""+ """What the node classes themselves say, inside ComfyUI: which outputs ComfyUI doesn't type-check, which inputs are+ dropdowns, which inputs ComfyUI validates, which are hidden, which nodes are outputs and which are loop boundaries.+ It covers every node, your own listed ones too.++ `lookup(class_type)` gives (INPUT_TYPES(), RETURN_TYPES) or None (no such node type), optionally with a third item:+ {"output": OUTPUT_NODE, "loop": a loop boundary, "dynamic": a node whose inputs depend on its values}.+ `checked(class_type, inputs)`: the input names ComfyUI validates on one node of a dynamic type, worked out the way+ validate_inputs does it (else the names INPUT_TYPES lists). `replaced(class_type)`: ComfyUI would swap this missing+ node type for another before validating (its node replacements).- def __init__(self, lookup):+ A node's kinds are read once. A class that fails to say is asked again next time (ComfyUI refuses a graph with it+ anyway), and so is one that isn't there (a node pack could still load it)."""++ def __init__(self, lookup, checked=None, replaced=None):self._lookup = lookup- self._seen: dict[str, tuple] = {}+ self._checked = checked+ self._replaced = replaced+ self._seen: dict[str, dict] = {}++ def _kinds(self, cls: str) -> dict | None:+ """The class's kinds; _MISSING when there is no such class; None when it couldn't say."""+ if cls in self._seen:+ return self._seen[cls]+ try:+ found = self._lookup(cls)+ except Exception:+ return None+ if found is None:+ return _MISSING+ inputs, outputs = found[0], found[1]+ about = found[2] if len(found) > 2 and isinstance(found[2], dict) else {}+ rec: dict = {"found": True, "loose": frozenset(), "drops": frozenset(), "names": None, "hidden": frozenset()}+ try:+ rec["loose"] = frozenset(i for i, t in enumerate(outputs or ()) if loose_type(t))+ except Exception:+ rec["loose"] = frozenset(range(64))+ try:+ rec["drops"] = frozenset(k for part in ("required", "optional") for k, spec in dict((inputs or {}).get(part) or {}).items() if dropdown_spec(spec))+ except Exception:+ pass+ try:+ rec["names"] = _input_names(inputs)+ except Exception:+ pass+ try:+ rec["hidden"] = frozenset((inputs or {}).get("hidden") or {})+ except Exception:+ rec["names"] = None # its hidden inputs are unknown, so no input of it can be checked+ rec["output"] = about.get("output") is True+ rec["loop"] = bool(about.get("loop"))+ rec["dynamic"] = bool(about.get("dynamic"))+ self._seen[cls] = rec+ return rec++ def loose(self, cls: str, slot: int) -> bool:+ rec = self._kinds(cls)+ return slot in rec["loose"] if rec and rec["found"] else False- def _kinds(self, cls: str) -> tuple:- if cls not in self._seen:- loose, drops = frozenset(), frozenset()+ def dropdown(self, cls: str, key: str) -> bool:+ rec = self._kinds(cls)+ return key in rec["drops"] if rec and rec["found"] else False++ def found(self, cls: str) -> bool | None:+ """True: ComfyUI has this node type. False: it hasn't. None: the class couldn't say."""+ rec = self._kinds(cls)+ return None if rec is None else rec["found"]++ def checked(self, cls: str, inputs: dict) -> frozenset | None:+ """The input names ComfyUI validates on this node; None when that can't be known (the graph is refused)."""+ rec = self._kinds(cls)+ if not rec or not rec["found"]:+ return None+ if rec["dynamic"] and self._checked is not None:try:- found = self._lookup(cls)+ names = self._checked(cls, inputs)except Exception:- return loose, drops- if found is not None:- inputs, outputs = found- try:- loose = frozenset(i for i, t in enumerate(outputs or ()) if loose_type(t))- except Exception:- loose = frozenset(range(64))- try:- drops = frozenset(- k for part in ("required", "optional") for k, spec in dict((inputs or {}).get(part) or {}).items() if dropdown_spec(spec)- )- except Exception:- drops = frozenset()- self._seen[cls] = (loose, drops)- return self._seen[cls]+ return None+ return None if names is None else frozenset(names)+ return rec["names"]++ def hidden(self, cls: str) -> frozenset:+ rec = self._kinds(cls)+ return rec["hidden"] if rec and rec["found"] else frozenset()++ def output(self, cls: str) -> bool:+ rec = self._kinds(cls)+ return bool(rec and rec["found"] and rec["output"])++ def loop(self, cls: str) -> bool:+ rec = self._kinds(cls)+ return bool(rec and rec["found"] and rec["loop"])++ def replaced(self, cls: str) -> bool:+ """ComfyUI would swap this node type for another before validating. When that can't be known: yes."""+ if self._replaced is None:+ return False+ try:+ return bool(self._replaced(cls))+ except Exception:+ return True- def loose(self, cls: str, slot: int) -> bool:- return slot in self._kinds(cls)[0]- def dropdown(self, cls: str, key: str) -> bool:- return key in self._kinds(cls)[1]+def _comfy_replacements():+ """ComfyUI's node replacement manager (server.PromptServer.instance.node_replace_manager), when there is one."""+ prompt_server = getattr(sys.modules.get("server"), "PromptServer", None)+ return getattr(getattr(prompt_server, "instance", None), "node_replace_manager", None)-def comfy_kinds(mappings) -> NodeKinds:- """NodeKinds from ComfyUI's NODE_CLASS_MAPPINGS (a callable that returns it, read at each new node type)."""+def comfy_kinds(mappings, replacements=None) -> NodeKinds:+ """NodeKinds from ComfyUI's NODE_CLASS_MAPPINGS (a callable that returns it, read at each new node type), with the+ inputs ComfyUI validates worked out by ComfyUI's own code. `replacements`: a callable that returns ComfyUI's node+ replacement manager (default: the running server's)."""++ def v3(klass) -> bool:+ try:+ from comfy_api.internal import _ComfyNodeInternal+ except Exception:+ return False+ try:+ return issubclass(klass, _ComfyNodeInternal)+ except TypeError:+ return Falsedef lookup(cls):klass = mappings().get(cls)if klass is None:return None- return klass.INPUT_TYPES(), getattr(klass, "RETURN_TYPES", ())+ about = {"output": getattr(klass, "OUTPUT_NODE", False) is True, "dynamic": v3(klass)}+ if about["dynamic"]:+ # As validate_prompt reads it: GET_SCHEMA().loop_boundary is "start" or "end".+ try:+ about["loop"] = getattr(klass.GET_SCHEMA(), "loop_boundary", None) in ("start", "end")+ except Exception:+ about["loop"] = False+ return klass.INPUT_TYPES(), getattr(klass, "RETURN_TYPES", ()), about++ def checked(cls, inputs):+ # validate_inputs: INPUT_TYPES(), then for a v3 node get_finalized_class_inputs(class_inputs, inputs), then+ # set(required) | set(optional).+ klass = mappings().get(cls)+ if klass is None:+ return None+ class_inputs = klass.INPUT_TYPES()+ if v3(klass):+ from comfy_api.latest import _io- return NodeKinds(lookup)+ class_inputs = _io.get_finalized_class_inputs(class_inputs, inputs)[0]+ return _input_names(class_inputs)++ def replaced(cls):+ manager = replacements() if replacements is not None else _comfy_replacements()+ has = getattr(manager, "has_replacement", None)+ return bool(has(cls)) if callable(has) else False++ return NodeKinds(lookup, checked, replaced)+++def kinds_problem(graph: dict, kinds: NodeKinds) -> str | None:+ """What ComfyUI itself would run without validating, inside ComfyUI: 'unknown-node', 'unsafe-graph', or None.++ validate_prompt validates from the output nodes, through the inputs each node lists (validate_inputs). The+ scheduler (TopologicalSort.add_node) follows a link in any input of a node. So a link in an input the node doesn't+ list (or a hidden one) runs the node it names unvalidated. A loop (validate_loops, Start Loop's expansion) runs+ nodes downstream of an output and its body without validating them."""+ missing = False+ for node in graph.values():+ if kinds.found(node["class_type"]) is False:+ # ComfyUI swaps a missing node type for another (apply_replacements) after this check, with other inputs.+ if kinds.replaced(node["class_type"]):+ return "unknown-node"+ missing = True+ if missing:+ # validate_prompt refuses the whole graph (missing_node_type) before it validates or runs any node of it, and+ # says which node type is missing.+ return None+ loop = False+ for node in graph.values():+ cls = node["class_type"]+ inputs = node.get("inputs") or {}+ names = kinds.checked(cls, inputs)+ if names is None:+ return "unsafe-graph"+ hidden = kinds.hidden(cls)+ for k, v in inputs.items():+ if k not in names and (is_link(v) or k in hidden):+ return "unsafe-graph"+ loop = loop or kinds.loop(cls)+ if loop:+ validated: set = set()+ todo = [nid for nid, n in graph.items() if kinds.output(n["class_type"])]+ while todo:+ nid = todo.pop()+ if nid in validated or nid not in graph:+ continue+ validated.add(nid)+ todo.extend(v[0] for v in (graph[nid].get("inputs") or {}).values() if is_link(v))+ if len(validated) < len(graph):+ return "unsafe-graph"+ return Nonedef is_link(v) -> bool:@@ -331,7 +628,14 @@ def link_problem(graph: dict, cls: str, key: str, v, kinds: NodeKinds | None = Ndef input_problem(graph: dict, cls: str, key: str, v, kinds: NodeKinds | None = None) -> str | None:"""What is wrong with one input under its node's own rule: 'unsafe-path', 'unsafe-graph', or None."""- if isinstance(v, dict) and (cls, key) not in OBJECT_INPUTS:+ if isinstance(v, dict):+ shape = OBJECT_INPUTS.get((cls, key))+ return None if shape is not None and shape(v) else "unsafe-graph"+ if isinstance(v, list) and not is_link(v):+ # ComfyUI reads a list as a link: one that isn't [node, output] is never a value a node gets as written.+ return "unsafe-graph"+ if isinstance(v, float) and not math.isfinite(v):+ # NaN passes every min and max ComfyUI checks.return "unsafe-graph"if is_link(v) and not plain_slot(v):return "unsafe-graph"@@ -453,7 +757,7 @@ def graph_problem(graph, staged: list[str] | None) -> str | None:pics = inputs["image"]if isinstance(pics, dict):for f, x in pics.items():- if f == "camera_info" or x in ("", None):+ if f in ("camera_info", "model_3d_info") or x in ("", None):continueif not _staged(x, staged):return f"Node {node_id} ({cls}) reads a file this run didn't send"@@ -465,18 +769,21 @@ def graph_problem(graph, staged: list[str] | None) -> str | None:def vet_graph(graph, allowed: frozenset | set, staged: list[str] | None, kinds: NodeKinds | None = None) -> str | None:"""The first reason this graph may not run here, or None. The reasons are the worker program's('unknown-node', 'unsafe-path') and 'unsafe-graph': a loader that reads a file this run didn't send, a JSON object- the graph writes, or a link from a node that may not feed that input. `kinds`: what ComfyUI's node classes say- (inside ComfyUI); without it, only the shipped list of untyped outputs is known."""+ or a list the graph writes, a key ComfyUI reads as its own, or a link from a node that may not feed that input.+ `kinds`: what ComfyUI's node classes say (inside ComfyUI); without it, only the shipped list of untyped outputs is+ known, and the checks that need the node classes (kinds_problem) are left out."""if not isinstance(graph, dict) or not graph or len(graph) > 5000:return "unsafe-graph"for node in graph.values():if not isinstance(node, dict) or not isinstance(node.get("class_type"), str) or node["class_type"] not in allowed:return "unknown-node"for node in graph.values():+ if not node_keys_ok(node):+ return "unsafe-graph"inputs = node.get("inputs")if inputs is None:continue- if not isinstance(inputs, dict):+ if not isinstance(inputs, dict) or has_value_key(inputs):return "unsafe-graph"for k, v in inputs.items():for s in _strings(v):@@ -485,6 +792,10 @@ def vet_graph(graph, allowed: frozenset | set, staged: list[str] | None, kinds:why = input_problem(graph, node["class_type"], k, v, kinds)if why:return why+ if kinds is not None:+ why = kinds_problem(graph, kinds)+ if why:+ return whyif graph_problem(graph, staged):return "unsafe-graph"return None@@ -507,15 +818,20 @@ def _strings(v, depth: int = 0):# Results+# What ComfyUI's 3D nodes show in a run's history beside their files (Saved3DModels): data the graph wrote, never a file.+UI_DATA = frozenset({"camera_info", "model_3d_info"})++def files_in(entries: list) -> list[dict]:+ """Every file the entries' outputs list."""out = []for e in entries or []:outputs = e.get("outputs") if isinstance(e, dict) else Nonefor ui in (outputs or {}).values() if isinstance(outputs, dict) else []:if not isinstance(ui, dict):continue- for v in ui.values():- if isinstance(v, list):+ for name, v in ui.items():+ if isinstance(v, list) and name not in UI_DATA:for f in v:if isinstance(f, dict) and isinstance(f.get("filename"), str) and isinstance(f.get("type"), str):out.append(f)diff --git a/integrations/fuobe-connect/tests/comfy_engine.py b/integrations/fuobe-connect/tests/comfy_engine.pynew file mode 100644index 00000000..c25f577c--- /dev/null+++ b/integrations/fuobe-connect/tests/comfy_engine.py@@ -0,0 +1,258 @@+"""Each attack on ComfyUI's own code: what ComfyUI does with the graph, and what Fuobe Connect's check says.++Run by test_comfy_engine.py in a process of its own (python -I comfy_engine.py <ComfyUI folder> <pack folder>+<scratch folder> [<Fuobe's workflows folder>]). It imports ComfyUI's execution code from that folder as main.py would+with --cpu --disable-all-custom-nodes --disable-api-nodes, with its input, output, temp and user folders in the scratch+folder: no server starts, no port opens, and nothing in the ComfyUI folder changes. It prints one JSON object.++For each attack, "comfy" is what ComfyUI itself does: whether validate_prompt takes the graph, which nodes+validate_inputs validated, and which nodes run anyway (the scheduler's, a loop's, a node replacement's, the history's).+"vet" is vet_graph's answer with the node classes' own kinds, as inside ComfyUI.+"""++from __future__ import annotations++import asyncio+import copy+import json+import os+import sys++root, pack, scratch = sys.argv[1], sys.argv[2], sys.argv[3]+workflows = sys.argv[4] if len(sys.argv) > 4 else ""+out = sys.stdout+sys.stdout = sys.stderr # ComfyUI's own messages stay out of the answer+sys.argv = ["main.py", "--cpu", "--disable-all-custom-nodes", "--disable-api-nodes"]+sys.path.insert(0, root)+sys.path.insert(0, pack)+sys.path.insert(0, os.path.join(pack, "tests"))+os.chdir(scratch)++import folder_paths # noqa: E402++for sub in ("input", "output", "temp", "user"):+ os.makedirs(os.path.join(scratch, sub), exist_ok=True)+folder_paths.set_input_directory(os.path.join(scratch, "input"))+folder_paths.set_output_directory(os.path.join(scratch, "output"))+folder_paths.set_temp_directory(os.path.join(scratch, "temp"))+folder_paths.set_user_directory(os.path.join(scratch, "user"))++import nodes # noqa: E402+import execution # noqa: E402+from comfy_execution.graph import DynamicPrompt, TopologicalSort # noqa: E402+from comfy_execution.graph_utils import is_link # noqa: E402++asyncio.run(nodes.init_extra_nodes(init_custom_nodes=False, init_api_nodes=False))++from fuobe_connect.graph import comfy_kinds, files_in, shipped_nodes, vet_graph # noqa: E402++MODEL = "fuobe_abcdefgh12.glb"+PICTURE = "fuobe_abcdefgh12.png"+with open(os.path.join(scratch, "input", MODEL), "wb") as f:+ f.write(b"glTF")+from PIL import Image # noqa: E402++Image.new("RGB", (8, 8), (200, 10, 10)).save(os.path.join(scratch, "input", PICTURE))+# A file of yours in the output folder, under a name ComfyUI makes up the same way on every computer.+Image.new("RGB", (8, 8), (10, 200, 10)).save(os.path.join(scratch, "output", "ComfyUI_00001_.png"))+STAGED = [MODEL, PICTURE]++from app.node_replace_manager import NodeReplaceManager # noqa: E402+from comfy_api.latest._io import NodeReplace # noqa: E402++replacements = NodeReplaceManager()+replacements.register(NodeReplace(new_node_id="LoadImage", old_node_id="FuobeOldLoader", input_mapping=[{"new_id": "image", "old_id": "path"}]))+KINDS = comfy_kinds(lambda: nodes.NODE_CLASS_MAPPINGS, lambda: replacements)+ALLOWED = shipped_nodes()++validated_ids: set = set()+_validate_inputs = execution.validate_inputs+++async def recording_validate_inputs(prompt_id, prompt, item, validated, visiting=None):+ validated_ids.add(item)+ return await _validate_inputs(prompt_id, prompt, item, validated, visiting)+++# validate_inputs calls itself through the module's name, so every node it validates is seen here.+execution.validate_inputs = recording_validate_inputs+++def comfy_check(graph: dict) -> dict:+ """What ComfyUI does: validate_prompt, then the nodes its scheduler would run from the outputs it kept."""+ prompt = copy.deepcopy(graph)+ validated_ids.clear()+ valid, error, outputs, node_errors = asyncio.run(execution.validate_prompt("p", prompt, None))+ scheduled: set = set()+ if valid:+ sort = TopologicalSort(DynamicPrompt(prompt))+ for o in outputs:+ sort.add_node(o)+ scheduled = set(sort.pendingNodes)+ return {+ "valid": bool(valid),+ "validated": sorted(validated_ids),+ "scheduled": sorted(scheduled),+ "unvalidated_scheduled": sorted(scheduled - validated_ids),+ "errors": {k: [e["type"] for e in v["errors"]] for k, v in node_errors.items()},+ "error": error.get("type") if isinstance(error, dict) else None,+ "prompt": prompt,+ }+++def vet(graph: dict, staged=STAGED, kinds=KINDS):+ return vet_graph(copy.deepcopy(graph), ALLOWED, staged, kinds)+++def save3d(view, model=("30", 6), **more) -> dict:+ return {"class_type": "Save3DAdvanced", "inputs": {"model_3d": list(model), "viewport_state": view, "width": 512, "height": 512, "filename_prefix": "fuobe/abcdef12", **more}}+++LOAD3D = {"class_type": "Load3D", "inputs": {"model_file": MODEL, "image": {"image": PICTURE, "mask": PICTURE, "normal": PICTURE, "recording": "", "camera_info": {}}, "width": 512, "height": 512}}+# A node ComfyUI refuses when it validates it: a dropdown value not in its list, an option that isn't one.+UNCHECKED = {"class_type": "CLIPLoader", "inputs": {"clip_name": "not-in-the-list/anything.safetensors", "type": "no_such_type", "device": "nowhere"}}++results: dict = {}++# 1. {"__value__": [node, slot]} in Save3DAdvanced.viewport_state: validate_inputs unwraps it into a link in place.+graph = {"10": save3d({"__value__": ["20", 0]}), "30": LOAD3D, "20": UNCHECKED}+c = comfy_check(graph)+control = comfy_check({**graph, "10": save3d({}), "11": {"class_type": "PreviewAny", "inputs": {"source": ["20", 0]}}})+results["value-wrapper"] = {+ "vet": vet(graph),+ "vet_direct": vet(graph, None),+ "valid": c["valid"],+ "unvalidated_scheduled": c["unvalidated_scheduled"],+ "now_a_link": is_link(c["prompt"]["10"]["inputs"]["viewport_state"]),+ "control_refused": control["errors"].get("20", []),+}++# 2. A link in an input the node doesn't list: the scheduler runs node 20, validate_inputs never looks at it.+graph = {"10": {"class_type": "SaveImage", "inputs": {"images": ["40", 0], "filename_prefix": "fuobe/abcdef12", "zzz": ["20", 0]}}, "40": {"class_type": "EmptyImage", "inputs": {"width": 8, "height": 8, "batch_size": 1, "color": 0}}, "20": UNCHECKED}+c = comfy_check(graph)+results["unlisted-input"] = {"vet": vet(graph), "vet_without_kinds": vet(graph, kinds=None), "valid": c["valid"], "unvalidated_scheduled": c["unvalidated_scheduled"]}++# 3. The same through a hidden input's name (SaveImage's "prompt").+graph = {**graph, "10": {"class_type": "SaveImage", "inputs": {"images": ["40", 0], "filename_prefix": "fuobe/abcdef12", "prompt": ["20", 0]}}}+c = comfy_check(graph)+results["hidden-input"] = {"vet": vet(graph), "valid": c["valid"], "unvalidated_scheduled": c["unvalidated_scheduled"]}++# 4. A dynamic node's inputs: ComfyUI works out which ones it validates from the node's own values.+graph = {+ "10": {"class_type": "SaveImage", "inputs": {"images": ["41", 0], "filename_prefix": "fuobe/abcdef12"}},+ "40": {"class_type": "EmptyImage", "inputs": {"width": 8, "height": 8, "batch_size": 1, "color": 0}},+ "41": {"class_type": "BatchImagesNode", "inputs": {"images.image0": ["40", 0], "images.image1": ["40", 0]}},+}+c = comfy_check(graph)+bad = copy.deepcopy(graph)+bad["41"]["inputs"]["pictures.image9"] = ["20", 0]+bad["20"] = UNCHECKED+cb = comfy_check(bad)+results["dynamic-inputs"] = {"vet_ok": vet(graph), "valid_ok": c["valid"], "vet_bad": vet(bad), "valid_bad": cb["valid"], "unvalidated_scheduled_bad": cb["unvalidated_scheduled"]}++# 5. "is_changed" on a node: ComfyUI takes it in place of the node's own IS_CHANGED (the key of its cached output).+graph = {"10": {"class_type": "SaveImage", "inputs": {"images": ["42", 0], "filename_prefix": "fuobe/abcdef12"}}, "42": {"class_type": "LoadImage", "inputs": {"image": PICTURE}, "is_changed": ["chosen by the studio"]}}+c = comfy_check(graph)+own = asyncio.run(execution.IsChangedCache("p", DynamicPrompt(copy.deepcopy({**graph, "42": {k: v for k, v in graph["42"].items() if k != "is_changed"}})), None).get("42"))+taken = asyncio.run(execution.IsChangedCache("p", DynamicPrompt(copy.deepcopy(graph)), None).get("42"))+results["is-changed"] = {"vet": vet(graph), "valid": c["valid"], "comfy_takes": taken == ["chosen by the studio"], "own_differs": own != taken}++# 6. A loop: validate_loops pairs an End Loop downstream of an output with its Start Loop, and Start Loop's expansion+# runs the body and the End Loop. Node 3 (any node: here an INT far past its max) is never validated.+graph = {+ "1": {"class_type": "StartLoop", "inputs": {"mode": "simple", "mode.num_iterations": 2, "cache_iterations": False}},+ "2": save3d({}, model=("5", 6), **{}),+ "3": {"class_type": "CreateCameraInfo", "inputs": {"mode": "orbit", "mode.yaw": ["1", 0], "mode.pitch": 10, "mode.distance": 5, "target_x": 0, "target_y": 0, "target_z": 0, "roll": 0, "fov": 99999, "zoom": 1}},+ "4": {"class_type": "EndLoop", "inputs": {"accumulate": False, "terminations.termination0": ["2", 3], "next_iteration_value": ["3", 0]}},+ "5": LOAD3D,+}+graph["2"]["inputs"]["width"] = ["1", 0]+c = comfy_check(graph)+body = c["prompt"]["1"].get("_loop_body", [])+results["loop-body"] = {+ "vet": vet(graph),+ "valid": c["valid"],+ "error": c["error"],+ "validated": c["validated"],+ "loop_body": body,+ "loop_end": c["prompt"]["1"].get("_loop_end"),+ "body_unvalidated": sorted(set(body + [c["prompt"]["1"].get("_loop_end")]) - set(c["validated"]) - {None}),+}+# 6b. "_loop_body" written by the studio: refused before ComfyUI writes its own.+forged = copy.deepcopy(graph)+forged["1"]["_loop_body"] = ["3"]+forged["1"]["_loop_end"] = "4"+results["loop-keys"] = {"vet": vet(forged)}++# 7. A node type ComfyUI swaps before it validates: "FuobeOldLoader" (missing) becomes LoadImage, its "path" the image,+# so it reads a picture of yours from the input folder.+Image.new("RGB", (8, 8), (10, 10, 200)).save(os.path.join(scratch, "input", "my_photo.png"))+graph = {"10": {"class_type": "SaveImage", "inputs": {"images": ["43", 0], "filename_prefix": "fuobe/abcdef12"}}, "43": {"class_type": "FuobeOldLoader", "inputs": {"path": "my_photo.png"}}}+swapped = copy.deepcopy(graph)+replacements.apply_replacements(swapped)+c = comfy_check(swapped)+results["node-replacement"] = {+ "vet": vet_graph(copy.deepcopy(graph), ALLOWED | {"FuobeOldLoader"}, STAGED, KINDS),+ "swapped_to": swapped["43"]["class_type"],+ "reads": swapped["43"]["inputs"].get("image"),+ "valid": c["valid"],+}++# 8. A camera that names a file: Save3DAdvanced shows it in the run's history, where it read as one of the run's files.+echo = {"filename": "ComfyUI_00001_.png", "subfolder": "", "type": "output"}+graph = {"10": save3d({"image": "", "mask": "", "normal": "", "recording": "", "camera_info": echo, "model_3d_info": [echo]}), "30": LOAD3D}+c = comfy_check(graph)+import types # noqa: E402++server = types.SimpleNamespace(client_id=None, last_node_id=None, send_sync=lambda *a, **k: None, queue_updated=lambda *a, **k: None)+ex = execution.PromptExecutor(server, cache_type=False, cache_args={"lru": 0, "ram": 0, "ram_inactive": 0})+ran = ex.execute_async(copy.deepcopy(c["prompt"]), "p8", {}, ["10"] if c["valid"] else [])+if asyncio.iscoroutine(ran):+ asyncio.run(ran)+ui = (getattr(ex, "history_result", None) or {}).get("outputs", {})+entry = {"outputs": ui}+++def old_files_in(entries):+ """files_in before this change: every dict in every list of the history's outputs."""+ found = []+ for e in entries:+ for u in (e.get("outputs") or {}).values():+ for v in u.values() if isinstance(u, dict) else []:+ if isinstance(v, list):+ found += [f for f in v if isinstance(f, dict) and isinstance(f.get("filename"), str) and isinstance(f.get("type"), str)]+ return found+++results["history-echo"] = {+ "vet": vet(graph),+ "valid": c["valid"],+ "ran": bool(ex.success),+ "ui_keys": sorted({k for u in ui.values() if isinstance(u, dict) for k in u}),+ "old_lists_it": any(f.get("filename") == "ComfyUI_00001_.png" for f in old_files_in([entry])),+ "lists_it": any(f.get("filename") == "ComfyUI_00001_.png" for f in files_in([entry])),+ "results": [f.get("filename") for f in files_in([entry])],+}++# 9. Fuobe's own workflows pass with ComfyUI's own kinds (node types this ComfyUI doesn't have are left to ComfyUI).+checked, refused, core_only = 0, {}, 0+if workflows and os.path.isdir(workflows):+ from test_graph import staged_like_the_studio # noqa: E402++ for name in sorted(os.listdir(workflows)):+ if not name.endswith(".json") or name in ("requirements.json", "manifest.json", "object_info.subset.json"):+ continue+ with open(os.path.join(workflows, name), encoding="utf-8") as f:+ wf = json.load(f)+ if not isinstance(wf, dict) or not wf or not all(isinstance(n, dict) and "class_type" in n for n in wf.values()):+ continue+ checked += 1+ core_only += all(n["class_type"] in nodes.NODE_CLASS_MAPPINGS for n in wf.values())+ why = vet_graph(staged_like_the_studio(wf), ALLOWED, None, KINDS)+ if why:+ refused[name] = why+results["fuobe-workflows"] = {"checked": checked, "core_only": core_only, "refused": refused}++json.dump(results, out, default=str)+out.write("\n")+out.flush()diff --git a/integrations/fuobe-connect/tests/test_comfy_engine.py b/integrations/fuobe-connect/tests/test_comfy_engine.pynew file mode 100644index 00000000..2c9a62cf--- /dev/null+++ b/integrations/fuobe-connect/tests/test_comfy_engine.py@@ -0,0 +1,125 @@+"""Each attack against ComfyUI's own validate and execute code, and Fuobe Connect's answer to it.++Needs COMFYUI_DIR (a ComfyUI folder) and this Python able to import it (torch and ComfyUI's requirements): ComfyUI's+own embedded Python, for one. comfy_engine.py imports ComfyUI's execution code from that folder in a process of its+own, on the CPU, with no custom nodes and with its input, output, temp and user folders in a scratch folder. No server+starts and nothing in the ComfyUI folder changes. Each test first shows what ComfyUI itself does with the graph (it+takes it, and runs a node it never validated, or lists a file of yours as a result), then that vet_graph refuses it.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+import tempfile+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+PACK = os.path.dirname(HERE)+WORKFLOWS = os.path.normpath(os.path.join(PACK, "..", "..", "workflows", "comfyui"))+++class ComfyEngineTest(unittest.TestCase):+ results: dict = {}++ @classmethod+ def setUpClass(cls):+ folder = os.environ.get("COMFYUI_DIR")+ if not folder:+ raise unittest.SkipTest("Set COMFYUI_DIR to a ComfyUI folder to run the attacks against ComfyUI's own code")+ scratch = tempfile.mkdtemp(prefix="fuobe-connect-engine-")+ try:+ done = subprocess.run(+ [sys.executable, "-I", os.path.join(HERE, "comfy_engine.py"), folder, PACK, scratch, WORKFLOWS if os.path.isdir(WORKFLOWS) else ""],+ cwd=scratch,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=1200,+ )+ finally:+ shutil.rmtree(scratch, ignore_errors=True)+ if done.returncode != 0 or not done.stdout.strip():+ raise AssertionError(f"comfy_engine.py failed ({done.returncode}):\n{done.stderr[-4000:]}")+ cls.results = json.loads(done.stdout.strip().splitlines()[-1])++ def test_value_wrapper(self):+ """{"__value__": ["20", 0]} in Save3DAdvanced.viewport_state: ComfyUI unwraps it into a link and runs node 20+ (a dropdown value not in its list) unvalidated; linked normally, ComfyUI refuses node 20."""+ r = self.results["value-wrapper"]+ self.assertTrue(r["valid"])+ self.assertTrue(r["now_a_link"])+ self.assertEqual(r["unvalidated_scheduled"], ["20"])+ self.assertIn("value_not_in_list", r["control_refused"])+ self.assertEqual(r["vet"], "unsafe-graph")+ self.assertEqual(r["vet_direct"], "unsafe-graph")++ def test_link_in_an_input_the_node_doesnt_list(self):+ r = self.results["unlisted-input"]+ self.assertTrue(r["valid"])+ self.assertEqual(r["unvalidated_scheduled"], ["20"])+ self.assertEqual(r["vet"], "unsafe-graph")++ def test_link_in_a_hidden_input(self):+ r = self.results["hidden-input"]+ self.assertTrue(r["valid"])+ self.assertEqual(r["unvalidated_scheduled"], ["20"])+ self.assertEqual(r["vet"], "unsafe-graph")++ def test_dynamic_inputs_as_comfyui_works_them_out(self):+ r = self.results["dynamic-inputs"]+ self.assertTrue(r["valid_ok"])+ self.assertIsNone(r["vet_ok"])+ self.assertTrue(r["valid_bad"])+ self.assertEqual(r["unvalidated_scheduled_bad"], ["20"])+ self.assertEqual(r["vet_bad"], "unsafe-graph")++ def test_is_changed_key(self):+ r = self.results["is-changed"]+ self.assertTrue(r["valid"])+ self.assertTrue(r["comfy_takes"])+ self.assertTrue(r["own_differs"])+ self.assertEqual(r["vet"], "unsafe-graph")++ def test_loop_runs_unvalidated_nodes(self):+ """ComfyUI validates nodes 1, 2 and 5 only, yet its loop runs node 3 (the body) and node 4 (the End Loop)."""+ r = self.results["loop-body"]+ self.assertTrue(r["valid"], r["error"])+ self.assertEqual(r["loop_end"], "4")+ self.assertIn("3", r["loop_body"])+ self.assertEqual(r["body_unvalidated"], ["3", "4"])+ self.assertEqual(r["vet"], "unsafe-graph")+ self.assertEqual(self.results["loop-keys"]["vet"], "unsafe-graph")++ def test_node_replacement(self):+ r = self.results["node-replacement"]+ self.assertEqual(r["swapped_to"], "LoadImage")+ self.assertEqual(r["reads"], "my_photo.png")+ self.assertTrue(r["valid"])+ self.assertEqual(r["vet"], "unknown-node")++ def test_history_echo(self):+ """A camera naming a file of yours: Save3DAdvanced runs and shows it in the history, where the old check read it+ as one of the run's results."""+ r = self.results["history-echo"]+ self.assertTrue(r["valid"])+ self.assertTrue(r["ran"])+ self.assertIn("camera_info", r["ui_keys"])+ self.assertTrue(r["old_lists_it"])+ self.assertFalse(r["lists_it"])+ self.assertEqual(r["vet"], "unsafe-graph")++ def test_fuobe_workflows_pass(self):+ r = self.results["fuobe-workflows"]+ if not r["checked"]:+ self.skipTest("Fuobe's workflows aren't beside this copy of the pack")+ self.assertEqual(r["refused"], {})+ self.assertGreater(r["core_only"], 50)+++if __name__ == "__main__":+ unittest.main()diff --git a/integrations/fuobe-connect/tests/test_graph.py b/integrations/fuobe-connect/tests/test_graph.pyindex 70ca0b39..d713af93 100644--- a/integrations/fuobe-connect/tests/test_graph.py+++ b/integrations/fuobe-connect/tests/test_graph.py@@ -3,6 +3,7 @@ to the studio."""from __future__ import annotations+import enumimport globimport jsonimport os@@ -29,9 +30,13 @@ from fuobe_connect.graph import ( # noqa: E402NodeKinds,NodeList,comfy_kinds,+ dropdown_spec,+ files_in,graph_problem,+ has_value_key,input_kind,is_link,+ loose_type,may_download,refusal,run_prefix,@@ -202,7 +207,7 @@ class VetTest(unittest.TestCase):node("Load3D", model_file="fuobe_abcdefgh34.spz", image={"image": "secret.png", "camera_info": {}}),]:self.assertEqual(vet_graph(g(bad, node("PrimitiveString", value="x")), NODES, STAGED), "unsafe-graph", bad)- self.assertIsNone(vet_graph(g(node("Load3D", model_file="fuobe_abcdefgh34.spz", image={"image": "fuobe_abcdefgh12.png", "mask": "", "camera_info": {"x": 1}})), NODES, STAGED))+ self.assertIsNone(vet_graph(g(node("Load3D", model_file="fuobe_abcdefgh34.spz", image={"image": "fuobe_abcdefgh12.png", "mask": "", "camera_info": {"position": {"x": 1, "y": 2, "z": 3}, "zoom": 1}})), NODES, STAGED))# Direct mode doesn't know the run: any name Fuobe gives an input.self.assertIsNone(graph_problem(g(node("LoadImage", image="fuobe_zzzzzzzz99.png")), None))self.assertIsNotNone(graph_problem(g(node("LoadImage", image="my_photo.png")), None))@@ -389,6 +394,37 @@ def chain(*nodes) -> dict:return g(*nodes)+_DYNAMIC = ("COMFY_AUTOGROW_V3", "COMFY_DYNAMICCOMBO_V3")+++def recorded_kinds(info_file: str) -> NodeKinds:+ """NodeKinds from a recorded /object_info. A v3 node's dynamic input ("images", "mode") stands for the inputs+ ComfyUI works out under its name ("images.image_1", "mode.yaw"); inside ComfyUI, comfy_kinds asks ComfyUI's own+ get_finalized_class_inputs (test_comfy_engine.py runs that). Start Loop and End Loop are ComfyUI 0.42's loops."""+ with open(info_file, encoding="utf-8") as f:+ info = {k: v for k, v in json.load(f).items() if isinstance(v, dict)}++ def specs(cls):+ inputs = info[cls].get("input") or {}+ return {k: s for part in ("required", "optional") for k, s in (inputs.get(part) or {}).items()}++ def dynamic(cls):+ return [k for k, s in specs(cls).items() if isinstance(s, list) and s and s[0] in _DYNAMIC]++ def lookup(cls):+ if cls not in info:+ return None+ about = {"output": info[cls].get("output_node") is True, "loop": cls in ("StartLoop", "EndLoop"), "dynamic": bool(dynamic(cls))}+ return info[cls].get("input") or {}, info[cls].get("output") or [], about++ def checked(cls, inputs):+ names = set(specs(cls))+ grows = dynamic(cls)+ return names | {k for k in inputs if "." in k and k.split(".")[0] in grows}++ return NodeKinds(lookup, checked)++class FakeNode:"""A node class as ComfyUI's NODE_CLASS_MAPPINGS holds it."""@@ -407,6 +443,34 @@ class AnyType(str):return False+class IO(str, enum.Enum):+ """ComfyUI's own IO types (comfy/comfy_types/node_typing.py, ComfyUI 0.42): a str enum whose __ne__ treats "*" as+ every type and compares comma-separated types as sets."""++ STRING = "STRING"+ IMAGE = "IMAGE"+ CLIP = "CLIP"+ MODEL = "MODEL"+ LATENT = "LATENT"+ CONDITIONING = "CONDITIONING"+ COMBO = "COMBO"+ MATCHTYPE = "COMFY_MATCHTYPE_V3"+ NUMBER = "FLOAT,INT"+ ANY = "*"++ def __str__(self) -> str:+ return self.value++ def __ne__(self, value: object) -> bool:+ if self == "*" or value == "*":+ return False+ if not isinstance(value, str):+ return True+ a = frozenset(self.split(","))+ b = frozenset(value.split(","))+ return not (b.issubset(a) or a.issubset(b))++# What ComfyUI's node classes say about the nodes the tests below use (as /object_info shows them).CLASSES = {"CreateList": FakeNode({"required": {"input1": ("*", {})}}, ("*",)),@@ -528,6 +592,27 @@ class LinkTest(unittest.TestCase):odd = NodeKinds(lambda cls: ({"required": {}}, 5))self.assertTrue(odd.loose("X", 0))+ def test_comfyuis_own_io_types(self):+ """ComfyUI's core nodes name their types with its IO enum (CLIPTextEncode: (IO.CONDITIONING,)): texts that+ compare by name, except IO.ANY ("*"), which equals every type. A link from IO.CONDITIONING is typed."""+ for t in (IO.CONDITIONING, IO.IMAGE, IO.NUMBER, "IMAGE", "IMAGE,MASK"):+ self.assertFalse(loose_type(t), t)+ for t in (IO.ANY, IO.MATCHTYPE, IO.COMBO, "*", "COMBO", "STRING,*", ["a", "b"], AnyType("ANYTHING")):+ self.assertTrue(loose_type(t), t)+ # Not text, and saying it equals nothing: ComfyUI matches it to no input.+ self.assertFalse(loose_type(None))+ self.assertTrue(dropdown_spec((IO.COMBO, {})))+ self.assertFalse(dropdown_spec((IO.STRING, {})))+ classes = {+ "CLIPTextEncode": FakeNode({"required": {"text": (IO.STRING, {}), "clip": (IO.CLIP, {})}}, (IO.CONDITIONING,)),+ "KSampler": FakeNode({"required": {"model": (IO.MODEL, {}), "positive": (IO.CONDITIONING, {}), "sampler_name": (["euler"],)}}, (IO.LATENT,)),+ "PrimitiveAny": FakeNode({"required": {"value": (IO.STRING, {})}}, (IO.ANY,)),+ }+ kinds = comfy_kinds(lambda: classes)+ encode = node("CLIPTextEncode", text="a red door", clip=["8", 0])+ self.assertIsNone(vet_graph(chain(encode, node("KSampler", model=["8", 0], positive=["1", 0], sampler_name="euler")), SHIPPED, STAGED, kinds))+ self.assertEqual(vet_graph(chain(node("PrimitiveAny", value="x"), node("KSampler", model=["8", 0], positive=["1", 0])), SHIPPED | {"PrimitiveAny"}, STAGED, kinds), "unsafe-graph")+def test_ffmpeg_format_file(self):"""VHS_VideoCombine opens video_formats/<format>.json with the name as given and hands what it reads to ffmpeg:a format worked out at run time could name a .json in the input folder."""@@ -583,9 +668,7 @@ class LinkTest(unittest.TestCase):info_file = os.path.join(folder, "object_info.subset.json")if not os.path.exists(info_file):self.skipTest("Fuobe's workflows aren't beside this copy of the pack")- with open(info_file, encoding="utf-8") as f:- info = {k: v for k, v in json.load(f).items() if isinstance(v, dict)}- kinds = NodeKinds(lambda cls: (info[cls].get("input") or {}, info[cls].get("output") or []) if cls in info else None)+ kinds = recorded_kinds(info_file)checked = 0for path in glob.glob(os.path.join(folder, "*.json")):if os.path.basename(path) in ("requirements.json", "manifest.json", "object_info.subset.json"):@@ -599,6 +682,290 @@ class LinkTest(unittest.TestCase):self.assertGreater(checked, 50)+# Fuobe's own 3D view (workflows/comfyui/image-to-3d-trellis2.json, Save3DAdvanced's viewport_state).+FUOBE_CAMERA = {+ "position": {"x": 10, "y": 10, "z": 10.000000000000002},+ "target": {"x": 0, "y": 0, "z": 0},+ "zoom": 1,+ "cameraType": "perspective",+ "quaternion": {"x": -0.2798481423331213, "y": 0.3647051996310008, "z": 0.11591689595929511, "w": 0.8804762392171493},+ "fov": 35,+ "aspect": 1,+ "near": 0.01,+ "far": 10000,+ "frustum": {"left": -5, "right": 5, "top": 5, "bottom": -5},+}+FUOBE_VIEW = {"image": "", "mask": "", "normal": "", "camera_info": FUOBE_CAMERA, "recording": "", "model_3d_info": []}+# A file in your output folder whose name ComfyUI makes up the same way on every computer.+ECHOED_FILE = {"filename": "ComfyUI_00001_.png", "subfolder": "", "type": "output"}+++def save3d(view, **more) -> dict:+ return node("Save3DAdvanced", model_3d=["2", 6], viewport_state=view, width=512, height=512, filename_prefix="fuobe/abcdef12", **more)+++def load3d(view) -> dict:+ return node("Load3D", model_file="fuobe_abcdefgh34.spz", image=view, width=512, height=512)+++class SpecNode(FakeNode):+ """A node class with ComfyUI's other attributes: an output node, or one whose optional inputs claim every name."""++ def __init__(self, inputs: dict, outputs: tuple, output_node: bool = False):+ super().__init__(inputs, outputs)+ self.OUTPUT_NODE = output_node+++class AllNames(dict):+ """A node pack's optional inputs that say they hold every name (VHS_VideoCombine's): get_input_info finds any name+ there, but validate_inputs goes through only the names the dict holds."""++ def __contains__(self, key):+ return True+++ENGINE = {+ "SaveImage": SpecNode({"required": {"images": ("IMAGE",), "filename_prefix": ("STRING", {})}, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}}, (), True),+ "CLIPLoader": SpecNode({"required": {"clip_name": (["a.safetensors"],), "type": (["sd3"],)}, "optional": {"device": (["default", "cpu"], {})}}, ("CLIP",)),+ "EmptyImage": SpecNode({"required": {"width": ("INT", {}), "height": ("INT", {}), "batch_size": ("INT", {}), "color": ("INT", {})}}, ("IMAGE",)),+ "VHS_VideoCombine": SpecNode(+ {"required": {"images": ("IMAGE",), "frame_rate": ("FLOAT", {}), "filename_prefix": ("STRING", {}), "format": (["video/h264-mp4"],)}, "optional": AllNames({"audio": ("AUDIO",)}), "hidden": {"unique_id": "UNIQUE_ID"}},+ ("VHS_FILENAMES",),+ True,+ ),+}+++class FakeReplacements:+ """ComfyUI's NodeReplaceManager, with the old node types it swaps."""++ def __init__(self, old: set):+ self.old = old++ def has_replacement(self, cls):+ return cls in self.old+++def spec_kinds(specs: dict) -> NodeKinds:+ """NodeKinds from (inputs, outputs, about) per class; a dynamic input's worked-out names are "<name>.<anything>"."""++ def lookup(cls):+ return specs.get(cls)++ def checked(cls, inputs):+ spec = specs[cls][0]+ names = set(spec.get("required") or {}) | set(spec.get("optional") or {})+ return names | {k for k in inputs if "." in k and k.split(".")[0] in names}++ return NodeKinds(lookup, checked)+++MT = "COMFY_MATCHTYPE_V3"+LOOPS = {+ "StartLoop": ({"required": {"mode": ("COMFY_DYNAMICCOMBO_V3", {}), "cache_iterations": ("BOOLEAN", {})}, "optional": {"initial_iteration_value": (MT, {})}, "hidden": {"dynprompt": "DYNPROMPT"}}, ("INT", "BOOLEAN", "BOOLEAN", MT, MT), {"loop": True, "dynamic": True}),+ "EndLoop": ({"required": {"accumulate": ("BOOLEAN", {})}, "optional": {"output_value": (MT, {}), "next_iteration_value": (MT, {}), "terminations": ("COMFY_AUTOGROW_V3", {})}}, (MT,), {"loop": True, "dynamic": True}),+ "Save3DAdvanced": ({"required": {"model_3d": ("FILE_3D", {}), "filename_prefix": ("STRING", {}), "viewport_state": ("LOAD_3D", {}), "width": ("INT", {}), "height": ("INT", {})}}, ("FILE_3D", "LOAD3D_MODEL_INFO", "LOAD3D_CAMERA", "INT", "INT"), {"output": True, "dynamic": True}),+ "Load3D": ({"required": {"model_file": ("COMBO", {}), "image": ("LOAD_3D", {}), "width": ("INT", {}), "height": ("INT", {})}}, ("IMAGE", "MASK", "STRING", "IMAGE", "LOAD3D_CAMERA", "VIDEO", "FILE_3D", "LOAD3D_MODEL_INFO"), {"dynamic": True}),+ "PrimitiveInt": ({"required": {"value": ("INT", {})}}, ("INT",), {"dynamic": True}),+ "EmptyImage": ({"required": {"width": ("INT", {}), "height": ("INT", {}), "batch_size": ("INT", {}), "color": ("INT", {})}}, ("IMAGE",), {}),+ "RebatchImages": ({"required": {"images": ("IMAGE",), "batch_size": ("INT", {})}}, ("IMAGE",), {}),+ "SaveImage": ({"required": {"images": ("IMAGE",), "filename_prefix": ("STRING", {})}}, (), {"output": True}),+}+++class ComfyOwnRulesTest(unittest.TestCase):+ """What ComfyUI's own validate and execute code does with a graph, which the per-input rules above don't see: a value+ it turns into a link, inputs it runs from but never validates, keys it reads as its own state, a node type it swaps+ after the check, nodes a loop runs unvalidated, and data it shows in the history beside the files.+ test_comfy_engine.py runs each attack against ComfyUI's own code."""++ def test_value_wrapper_becomes_a_link(self):+ """validate_inputs takes x out of {"__value__": x} in place: a link inside one runs a node it never validated."""+ attack = g(+ save3d({"__value__": ["3", 0]}),+ load3d({"image": "", "mask": "", "normal": "", "recording": ""}),+ node("CLIPLoader", clip_name="not-in-the-list/anything.safetensors", type="no_such_type", device="nowhere"),+ )+ for staged in (None, ["fuobe_abcdefgh34.spz"]):+ for kinds in (None, KINDS):+ self.assertEqual(vet_graph(attack, SHIPPED, staged, kinds), "unsafe-graph")+ # At any depth, in any input, as a key of the inputs themselves.+ for wrapped in (+ {"camera_info": {"__value__": ["3", 0]}},+ {"camera_info": {"position": {"__value__": 1}}},+ {"model_3d_info": [{"__value__": ["3", 0]}]},+ {**FUOBE_VIEW, "__value__": ""},+ ):+ self.assertEqual(vet1("Save3DAdvanced", viewport_state=wrapped), "unsafe-graph", wrapped)+ self.assertEqual(vet1("Load3D", model_file="fuobe_abcdefgh34.spz", image=wrapped), "unsafe-graph", wrapped)+ for value in ({"__value__": "a red door"}, {"__value__": ["3", 0]}, [[{"__value__": ["3", 0]}]], ["x", {"a": {"b": {"c": {"__value__": 1}}}}]):+ self.assertEqual(vet1("CLIPTextEncode", text=value, clip=["8", 0]), "unsafe-graph", value)+ self.assertEqual(vet_graph(g({"class_type": "CLIPTextEncode", "inputs": {"text": "x", "__value__": ["3", 0]}}), SHIPPED, STAGED), "unsafe-graph")+ self.assertFalse(has_value_key({"a": [{"b": "__value__"}], "__values__": 1}))++ def test_lists_and_numbers(self):+ """ComfyUI reads a list as a link, so a list a node gets as written could only come through an input ComfyUI+ never validates (VHS_VideoCombine takes any name). NaN passes every min and max."""+ for bad in (["a", "b", "c"], [], ["x"], [1, 0], [["3", 0]], ["3", 0, 0], [["3", 0], 0]):+ self.assertEqual(vet1("CLIPTextEncode", text=bad, clip=["8", 0]), "unsafe-graph", bad)+ video = {"images": ["9", 0], "format": "video/h264-mp4", "frame_rate": 24, "filename_prefix": "fuobe/x"}+ self.assertEqual(vet1("VHS_VideoCombine", **video, pix_fmt=["yuv420p", "-i", "x"]), "unsafe-graph")+ for bad in (float("nan"), float("inf"), float("-inf")):+ self.assertEqual(vet1("KSampler", model=["8", 0], cfg=bad), "unsafe-graph", bad)+ for ok in (7, 7.5, -1, True, None, "x"):+ self.assertIsNone(vet1("KSampler", model=["8", 0], cfg=ok), ok)++ def test_node_keys_comfyui_reads(self):+ """A node holds class_type, inputs and its title. "is_changed" stands in for IS_CHANGED (the cache key of a+ node's output); Start Loop reads "_loop_body" and "_loop_end"."""+ save = node("SaveImage", images=["1", 0], filename_prefix="fuobe/x")+ empty = node("EmptyImage", width=8, height=8, batch_size=1, color=0)+ for ok in ({**save, "_meta": {"title": "Save Image"}}, {**save, "_meta": {"title": "x", "cnr_id": "comfy-core", "ver": "0.3.1"}}, {**save, "_meta": {}}):+ self.assertIsNone(vet_graph(chain(empty, ok), SHIPPED, STAGED), ok)+ loop = node("StartLoop", mode="simple", cache_iterations=False)+ for bad in (+ {**save, "is_changed": "x"},+ {**save, "is_changed": [1.0]},+ {**loop, "_loop_body": ["1"], "_loop_end": "3"},+ {**save, "_meta": "Save Image"},+ {**save, "_meta": {"title": ["x"]}},+ {**save, "_meta": {"title": {"__value__": ["1", 0]}}},+ {**save, "outputs": {}},+ ):+ self.assertEqual(vet_graph(chain(empty, bad), SHIPPED, STAGED), "unsafe-graph", bad)++ def test_3d_views_have_comfyuis_own_form(self):+ """The camera and the models' placements: numbers under ComfyUI's own names, nothing else. Save3DAdvanced shows+ both in the run's history, where a camera that named a file read as one of the run's results."""+ self.assertIsNone(vet1("Save3DAdvanced", viewport_state=FUOBE_VIEW))+ self.assertIsNone(vet1("Save3DAdvanced", viewport_state={}))+ self.assertIsNone(vet1("Save3DAdvanced", viewport_state={**FUOBE_VIEW, "camera_info": None}))+ placed = [{"position": {"x": 0, "y": 1, "z": 0}, "quaternion": {"x": 0, "y": 0, "z": 0, "w": 1}, "scale": {"x": 1, "y": 1, "z": 1}}]+ self.assertIsNone(vet1("Save3DAdvanced", viewport_state={**FUOBE_VIEW, "model_3d_info": placed}))+ self.assertIsNone(vet1("Save3DAdvanced", viewport_state={**FUOBE_VIEW, "camera_info": {**FUOBE_CAMERA, "useCustomUp": True, "cameraType": "orthographic"}}))+ any_angle = {"image": "fuobe_abcdefgh12.png", "mask": "fuobe_abcdefgh12.png", "normal": "fuobe_abcdefgh12.png", "recording": "", "camera_info": None}+ self.assertIsNone(vet1("Load3D", model_file="fuobe_abcdefgh34.spz", image=any_angle))+ self.assertIsNone(vet1("Load3D", model_file="fuobe_abcdefgh34.spz", image={**any_angle, "camera_info": FUOBE_CAMERA, "model_3d_info": placed}))+ for camera in (+ ECHOED_FILE,+ {**FUOBE_CAMERA, **ECHOED_FILE},+ {**FUOBE_CAMERA, "position": {"x": "10", "y": 10, "z": 10}},+ {**FUOBE_CAMERA, "position": {"x": 1, "y": 2, "z": 3, "w": 4}},+ {**FUOBE_CAMERA, "position": ECHOED_FILE},+ {**FUOBE_CAMERA, "cameraType": "fisheye"},+ {**FUOBE_CAMERA, "zoom": True},+ {**FUOBE_CAMERA, "zoom": float("nan")},+ {**FUOBE_CAMERA, "near": [0.01]},+ {**FUOBE_CAMERA, "useCustomUp": 1},+ {**FUOBE_CAMERA, "up": {"x": 0, "y": 1, "z": 0}},+ ["3", 0],+ "perspective",+ ):+ for view in ({**FUOBE_VIEW, "camera_info": camera}, {**any_angle, "camera_info": camera}):+ self.assertEqual(vet_graph(g(save3d(view) if "mask" in view and view["mask"] == "" else load3d(view)), SHIPPED, STAGED + ["fuobe_abcdefgh34.spz"]), "unsafe-graph", camera)+ for placements in ([ECHOED_FILE], [{**placed[0], "filename": "x.png"}], [{"position": {"x": 1}, "name": "chair"}], [[0, 1, 0]], ["x"], {}, "x", [{"scale": {"x": 1, "y": 1, "z": 1, "w": 1}}], placed * 65):+ self.assertEqual(vet1("Save3DAdvanced", viewport_state={**FUOBE_VIEW, "model_3d_info": placements}), "unsafe-graph", placements)+ self.assertEqual(vet1("Load3D", model_file="fuobe_abcdefgh34.spz", image={**any_angle, "model_3d_info": placements}), "unsafe-graph", placements)+ # Save3DAdvanced reads no picture entry; Load3D's are texts (each one of this run's files, checked as such).+ for view in ({**FUOBE_VIEW, "image": "fuobe_abcdefgh12.png"}, {**FUOBE_VIEW, "recording": None}, {**FUOBE_VIEW, "files": []}, {**FUOBE_VIEW, "camera": {}}):+ self.assertEqual(vet1("Save3DAdvanced", viewport_state=view), "unsafe-graph", view)+ for view in ({**any_angle, "image": 5}, {**any_angle, "image": None}, {**any_angle, "image": {"image": "fuobe_abcdefgh12.png"}}, {**any_angle, "extra": ""}, {**any_angle, "image": "secret.png"}):+ self.assertEqual(vet1("Load3D", model_file="fuobe_abcdefgh34.spz", image=view), "unsafe-graph", view)++ def test_history_data_is_never_a_file(self):+ """What a 3D node shows beside its files (the camera, the placements) never counts as one of the run's files."""+ entry = {+ "outputs": {+ "7": {+ "3d": [{"filename": "abcdef12_00001_.glb", "subfolder": "fuobe", "type": "output"}],+ "camera_info": [ECHOED_FILE],+ "model_3d_info": [{**ECHOED_FILE, "filename": "secret.png"}],+ }+ }+ }+ self.assertEqual([f["filename"] for f in files_in([entry])], ["abcdef12_00001_.glb"])+ self.assertFalse(may_download(ECHOED_FILE, [entry]))+ self.assertTrue(may_download({"filename": "abcdef12_00001_.glb", "subfolder": "fuobe", "type": "output"}, [entry]))++ def test_links_only_into_inputs_comfyui_validates(self):+ """ComfyUI's scheduler follows a link in any input; validate_inputs goes through only the required and optional+ ones. A link anywhere else runs a node that nothing validated (its dropdowns, its numbers, its own links)."""+ kinds = comfy_kinds(lambda: ENGINE)+ loader = node("CLIPLoader", clip_name="not-in-the-list.safetensors", type="no_such_type")+ empty = node("EmptyImage", width=8, height=8, batch_size=1, color=0)+ for extra in ({"zzz": ["1", 0]}, {"prompt": ["1", 0]}, {"extra_pnginfo": ["1", 0]}):+ attack = chain(loader, empty, node("SaveImage", images=["2", 0], filename_prefix="fuobe/x", **extra))+ self.assertEqual(vet_graph(attack, SHIPPED, STAGED, kinds), "unsafe-graph", extra)+ # Without the node classes this can't be seen; inside ComfyUI they are always there.+ self.assertIsNone(vet_graph(attack, SHIPPED, STAGED), extra)+ # A hidden input as written goes to the node unchecked.+ self.assertEqual(vet_graph(chain(empty, node("SaveImage", images=["1", 0], filename_prefix="fuobe/x", prompt="x")), SHIPPED, STAGED, kinds), "unsafe-graph")+ # A text in an input the node doesn't list is dropped by ComfyUI: fine. Links into listed inputs: fine.+ self.assertIsNone(vet_graph(chain(empty, node("SaveImage", images=["1", 0], filename_prefix="fuobe/x", note="hi")), SHIPPED, STAGED, kinds))+ self.assertIsNone(vet_graph(chain(node("CLIPLoader", clip_name="a.safetensors", type="sd3", device=["9", 0]), empty), SHIPPED, STAGED, kinds))+ # A pack's inputs that claim every name: validate_inputs still goes through only its own.+ video = {"images": ["1", 0], "format": "video/h264-mp4", "frame_rate": 24, "filename_prefix": "fuobe/x"}+ self.assertIsNone(vet_graph(chain(empty, node("VHS_VideoCombine", **video, audio=["1", 0])), SHIPPED, STAGED, kinds))+ self.assertEqual(vet_graph(chain(empty, node("VHS_VideoCombine", **video, vae=["1", 0])), SHIPPED, STAGED, kinds), "unsafe-graph")+ # A dynamic node: only the inputs ComfyUI works out from its values.+ dyn = spec_kinds({**LOOPS, "BatchImagesNode": ({"required": {"images": ("COMFY_AUTOGROW_V3", {})}}, ("IMAGE",), {"dynamic": True})})+ batch = lambda **i: chain(node("EmptyImage", width=8, height=8, batch_size=1, color=0), node("BatchImagesNode", **i), node("SaveImage", images=["2", 0], filename_prefix="fuobe/x")) # noqa: E731+ self.assertIsNone(vet_graph(batch(**{"images.image0": ["1", 0], "images.image1": ["1", 0]}), SHIPPED, STAGED, dyn))+ self.assertEqual(vet_graph(batch(**{"images.image0": ["1", 0], "pictures.image1": ["1", 0]}), SHIPPED, STAGED, dyn), "unsafe-graph")+ # A class that can't say what it validates: refused (ComfyUI can't validate it either).+ broken = NodeKinds(lambda cls: (_ for _ in ()).throw(RuntimeError("no")))+ self.assertEqual(vet_graph(chain(empty), SHIPPED, STAGED, broken), "unsafe-graph")+ failing = NodeKinds(lambda cls: ({"required": {}}, ()), lambda cls, inputs: (_ for _ in ()).throw(RuntimeError("no")))+ self.assertIsNone(vet_graph(chain(empty), SHIPPED, STAGED, failing)) # not dynamic: its listed inputs+ failing_dyn = NodeKinds(lambda cls: ({"required": {}}, (), {"dynamic": True}), lambda cls, inputs: (_ for _ in ()).throw(RuntimeError("no")))+ self.assertEqual(vet_graph(chain(empty), SHIPPED, STAGED, failing_dyn), "unsafe-graph")++ def test_node_types_comfyui_swaps(self):+ """ComfyUI swaps a missing node type for another (its node replacements) after this check, with other inputs."""+ graph = chain(node("EmptyImage", width=8, height=8, batch_size=1, color=0), node("OldLoader", path="photo.png"), node("SaveImage", images=["2", 0], filename_prefix="fuobe/x"))+ allowed = SHIPPED | {"OldLoader"}+ swaps = comfy_kinds(lambda: ENGINE, lambda: FakeReplacements({"OldLoader"}))+ self.assertEqual(vet_graph(graph, allowed, STAGED, swaps), "unknown-node")+ # A missing node type ComfyUI doesn't swap: ComfyUI refuses the whole graph itself (before it validates or runs+ # any node), and says which type is missing.+ self.assertIsNone(vet_graph(graph, allowed, STAGED, comfy_kinds(lambda: ENGINE, lambda: FakeReplacements(set()))))+ self.assertIsNone(vet_graph(graph, allowed, STAGED, comfy_kinds(lambda: ENGINE, lambda: None)))+ unlisted = {**graph, "3": node("SaveImage", images=["1", 0], filename_prefix="fuobe/x", zzz=["2", 0])}+ self.assertIsNone(vet_graph(unlisted, allowed, STAGED, comfy_kinds(lambda: ENGINE, lambda: None)))+ self.assertEqual(vet_graph({k: v for k, v in unlisted.items() if k != "2"}, allowed, STAGED, comfy_kinds(lambda: ENGINE, lambda: None)), "unsafe-graph")+ # When the replacements can't be read: refused.+ self.assertEqual(vet_graph(graph, allowed, STAGED, comfy_kinds(lambda: ENGINE, lambda: (_ for _ in ()).throw(RuntimeError("no")))), "unknown-node")++ def test_loops_validate_every_node(self):+ """validate_loops pairs an End Loop downstream of an output with its Start Loop, and Start Loop's expansion runs+ the body and the End Loop: nodes validate_inputs never reached. A graph with a loop has only validated nodes."""+ kinds = spec_kinds(LOOPS)+ start = node("StartLoop", mode="simple", **{"mode.num_iterations": 2}, cache_iterations=False)+ model = load3d({"image": "", "mask": "", "normal": "", "recording": ""})+ # 1 Start Loop -> 2 Save3DAdvanced (an output, with outputs) -> 4 End Loop; 1 -> 3 (never validated) -> 4.+ attack = {+ "1": start,+ "2": node("Save3DAdvanced", model_3d=["5", 6], viewport_state={}, width=["1", 0], height=512, filename_prefix="fuobe/abcdef12"),+ "3": node("PrimitiveInt", value=["1", 0]),+ "4": node("EndLoop", accumulate=False, **{"terminations.termination0": ["2", 3]}, next_iteration_value=["3", 0]),+ "5": model,+ }+ self.assertEqual(vet_graph(attack, SHIPPED, ["fuobe_abcdefgh34.spz"], kinds), "unsafe-graph")+ # Fuobe's form: everything feeds the output.+ ok = {+ "1": start,+ "2": node("EmptyImage", width=8, height=8, batch_size=1, color=["1", 0]),+ "3": node("EndLoop", accumulate=True, output_value=["2", 0]),+ "4": node("RebatchImages", images=["3", 0], batch_size=64),+ "5": node("SaveImage", images=["4", 0], filename_prefix="fuobe/x"),+ }+ self.assertIsNone(vet_graph(ok, SHIPPED, STAGED, kinds))+ # A node no output needs: ComfyUI never runs it in a graph without a loop; with one, refused.+ spare = node("PrimitiveInt", value=5)+ self.assertIsNone(vet_graph(chain(node("EmptyImage", width=8, height=8, batch_size=1, color=0), node("SaveImage", images=["1", 0], filename_prefix="fuobe/x"), spare), SHIPPED, STAGED, kinds))+ self.assertEqual(vet_graph({**ok, "6": spare}, SHIPPED, STAGED, kinds), "unsafe-graph")++class NodeListTest(unittest.TestCase):def test_shipped_and_own(self):shipped = shipped_nodes()