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 1.0.2: shorter code notes and tests, steady logs on every Windows language
Adarsh4069c1ef0245
diff --git a/integrations/fuobe-connect/README.md b/integrations/fuobe-connect/README.mdindex 2c4d7a01..d8a6aa57 100644--- a/integrations/fuobe-connect/README.md+++ b/integrations/fuobe-connect/README.md@@ -5,8 +5,8 @@ computer, the way ComfyUI's own page uses it at `http://127.0.0.1:8188`. You door a changed start file. It adds no nodes. It is optional: Fuobe also runs without it.The source of this pack is the `integrations/fuobe-connect` folder of the Fuobe repository:-<https://github.com/workingprototype/Fuobe/tree/main/integrations/fuobe-connect>. This repository is a copy of that-folder. Every change is made there first.+<https://github.com/workingprototype/Fuobe/tree/main/integrations/fuobe-connect>. Every change is made there first,+and each release is published from that folder.## Two modes@@ -76,8 +76,8 @@ allow that (below). Its page can:- a link has the form that ComfyUI's page writes: a node's id and an output number from 0 (`["4", 0]`). A valuewritten in the workflow is a text, a number, `true`, `false` or `null`. A 3D view's entries have the form ofComfyUI's own 3D nodes;- - a node holds only its type, its inputs and its title, and every node that ComfyUI runs is one that ComfyUI checks- first.+ - a node holds only its type, its inputs and its title. A link goes only into an input that the node lists, and in+ a workflow with a loop, every node feeds an output node.Its workflows save their results into your output folder, as ComfyUI's own page does;- see, follow, cancel, stop and remove only the prompts it queued (and a batch's later passes, which save under@@ -107,8 +107,8 @@ When it is set, it wins over the setting, and ComfyUI shows a note about it.**Your own node list.** If your studio uses a node type that isn't on the shipped list, add it to`fuobe-connect-nodes.json` in ComfyUI's `user` folder: `{"nodes": ["MyNode"]}`. Only you can change this file. A-studio can't. Every check above applies to your nodes too: a workflow can't link from an output of theirs that-ComfyUI doesn't type-check, or into a dropdown of theirs.+studio can't. Every check above applies to your nodes too, including the rules for links from loosely typed outputs+and into dropdowns.**A network address.** A trusted studio reaches this ComfyUI only on this computer. To let it reach a ComfyUI thatruns with `--listen` at a network address, start ComfyUI with `FUOBE_CONNECT_LAN=1`. Its requests get the same checks@@ -186,8 +186,10 @@ python -m unittest discover -s testsThe tests load ComfyUI's own origin check and run it behind Fuobe Connect over real HTTP on ports 3360, 3364, 3365and 3366. Set `FUOBE_CONNECT_TEST_PORT` to move them (the tests use that port and the three after it, +4 to +6). Set-`COMFYUI_DIR` to a ComfyUI folder to read the middleware from that copy of ComfyUI. The tests need only `aiohttp`.-They do not need models, a GPU or a running ComfyUI. The `tests` folder is not part of the published pack.+`COMFYUI_DIR` to a ComfyUI folder to read the middleware from that copy of ComfyUI. Run them with ComfyUI's own Python+as well, and `tests/test_comfy_kinds.py` also checks workflows with that ComfyUI's own node classes, on the CPU. The+other tests need only `aiohttp`. No test needs models, a GPU or a running ComfyUI. The `tests` folder is not part of+the published pack.## Releases@@ -197,7 +199,7 @@ publish a version:1. In the Fuobe repository, set the new version in `pyproject.toml` and in `fuobe_connect/__init__.py`. The testscheck that the two are the same.2. Bring that folder into this repository as one new commit.-3. Push a tag with the same version and a `v` in front, for example `v1.0.1`.+3. Push a tag with the same version and a `v` in front, for example `v1.0.2`.The tag starts the workflow `.github/workflows/publish.yml`. The workflow publishes nothing when the tag and theversion in `pyproject.toml` are different, or when the repository has no publishing key (the secretdiff --git a/integrations/fuobe-connect/__init__.py b/integrations/fuobe-connect/__init__.pyindex c89cc47c..b09bd977 100644--- a/integrations/fuobe-connect/__init__.py+++ b/integrations/fuobe-connect/__init__.py@@ -17,6 +17,6 @@ try:install()except Exception as e: # never stop ComfyUI from starting- logging.warning("[Fuobe Connect] Couldn't start: %s", e)+ logging.warning("[Fuobe Connect] Couldn't start: %s", str(e).encode("ascii", "backslashreplace").decode("ascii"))__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]diff --git a/integrations/fuobe-connect/fuobe_connect/__init__.py b/integrations/fuobe-connect/fuobe_connect/__init__.pyindex 87690a08..e1c7d492 100644--- a/integrations/fuobe-connect/fuobe_connect/__init__.py+++ b/integrations/fuobe-connect/fuobe_connect/__init__.py@@ -1,3 +1,3 @@"""Fuobe Connect: use this ComfyUI from Fuobe with one install."""-__version__ = "1.0.1"+__version__ = "1.0.2"diff --git a/integrations/fuobe-connect/fuobe_connect/agent.py b/integrations/fuobe-connect/fuobe_connect/agent.pyindex 0e18393a..a26d1b3c 100644--- a/integrations/fuobe-connect/fuobe_connect/agent.py+++ b/integrations/fuobe-connect/fuobe_connect/agent.py@@ -16,7 +16,6 @@ the studio's settings ends it too.from __future__ import annotationsimport asyncio-import loggingimport osimport reimport socket@@ -28,11 +27,12 @@ from urllib.parse import urlsplitimport aiohttpfrom .graph import NodeList+from .logs import get_logfrom .net import Comfy, Site, site_basefrom .runner import Runner, Unpairedfrom .store import Store-log = logging.getLogger("fuobe_connect")+log = get_log()CODE = re.compile(r"^[A-Z0-9]{2,8}(?:-[A-Z0-9]{2,8})?\Z")NAME = re.compile(r"^[^\x00-\x1f\x7f]{1,48}\Z")diff --git a/integrations/fuobe-connect/fuobe_connect/graph.py b/integrations/fuobe-connect/fuobe_connect/graph.pyindex 497189ab..e6b6398d 100644--- a/integrations/fuobe-connect/fuobe_connect/graph.py+++ b/integrations/fuobe-connect/fuobe_connect/graph.py@@ -9,43 +9,33 @@ A graph from a studio (a trusted page in direct mode, or the paired studio in paone of ComfyUI's folder tags ("name [output]", "name [temp]"), or a JSON key that names a file, folder or address("video_path": ...). The check looks at the text after its leading spaces and quotes, as a node that trims it sees it;- every input that a listed node reads as a file or a folder, or a name it downloads (PATH_INPUTS), holds a value the- graph writes itself, in the one form Fuobe's own graphs use. It never takes a link: another node could work out any- text;+ graph writes itself, in the one form Fuobe's own graphs use, never a link;- every file loader reads one of the files Fuobe sent for the run (named fuobe_<id>.<ext>), never a file of yours andnever a value that another node works out;-- a link that ComfyUI doesn't type-check feeds only what Fuobe's own graphs feed that way (LOOSE_LINKS): a link from- an output typed "any", match-typed or dropdown-typed (LOOSE, and inside ComfyUI every such output of every node), and- any link into a dropdown. ComfyUI checks a dropdown's value against its list only when the graph writes it, so a- value another node works out would reach a dropdown, or any other input, unchecked;+- a link from a loosely typed output (typed "any", match-typed or dropdown-typed: LOOSE, and inside ComfyUI every such+ output of every node), and every link into a dropdown, goes only where Fuobe's own graphs put one (LOOSE_LINKS);- 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 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 with- a point (0.0) or -1 as an output. is_link here sees every link that ComfyUI sees, and a link in any of those forms- is refused;+- a value the graph writes is one plain thing: a text, a number (never NaN or infinity), true, false or null, never a+ list or a JSON object. 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;+- a node holds only "class_type", "inputs" and "_meta" (its title);+- a link names its node's output with a whole number from 0 (["4", 0]), the form ComfyUI's page writes. is_link here+ takes every value that ComfyUI takes as a link, and a link in any other form is refused;- a few inputs take only a link from one node type, or text of one shape (LINK_INPUTS, TEXT_INPUTS).-Inside ComfyUI, where the node classes can say what they take (NodeKinds), also:+Inside ComfyUI, where the node classes 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 link goes only into an input that the node lists as required or optional (for a v3 node, the dynamic inputs worked+ out from the node's own values, as ComfyUI's validate_inputs works them out);+- no input names one of the node's hidden inputs;+- a node type that isn't installed but that ComfyUI has a node replacement for is refused;+- in a graph with a loop (Start Loop, End Loop), every node is reached from an output node.-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.+A result is downloaded only when this run's own history lists it as a file (never what a 3D node shows 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."""@@ -61,7 +51,7 @@ 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}$")# The file types a run sends: pictures, clips, sound, 3D scenes, arrays and subtitles. Never a page, a script, a-# program, or a settings file (.json, .txt, .csv) or a file of no known type (.bin, .octet) that a node could read as one.+# program, a settings file (.json, .txt, .csv) or a file of no known type (.bin, .octet).INPUT_EXTS = frozenset("png jpg jpeg jpe webp gif bmp tif tiff avif heic heif jxl exr hdr ""mp4 m4v mov webm mkv avi mpg mpeg wmv flv 3gp quick "@@ -103,7 +93,7 @@ OPTIONAL_FILES = {_FILEISH = re.compile(r"image|video|audio|file|path|directory", re.I)_PATHLIKE = [- re.compile(r"^[\\/]"), # /etc/passwd, \Users\x, //host/share, //?/C:/x, \\host\share, \\?\C:\x, \/host/share+ re.compile(r"^[\\/]"), # /home/x, \Users\x, //host/share, //?/C:/x, \\host\share, \\?\C:\x, \/host/sharere.compile(r"^[A-Za-z]:(?![ \t])"), # C:\x, C:/x, and C:x or D:Users\x (a drive with no slash)re.compile(r"^~(?!\s)"), # ~, ~/x, ~user/x# $HOME/x, %USERPROFILE%\x, %HOMEDRIVE%%HOMEPATH%\x@@ -111,7 +101,7 @@ _PATHLIKE = [re.compile(r"(^|[\\/])\.\.([\\/]|\Z)"), # a ".." stepre.compile(r"^[A-Za-z][A-Za-z0-9+.-]*://"), # a URLre.compile(r"^file:", re.I),- re.compile(r"^blake3:", re.I), # ComfyUI's asset names reach any registered file+ re.compile(r"^blake3:", re.I), # ComfyUI's asset namesre.compile(r"\x00"),]# A key in JSON (or a Python dict) inside a text: "video_path": ..., 'output_folder': ...@@ -167,20 +157,19 @@ PATH_INPUTS: dict[str, dict[str, re.Pattern]] = {"MiniMaxH3SourceTimeline": {"video_path": _NONE, "audio_path": _NONE},# The run's own folder under output/h3_chains: Fuobe's jobs are named fuobe_<id> (or come from the swap plan nodes)."MiniMaxH3ChainPlanModern": {"run_name": re.compile(r"fuobe_[A-Za-z0-9_-]{0,60}[A-Za-z0-9]")},- # A latent saved in output/open_h3_latents: only one a Fuobe draft saved (fuobe_h3_<id>_00001), never "(newest)",- # which would be whatever was saved last, yours too.+ # A latent saved in output/open_h3_latents: only one a Fuobe draft saved (fuobe_h3_<id>_00001), never "(newest)"."OpenH3LoadRefinedLatent": {"latent_file": re.compile(r"fuobe_[A-Za-z0-9_-]{1,96}_\d{5}\.safetensors")},- # A SAM model in models/sams, else a path from ComfyUI's working folder (loaded with torch).+ # A SAM model in models/sams."QWMRefineMask": {"sam_model": re.compile(r"sam_vit_[bhl][A-Za-z0-9_.-]{0,64}\.pth")},# Writes every window's frames into this folder."WanVideoImageToVideoMultiTalk": {"output_path": _NONE},- # ffmpeg's settings for the format: video_formats/<name>.json, opened with the name as given, so never a folder in it.+ # The format's settings file, video_formats/<name>.json: a plain name, with no folder in it."VHS_VideoCombine": {"format": re.compile(rf"image/(?:gif|webp)|video/{_NAME}")},- # Downloads the Hugging Face repo it names (into models/transformers/<name>) before it looks at the name.+ # Downloads the Hugging Face repo it names (into models/transformers/<name>)."DownloadAndLoadWav2VecModel": {"model": re.compile(r"TencentGameMate/chinese-wav2vec2-base|facebook/wav2vec2-base-960h")},# Downloads the checkpoint it names."RIFE VFI": {"ckpt_name": re.compile(r"rife47\.pth|rife49\.pth|rife417\.pth|rife426\.pth|sudo_rife4_269\.662_testV1_scale1\.pth")},- # A YOLO model in models/ultralytics (or its bbox and segm folders), loaded with pickle.+ # A YOLO model in models/ultralytics (or its bbox and segm folders)."H3FaceTrackCrop": {"detector": re.compile(rf"(?:(?:bbox|segm)[\\/])?{_NAME}\.pt")},# A model folder, the adapter file and the text encoder (a folder, or a Hugging Face id it downloads)."ZenImage21AdapterLoader": {@@ -199,8 +188,8 @@ LINK_INPUTS: dict[str, dict[str, frozenset]] = {"TS_SVGStringToSVGBytesIO": {"SVG_String": frozenset({"TS_ImageToSVGStringColor_Vtracer"})},}-# A replacement field that reads an attribute or an item ("{a.__class__}", "{a[0]}"): Python's format can reach a-# module's globals (os.environ) through a node's object.+# A replacement field that reads an attribute or an item ("{a.__class__}", "{a[0]}"). StringFormat takes only plain+# fields ("{a}", "{b:.2f}", "{a!r}")._FIELD_ACCESS = re.compile(r"(?<!\{)(?:\{\{)*\{[^{}!:]*[.\[]")# Text inputs that must have one shape (a value the graph writes; never a link).@@ -211,10 +200,10 @@ TEXT_INPUTS: dict[str, dict] = {# ---------------------------------------------------------------------------# 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.+# 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). 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:@@ -288,8 +277,7 @@ OBJECT_INPUTS = {("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).+# The keys a node may hold: its type, its inputs and its title.NODE_KEYS = frozenset({"class_type", "inputs", "_meta"})@@ -302,8 +290,7 @@ def node_keys_ok(node: dict) -> bool: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."""+ """An object, at any depth, with a "__value__" key."""stack = [v]while stack:x = stack.pop()@@ -316,9 +303,9 @@ def has_value_key(v) -> bool: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-# their value. Such a node takes a link only into the inputs named here, and any other text only as one plain word-# ("yuv420p", "hq", "sierra2_4a"), except the texts named here (a file name prefix: ComfyUI keeps the file in output).+# format's settings to ffmpeg, one inside a filter (the GIF format's dither). Such a node takes a link only into the+# inputs named here, and any other text only as one plain word ("yuv420p", "hq", "sierra2_4a"), except the texts named+# here (a file name prefix: ComfyUI keeps the file in output).ARG_NODES: dict[str, dict[str, frozenset]] = {"VHS_VideoCombine": {"links": frozenset({"images", "audio", "meta_batch", "vae", "frame_rate"}), "texts": frozenset({"filename_prefix"})},}@@ -326,14 +313,11 @@ _WORD = re.compile(r"[A-Za-z0-9_.-]{0,64}")# ----------------------------------------------------------------------------# Links ComfyUI doesn't check+# Loosely typed links#-# ComfyUI checks that a link's output type fits the input, but any type fits an output typed "any" ("*") or a-# match-typed one, and a dropdown-typed output fits every dropdown. It checks a dropdown's value against its list only-# when the graph writes the value, never for a link. So a value another node works out (a text, a list) would reach-# any input through such a link: a dropdown of model names, or an input that takes a file's path inside an object.-# Such links, and every link into a dropdown, may feed only what Fuobe's own graphs feed that way (generated with the-# node list by Fuobe's scripts/connect-nodes.mjs).+# An output typed "any" ("*") or match-typed fits any input, and a dropdown-typed output fits every dropdown. Links+# from such outputs, and every link into a dropdown, may feed only what Fuobe's own graphs feed that way (generated with+# the node list by Fuobe's scripts/connect-nodes.mjs)._LOOSE_TYPES = frozenset({"*", "COMFY_MATCHTYPE_V3", "COMBO"})_DROPDOWN_TYPES = frozenset({"COMBO", "COMFY_DYNAMICCOMBO_V3"})@@ -351,7 +335,7 @@ def input_kind(key: str) -> str:_DATA = _shipped()-# Node types on the shipped list whose outputs ComfyUI doesn't type-check, by output slot.+# Node types on the shipped list with loosely typed outputs, by output slot.LOOSE: dict[str, frozenset] = {c: frozenset(s for s in slots if isinstance(s, int)) for c, slots in (_DATA.get("loose") or {}).items() if isinstance(c, str) and isinstance(slots, list)}@@ -366,9 +350,9 @@ _NO_TYPE = "\x00FUOBE_CONNECT_NO_SUCH_TYPE"def loose_type(t) -> bool:- """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."""+ """A loosely typed output: 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 Truetry:@@ -377,7 +361,7 @@ def loose_type(t) -> bool:except Exception:return Trueif not isinstance(t, str):- return False # ComfyUI matches a type that isn't text to no input+ return False # a type that isn't text fits no inputreturn any(p.strip() in _LOOSE_TYPES for p in str.__str__(t).split(","))@@ -388,8 +372,8 @@ def dropdown_spec(spec) -> bool: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)."""+ """A node's required and optional inputs: only the names the dicts hold (a node pack's dict that says it holds every+ name lists only its own)."""inputs = inputs if isinstance(inputs, dict) else {}return frozenset(inputs.get("required") or {}) | frozenset(inputs.get("optional") or {})@@ -398,15 +382,15 @@ _MISSING = {"found": False}class NodeKinds:- """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.+ """What the node classes themselves say, inside ComfyUI: which outputs are loosely typed, which inputs are+ dropdowns, which inputs a node lists, 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).+ `checked(class_type, inputs)`: the input names one node of a dynamic type lists, worked out the way validate_inputs+ does it (else the names INPUT_TYPES lists). `replaced(class_type)`: ComfyUI has a node replacement for this missing+ node type.A node's kinds are read once. A class that fails to say is asked again next time (ComfyUI refuses a graph with itanyway), and so is one that isn't there (a node pack could still load it)."""@@ -466,7 +450,7 @@ class NodeKinds: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)."""+ """The input names this node lists; None when that can't be known (the graph is refused)."""rec = self._kinds(cls)if not rec or not rec["found"]:return None@@ -491,7 +475,7 @@ class NodeKinds: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."""+ """ComfyUI has a node replacement for this node type. When that can't be known: yes."""if self._replaced is None:return Falsetry:@@ -507,8 +491,8 @@ def _comfy_replacements():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+ """NodeKinds from ComfyUI's NODE_CLASS_MAPPINGS (a callable that returns it, read at each new node type), with a+ dynamic node's inputs worked out by ComfyUI's own code. `replacements`: a callable that returns ComfyUI's nodereplacement manager (default: the running server's)."""def v3(klass) -> bool:@@ -556,22 +540,19 @@ def comfy_kinds(mappings, replacements=None) -> NodeKinds:def kinds_problem(graph: dict, kinds: NodeKinds) -> str | None:- """What ComfyUI itself would run without validating, inside ComfyUI: 'unknown-node', 'unsafe-graph', or None.+ """The checks that need the node classes, 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."""+ A link goes only into an input the node lists as required or optional, and no input names a hidden one. A missing+ node type that ComfyUI has a node replacement for is refused. In a graph with a loop, every node is reached from an+ output node through links."""missing = Falsefor 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 = Trueif 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.+ # ComfyUI refuses the graph itself (missing_node_type) and says which node type is missing.return Noneloop = Falsefor node in graph.values():@@ -600,22 +581,20 @@ def kinds_problem(graph: dict, kinds: NodeKinds) -> str | None:def is_link(v) -> bool:- """[node id, output slot]: a value another node works out. Every value ComfyUI reads as a link- (comfy_execution/graph_utils.py is_link): the slot may be any number, true or false too. ComfyUI reads [n, false] as- output 0, [n, true] as output 1 and [n, -1] as the last output."""+ """[node id, output slot]: a value another node works out. The same test as ComfyUI's own is_link+ (comfy_execution/graph_utils.py): the slot is any number, true or false."""return isinstance(v, list) and len(v) == 2 and isinstance(v[0], str) and isinstance(v[1], (int, float))def plain_slot(v) -> bool:"""A link whose slot is written the way Fuobe's graphs (and ComfyUI's own page) write it: a whole number from 0- (0, 1, 2 ...). Any other form is refused: -1 is the last output, which the checks here would take for another- one, and Fuobe's graphs never write true, false or a number with a point."""+ (0, 1, 2 ...). Any other form (true, false, -1, a number with a point) is refused."""return type(v[1]) is int and 0 <= v[1] < 1000def link_problem(graph: dict, cls: str, key: str, v, kinds: NodeKinds | None = None) -> str | None:- """A link from an output ComfyUI doesn't type-check, or into a dropdown, that Fuobe's own graphs don't make:- 'unsafe-graph'. A link to no node is ComfyUI's to refuse."""+ """A link from a loosely typed output, or into a dropdown, that Fuobe's own graphs don't make: 'unsafe-graph'. A+ link to no node is ComfyUI's to refuse."""src = graph.get(v[0])if not isinstance(src, dict) or not isinstance(src.get("class_type"), str):return None@@ -632,10 +611,10 @@ def input_problem(graph: dict, cls: str, key: str, v, kinds: NodeKinds | None =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.+ # A list that isn't a link [node, output].return "unsafe-graph"if isinstance(v, float) and not math.isfinite(v):- # NaN passes every min and max ComfyUI checks.+ # NaN or infinity.return "unsafe-graph"if is_link(v) and not plain_slot(v):return "unsafe-graph"@@ -741,7 +720,7 @@ def graph_problem(graph, staged: list[str] | None) -> str | None:if v is None:continueif isinstance(v, list):- # The studio names its files as values; a loader fed by another node could be fed any name.+ # The studio names its files as values, never as links.if known:return f"Node {node_id} ({cls}) reads a file named by another node"continue@@ -769,7 +748,8 @@ 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- 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.+ or a list the graph writes, a node key other than its type, inputs and title, 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 isknown, 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:@@ -802,8 +782,8 @@ def vet_graph(graph, allowed: frozenset | set, staged: list[str] | None, kinds:def _strings(v, depth: int = 0):- """Every text in an input value (a picture entry list is a dict of texts). A link [node, slot] has none: ComfyUI- reads one only as the input's whole value, so a list inside a value is read for its texts like any other."""+ """Every text in an input value (a picture entry list is a dict of texts). A link [node, slot], as an input's whole+ value, has none; a list inside a value is read for its texts like any other."""if isinstance(v, str):yield velif isinstance(v, dict) and depth < 4:diff --git a/integrations/fuobe-connect/fuobe_connect/logs.py b/integrations/fuobe-connect/fuobe_connect/logs.pynew file mode 100644index 00000000..05bac806--- /dev/null+++ b/integrations/fuobe-connect/fuobe_connect/logs.py@@ -0,0 +1,64 @@+"""Fuobe Connect's log: one logger for the whole pack, and every line it writes in plain ASCII.++A console, a file or a pipe takes ASCII in every Windows language, so a line with a masked account (a•••@... is+written a***@...) or a computer's name never stops a log handler. The pack's own marks become their nearest ASCII (a+bullet "*", an arrow ">"); any other character becomes a \\u escape. Only the log line changes: the Connect to Fuobe+window in ComfyUI shows the text as it is.+"""++from __future__ import annotations++import logging++NAME = "fuobe_connect"++_MARKS = str.maketrans(+ {+ "•": "*", # bullet+ "·": "-", # middle dot+ "→": ">", # arrow+ "←": "<",+ "…": "...",+ "‘": "'",+ "’": "'",+ "“": '"',+ "”": '"',+ "–": "-",+ "—": "-",+ " ": " ",+ }+)+++def ascii_text(text) -> str:+ """The text in ASCII: the marks above as their nearest ASCII, anything else as a \\u escape."""+ return str(text).translate(_MARKS).encode("ascii", "backslashreplace").decode("ascii")+++class AsciiLines(logging.Filter):+ """Writes each record's message, and its traceback, in ASCII before any handler sees it."""++ fuobe_ascii = True++ def filter(self, record: logging.LogRecord) -> bool:+ try:+ message = record.getMessage()+ except Exception:+ message = f"{record.msg!r} {record.args!r}"+ record.msg = ascii_text(message)+ record.args = None+ if record.exc_info and not record.exc_text:+ record.exc_text = logging.Formatter().formatException(record.exc_info)+ if record.exc_text:+ record.exc_text = ascii_text(record.exc_text)+ if record.stack_info:+ record.stack_info = ascii_text(record.stack_info)+ return True+++def get_log() -> logging.Logger:+ """The pack's logger, with AsciiLines on it once."""+ log = logging.getLogger(NAME)+ if not any(getattr(f, "fuobe_ascii", False) for f in log.filters):+ log.addFilter(AsciiLines())+ return logdiff --git a/integrations/fuobe-connect/fuobe_connect/middleware.py b/integrations/fuobe-connect/fuobe_connect/middleware.pyindex 5e36deb6..ae094c18 100644--- a/integrations/fuobe-connect/fuobe_connect/middleware.py+++ b/integrations/fuobe-connect/fuobe_connect/middleware.py@@ -16,13 +16,12 @@ is 127.0.0.1, ::1 or localhost) for a path a Fuobe run needs (origins.allowed).in your input folder (Studios.answer).Any other request from a trusted studio (another path, another Host, a preflight a run never sends) is turned away-here, so a studio never reaches ComfyUI unchecked, whatever ComfyUI's start options say. Every other request goes on-untouched, so ComfyUI's own check still turns away every other website.+here, whatever ComfyUI's start options say. Every other request goes on untouched, to ComfyUI's own check.-When ComfyUI was started with --enable-cors-header (which switches its own check off), the middleware also does what-Fuobe's guard does: a request from any other web page gets in only when the page is ComfyUI's own or the origin the-setting names. A trusted studio still gets only the checked paths above, even when the setting names it. With-"--enable-cors-header *" (every site, the person's choice) it adds no check for other websites.+When ComfyUI was started with --enable-cors-header and a site's address, the middleware also does what Fuobe's guard+does: a request from any other web page gets in only when the page is ComfyUI's own or the origin the setting names. A+trusted studio still gets only the checked paths above, even when the setting names it. "--enable-cors-header *" (every+site) is the person's own choice, and other websites get in as that setting says.Pure aiohttp: the tests load it with ComfyUI's own middleware and nothing else."""@@ -30,13 +29,13 @@ Pure aiohttp: the tests load it with ComfyUI's own middleware and nothing else.from __future__ import annotationsimport json-import loggingfrom collections import OrderedDictfrom typing import Callable, Iterablefrom aiohttp import webfrom .graph import CLIENT_ID, FILE_LOADERS, UUID, fuobe_prefixed, files_in, staged_name_ok, vet_graph+from .logs import get_logfrom .origins import allowed, host_name, is_loopback, normalise, same_hostALLOW_METHODS = "GET, POST, OPTIONS"@@ -46,13 +45,15 @@ MARKER = "X-Fuobe-Connect-Studio"ALLOW_HEADERS = {"content-type"}MAX_AGE = "600"+log = get_log()+_told: set[str] = set()def _note(why: str) -> None:if why not in _told and len(_told) < 50:_told.add(why)- logging.warning("[Fuobe Connect] Turned away a request from %s", why)+ log.warning("[Fuobe Connect] Turned away a request from %s", why)def _cors_headers(origin: str) -> dict[str, str]:@@ -119,8 +120,7 @@ class Studios:def __init__(self, nodes: Callable[[], Iterable[str]] | None = None, held: Callable[[str], bool] | None = None):"""`held(prompt_id)`: ComfyUI already has a prompt with this id, in its queue or its history (comfy_held, inside- ComfyUI). ComfyUI takes any new prompt under an id it already holds, so a studio that learned the id of a- prompt of yours (from the live socket) could otherwise claim it."""+ ComfyUI). A studio's prompt under such an id is refused."""self.nodes = nodes or (lambda: frozenset())self.held = heldself.prompts: OrderedDict[str, None] = OrderedDict()@@ -209,7 +209,7 @@ class Studios:try:taken = bool(self.held(pid))except Exception:- logging.exception("[Fuobe Connect] Couldn't read ComfyUI's queue and history")+ log.exception("[Fuobe Connect] Couldn't read ComfyUI's queue and history")return _refuse("Fuobe Connect couldn't check this prompt's id against ComfyUI's queue. Update Fuobe Connect in ComfyUI-Manager, then retry.", 503)if taken:_note("a trusted studio: it sent the id of a prompt that ComfyUI already holds")@@ -361,13 +361,13 @@ def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | Noneflag_origin = normalise(flag) if flag and flag != "*" else Noneguard_on = bool(flag) and flag != "*"if guard_on and flag_origin is None:- logging.warning("[Fuobe Connect] --enable-cors-header %r isn't a website's address (like http://localhost:3000), so only ComfyUI's own page and the trusted studios get in.", flag[:80])+ log.warning("[Fuobe Connect] --enable-cors-header %r isn't a website's address (like http://localhost:3000), so only ComfyUI's own page and the trusted studios get in.", flag[:80])try:named = flag_origin is not None and flag_origin in set(trusted())except Exception:named = Falseif named:- logging.warning(+ log.warning("[Fuobe Connect] --enable-cors-header %s isn't needed for that studio: Fuobe Connect lets it use this ComfyUI on this computer (at a network address too with FUOBE_CONNECT_LAN=1), with its checks. The setting gives it nothing more.",flag_origin,)@@ -400,8 +400,8 @@ def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | Noneresponse.headers.update(_cors_headers(origin))return response# Anything else a trusted studio asks for (another path, a preflight a run never sends, or this ComfyUI- # under another name or a network address) never reaches ComfyUI unchecked, even when- # --enable-cors-header names that studio and ComfyUI's own check is off.+ # under another name or a network address) is turned away here, also when --enable-cors-header names+ # that studio.return web.Response(status=403)if guard_on and (origin is None or origin != flag_origin) and not same_host(raw, host):_note(raw[:120])diff --git a/integrations/fuobe-connect/fuobe_connect/net.py b/integrations/fuobe-connect/fuobe_connect/net.pyindex 7dee8d19..373a97f6 100644--- a/integrations/fuobe-connect/fuobe_connect/net.py+++ b/integrations/fuobe-connect/fuobe_connect/net.py@@ -1,8 +1,8 @@"""The two places Fuobe Connect talks to: the paired Fuobe studio (over HTTPS, with its token) and this ComfyUI itself(on this computer, as a program: no browser headers, so ComfyUI's own checks treat it as it treats any local tool).-Every answer from the studio is read with a size limit, and files go through a temporary file, so a broken or taken-over-studio can't fill ComfyUI's memory. Only aiohttp, which ComfyUI already has.+Every answer from the studio is read with a size limit, and files go through a temporary file, so ComfyUI's memory use+stays small. Only aiohttp, which ComfyUI already has."""from __future__ import annotationsdiff --git a/integrations/fuobe-connect/fuobe_connect/origins.py b/integrations/fuobe-connect/fuobe_connect/origins.pyindex aa18efe8..75dc4056 100644--- a/integrations/fuobe-connect/fuobe_connect/origins.py+++ b/integrations/fuobe-connect/fuobe_connect/origins.py@@ -140,8 +140,7 @@ def trusted_origins(env_value: str | None, configured: str | list | None) -> tup# body or the answer of several of these (middleware.py)._UUID = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"-# A model folder's list. ComfyUI also answers for folders that hold no models: custom_nodes (every file of every node-# pack) and configs.+# A model folder's list: any folder ComfyUI lists except custom_nodes and configs, which hold no models._MODELS = r"models(?:/(?!(?:custom_nodes|configs)\Z)[A-Za-z0-9_.-]{1,64})?"_GET = re.compile(r"/(?:"diff --git a/integrations/fuobe-connect/fuobe_connect/plugin.py b/integrations/fuobe-connect/fuobe_connect/plugin.pyindex 9988a10a..a2fefeea 100644--- a/integrations/fuobe-connect/fuobe_connect/plugin.py+++ b/integrations/fuobe-connect/fuobe_connect/plugin.py@@ -8,7 +8,6 @@ files changes.from __future__ import annotationsimport asyncio-import loggingimport osimport reimport sys@@ -17,10 +16,11 @@ from aiohttp import webfrom . import __version__from .graph import NodeList, comfy_kinds+from .logs import get_logfrom .middleware import MARKER, Studios, comfy_held, make_middlewarefrom .origins import DEFAULT_STUDIOS, NONE, host_name, is_ip, is_loopback, normalise, parse_list, same_host, says_none, studio, trusted_origins, with_twins-log = logging.getLogger("fuobe_connect")+log = get_log()_state: dict = {}@@ -49,9 +49,9 @@ def own_hosts() -> set[str]:def _own_page(request: web.Request, post: bool = False) -> bool:"""A call from ComfyUI's own page, or from a program on this computer: never from a trusted studio or any website.- The Host must be this computer (127.0.0.1, ::1, localhost), an IP address, or a name in FUOBE_CONNECT_HOSTS: a page- whose own name was pointed at this computer (DNS rebinding) has neither. The Origin, when there is one, is that- Host with the same port; the browser's Sec-Fetch-Site, when sent, says same-origin; a change is JSON."""+ The Host must be this computer (127.0.0.1, ::1, localhost), an IP address, or a name in FUOBE_CONNECT_HOSTS. The+ Origin, when there is one, is that Host with the same port; the browser's Sec-Fetch-Site, when sent, says+ same-origin; a change is JSON."""if request.headers.get(MARKER):return Falsehost = host_name(request.headers.get("Host"))diff --git a/integrations/fuobe-connect/fuobe_connect/runner.py b/integrations/fuobe-connect/fuobe_connect/runner.pyindex 128a3eb8..2a28d04c 100644--- a/integrations/fuobe-connect/fuobe_connect/runner.py+++ b/integrations/fuobe-connect/fuobe_connect/runner.py@@ -18,7 +18,6 @@ from __future__ import annotationsimport asyncioimport json-import loggingimport osimport reimport time@@ -41,9 +40,10 @@ from .graph import (staged_name_ok,vet_graph,)+from .logs import get_logfrom .net import Comfy, Site, TooBig, seg-log = logging.getLogger("fuobe_connect")+log = get_log()BEAT_S = 10BUSY_BEAT_S = 5diff --git a/integrations/fuobe-connect/fuobe_connect/store.py b/integrations/fuobe-connect/fuobe_connect/store.pyindex 3070e12e..2c2b7356 100644--- a/integrations/fuobe-connect/fuobe_connect/store.py+++ b/integrations/fuobe-connect/fuobe_connect/store.py@@ -8,13 +8,14 @@ inherited entries), set before the token is written.from __future__ import annotationsimport json-import loggingimport osimport threading+from .logs import get_log+FILE_NAME = "fuobe-connect.json"-log = logging.getLogger("fuobe_connect")+log = get_log()def _current_user_sid() -> str | None:diff --git a/integrations/fuobe-connect/pyproject.toml b/integrations/fuobe-connect/pyproject.tomlindex 5c13e218..c66f58b9 100644--- a/integrations/fuobe-connect/pyproject.toml+++ b/integrations/fuobe-connect/pyproject.toml@@ -1,7 +1,7 @@[project]name = "fuobe-connect"description = "Use this ComfyUI from Fuobe with one install: no start flag, no extra file. Trusts only the Fuobe studios you name, checks every workflow they send against the node list it ships, keeps ComfyUI's own check for every other website, and can pair with your Fuobe account for Safari, phones and PCs with no screen."-version = "1.0.1"+version = "1.0.2"license = { file = "LICENSE" }requires-python = ">=3.9"# aiohttp comes with ComfyUI: naming it here could make ComfyUI-Manager change ComfyUI's own copy.diff --git a/integrations/fuobe-connect/tests/comfy_engine.py b/integrations/fuobe-connect/tests/comfy_engine.pydeleted file mode 100644index c25f577c..00000000--- a/integrations/fuobe-connect/tests/comfy_engine.py+++ /dev/null@@ -1,258 +0,0 @@-"""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/comfy_kinds_check.py b/integrations/fuobe-connect/tests/comfy_kinds_check.pynew file mode 100644index 00000000..782699a0--- /dev/null+++ b/integrations/fuobe-connect/tests/comfy_kinds_check.py@@ -0,0 +1,144 @@+"""Fuobe Connect's graph check with ComfyUI's own node classes, for test_comfy_kinds.py.++Run as: python -I -B comfy_kinds_check.py <ComfyUI folder> <pack folder> <scratch folder> [<Fuobe's workflows folder>].+It loads ComfyUI's nodes 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: vet_graph's answer for each graph below, with comfy_kinds reading+ComfyUI's own NODE_CLASS_MAPPINGS and node replacements. Exit code 3: this Python can't load ComfyUI (no torch).+"""++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+try:+ import torch # noqa: F401+except ImportError:+ sys.exit(3)+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++asyncio.run(nodes.init_extra_nodes(init_custom_nodes=False, init_api_nodes=False))++from app.node_replace_manager import NodeReplaceManager # noqa: E402+from comfy_api.latest._io import NodeReplace # noqa: E402++from fuobe_connect.graph import comfy_kinds, shipped_nodes, vet_graph # noqa: E402++MODEL = "fuobe_abcdefgh12.glb"+PICTURE = "fuobe_abcdefgh12.png"+STAGED = [MODEL, PICTURE]++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()+++def vet(graph: dict, staged=STAGED, kinds=KINDS, allowed=ALLOWED):+ return vet_graph(copy.deepcopy(graph), allowed, staged, kinds)+++def save(images, **more) -> dict:+ return {"class_type": "SaveImage", "inputs": {"images": images, "filename_prefix": "fuobe/abcdef12", **more}}+++def save3d(view, model=("30", 6)) -> dict:+ return {"class_type": "Save3DAdvanced", "inputs": {"model_3d": list(model), "viewport_state": view, "width": 512, "height": 512, "filename_prefix": "fuobe/abcdef12"}}+++EMPTY = {"class_type": "EmptyImage", "inputs": {"width": 8, "height": 8, "batch_size": 1, "color": 0}}+CLIP = {"class_type": "CLIPLoader", "inputs": {"clip_name": "a.safetensors", "type": "sd3", "device": "default"}}+LOAD3D = {"class_type": "Load3D", "inputs": {"model_file": MODEL, "image": {"image": PICTURE, "mask": PICTURE, "normal": PICTURE, "recording": "", "camera_info": {}}, "width": 512, "height": 512}}++results: dict = {"listed": vet({"10": save(["40", 0]), "40": EMPTY})}++# A link into an input SaveImage doesn't list, and into one of its hidden inputs.+for name, extra in (("unlisted-input", {"zzz": ["20", 0]}), ("hidden-input", {"prompt": ["20", 0]})):+ graph = {"10": save(["40", 0], **extra), "40": EMPTY, "20": CLIP}+ results[name] = {"vet": vet(graph), "vet_without_kinds": vet(graph, kinds=None)}++# A dynamic node's inputs: the ones ComfyUI works out from the node's own values, and one it doesn't list.+graph = {"10": save(["41", 0]), "40": EMPTY, "41": {"class_type": "BatchImagesNode", "inputs": {"images.image0": ["40", 0], "images.image1": ["40", 0]}}}+other = copy.deepcopy(graph)+other["41"]["inputs"]["pictures.image9"] = ["40", 0]+results["dynamic-inputs"] = {"vet_listed": vet(graph), "vet_other": vet(other)}++# A {"__value__": ...} object in a 3D view.+graph = {"10": save3d({"__value__": ["20", 0]}), "30": LOAD3D, "20": CLIP}+results["value-object"] = {"vet": vet(graph), "vet_direct": vet(graph, None)}++# A node key other than its type, inputs and title.+results["node-key"] = {"vet": vet({"10": save(["42", 0]), "42": {"class_type": "LoadImage", "inputs": {"image": PICTURE}, "is_changed": ["x"]}})}++# A loop: every node reached from an output node, and one more node (3) that no output needs.+start = {"class_type": "StartLoop", "inputs": {"mode": "simple", "mode.num_iterations": 2, "cache_iterations": False}}+reached = {+ "1": start,+ "2": {"class_type": "EmptyImage", "inputs": {"width": 8, "height": 8, "batch_size": 1, "color": ["1", 0]}},+ "3": {"class_type": "EndLoop", "inputs": {"accumulate": True, "output_value": ["2", 0]}},+ "4": {"class_type": "RebatchImages", "inputs": {"images": ["3", 0], "batch_size": 64}},+ "5": save(["4", 0]),+}+spare = {+ "1": start,+ "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": 35, "zoom": 1}},+ "4": {"class_type": "EndLoop", "inputs": {"accumulate": False, "terminations.termination0": ["2", 3], "next_iteration_value": ["3", 0]}},+ "5": LOAD3D,+}+spare["2"]["inputs"] = {**spare["2"]["inputs"], "width": ["1", 0]}+results["loop"] = {"vet_reached": vet(reached), "vet_spare": vet(spare)}++# A missing node type that ComfyUI has a node replacement for, and one it hasn't.+replaced = {"10": save(["43", 0]), "43": {"class_type": "FuobeOldLoader", "inputs": {"path": PICTURE}}}+missing = {"10": save(["43", 0]), "43": {"class_type": "FuobeOtherLoader", "inputs": {"path": PICTURE}}}+results["node-replacement"] = {+ "vet_replaced": vet(replaced, allowed=ALLOWED | {"FuobeOldLoader"}),+ "vet_missing": vet(missing, allowed=ALLOWED | {"FuobeOtherLoader"}),+}++# Fuobe's own workflows (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/pair_and_run.py b/integrations/fuobe-connect/tests/pair_and_run.pyindex 6bc73dcd..97998e7d 100644--- a/integrations/fuobe-connect/tests/pair_and_run.py+++ b/integrations/fuobe-connect/tests/pair_and_run.py@@ -4,7 +4,7 @@ line, waits for the approval, then runs that person's jobs on the ComfyUI at --cIt prints the worker token only when FUOBE_CONNECT_TEST_PRINT_TOKEN=1 (the end-to-end test needs it, with a throwawaystudio); otherwise only its last four characters. A token to start with comes from FUOBE_CONNECT_TOKEN, never from the-command line (where other programs on this computer could read it). Not part of the published pack.+command line. Not part of the published pack.python tests/pair_and_run.py --site http://127.0.0.1:3361 --comfy http://127.0.0.1:3362"""diff --git a/integrations/fuobe-connect/tests/test_comfy_engine.py b/integrations/fuobe-connect/tests/test_comfy_engine.pydeleted file mode 100644index 2c9a62cf..00000000--- a/integrations/fuobe-connect/tests/test_comfy_engine.py+++ /dev/null@@ -1,125 +0,0 @@-"""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_comfy_kinds.py b/integrations/fuobe-connect/tests/test_comfy_kinds.pynew file mode 100644index 00000000..37bfd259--- /dev/null+++ b/integrations/fuobe-connect/tests/test_comfy_kinds.py@@ -0,0 +1,94 @@+"""Fuobe Connect's graph check with the node classes of a real ComfyUI (comfy_kinds reading NODE_CLASS_MAPPINGS).++Needs COMFYUI_DIR (a ComfyUI folder) and a Python that can load it (torch and ComfyUI's requirements): ComfyUI's own+embedded Python, for one. Without torch the tests are skipped. comfy_kinds_check.py loads ComfyUI's nodes 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.+"""++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 ComfyKindsTest(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 check graphs with its own node classes")+ scratch = tempfile.mkdtemp(prefix="fuobe-connect-kinds-")+ try:+ done = subprocess.run(+ [sys.executable, "-I", "-B", os.path.join(HERE, "comfy_kinds_check.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 == 3:+ raise unittest.SkipTest("This Python can't load ComfyUI (no torch): run the tests with ComfyUI's own Python")+ if done.returncode != 0 or not done.stdout.strip():+ raise AssertionError(f"comfy_kinds_check.py failed ({done.returncode}):\n{done.stderr[-4000:]}")+ cls.results = json.loads(done.stdout.strip().splitlines()[-1])++ def test_takes_a_graph_with_listed_inputs(self):+ self.assertIsNone(self.results["listed"])++ def test_refuses_a_link_into_an_input_the_node_doesnt_list(self):+ r = self.results["unlisted-input"]+ self.assertEqual(r["vet"], "unsafe-graph")+ self.assertIsNone(r["vet_without_kinds"])++ def test_refuses_a_link_into_a_hidden_input(self):+ self.assertEqual(self.results["hidden-input"]["vet"], "unsafe-graph")++ def test_takes_only_a_dynamic_nodes_own_inputs(self):+ r = self.results["dynamic-inputs"]+ self.assertIsNone(r["vet_listed"])+ self.assertEqual(r["vet_other"], "unsafe-graph")++ def test_refuses_a_value_object(self):+ r = self.results["value-object"]+ self.assertEqual(r["vet"], "unsafe-graph")+ self.assertEqual(r["vet_direct"], "unsafe-graph")++ def test_refuses_a_node_key_other_than_type_inputs_and_title(self):+ self.assertEqual(self.results["node-key"]["vet"], "unsafe-graph")++ def test_loop_nodes_are_reached_from_an_output(self):+ r = self.results["loop"]+ self.assertIsNone(r["vet_reached"])+ self.assertEqual(r["vet_spare"], "unsafe-graph")++ def test_refuses_a_node_type_with_a_replacement(self):+ r = self.results["node-replacement"]+ self.assertEqual(r["vet_replaced"], "unknown-node")+ self.assertIsNone(r["vet_missing"])++ 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 bfef75d2..6b3ee615 100644--- a/integrations/fuobe-connect/tests/test_graph.py+++ b/integrations/fuobe-connect/tests/test_graph.py@@ -89,14 +89,14 @@ class NamesTest(unittest.TestCase):self.assertTrue(staged_name_ok(ok), ok)for bad in ["my_photo.png", "fuobe_short.png", "fuobe_abcdefgh12.html", "fuobe_abcdefgh12.svg", "fuobe_abcdefgh12.py", "fuobe_abcdefgh12.js", "fuobe_abcdefgh12.png [output]", "../fuobe_abcdefgh12.png", None, 3]:self.assertFalse(staged_name_ok(bad), bad)- # A settings file, or a file of no known type, that a node could read as one (ffmpeg's format file is a .json).+ # A settings file, or a file of no known type: never one of a run's inputs.for bad in ["fuobe_abcdefgh12.json", "fuobe_abcdefgh12.txt", "fuobe_abcdefgh12.csv", "fuobe_abcdefgh12.bin", "fuobe_abcdefgh12.octet"]:self.assertFalse(staged_name_ok(bad), bad)class VetTest(unittest.TestCase):def test_unknown_node(self):- self.assertEqual(vet_graph(g(node("KJ_RunPython", code="import os")), NODES, STAGED), "unknown-node")+ self.assertEqual(vet_graph(g(node("SomePackNode", text="x")), NODES, STAGED), "unknown-node")self.assertEqual(vet_graph(g({"inputs": {}}), NODES, STAGED), "unknown-node")self.assertEqual(vet_graph({}, NODES, STAGED), "unsafe-graph")self.assertEqual(vet_graph("x", NODES, STAGED), "unsafe-graph")@@ -106,15 +106,15 @@ class VetTest(unittest.TestCase):"C:/Users/me/Pictures","C:" + B + "Users" + B + "me",B + B + "server" + B + "share",- "/etc/passwd",- "/secret.png",+ "/home/me/notes.txt",+ "/photo.png","/",- "../../secret.png",+ "../../photo.png","fuobe/" + ".." + "/x",- "~/.ssh/id_rsa",- "http://192.168.1.1/admin",+ "~/notes.txt",+ "http://192.168.1.1/x.png","https://example.com/x.png",- "file:///etc/passwd",+ "file:///home/me/x.png","blake3:0123456789abcdef","ComfyUI_00001_.png [output]","preview.png [temp]",@@ -129,11 +129,11 @@ class VetTest(unittest.TestCase):"""Every way Windows, Linux and macOS read a text as a place outside a node's own folder."""for v in ["//?/C:/Users/Public/x.srt", # a Win32 device path with forward slashes- "//attacker.example/share/x.srt", # a network share with forward slashes+ "//other.example/share/x.srt", # a network share with forward slashesB + B + "?" + B + "C:" + B + "x", # \\?\C:\xB + B + "." + B + "PhysicalDrive0", # \\.\PhysicalDrive0B + "Users" + B + "Public" + B + "x.srt", # \Users\...: the root of ComfyUI's drive- B + "/attacker.example/share/x.srt", # \/host/share: a share too+ B + "/other.example/share/x.srt", # \/host/share: a share too"D:Users" + B + "x.srt", # a drive with no slash: that drive's own working folder"C:x.srt","C:",@@ -149,7 +149,7 @@ class VetTest(unittest.TestCase):"${HOME}$USER/x",# What a node that trims its text sees." C:/Users/me",- "\t/etc/passwd",+ "\t/home/me","\u3000" + B + "Users",'"C:/Users/me"',"'//host/share'",@@ -188,9 +188,9 @@ class VetTest(unittest.TestCase):path check when the person added them to their own list."""risky = [node("LoadImagesFromFolderKJ", folder="C:/Users/me/Pictures"),- node("LoadImageFromUrl", url="http://192.168.1.1/admin"),+ node("LoadImageFromUrl", url="http://192.168.1.1/x.png"),node("Image Load", image_path="C:/ProgramData/x.png"),- node("Image Saver", path="C:/ProgramData/Microsoft/Windows/Start Menu", images=["1", 0]),+ node("Image Saver", path="C:/Users/Public/Pictures", images=["1", 0]),]for n in risky:self.assertEqual(vet_graph(g(n), frozenset({"SaveImage"}), STAGED), "unknown-node", n)@@ -205,7 +205,7 @@ class VetTest(unittest.TestCase):node("LoadImage", image=["2", 0]), # a name another node works outnode("VHS_LoadVideo", video="clip.mp4"),node("Load3D", model_file="3d/scene.spz"),- node("Load3D", model_file="fuobe_abcdefgh34.spz", image={"image": "secret.png", "camera_info": {}}),+ node("Load3D", model_file="fuobe_abcdefgh34.spz", image={"image": "photo.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": {"position": {"x": 1, "y": 2, "z": 3}, "zoom": 1}})), NODES, STAGED))@@ -281,9 +281,9 @@ class NodeRulesTest(unittest.TestCase):self.assertIsNone(vet1("AILab_Qwen3ASRSubtitle", output_path=ok, audio=["9", 0]), ok)for bad in ["//?/C:/Users/Public/x.srt",- "//attacker.example/share/x.srt",+ "//other.example/share/x.srt",B + "Users" + B + "Public" + B + "x.srt",- B + "/attacker.example/share/x.srt",+ B + "/other.example/share/x.srt","D:Users" + B + "x.srt","C:/Users/Public/x.srt","captions", # anywhere in your output folder@@ -364,7 +364,8 @@ class NodeRulesTest(unittest.TestCase):self.assertEqual(vet1("Hi3DLoadMesh", mesh_file=bad), "unsafe-graph", bad)def test_json_objects(self):- """ComfyUI passes an object the graph writes to a node unchecked (a LoRA list, a model path, a {"__value__"})."""+ """A value the graph writes is never a JSON object (a LoRA list, a model path, a {"__value__"}), except a 3D+ view's entries."""for bad in [node("WanVideoModelLoader", extra_model={"path": "models/x.safetensors"}),node("WanVideoModelLoader", lora={"__value__": [{"path": "loras/x.safetensors", "strength": 1}]}),@@ -383,10 +384,10 @@ class NodeRulesTest(unittest.TestCase):self.assertEqual(vet_graph(g(node("StringConcatenate", string_a="<svg", string_b="></svg>", delimiter=""), node("TS_SVGStringToSVGBytesIO", SVG_String=["1", 0])), SHIPPED, STAGED), "unsafe-graph")def test_format_reads_no_attribute(self):- """Python's format reaches a module's globals through an object: "{a.__init__.__globals__[os].environ}"."""+ """StringFormat takes only plain replacement fields, never one that reads an attribute or an item."""for ok in ["Dress {a} in image 1 in {b}. Keep the rest.", '{{"width": {a}, "height": {b}, "coords": "relative-1000"}}', "{a:.2f} and {b!r}", "{{a.b}}"]:self.assertIsNone(vet1("StringFormat", f_string=ok), ok)- for bad in ["{a.__init__.__globals__[os].environ}", "{a[0]}", "x {b.real}", "{{{a.x}}}", "{a:{b.__class__}}", ["2", 0]]:+ for bad in ["{a.__class__}", "{a[0]}", "x {b.real}", "{{{a.x}}}", "{a:{b.__class__}}", ["2", 0]]:self.assertEqual(vet1("StringFormat", f_string=bad), "unsafe-path", bad)@@ -401,7 +402,7 @@ _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 inputsComfyUI 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."""+ get_finalized_class_inputs (test_comfy_kinds.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)}@@ -493,8 +494,7 @@ WITH_OWN = SHIPPED | {"MyAnyNode", "MyOptions"}class LinkTest(unittest.TestCase):- """ComfyUI doesn't type-check a link from an "any", match-typed or dropdown-typed output, and checks a dropdown's- value against its list only when the graph writes it. Such links, and links into a dropdown, feed only what Fuobe's+ """A link from an "any", match-typed or dropdown-typed output, and a link into a dropdown, feeds only what Fuobe'sown graphs feed that way."""def test_shipped_list(self):@@ -510,19 +510,19 @@ class LinkTest(unittest.TestCase):self.assertEqual(input_kind("images.image12"), "images.image#")self.assertEqual(input_kind("audio2"), "audio#")- def test_any_link_into_a_dropdown(self):- """CreateList or VRAM_Debug ("*") hands a dropdown any text: a model name it then downloads, or a file name."""- evil = "attacker/evil-repo"+ def test_refuses_a_loose_link_into_a_dropdown(self):+ """Refuses a text passed on by CreateList, GetItemFromList or VRAM_Debug ("*") into a dropdown or a text input."""+ text = "someone/other-model"for kinds in (None, KINDS):- through_list = chain(node("CreateList", input1=evil), node("GetItemFromList", list=["1", 0], index=0), node("DownloadAndLoadWav2VecModel", model=["2", 0], base_precision="fp16", load_device="main_device"))+ through_list = chain(node("CreateList", input1=text), node("GetItemFromList", list=["1", 0], index=0), node("DownloadAndLoadWav2VecModel", model=["2", 0], base_precision="fp16", load_device="main_device"))self.assertIsNotNone(vet_graph(through_list, SHIPPED, STAGED, kinds))- through_debug = chain(node("PrimitiveStringMultiline", value=evil), node("VRAM_Debug", any_input=["1", 0]), node("DownloadAndLoadWav2VecModel", model=["2", 0]))+ through_debug = chain(node("PrimitiveStringMultiline", value=text), node("VRAM_Debug", any_input=["1", 0]), node("DownloadAndLoadWav2VecModel", model=["2", 0]))self.assertIsNotNone(vet_graph(through_debug, SHIPPED, STAGED, kinds))# A dropdown that no rule here names: the link itself is refused.for src in (node("GetItemFromList", list=["9", 0], index=0), node("VRAM_Debug", any_input=["9", 0]), node("ComfySwitchNode", switch=True, on_true=["9", 0], on_false=["9", 0])):self.assertEqual(vet_graph(chain(src, node("LoraLoader", model=["8", 0], clip=["8", 1], lora_name=["1", 0])), SHIPPED, STAGED, kinds), "unsafe-graph", src)self.assertEqual(vet_graph(chain(src, node("Apply Whisper", audio=["8", 0], model=["1", 0])), SHIPPED, STAGED, kinds), "unsafe-graph", src)- # Into any input Fuobe's graphs don't feed that way: the text would reach it unchecked.+ # Into any other input that Fuobe's graphs don't feed that way: refused too.self.assertEqual(vet_graph(chain(src, node("CLIPTextEncode", text=["1", 0], clip=["8", 0])), SHIPPED, STAGED, kinds), "unsafe-graph", src)def test_links_fuobe_graphs_make(self):@@ -536,10 +536,9 @@ class LinkTest(unittest.TestCase):# The bit depth into another dropdown: no.self.assertEqual(vet_graph(chain(node("GetVideoComponents", video=["9", 0]), node("Apply Whisper", audio=["9", 0], model=["1", 3])), SHIPPED, STAGED, kinds), "unsafe-graph")- def test_every_link_comfyui_reads(self):- """ComfyUI reads [node, false] as output 0, [node, true] as output 1 and [node, -1] as the last output, and- takes a number with a point as a link too. Each one is a link here, and each one is refused: a value worked out- by a loose output would otherwise reach a dropdown or ffmpeg's arguments as if no link were there."""+ def test_refuses_a_link_slot_that_isnt_a_whole_number(self):+ """Every value that ComfyUI's is_link takes as a link is a link here too. Only a whole number from 0 passes as+ its output: [node, false], [node, true], [node, -1] and a number with a point are refused."""comfy = comfy_is_link()for v in (["1", 0], ["1", 3], ["1", False], ["1", True], ["1", 0.0], ["1", -1], ["1", 2.5], ["1", "0"], [1, 0], ["1"], ["1", 0, 0], ("1", 0), "1"):self.assertEqual(is_link(v), comfy(v), v)@@ -568,15 +567,15 @@ class LinkTest(unittest.TestCase):def test_lists_inside_a_value_are_read(self):"""ComfyUI reads a link only as an input's whole value. A list inside a value is never a link, so its texts areread like any other."""- for inner in (["//host/share/x", 0], ["C:" + B + "Users" + B + "x", False], ["/etc/passwd", 0.0]):+ for inner in (["//host/share/x", 0], ["C:" + B + "Users" + B + "x", False], ["/home/me", 0.0]):self.assertEqual(vet1("CLIPTextEncode", text="a red door", clip=[inner, 0]), "unsafe-path", inner)self.assertEqual(vet1("CLIPTextEncode", text=["x", [inner]], clip=["8", 0]), "unsafe-path", inner)# A link's own node id isn't text a node reads.self.assertIsNone(vet1("CLIPTextEncode", text="a red door", clip=["8", 0]))def test_node_kinds_inside_comfyui(self):- """Inside ComfyUI the node classes say more: any node's untyped outputs (your own listed nodes' too), and- every dropdown, which a typed link may not feed either when a node skips ComfyUI's type check."""+ """Inside ComfyUI the node classes say more: any node's loosely typed outputs (your own listed nodes' too), and+ every dropdown, which takes only the links that Fuobe's own graphs make."""own_any = chain(node("MyAnyNode", value="x"), node("CLIPTextEncode", text=["1", 0], clip=["8", 0]))self.assertIsNone(vet_graph(own_any, WITH_OWN, STAGED)) # not on the shipped list of untyped outputsself.assertEqual(vet_graph(own_any, WITH_OWN, STAGED, KINDS), "unsafe-graph")@@ -614,19 +613,18 @@ class LinkTest(unittest.TestCase):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."""+ def test_video_format_is_a_written_name(self):+ """VHS_VideoCombine's format is a plain name the graph writes (video/h264-mp4): never a link, never a folder."""for staged in (None, ["fuobe_abcdefgh12.json"]):for kinds in (None, KINDS):replaced = chain(- node("StringReplace", string="video/@@" + B + "@@" + B + "@@" + B + "input" + B + "fuobe_abcdefgh12", find="@", replace="."),+ node("StringReplace", string="video/h264-mp4", find="2", replace="5"),node("GetItemFromList", list=["1", 0], index=0),node("VHS_VideoCombine", images=["9", 0], format=["2", 0], frame_rate=24, filename_prefix="fuobe/x"),)self.assertIsNotNone(vet_graph(replaced, SHIPPED, staged, kinds))switched = chain(- node("PrimitiveStringMultiline", value="video/C:" + B + "ComfyUI" + B + "input" + B + "fuobe_abcdefgh12"),+ node("PrimitiveStringMultiline", value="video/h264-mp4"),node("ComfySwitchNode", switch=True, on_true=["1", 0], on_false=["1", 0]),node("VHS_VideoCombine", images=["9", 0], format=["2", 0], frame_rate=24, filename_prefix="fuobe/x"),)@@ -637,10 +635,10 @@ class LinkTest(unittest.TestCase):self.assertEqual(vet1("VHS_VideoCombine", images=["9", 0], format=bad, frame_rate=24, filename_prefix="fuobe/x"), "unsafe-path", bad)def test_ffmpeg_settings_are_plain_words(self):- """The format's settings go into ffmpeg's arguments, the GIF dither into a filter (where "movie=" reads a file)."""+ """VHS_VideoCombine's other settings are each one plain word that the graph writes."""base = {"images": ["9", 0], "format": "video/h264-mp4", "frame_rate": 24, "filename_prefix": "fuobe/x"}self.assertIsNone(vet1("VHS_VideoCombine", **base, pix_fmt="yuv420p", crf=19, save_metadata=True, profile="hq", dither="sierra2_4a", audio=["8", 0]))- for bad in ["none[x];movie=secret.png[y];[x][y]overlay", "sierra2_4a:diff_mode=rectangle", "yuv420p -i x", "a,b"]:+ for bad in ["a;b", "a[b]", "a=b", "a:b", "a b", "a,b"]:self.assertEqual(vet1("VHS_VideoCombine", **{**base, "format": "video/ffmpeg-gif"}, dither=bad), "unsafe-path", bad)# A link only into the pictures, the sound, the batch, the VAE and the frame rate.made = chain(node("StringConcatenate", string_a="none", string_b="x", delimiter=","), node("VHS_VideoCombine", **{**base, "format": "video/ffmpeg-gif"}, dither=["1", 0]))@@ -649,14 +647,14 @@ class LinkTest(unittest.TestCase):self.assertEqual(vet_graph(prefix, SHIPPED, STAGED), "unsafe-graph")def test_download_names(self):- """Nodes that download what their dropdown names, or load a pickle by name: only the names on their lists."""+ """Nodes that download what their dropdown names, or load a model file by name: only the names on their lists."""for ok in ["TencentGameMate/chinese-wav2vec2-base", "facebook/wav2vec2-base-960h"]:self.assertIsNone(vet1("DownloadAndLoadWav2VecModel", model=ok, base_precision="fp16"), ok)- for bad in ["attacker/evil-repo", "facebook/wav2vec2-base-960h-evil", "TencentGameMate/chinese-wav2vec2-base/../x", ["2", 0]]:+ for bad in ["someone/other-model", "facebook/wav2vec2-base-960h-other", "TencentGameMate/chinese-wav2vec2-base/../x", ["2", 0]]:self.assertEqual(vet1("DownloadAndLoadWav2VecModel", model=bad), "unsafe-path", bad)for ok in ["rife47.pth", "rife49.pth", "rife417.pth", "rife426.pth", "sudo_rife4_269.662_testV1_scale1.pth"]:self.assertIsNone(vet1("RIFE VFI", ckpt_name=ok, frames=["9", 0]), ok)- for bad in ["rife50.pth", "x/rife49.pth", "rife49.pth.evil", ["2", 0]]:+ for bad in ["rife50.pth", "x/rife49.pth", "rife49.pth.bak", ["2", 0]]:self.assertEqual(vet1("RIFE VFI", ckpt_name=bad), "unsafe-path", bad)for ok in ["face_yolov8m.pt", "bbox" + B + "face_yolov8m.pt", "segm/person_yolov8m-seg.pt"]:self.assertIsNone(vet1("H3FaceTrackCrop", detector=ok), ok)@@ -697,8 +695,8 @@ FUOBE_CAMERA = {"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"}+# A file in your output folder, under ComfyUI's default name.+OUTPUT_FILE = {"filename": "ComfyUI_00001_.png", "subfolder": "", "type": "output"}def save3d(view, **more) -> dict:@@ -718,14 +716,14 @@ class SpecNode(FakeNode):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."""+ """A node pack's optional inputs that say they hold every name (VHS_VideoCombine's): only the names the dict holds+ count as listed."""def __contains__(self, key):return True-ENGINE = {+SPEC_CLASSES = {"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",)),@@ -738,7 +736,7 @@ ENGINE = {class FakeReplacements:- """ComfyUI's NodeReplaceManager, with the old node types it swaps."""+ """ComfyUI's NodeReplaceManager, with the old node types it has replacements for."""def __init__(self, old: set):self.old = old@@ -774,22 +772,21 @@ LOOPS = {}-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."""+class GraphShapeTest(unittest.TestCase):+ """Rules on a graph's shape beyond each input's own rule: no "__value__" object, no written list or JSON object, a+ node's keys, a 3D view's form, a run's files in its history, links only into listed inputs, node replacements and+ loops."""- 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(+ def test_refuses_a_value_object(self):+ """Refuses a graph with a {"__value__": ...} object: at any depth, in any input, or as an input's name."""+ graph = 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"),+ node("CLIPLoader", clip_name="a.safetensors", type="sd3", device="default"),)for staged in (None, ["fuobe_abcdefgh34.spz"]):for kinds in (None, KINDS):- self.assertEqual(vet_graph(attack, SHIPPED, staged, kinds), "unsafe-graph")+ self.assertEqual(vet_graph(graph, 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]}},@@ -805,8 +802,8 @@ class ComfyOwnRulesTest(unittest.TestCase):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."""+ """A value the graph writes is never a list (a link is [node, output]), and a number is never NaN or+ infinity."""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"}@@ -816,9 +813,8 @@ class ComfyOwnRulesTest(unittest.TestCase):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"."""+ def test_node_keys(self):+ """A node holds only class_type, inputs and its title (_meta): refuses a node with any other key."""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": {}}):@@ -836,8 +832,7 @@ class ComfyOwnRulesTest(unittest.TestCase):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."""+ """The camera and the models' placements: numbers under ComfyUI's own names, nothing else."""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}))@@ -848,11 +843,11 @@ class ComfyOwnRulesTest(unittest.TestCase):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},+ OUTPUT_FILE,+ {**FUOBE_CAMERA, **OUTPUT_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, "position": OUTPUT_FILE},{**FUOBE_CAMERA, "cameraType": "fisheye"},{**FUOBE_CAMERA, "zoom": True},{**FUOBE_CAMERA, "zoom": float("nan")},@@ -864,13 +859,13 @@ class ComfyOwnRulesTest(unittest.TestCase):):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):+ for placements in ([OUTPUT_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"}):+ for view in ({**any_angle, "image": 5}, {**any_angle, "image": None}, {**any_angle, "image": {"image": "fuobe_abcdefgh12.png"}}, {**any_angle, "extra": ""}, {**any_angle, "image": "photo.png"}):self.assertEqual(vet1("Load3D", model_file="fuobe_abcdefgh34.spz", image=view), "unsafe-graph", view)def test_history_data_is_never_a_file(self):@@ -879,32 +874,32 @@ class ComfyOwnRulesTest(unittest.TestCase):"outputs": {"7": {"3d": [{"filename": "abcdef12_00001_.glb", "subfolder": "fuobe", "type": "output"}],- "camera_info": [ECHOED_FILE],- "model_3d_info": [{**ECHOED_FILE, "filename": "secret.png"}],+ "camera_info": [OUTPUT_FILE],+ "model_3d_info": [{**OUTPUT_FILE, "filename": "photo.png"}],}}}self.assertEqual([f["filename"] for f in files_in([entry])], ["abcdef12_00001_.glb"])- self.assertFalse(may_download(ECHOED_FILE, [entry]))+ self.assertFalse(may_download(OUTPUT_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")+ def test_links_only_into_listed_inputs(self):+ """A link goes only into an input the node lists as required or optional: refuses a link into any other input+ name, and any value in a hidden input."""+ kinds = comfy_kinds(lambda: SPEC_CLASSES)+ loader = node("CLIPLoader", clip_name="a.safetensors", type="sd3")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.+ graph = chain(loader, empty, node("SaveImage", images=["2", 0], filename_prefix="fuobe/x", **extra))+ self.assertEqual(vet_graph(graph, SHIPPED, STAGED, kinds), "unsafe-graph", extra)+ # Without the node classes the inputs aren't known; inside ComfyUI they are always there.+ self.assertIsNone(vet_graph(graph, SHIPPED, STAGED), extra)+ # A hidden input's name with a written value: refused too.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.+ # A pack's inputs that claim every name: only the names its dict holds count.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")@@ -913,7 +908,7 @@ class ComfyOwnRulesTest(unittest.TestCase):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: E731self.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).+ # A class that can't say what it takes: refused.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")))@@ -921,37 +916,36 @@ class ComfyOwnRulesTest(unittest.TestCase):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."""+ def test_refuses_a_node_type_with_a_replacement(self):+ """Refuses a missing node type that ComfyUI has a node replacement for."""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"}))+ swaps = comfy_kinds(lambda: SPEC_CLASSES, 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)))+ # A missing node type with no replacement: ComfyUI refuses the graph itself and says which type is missing.+ self.assertIsNone(vet_graph(graph, allowed, STAGED, comfy_kinds(lambda: SPEC_CLASSES, lambda: FakeReplacements(set()))))+ self.assertIsNone(vet_graph(graph, allowed, STAGED, comfy_kinds(lambda: SPEC_CLASSES, 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")+ self.assertIsNone(vet_graph(unlisted, allowed, STAGED, comfy_kinds(lambda: SPEC_CLASSES, lambda: None)))+ self.assertEqual(vet_graph({k: v for k, v in unlisted.items() if k != "2"}, allowed, STAGED, comfy_kinds(lambda: SPEC_CLASSES, 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")+ self.assertEqual(vet_graph(graph, allowed, STAGED, comfy_kinds(lambda: SPEC_CLASSES, 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."""+ def test_loops_reach_every_node_from_an_output(self):+ """In a graph with a loop (Start Loop, End Loop), every node is reached from an output node through links:+ refuses one that isn't."""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 Loop -> 2 Save3DAdvanced (an output, with outputs) -> 4 End Loop; 1 -> 3 -> 4, which no output needs.+ graph = {"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")+ self.assertEqual(vet_graph(graph, SHIPPED, ["fuobe_abcdefgh34.spz"], kinds), "unsafe-graph")# Fuobe's form: everything feeds the output.ok = {"1": start,@@ -961,7 +955,7 @@ class ComfyOwnRulesTest(unittest.TestCase):"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.+ # A node no output needs: fine 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")diff --git a/integrations/fuobe-connect/tests/test_logs.py b/integrations/fuobe-connect/tests/test_logs.pynew file mode 100644index 00000000..245b5fa9--- /dev/null+++ b/integrations/fuobe-connect/tests/test_logs.py@@ -0,0 +1,95 @@+"""Fuobe Connect's log (logs.py): every line in plain ASCII, so a log written to a file or a pipe in any Windows+language takes it."""++from __future__ import annotations++import io+import logging+import os+import re+import sys+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+PACK = os.path.dirname(HERE)+sys.path.insert(0, PACK)++from fuobe_connect.logs import NAME, ascii_text, get_log # noqa: E402++BULLETS = "a•••@example.com"+++class LogTest(unittest.TestCase):+ def logged(self, encoding: str, write) -> str:+ """What the pack's log writes through a handler whose stream takes only `encoding`; fails on a logging error."""+ out = io.TextIOWrapper(io.BytesIO(), encoding=encoding, errors="strict", write_through=True)+ handler = logging.StreamHandler(out)+ failed = []+ handler.handleError = lambda record: failed.append(sys.exc_info()[1])+ log = get_log()+ level, propagate = log.level, log.propagate+ log.addHandler(handler)+ log.setLevel(logging.INFO)+ log.propagate = False+ try:+ write(log)+ finally:+ log.removeHandler(handler)+ log.setLevel(level)+ log.propagate = propagate+ self.assertEqual(failed, [], encoding)+ return out.buffer.getvalue().decode(encoding)++ def test_masked_account_in_every_windows_language(self):+ line = f"Connected to https://fuobe.com as {BULLETS}. Your Fuobe jobs now run on this ComfyUI."+ for encoding in ("cp932", "cp936", "cp949", "cp950", "cp1251", "cp1252", "cp437", "ascii"):+ text = self.logged(encoding, lambda log: log.info("[Fuobe Connect] %s", line))+ self.assertIn("as a***@example.com.", text, encoding)++ def test_marks_and_other_text(self):+ text = self.logged("cp932", lambda log: log.warning("[Fuobe Connect] %s", "Settings → Fuobe Connect — “Studio” … スタジオ"))+ self.assertIn('Settings > Fuobe Connect - "Studio" ... \\u30b9\\u30bf\\u30b8\\u30aa', text)++ def test_a_traceback(self):+ def write(log):+ try:+ raise RuntimeError(f"no answer from {BULLETS}")+ except RuntimeError:+ log.exception("[Fuobe Connect] Couldn't reach %s", "スタジオ")++ text = self.logged("cp949", write)+ self.assertIn("RuntimeError: no answer from a***@example.com", text)+ self.assertIn("Couldn't reach \\u30b9", text)++ def test_text_is_formatted_once(self):+ text = self.logged("ascii", lambda log: log.info("%s and %d%%", "100% done", 5))+ self.assertIn("100% done and 5%", text)+ self.assertEqual(self.logged("ascii", lambda log: log.info("50% off")).strip(), "50% off")++ def test_ascii_text(self):+ self.assertEqual(ascii_text("plain [text] 100%"), "plain [text] 100%")+ self.assertEqual(ascii_text(BULLETS), "a***@example.com")+ self.assertEqual(ascii_text("·←‘x’– "), "-<'x'- ")+ self.assertTrue(ascii_text("\U0001f3ac é").isascii())++ def test_one_filter(self):+ for _ in range(3):+ log = get_log()+ self.assertIs(log, logging.getLogger(NAME))+ self.assertEqual(sum(1 for f in log.filters if getattr(f, "fuobe_ascii", False)), 1)++ def test_every_module_logs_through_it(self):+ """No module of the pack logs through another logger (only logs.py makes it)."""+ folder = os.path.join(PACK, "fuobe_connect")+ for name in os.listdir(folder):+ if not name.endswith(".py") or name == "logs.py":+ continue+ with open(os.path.join(folder, name), encoding="utf-8") as f:+ source = f.read()+ self.assertIsNone(re.search(r"\blogging\.", source), name)+ if re.search(r"\blog\.(?:info|warning|error|exception)\(", source):+ self.assertIn("log = get_log()", source, name)+++if __name__ == "__main__":+ unittest.main()diff --git a/integrations/fuobe-connect/tests/test_middleware.py b/integrations/fuobe-connect/tests/test_middleware.pyindex f5a8a95e..147f5185 100644--- a/integrations/fuobe-connect/tests/test_middleware.py+++ b/integrations/fuobe-connect/tests/test_middleware.py@@ -28,7 +28,7 @@ from fuobe_connect.origins import allowed, normalise, parse_list, same_host, stuPORT = int(os.environ.get("FUOBE_CONNECT_TEST_PORT", "3360"))BASE = f"http://127.0.0.1:{PORT}"FUOBE = "https://fuobe.com"-EVIL = "https://evil.example"+OTHER = "https://other.example"NODES = frozenset({"CheckpointLoaderSimple", "CLIPTextEncode", "KSampler", "VAEDecode", "SaveImage", "LoadImage", "EmptyLatentImage", "PreviewImage"})@@ -164,7 +164,7 @@ class OriginsTest(unittest.TestCase):self.assertFalse(allowed(m, p, q), p)def test_model_lists_only(self):- # A model folder's list, yes; ComfyUI's lists of every node pack's files and of its configs, no.+ # A model folder's list, yes; custom_nodes and configs, no.for p in ["/models", "/models/loras", "/api/models/checkpoints", "/experiment/models", "/experiment/models/loras", "/models/custom_nodes_extra"]:self.assertTrue(allowed("GET", p), p)for p in ["/models/custom_nodes", "/api/models/custom_nodes", "/models/configs", "/experiment/models/custom_nodes", "/api/experiment/models/configs"]:@@ -256,10 +256,10 @@ class DirectModeTest(unittest.TestCase):app, _ = with_connect()async with Server(app) as s:refused = {- "a node this pack doesn't ship": graph(**{"10": {"class_type": "Image Load", "inputs": {"image_path": "C:/Users/me/secret.png"}}}),+ "a node this pack doesn't ship": graph(**{"10": {"class_type": "Image Load", "inputs": {"image_path": "C:/Users/me/photo.png"}}}),"an absolute path": graph(**{"10": {"class_type": "SaveImage", "inputs": {"filename_prefix": "/etc/cron.d/x", "images": ["8", 0]}}}),"a Windows path": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "C:\\Users\\me\\x.png", "clip": ["4", 1]}}}),- "a share with forward slashes": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "//attacker.example/share/x", "clip": ["4", 1]}}}),+ "a share with forward slashes": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "//other.example/share/x", "clip": ["4", 1]}}}),"a device path": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "//?/C:/Users/Public/x", "clip": ["4", 1]}}}),"the drive's root": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "\\Users\\Public\\x", "clip": ["4", 1]}}}),"a drive with no slash": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "D:Users\\x", "clip": ["4", 1]}}}),@@ -390,9 +390,9 @@ class DirectModeTest(unittest.TestCase):run(go())- def test_prompt_id_of_yours_cant_be_taken(self):- """ComfyUI takes a new prompt under any id, one it already holds too. A studio that learned the id of a prompt of- yours (ComfyUI sends the progress of a prompt queued without a client id to every socket) can't make it its own."""+ def test_refuses_a_prompt_id_comfyui_already_holds(self):+ """A studio's prompt under an id that ComfyUI already holds (in its queue or its history) is refused, and the+ prompt stays yours."""async def go():comfy = Comfy()@@ -550,7 +550,7 @@ class DirectModeTest(unittest.TestCase):self.assertEqual(status, 403)self.assertNotIn("Access-Control-Allow-Origin", h)# Another website's preflight: refused by ComfyUI, as before.- status, h, _ = await s.req("OPTIONS", "/prompt", browser(EVIL, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Private-Network": "true"}))+ status, h, _ = await s.req("OPTIONS", "/prompt", browser(OTHER, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Private-Network": "true"}))self.assertEqual(status, 403)self.assertNotIn("Access-Control-Allow-Private-Network", h)@@ -560,13 +560,13 @@ class DirectModeTest(unittest.TestCase):async def go():app, _ = with_connect()async with Server(app) as s:- for origin in [EVIL, "https://fuobe.com.evil.example", "http://fuobe.com", "https://fuobe.com:444", "null"]:+ for origin in [OTHER, "https://fuobe.com.other.example", "http://fuobe.com", "https://fuobe.com:444", "null"]:for method, path in [("GET", "/system_stats"), ("POST", "/prompt")]:status, h, _ = await s.req(method, path, browser(origin), data=b"{}" if method == "POST" else None)self.assertEqual(status, 403, f"{origin} {method} {path}")self.assertNotIn("Access-Control-Allow-Origin", h)# Without Sec-Fetch-Site (an older browser): ComfyUI's host check still refuses it.- status, _, _ = await s.req("POST", "/prompt", {"Origin": EVIL}, data=b"{}")+ status, _, _ = await s.req("POST", "/prompt", {"Origin": OTHER}, data=b"{}")self.assertEqual(status, 403)run(go())@@ -605,7 +605,7 @@ class DirectModeTest(unittest.TestCase):app, _ = with_connect()async with Server(app) as s:for method, path in [("GET", "/userdata/comfy.settings.json"), ("POST", "/v2/manager/queue/install"), ("POST", "/fuobe/connect/studios"), ("GET", "/view?filename=a.png&subfolder=&type=input"), ("GET", "/view?filename=a.png%20[input]&subfolder=&type=output")]:- status, h, _ = await s.req(method, path, browser(FUOBE, **{"Content-Type": "application/json"}), data=b'{"studios":"https://evil.example"}' if method == "POST" else None)+ status, h, _ = await s.req(method, path, browser(FUOBE, **{"Content-Type": "application/json"}), data=b'{"studios":"https://other.example"}' if method == "POST" else None)self.assertEqual(status, 403, path)self.assertNotIn("Access-Control-Allow-Origin", h)status, h, _ = await s.req("OPTIONS", "/v2/manager/queue/install", browser(FUOBE, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "content-type"}))@@ -633,8 +633,8 @@ class DirectModeTest(unittest.TestCase):async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId=fuobe-abc12345", headers=browser(FUOBE, **{"Sec-Fetch-Mode": "websocket"})) as ws:msg = await ws.receive(timeout=5)self.assertIn("status", msg.data)- # Your own ComfyUI tab's socket can't be taken over.- for origin, cid in [(FUOBE, "abc12345"), (EVIL, "fuobe-abc12345")]:+ # The live socket only under a Fuobe client id, never your own ComfyUI tab's.+ for origin, cid in [(FUOBE, "abc12345"), (OTHER, "fuobe-abc12345")]:with self.assertRaises(aiohttp.WSServerHandshakeError) as e:async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId={cid}", headers=browser(origin, **{"Sec-Fetch-Mode": "websocket"})):pass@@ -649,7 +649,7 @@ class DirectModeTest(unittest.TestCase):status, h, body = await s.req("GET", "/fuobe/guard", browser(FUOBE))self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE))self.assertIn(b'"guard": 1', body)- status, _, _ = await s.req("GET", "/fuobe/guard", browser(EVIL))+ status, _, _ = await s.req("GET", "/fuobe/guard", browser(OTHER))self.assertEqual(status, 403)run(go())@@ -664,7 +664,7 @@ class DirectModeTest(unittest.TestCase):self.assertIn(b'"connect": 1', body)status, _, body = await s.req("GET", "/fuobe/connect")self.assertIn(b"studios", body)- # A program can't pass itself off as a studio to get less, or more: the marker is dropped on the way in.+ # The marker is dropped from every incoming request: only Fuobe Connect sets it.status, _, body = await s.req("GET", "/fuobe/connect", {MARKER: FUOBE})self.assertIn(b"studios", body)# Only ComfyUI's own page changes the studios.@@ -675,7 +675,7 @@ class DirectModeTest(unittest.TestCase):class WithCorsFlagTest(unittest.TestCase):- """ComfyUI started with --enable-cors-header: its own check is off, so Fuobe Connect does what Fuobe's guard did."""+ """ComfyUI started with --enable-cors-header and a site's address: Fuobe Connect does what Fuobe's guard did."""def test_guard(self):async def go():@@ -683,7 +683,7 @@ class WithCorsFlagTest(unittest.TestCase):async with Server(app) as s:status, h, _ = await s.req("GET", "/system_stats", browser(FUOBE))self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE))- status, _, _ = await s.req("POST", "/prompt", browser(EVIL), data=b"{}")+ status, _, _ = await s.req("POST", "/prompt", browser(OTHER), data=b"{}")self.assertEqual(status, 403)status, _, _ = await s.req("POST", "/prompt", browser("https://other-studio.example"), data=b"{}")self.assertEqual(status, 200)@@ -698,9 +698,8 @@ class WithCorsFlagTest(unittest.TestCase):run(go())def test_flag_naming_a_studio_gives_it_nothing_more(self):- """--enable-cors-header <a trusted studio> switches ComfyUI's own check off for that site. The studio still gets- only the checked paths, and only at this computer's own address (or a network address with FUOBE_CONNECT_LAN=1),- never under a name that points at this computer."""+ """--enable-cors-header <a trusted studio>: the studio still gets only the checked paths, and only at this+ computer's own address (or a network address with FUOBE_CONNECT_LAN=1), never under another name."""def form(name, kind):f = aiohttp.FormData()@@ -754,7 +753,7 @@ class WithCorsFlagTest(unittest.TestCase):async def go():app, _ = with_connect(cors_flag="localhost:8080")async with Server(app) as s:- for origin in ["null", EVIL]:+ for origin in ["null", OTHER]:status, _, _ = await s.req("POST", "/prompt", {"Origin": origin, "Content-Type": "text/plain"}, data=b"{}")self.assertEqual(status, 403, origin)status, _, _ = await s.req("POST", "/prompt", {"Origin": BASE}, data=b"{}")@@ -766,7 +765,7 @@ class WithCorsFlagTest(unittest.TestCase):async def go():app, _ = with_connect(cors_flag="*")async with Server(app) as s:- status, _, _ = await s.req("POST", "/prompt", browser(EVIL), data=b"{}")+ status, _, _ = await s.req("POST", "/prompt", browser(OTHER), data=b"{}")self.assertEqual(status, 200)run(go())diff --git a/integrations/fuobe-connect/tests/test_plugin.py b/integrations/fuobe-connect/tests/test_plugin.pyindex ca9ffee5..032de3a3 100644--- a/integrations/fuobe-connect/tests/test_plugin.py+++ b/integrations/fuobe-connect/tests/test_plugin.py@@ -88,8 +88,8 @@ class FakeAgent:class OwnPageTest(unittest.TestCase):- """Only ComfyUI's own page (or a program here) changes the studios, pairs, or pauses: never a page whose own name- was pointed at this computer, a page on another port, or another website."""+ """Only ComfyUI's own page (or a program here) changes the studios, pairs, or pauses: never a page under another+ host name, a page on another port, or another website."""def setUp(self):self.env = mock.patch.dict(os.environ, {}, clear=False)@@ -129,27 +129,27 @@ class OwnPageTest(unittest.TestCase):asyncio.run(go())- def test_rebinding_and_other_pages(self):+ def test_refuses_requests_from_other_pages(self):async def test(req):own = {"Origin": PAGE, "Sec-Fetch-Site": "same-origin"}status, body = await req("GET", "/fuobe/connect", own)self.assertIn("studios", body)- # A page at attacker.example whose name now points at 127.0.0.1: same Origin and Host, still not ComfyUI's page.- rebound = {"Host": f"attacker.example:{PAGE_PORT}", "Origin": f"http://attacker.example:{PAGE_PORT}", "Sec-Fetch-Site": "same-origin"}- status, body = await req("GET", "/fuobe/connect", rebound)+ # A page at other.example on ComfyUI's port: its Origin and Host agree, but the name isn't one of ComfyUI's own.+ other_name = {"Host": f"other.example:{PAGE_PORT}", "Origin": f"http://other.example:{PAGE_PORT}", "Sec-Fetch-Site": "same-origin"}+ status, body = await req("GET", "/fuobe/connect", other_name)self.assertNotIn("studios", body)- for path, b in [("/fuobe/connect/studios", {"studios": "https://attacker.example"}), ("/fuobe/connect/pair", {"site": "https://attacker.example"}), ("/fuobe/connect/jobs", {"paused": False})]:- status, _ = await req("POST", path, rebound, b)+ for path, b in [("/fuobe/connect/studios", {"studios": "https://other.example"}), ("/fuobe/connect/pair", {"site": "https://other.example"}), ("/fuobe/connect/jobs", {"paused": False})]:+ status, _ = await req("POST", path, other_name, b)self.assertEqual(status, 403, path)# A page on port 80 of this computer, another website, a form post: not ComfyUI's page either.for headers in [{"Origin": "http://127.0.0.1", "Host": f"127.0.0.1:{PAGE_PORT}"},- {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"},+ {"Origin": "https://other.example", "Sec-Fetch-Site": "cross-site"},{"Origin": PAGE, "Sec-Fetch-Site": "cross-site"},]:- status, _ = await req("POST", "/fuobe/connect/studios", headers, {"studios": "https://evil.example"})+ status, _ = await req("POST", "/fuobe/connect/studios", headers, {"studios": "https://other.example"})self.assertEqual(status, 403, headers)- status, _ = await req("POST", "/fuobe/connect/studios", {"Origin": PAGE, "Content-Type": "text/plain"}, raw=b'{"studios":"https://evil.example"}')+ status, _ = await req("POST", "/fuobe/connect/studios", {"Origin": PAGE, "Content-Type": "text/plain"}, raw=b'{"studios":"https://other.example"}')self.assertEqual(status, 403)self.assertNotIn("studios", plugin._state["store"].data)# A name the person lists is ComfyUI's own page.@@ -179,7 +179,7 @@ class OwnPageTest(unittest.TestCase):def test_pairs_only_with_a_trusted_studio(self):async def test(req):own = {"Origin": PAGE, "Sec-Fetch-Site": "same-origin"}- for site in ["https://attacker.example", "http://fuobe.com", "javascript:alert(1)"]:+ for site in ["https://other.example", "http://fuobe.com", "javascript:alert(1)"]:status, _ = await req("POST", "/fuobe/connect/pair", own, {"site": site})self.assertEqual(status, 400, site)status, _ = await req("POST", "/fuobe/connect/pair", own, {"name": "Studio PC"})@@ -216,7 +216,7 @@ class FakeStudio:self.polls += 1if self.polls < 2:return web.json_response({"state": "waiting"})- return web.json_response({"state": "approved", "token": "fuobe_wkr_" + "T" * 43, "workerId": "w1", "name": self.name, "account": "a***@example.com"})+ return web.json_response({"state": "approved", "token": "fuobe_wkr_" + "T" * 43, "workerId": "w1", "name": self.name, "account": "a\u2022\u2022\[email protected]"})async def beat(self, request):self.calls.append(f"beat:{request.headers.get('Authorization', '')[:20]}")@@ -281,6 +281,17 @@ class PluginTest(unittest.TestCase):def test_loads_into_comfyui_and_pairs(self):user_dir = self.user_dir+ # On Japanese Windows, ComfyUI's log written to a file or a pipe takes only cp932.+ log_out = io.TextIOWrapper(io.BytesIO(), encoding="cp932", errors="strict", write_through=True)+ handler = logging.StreamHandler(log_out)+ failed = []+ handler.handleError = lambda record: failed.append(sys.exc_info()[1])+ root = logging.getLogger()+ level = root.level+ root.addHandler(handler)+ root.setLevel(logging.INFO)+ self.addCleanup(root.setLevel, level)+ self.addCleanup(root.removeHandler, handler)module, instance = load_pack(user_dir)agent_module = sys.modules["fuobe_connect_pack.fuobe_connect.agent"]agent_module.REVOKE_RETRY_S = 0.3@@ -341,8 +352,10 @@ class PluginTest(unittest.TestCase):breakawait asyncio.sleep(0.3)self.assertEqual(st["paired"]["site"], SITE)- # The account that approved it, as the studio names it.- self.assertEqual(st["paired"]["account"], "a***@example.com")+ # The account that approved it, as the studio names it; the log writes it in ASCII.+ self.assertEqual(st["paired"]["account"], "a\u2022\u2022\[email protected]")+ self.assertEqual(failed, [])+ self.assertIn("as a***@example.com.", log_out.buffer.getvalue().decode("cp932"))self.assertTrue(any(c.startswith("beat:Bearer fuobe_wkr_") for c in studio.calls), studio.calls)with open(file, encoding="utf-8") as f:saved = json.load(f)diff --git a/integrations/fuobe-connect/tests/test_runner.py b/integrations/fuobe-connect/tests/test_runner.pyindex e5f8a11c..65bd169f 100644--- a/integrations/fuobe-connect/tests/test_runner.py+++ b/integrations/fuobe-connect/tests/test_runner.py@@ -155,7 +155,7 @@ class VetTest(unittest.TestCase):def test_bad_task_id_is_skipped(self):site = FakeSite()run(runner(site).run(task(id="../../api/settings")))- run(runner(site).run(task(lease="x\r\nX-Evil: 1")))+ run(runner(site).run(task(lease="x\r\nX-Other: 1")))self.assertEqual(site.calls, [])@@ -179,7 +179,7 @@ class RunTest(unittest.TestCase):self.assertTrue(any(c[0] == "PUT" and c[1].startswith("/api/gpu/computer/tasks/task_abcdefgh1234/outputs/0?") for c in site.calls))def test_follow_only_its_own_batch(self):- """A studio can't point the runner at your own results with another prefix (ComfyUI's default 'ComfyUI')."""+ """The runner follows only its own job's prefix, never another one (ComfyUI's default 'ComfyUI')."""yours = str(uuid.uuid4())comfy = FakeComfy(history={yours: {"prompt": [1, yours, {"9": {"class_type": "SaveImage", "inputs": {"filename_prefix": "ComfyUI"}}}], "outputs": {"9": {"images": [{"filename": "ComfyUI_00001_.png", "subfolder": "", "type": "output"}]}}}})site = FakeSite({"/report": {"_event": "finished", "follow": "ComfyUI"}})@@ -225,13 +225,13 @@ class RunTest(unittest.TestCase):def test_refused_answer_is_slimmed(self):class Refusing(FakeComfy):async def post_json(self, path, body, timeout=60):- return 400, {"error": {"type": "prompt_outputs_failed_validation", "message": "x"}, "node_errors": {"4": {"class_type": "CheckpointLoaderSimple", "errors": [{"message": "Value not in list", "details": "ckpt_name: 'a' not in ['secret.safetensors']", "extra_info": {"received_value": "a"}}]}}}+ return 400, {"error": {"type": "prompt_outputs_failed_validation", "message": "x"}, "node_errors": {"4": {"class_type": "CheckpointLoaderSimple", "errors": [{"message": "Value not in list", "details": "ckpt_name: 'a' not in ['mine.safetensors']", "extra_info": {"received_value": "a"}}]}}}site = FakeSite()run(runner(site, Refusing()).run(task()))ev = site.events()[-1]self.assertEqual(ev["event"], "refused")- self.assertNotIn("secret.safetensors", str(ev))+ self.assertNotIn("mine.safetensors", str(ev))def test_paused_takes_no_job(self):site = FakeSite()