Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Fuobe Connect: refuse untyped links into dropdowns, pin ffmpeg's format and download names

Adarshe370b863f049
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index b98a6d3c..08ee3e26 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -27,20 +27,31 @@ page checked:
- no text names a place: an absolute path in any form (`/x`, `\x`, `//host/share`, `\\?\C:\x`, `C:\x`, `D:x`), a
`..` step, a home folder (`~`, `~user`), an environment variable at the start, a URL, a folder tag, or a JSON key
that names a file, a folder or an address. Spaces and quotes in front don't hide one;
- - an input that a listed node reads as a file or a folder holds the one value or form the studio's own graphs use,
- written in the graph, never a link (`PATH_INPUTS` in `fuobe_connect/graph.py`);
+ - an input that a listed node reads as a file or a folder, or a name that it downloads, holds the one value or form
+ the studio's own graphs use, written in the graph, never a link (`PATH_INPUTS` in `fuobe_connect/graph.py`);
+ - a link from an output that ComfyUI doesn't type-check ("any", match-typed or dropdown-typed, such as
+ `GetItemFromList`, `CreateList`, `VRAM_Debug` or `ComfySwitchNode`), and any link into a dropdown, feeds only what
+ the studio's own graphs feed that way (`loose` and `links` in `allowed_nodes.json`). ComfyUI checks a dropdown's
+ value against its list only when the graph writes it. Inside ComfyUI the pack also reads these kinds from every
+ node class;
+ - `VHS_VideoCombine` takes only a plain format name and plain-word settings (they go into ffmpeg's arguments), and
+ a link only for its pictures, sound, batch, VAE and frame rate;
- every loader reads a Fuobe input (`fuobe_<id>.<ext>`), and no node gets a JSON object except a 3D view's entries;
-- an upload goes only into the input folder, under a Fuobe input name;
+- an upload goes only into the input folder, under a Fuobe input name, as a picture, clip, sound, 3D scene, array or
+ subtitle file (never `.json`, `.txt`, `.csv` or a file of no known type);
- the studio sees, cancels, stops and downloads only its own prompts and their results; the queue shows other prompts
only as places in the line, the node list hides the names of the person's input files, and the model lists leave
out `custom_nodes` and `configs`.
When a graph builder starts giving one of those inputs a new value, add its form to `PATH_INPUTS` and ship it with the
next Fuobe Connect release (the pack's `tests/test_graph.py` runs every workflow in `workflows/comfyui` through the
-checks).
+checks). When a graph starts linking from an untyped output into a new input, or into a dropdown, run
+`node scripts/connect-nodes.mjs` too: until the pack ships the new link, people's ComfyUI refuses that graph.
It cannot reach the Manager's install calls, the person's user files or settings, a file of the person's in the input
-folder, or the person's own results, and its workflows cannot open a file of the person's by its path. Fuobe
+folder, or the person's own results. Its workflows cannot name a file of the person's by its path: path-like text is
+refused, a file input takes only Fuobe's own form, and a value that another node works out can't reach a file input, a
+dropdown or ffmpeg's arguments. Fuobe
Connect answers the CORS and Private Network Access preflights for the trusted origins only. Every other website still
meets ComfyUI's own check.
diff --git a/integrations/fuobe-connect/README.md b/integrations/fuobe-connect/README.md
index 4a96faf9..3af42d43 100644
--- a/integrations/fuobe-connect/README.md
+++ b/integrations/fuobe-connect/README.md
@@ -34,7 +34,9 @@ can:
model folders, with each folder's place on disk (every folder ComfyUI lists, except `custom_nodes` and `configs`). In
the node list, the loaders show only Fuobe's own input files, not your file names;
- upload a run's input into the input folder, only under a name Fuobe gives (`fuobe_<id>.png` and similar), only as a
- picture, clip, sound, 3D scene or data file. It can replace an earlier Fuobe input, never a file of yours;
+ picture, clip, sound, 3D scene, array (`.npy`, `.npz`) or subtitle file (`.srt`, `.vtt`). Never a settings or text
+ file (`.json`, `.txt`, `.csv`) or a file of no known type. It can replace an earlier Fuobe input, never a file of
+ yours;
- queue a workflow. Fuobe Connect checks every workflow here, in Python, before ComfyUI sees it:
- every node type must be on the list this pack ships (`fuobe_connect/allowed_nodes.json`: the nodes Fuobe's own
workflows use), or on your own list (below). A studio can't add to either list;
@@ -42,15 +44,29 @@ can:
drive with no slash such as `D:x`), a `..` step, a home folder (`~`, `~user`), an environment variable at the start
(`$HOME/`, `%USERPROFILE%\`), a URL, a ComfyUI folder tag such as `name [output]`, or a key in JSON that names a
file, a folder or an address (`"video_path": …`). Spaces and quotes in front don't hide one;
- - an input that a listed node reads as a file or a folder takes only the one value or form that Fuobe's own
- workflows use, written in the workflow itself and never worked out by another node. For example, the source
- paths of `MiniMaxH3SourceTimeline` must be empty, and the subtitle file of `AILab_Qwen3ASRSubtitle` must be empty
- or under `fuobe/` in your output folder. `PATH_INPUTS` in `fuobe_connect/graph.py` lists every one;
+ - an input that a listed node reads as a file or a folder, or a name that it downloads, takes only the one value or
+ form that Fuobe's own workflows use, written in the workflow itself and never worked out by another node. For
+ example, the source paths of `MiniMaxH3SourceTimeline` must be empty, the subtitle file of
+ `AILab_Qwen3ASRSubtitle` must be empty or under `fuobe/` in your output folder, the model of
+ `DownloadAndLoadWav2VecModel` must be one of its two models, and the format of `VHS_VideoCombine` must be a plain
+ name such as `video/h264-mp4`. `PATH_INPUTS` in `fuobe_connect/graph.py` lists every one;
- every file loader must read a Fuobe input (`fuobe_<id>.<ext>`), never a file of yours;
+ - a dropdown (a model name, a format, any list of choices) takes a link only where Fuobe's own workflows link one,
+ because ComfyUI checks no value that reaches a dropdown through a link. A value written in the workflow is checked
+ by ComfyUI against the dropdown's list, unless the node checks that input in its own way (a file loader, for
+ example);
+ - a link from an output that ComfyUI doesn't type-check (an "any" output such as `GetItemFromList`, `CreateList` or
+ `VRAM_Debug`, a match-typed one such as `ComfySwitchNode`, or a dropdown-typed one) feeds only the inputs that
+ Fuobe's own workflows feed from that node type. Inside ComfyUI, Fuobe Connect reads which outputs these are and
+ which inputs are dropdowns from every node, your own listed ones too. The shipped list is in
+ `fuobe_connect/allowed_nodes.json` (`loose` and `links`);
+ - `VHS_VideoCombine` puts its format's settings into ffmpeg's arguments, so each setting must be one plain word
+ (`yuv420p`, `hq`), and it takes a link only for its pictures, sound, batch, VAE and frame rate;
- the workflow may not give a node a JSON object (ComfyUI passes one on unchecked), except a 3D view's entries.
A workflow that uses an installed node from the list can still do what that node does in ComfyUI's own folders: for
- example, save into your output folder, or keep a node pack's own cache;
+ example, save into your output folder, or keep a node pack's own cache. These checks follow what the listed nodes do
+ at the versions Fuobe's workflows pin. A newer version of a node pack can read its inputs in a new way;
- see, follow, cancel, stop and remove only the prompts it queued (and a batch's later passes, which save under
`fuobe/<id>`). In the queue, your own prompts show only as places in the line. It can't clear the queue or stop
your own work;
@@ -58,7 +74,10 @@ can:
- open ComfyUI's live socket only under a Fuobe client id (`fuobe-…`), never your own ComfyUI tab's.
A trusted studio can't reach the Manager's install calls, your user files or your settings. It can't read a file of
-yours in the input folder or download a result of yours, and its workflows can't open a file of yours by its path. Of
+yours in the input folder or download a result of yours. Its workflows can't name a file of yours by its path: text
+that names a place (an absolute path, a `..` step, a home folder, a URL) is refused, an input that a listed node reads
+as a file takes only Fuobe's own form, and a value that another node works out can't reach such an input, a dropdown
+or ffmpeg's arguments. Of
ComfyUI's folder lists it can't read `custom_nodes` (every file of your node packs) or `configs`. Every other website
still meets ComfyUI's own check, unchanged. Nothing in ComfyUI's own files changes.
@@ -77,7 +96,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.
+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.
**A network address.** A trusted studio reaches this ComfyUI only on this computer. To let it reach a ComfyUI that
runs with `--listen` at a network address, start ComfyUI with `FUOBE_CONNECT_LAN=1`.
diff --git a/integrations/fuobe-connect/fuobe_connect/allowed_nodes.json b/integrations/fuobe-connect/fuobe_connect/allowed_nodes.json
index a1a6276d..f68b682b 100644
--- a/integrations/fuobe-connect/fuobe_connect/allowed_nodes.json
+++ b/integrations/fuobe-connect/fuobe_connect/allowed_nodes.json
@@ -458,5 +458,55 @@
"YuE2GenerateMusic",
"ZenImage21AdapterLoader",
"ZenImage21TextEncode"
+ ],
+ "loose": {
+ "ComfySwitchNode": [0],
+ "CreateList": [0],
+ "EndLoop": [0],
+ "GetItemFromList": [0],
+ "GetVideoComponents": [3,4],
+ "ResizeImageMaskNode": [0],
+ "StartLoop": [3,4],
+ "VRAM_Debug": [0]
+ },
+ "links": [
+ ["ComfySwitchNode","BatchImagesNode","images.image#"],
+ ["ComfySwitchNode","ComfySwitchNode","on_true"],
+ ["ComfySwitchNode","CreateVideo","images"],
+ ["ComfySwitchNode","EndLoop","output_value"],
+ ["ComfySwitchNode","IdolPreprocessImage","mask"],
+ ["ComfySwitchNode","KSampler","model"],
+ ["ComfySwitchNode","KSamplerAdvanced","model"],
+ ["ComfySwitchNode","MoGeInference","image"],
+ ["ComfySwitchNode","SaveAudioAdvanced","audio"],
+ ["ComfySwitchNode","SaveImage","images"],
+ ["ComfySwitchNode","TextGenerate","prompt"],
+ ["ComfySwitchNode","TripoSplatConditioning","image"],
+ ["ComfySwitchNode","TripoSplatPreprocessImage","mask"],
+ ["ComfySwitchNode","WanAnimate2ToVideo","continue_motion"],
+ ["ComfySwitchNode","WanAnimate2ToVideo","length"],
+ ["ComfySwitchNode","WanAnimate2ToVideo","video_frame_offset"],
+ ["CreateList","EndLoop","next_iteration_value"],
+ ["EndLoop","ConcatenateVideo","videos.video#"],
+ ["EndLoop","H3RelayFinishWindows","state"],
+ ["EndLoop","RebatchImages","images"],
+ ["EndLoop","TrimAudioDuration","audio"],
+ ["GetItemFromList","ComfySwitchNode","on_false"],
+ ["GetVideoComponents","CreateVideo","bit_depth"],
+ ["ResizeImageMaskNode","CLIPVisionEncode","image"],
+ ["ResizeImageMaskNode","GetImageSize","image"],
+ ["ResizeImageMaskNode","ImageFromBatch","image"],
+ ["ResizeImageMaskNode","LTXVPreprocess","image"],
+ ["ResizeImageMaskNode","ResizeImageMaskNode","input"],
+ ["ResizeImageMaskNode","SeedVR2PostProcessing","original_resized_images"],
+ ["ResizeImageMaskNode","SeedVR2Preprocess","resized_images"],
+ ["ResizeImageMaskNode","TextEncodeFibo2","images.image_#"],
+ ["ResizeImageMaskNode","VHS_VideoCombine","images"],
+ ["ResizeImageMaskNode","WanAnimate2ToVideo","pose_video"],
+ ["ResizeImageMaskNode","WanAnimate2ToVideo","reference_image"],
+ ["StartLoop","AudioConcat","audio#"],
+ ["StartLoop","GetItemFromList","list"],
+ ["StartLoop","H3RelayAppendWindow","previous"],
+ ["StartLoop","H3RelayWindowInputs","previous"]
]
}
diff --git a/integrations/fuobe-connect/fuobe_connect/graph.py b/integrations/fuobe-connect/fuobe_connect/graph.py
index 80fdeb29..8020405b 100644
--- a/integrations/fuobe-connect/fuobe_connect/graph.py
+++ b/integrations/fuobe-connect/fuobe_connect/graph.py
@@ -8,16 +8,23 @@ A graph from a studio (a trusted page in direct mode, or the paired studio in pa
".." step, a home folder ("~", "~user"), an environment variable at the start ("$HOME/", "%USERPROFILE%\\"), a URL,
one 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 (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;
+- 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;
- every file loader reads one of the files Fuobe sent for the run (named fuobe_<id>.<ext>), never a file of yours and
never 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 node that puts its inputs into a program's arguments (ARG_NODES: VHS_VideoCombine and ffmpeg) takes a link only
+ into its media inputs, and its other text only as one plain word;
- a value the graph writes is never a JSON object, except a 3D view's entries: ComfyUI hands an object to a node
unchecked, and some nodes read a file's path from one;
- a few inputs take only a link from one node type, or text of one shape (LINK_INPUTS, TEXT_INPUTS).
-A result is downloaded only when this run's own history lists it. A model name is not checked here: ComfyUI itself
-refuses a model name that isn't in your model folders.
+A result is downloaded only when this run's own history lists it. A model name the graph writes is checked by ComfyUI
+itself, against the files in your model folders.
Pure, so the tests run it alone.
"""
@@ -30,13 +37,14 @@ import re
# 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, and plain data. Never a page, a script or a program.
+# 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.
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 "
"wav mp3 flac ogg oga opus m4a aac aif aiff wma xwav "
"spz splat glb gltf ply obj fbx stl usdz "
- "npy npz txt json srt vtt csv bin octet".split()
+ "npy npz srt vtt".split()
)
UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\Z")
TASK_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}\Z")
@@ -75,7 +83,8 @@ _PATHLIKE = [
re.compile(r"^[\\/]"), # /etc/passwd, \Users\x, //host/share, //?/C:/x, \\host\share, \\?\C:\x, \/host/share
re.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
- re.compile(r"^(?:\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%)(?:[\\/]|\Z)"), # $HOME/x, %USERPROFILE%\x
+ # $HOME/x, %USERPROFILE%\x, %HOMEDRIVE%%HOMEPATH%\x
+ re.compile(r"^(?:\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z_][A-Za-z0-9_]*%)+(?:[\\/]|\Z)"),
re.compile(r"(^|[\\/])\.\.([\\/]|\Z)"), # a ".." step
re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*://"), # a URL
re.compile(r"^file:", re.I),
@@ -142,6 +151,14 @@ PATH_INPUTS: dict[str, dict[str, re.Pattern]] = {
"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.
+ "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.
+ "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.
+ "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": {
"model_folder": _NONE,
@@ -171,13 +188,136 @@ TEXT_INPUTS: dict[str, dict] = {
# The only inputs that take a JSON object the graph writes: a 3D view's entries (Load3D's are checked below).
OBJECT_INPUTS = frozenset({("Load3D", "image"), ("Save3DAdvanced", "viewport_state")})
+# 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).
+ARG_NODES: dict[str, dict[str, frozenset]] = {
+ "VHS_VideoCombine": {"links": frozenset({"images", "audio", "meta_batch", "vae", "frame_rate"}), "texts": frozenset({"filename_prefix"})},
+}
+_WORD = re.compile(r"[A-Za-z0-9_.-]{0,64}")
+
+
+# ---------------------------------------------------------------------------
+# Links ComfyUI doesn't check
+#
+# 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).
+
+_LOOSE_TYPES = frozenset({"*", "COMFY_MATCHTYPE_V3", "COMBO"})
+_DROPDOWN_TYPES = frozenset({"COMBO", "COMFY_DYNAMICCOMBO_V3"})
+
+
+def _shipped() -> dict:
+ with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "allowed_nodes.json"), encoding="utf-8") as f:
+ data = json.load(f)
+ return data if isinstance(data, dict) else {}
+
+
+def input_kind(key: str) -> str:
+ """An input's name with a trailing number made general: images.image1 and images.image2 are one kind of input."""
+ return re.sub(r"\d+\Z", "#", key)
+
+
+_DATA = _shipped()
+# Node types on the shipped list whose outputs ComfyUI doesn't type-check, 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)
+}
+# (source type, target type, input kind): the links of that kind that Fuobe's own graphs make.
+LOOSE_LINKS: frozenset = frozenset(
+ tuple(x) for x in (_DATA.get("links") or []) if isinstance(x, list) and len(x) == 3 and all(isinstance(p, str) for p in x)
+)
+
+
+def loose_type(t) -> bool:
+ """An output type that ComfyUI matches to any input: "*", a match type, a dropdown, a list of options, or a text
+ type of a node pack's own that says it equals every other type."""
+ if type(t) is not str:
+ return True
+ return any(p.strip() in _LOOSE_TYPES for p in t.split(","))
+
+
+def dropdown_spec(spec) -> bool:
+ """An input spec ComfyUI shows as a dropdown: a list of options, COMBO, or a dynamic dropdown."""
+ t = spec[0] if isinstance(spec, (list, tuple)) and spec else spec
+ return isinstance(t, (list, tuple)) or (isinstance(t, str) and t in _DROPDOWN_TYPES)
+
+
+class NodeKinds:
+ """What the node classes themselves say, inside ComfyUI: which outputs ComfyUI doesn't type-check and which inputs
+ are dropdowns. It covers every node, your own listed ones too. `lookup(class_type)` gives (INPUT_TYPES(),
+ RETURN_TYPES) or None. A node's kinds are read once (a class that fails to say is asked again next time: ComfyUI
+ refuses a graph with it anyway)."""
+
+ def __init__(self, lookup):
+ self._lookup = lookup
+ self._seen: dict[str, tuple] = {}
+
+ def _kinds(self, cls: str) -> tuple:
+ if cls not in self._seen:
+ loose, drops = frozenset(), frozenset()
+ try:
+ found = self._lookup(cls)
+ except Exception:
+ return loose, drops
+ if found is not None:
+ inputs, outputs = found
+ try:
+ loose = frozenset(i for i, t in enumerate(outputs or ()) if loose_type(t))
+ except Exception:
+ loose = frozenset(range(64))
+ try:
+ drops = frozenset(
+ k for part in ("required", "optional") for k, spec in dict((inputs or {}).get(part) or {}).items() if dropdown_spec(spec)
+ )
+ except Exception:
+ drops = frozenset()
+ self._seen[cls] = (loose, drops)
+ return self._seen[cls]
+
+ def loose(self, cls: str, slot: int) -> bool:
+ return slot in self._kinds(cls)[0]
+
+ def dropdown(self, cls: str, key: str) -> bool:
+ return key in self._kinds(cls)[1]
+
+
+def comfy_kinds(mappings) -> NodeKinds:
+ """NodeKinds from ComfyUI's NODE_CLASS_MAPPINGS (a callable that returns it, read at each new node type)."""
+
+ def lookup(cls):
+ klass = mappings().get(cls)
+ if klass is None:
+ return None
+ return klass.INPUT_TYPES(), getattr(klass, "RETURN_TYPES", ())
+
+ return NodeKinds(lookup)
+
def is_link(v) -> bool:
"""[node id, output slot]: a value another node works out."""
return isinstance(v, list) and len(v) == 2 and isinstance(v[0], str) and isinstance(v[1], int) and not isinstance(v[1], bool)
-def input_problem(graph: dict, cls: str, key: str, v) -> str | None:
+def 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."""
+ src = graph.get(v[0])
+ if not isinstance(src, dict) or not isinstance(src.get("class_type"), str):
+ return None
+ src_cls = src["class_type"]
+ loose = v[1] in LOOSE.get(src_cls, ()) or (kinds is not None and kinds.loose(src_cls, v[1]))
+ if not loose and not (kinds is not None and kinds.dropdown(cls, key)):
+ return None
+ return None if (src_cls, cls, input_kind(key)) in LOOSE_LINKS else "unsafe-graph"
+
+
+def input_problem(graph: dict, cls: str, key: str, v, kinds: NodeKinds | None = None) -> str | None:
"""What is wrong with one input under its node's own rule: 'unsafe-path', 'unsafe-graph', or None."""
if isinstance(v, dict) and (cls, key) not in OBJECT_INPUTS:
return "unsafe-graph"
@@ -193,6 +333,14 @@ def input_problem(graph: dict, cls: str, key: str, v) -> str | None:
return None if isinstance(v, str) and shape(v) else "unsafe-path"
if links is not None:
return "unsafe-graph"
+ args = ARG_NODES.get(cls)
+ if args is not None:
+ if is_link(v) and key not in args["links"]:
+ return "unsafe-graph"
+ if isinstance(v, str) and key not in args["texts"] and not _WORD.fullmatch(v):
+ return "unsafe-path"
+ if is_link(v):
+ return link_problem(graph, cls, key, v, kinds)
return None
@@ -205,9 +353,7 @@ OWN_NODES_FILE = "fuobe-connect-nodes.json"
def shipped_nodes() -> frozenset:
- with open(os.path.join(_HERE, "allowed_nodes.json"), encoding="utf-8") as f:
- data = json.load(f)
- return frozenset(n for n in data.get("nodes", []) if isinstance(n, str))
+ return frozenset(n for n in _shipped().get("nodes", []) if isinstance(n, str))
def own_nodes(user_dir: str | None) -> frozenset:
@@ -226,9 +372,11 @@ def own_nodes(user_dir: str | None) -> frozenset:
class NodeList:
"""The shipped list plus the person's own file, read again when that file changes."""
- def __init__(self, user_dir: str | None = None):
+ def __init__(self, user_dir: str | None = None, kinds: NodeKinds | None = None):
self.user_dir = user_dir
self.shipped = shipped_nodes()
+ # Inside ComfyUI: what the node classes say about their outputs and dropdowns (for vet_graph).
+ self.kinds = kinds
self._mtime = None
self._own = frozenset()
@@ -300,10 +448,11 @@ def graph_problem(graph, staged: list[str] | None) -> str | None:
return None
-def vet_graph(graph, allowed: frozenset | set, staged: list[str] | None) -> str | None:
+def vet_graph(graph, allowed: frozenset | set, staged: list[str] | None, kinds: NodeKinds | None = None) -> str | None:
"""The first reason this graph may not run here, or None. The reasons are the worker program's
('unknown-node', 'unsafe-path') and 'unsafe-graph': a loader that reads a file this run didn't send, a JSON object
- the graph writes, or a link from a node that may not feed that input."""
+ the graph writes, or a link from a node that may not feed that input. `kinds`: what ComfyUI's node classes say
+ (inside ComfyUI); without it, only the shipped list of untyped outputs is known."""
if not isinstance(graph, dict) or not graph or len(graph) > 5000:
return "unsafe-graph"
for node in graph.values():
@@ -319,7 +468,7 @@ def vet_graph(graph, allowed: frozenset | set, staged: list[str] | None) -> str
for s in _strings(v):
if unsafe_text(s) or (_TAG.search(s) and not _staged(s, staged)):
return "unsafe-path"
- why = input_problem(graph, node["class_type"], k, v)
+ why = input_problem(graph, node["class_type"], k, v, kinds)
if why:
return why
if graph_problem(graph, staged):
diff --git a/integrations/fuobe-connect/fuobe_connect/middleware.py b/integrations/fuobe-connect/fuobe_connect/middleware.py
index dfcb0469..06f7c847 100644
--- a/integrations/fuobe-connect/fuobe_connect/middleware.py
+++ b/integrations/fuobe-connect/fuobe_connect/middleware.py
@@ -191,7 +191,7 @@ class Studios:
return _refuse("Not a run's prompt", 400)
if "front" in body and not isinstance(body["front"], bool):
return _refuse("Not a run's prompt", 400)
- why = vet_graph(body.get("prompt"), frozenset(self.nodes()), None)
+ why = vet_graph(body.get("prompt"), frozenset(self.nodes()), None, getattr(self.nodes, "kinds", None))
if why:
_note(f"a trusted studio: its workflow was refused ({why})")
return _refuse(REASONS[why], 400)
diff --git a/integrations/fuobe-connect/fuobe_connect/plugin.py b/integrations/fuobe-connect/fuobe_connect/plugin.py
index bfade5a0..1374e756 100644
--- a/integrations/fuobe-connect/fuobe_connect/plugin.py
+++ b/integrations/fuobe-connect/fuobe_connect/plugin.py
@@ -11,11 +11,12 @@ import asyncio
import logging
import os
import re
+import sys
from aiohttp import web
from . import __version__
-from .graph import NodeList
+from .graph import NodeList, comfy_kinds
from .middleware import MARKER, Studios, make_middleware
from .origins import DEFAULT_STUDIOS, NONE, host_name, is_ip, is_loopback, normalise, parse_list, same_host, says_none, studio, trusted_origins, with_twins
@@ -167,7 +168,8 @@ def install():
user_dir = folder_paths.get_user_directory()
store = Store(user_dir)
_state["store"] = store
- nodes = NodeList(user_dir)
+ # ComfyUI's node classes, read when a graph first uses each type (node packs that load after this one count too).
+ nodes = NodeList(user_dir, comfy_kinds(lambda: getattr(sys.modules.get("nodes"), "NODE_CLASS_MAPPINGS", None) or {}))
studios = Studios(nodes)
_state["studios"] = studios
lan = os.environ.get("FUOBE_CONNECT_LAN") == "1"
diff --git a/integrations/fuobe-connect/fuobe_connect/runner.py b/integrations/fuobe-connect/fuobe_connect/runner.py
index 7779d1b1..128a3eb8 100644
--- a/integrations/fuobe-connect/fuobe_connect/runner.py
+++ b/integrations/fuobe-connect/fuobe_connect/runner.py
@@ -410,7 +410,7 @@ class Runner:
for w in t.get("wanted") or []:
if not isinstance(w, dict) or not _small_int(w.get("n")):
return "unsafe-graph"
- return vet_graph(t.get("graph"), frozenset(self.nodes()), names)
+ return vet_graph(t.get("graph"), frozenset(self.nodes()), names, getattr(self.nodes, "kinds", None))
def _record(self, t: dict, why: str | None) -> dict:
graph = t.get("graph") if isinstance(t.get("graph"), dict) else {}
diff --git a/integrations/fuobe-connect/tests/test_graph.py b/integrations/fuobe-connect/tests/test_graph.py
index f88ab2bb..43c6e730 100644
--- a/integrations/fuobe-connect/tests/test_graph.py
+++ b/integrations/fuobe-connect/tests/test_graph.py
@@ -17,14 +17,20 @@ sys.path.insert(0, PACK)
from fuobe_connect import __version__ # noqa: E402
from fuobe_connect.graph import ( # noqa: E402
+ ARG_NODES,
FILE_LOADERS,
LINK_INPUTS,
+ LOOSE,
+ LOOSE_LINKS,
OPTIONAL_FILES,
OWN_NODES_FILE,
PATH_INPUTS,
TEXT_INPUTS,
+ NodeKinds,
NodeList,
+ comfy_kinds,
graph_problem,
+ input_kind,
may_download,
refusal,
run_prefix,
@@ -54,6 +60,9 @@ 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).
+ 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):
@@ -107,6 +116,8 @@ class VetTest(unittest.TestCase):
"$HOME",
"%USERPROFILE%" + B + "x",
"%APPDATA%",
+ "%HOMEDRIVE%%HOMEPATH%" + B + "x", # two variables, one after the other
+ "${HOME}$USER/x",
# What a node that trims its text sees.
" C:/Users/me",
"\t/etc/passwd",
@@ -230,7 +241,7 @@ class NodeRulesTest(unittest.TestCase):
"""Inputs that a listed node reads as a file or a folder take only Fuobe's own form, and never a link."""
def test_rules_name_shipped_nodes(self):
- for table in (PATH_INPUTS, LINK_INPUTS, TEXT_INPUTS, OPTIONAL_FILES):
+ for table in (PATH_INPUTS, LINK_INPUTS, TEXT_INPUTS, OPTIONAL_FILES, ARG_NODES, LOOSE):
for cls in table:
self.assertIn(cls, SHIPPED, cls)
self.assertIn("Hi3DLoadMesh", FILE_LOADERS)
@@ -350,6 +361,183 @@ class NodeRulesTest(unittest.TestCase):
self.assertEqual(vet1("StringFormat", f_string=bad), "unsafe-path", bad)
+def chain(*nodes) -> dict:
+ """A graph whose last node is fed by the ones before it (ids "1", "2", ...)."""
+ return g(*nodes)
+
+
+class FakeNode:
+ """A node class as ComfyUI's NODE_CLASS_MAPPINGS holds it."""
+
+ def __init__(self, inputs: dict, outputs: tuple):
+ self._inputs = inputs
+ self.RETURN_TYPES = outputs
+
+ def INPUT_TYPES(self):
+ return self._inputs
+
+
+class AnyType(str):
+ """A node pack's own "any" type: a text that says it equals every other type."""
+
+ def __ne__(self, other):
+ return False
+
+
+# What ComfyUI's node classes say about the nodes the tests below use (as /object_info shows them).
+CLASSES = {
+ "CreateList": FakeNode({"required": {"input1": ("*", {})}}, ("*",)),
+ "GetItemFromList": FakeNode({"required": {"list": ("*", {}), "index": ("INT", {})}}, ("*",)),
+ "VRAM_Debug": FakeNode({"required": {"any_input": ("*", {})}}, ("*", "INT", "INT", "INT")),
+ "ComfySwitchNode": FakeNode({"required": {"switch": ("BOOLEAN", {}), "on_true": ("COMFY_MATCHTYPE_V3", {}), "on_false": ("COMFY_MATCHTYPE_V3", {})}}, ("COMFY_MATCHTYPE_V3",)),
+ "PrimitiveStringMultiline": FakeNode({"required": {"value": ("STRING", {})}}, ("STRING",)),
+ "StringConcatenate": FakeNode({"required": {"string_a": ("STRING", {}), "string_b": ("STRING", {}), "delimiter": ("STRING", {})}}, ("STRING",)),
+ "CLIPTextEncode": FakeNode({"required": {"text": ("STRING", {}), "clip": ("CLIP",)}}, ("CONDITIONING",)),
+ "LoraLoader": FakeNode({"required": {"model": ("MODEL",), "clip": ("CLIP",), "lora_name": (["mine.safetensors"],), "strength_model": ("FLOAT", {})}}, ("MODEL", "CLIP")),
+ "Apply Whisper": FakeNode({"required": {"audio": ("AUDIO",), "model": (["base", "small"],)}}, ("STRING", "whisper_alignment", "whisper_alignment")),
+ "GetVideoComponents": FakeNode({"required": {"video": ("VIDEO", {})}}, ("IMAGE", "AUDIO", "FLOAT", "COMBO", "COMBO")),
+ "CreateVideo": FakeNode({"required": {"images": ("IMAGE", {}), "fps": ("FLOAT", {}), "bit_depth": ("COMBO", {"options": ["8bit", "10bit"]})}}, ("VIDEO",)),
+ "MyAnyNode": FakeNode({"required": {"value": ("STRING", {})}}, (AnyType("ANYTHING"),)),
+ "MyOptions": FakeNode({"required": {}}, (["a", "b"],)),
+}
+KINDS = comfy_kinds(lambda: CLASSES)
+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
+ own graphs feed that way."""
+
+ def test_shipped_list(self):
+ for cls in ("CreateList", "GetItemFromList", "VRAM_Debug", "ComfySwitchNode", "StartLoop", "EndLoop"):
+ self.assertIn(cls, LOOSE, cls)
+ self.assertEqual(LOOSE["GetVideoComponents"], frozenset({3, 4}))
+ self.assertIn(("GetVideoComponents", "CreateVideo", "bit_depth"), LOOSE_LINKS)
+ self.assertIn(("StartLoop", "AudioConcat", "audio#"), LOOSE_LINKS)
+ for src, dst, key in LOOSE_LINKS:
+ self.assertIn(src, SHIPPED, src)
+ self.assertIn(dst, SHIPPED, dst)
+ self.assertEqual(input_kind(key), key)
+ 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"
+ 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"))
+ 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]))
+ 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.
+ 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):
+ for kinds in (None, KINDS):
+ # Fuobe's own: a switch picks a model for the sampler; a clip's bit depth goes to the encoder.
+ self.assertIsNone(vet_graph(chain(node("ComfySwitchNode", switch=True, on_true=["8", 0], on_false=["9", 0]), node("KSampler", model=["1", 0], positive=["7", 0])), SHIPPED, STAGED, kinds))
+ self.assertIsNone(vet_graph(chain(node("GetVideoComponents", video=["9", 0]), node("CreateVideo", images=["1", 0], fps=["1", 2], bit_depth=["1", 3])), SHIPPED, STAGED, kinds))
+ self.assertIsNone(vet_graph(chain(node("StartLoop", initial_iteration_value=["9", 0]), node("AudioConcat", audio1=["1", 4], audio2=["9", 0])), SHIPPED, STAGED, kinds))
+ # A typed output (pictures, a number) feeds any input it fits; ComfyUI checks its type.
+ self.assertIsNone(vet_graph(chain(node("GetVideoComponents", video=["9", 0]), node("SaveImage", images=["1", 0], filename_prefix="fuobe/x")), SHIPPED, STAGED, kinds))
+ # 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_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."""
+ 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 outputs
+ self.assertEqual(vet_graph(own_any, WITH_OWN, STAGED, KINDS), "unsafe-graph")
+ options = chain(node("MyOptions"), node("LoraLoader", model=["8", 0], clip=["8", 1], lora_name=["1", 0]))
+ self.assertEqual(vet_graph(options, WITH_OWN, STAGED, KINDS), "unsafe-graph")
+ typed_into_dropdown = chain(node("StringConcatenate", string_a="mine", string_b=".safetensors", delimiter=""), node("LoraLoader", model=["8", 0], clip=["8", 1], lora_name=["1", 0]))
+ self.assertIsNone(vet_graph(typed_into_dropdown, SHIPPED, STAGED)) # ComfyUI itself refuses STRING into a dropdown
+ self.assertEqual(vet_graph(typed_into_dropdown, SHIPPED, STAGED, KINDS), "unsafe-graph")
+ # A typed text into a text input stays fine.
+ self.assertIsNone(vet_graph(chain(node("StringConcatenate", string_a="a", string_b="b", delimiter=" "), node("CLIPTextEncode", text=["1", 0], clip=["8", 0])), SHIPPED, STAGED, KINDS))
+ # A class that can't say what it is counts as having nothing to say; one that fails on its outputs is untyped.
+ broken = NodeKinds(lambda cls: (_ for _ in ()).throw(RuntimeError("no")))
+ self.assertFalse(broken.loose("X", 0))
+ odd = NodeKinds(lambda cls: ({"required": {}}, 5))
+ self.assertTrue(odd.loose("X", 0))
+
+ 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."""
+ 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("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("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"),
+ )
+ self.assertIsNotNone(vet_graph(switched, SHIPPED, staged, kinds))
+ for ok in ["video/h264-mp4", "video/ffv1-mkv", "video/ProRes", "video/webm", "image/gif", "image/webp", "video/nvenc_h264-mp4"]:
+ self.assertIsNone(vet1("VHS_VideoCombine", images=["9", 0], format=ok, frame_rate=24, filename_prefix="fuobe/x"), ok)
+ for bad in ["video/.." + B + ".." + B + "input" + B + "fuobe_abcdefgh12", "video/../x", "video/a/b", "video/a" + B + "b", "video/", "video/.x", "text/plain", "image/png"]:
+ 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)."""
+ 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"]:
+ 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]))
+ self.assertEqual(vet_graph(made, SHIPPED, STAGED), "unsafe-graph")
+ prefix = chain(node("StringConcatenate", string_a="fuobe", string_b="x", delimiter="_"), node("VHS_VideoCombine", **{**base, "filename_prefix": ["1", 0]}))
+ 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."""
+ 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]]:
+ 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]]:
+ 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)
+ for bad in ["face.pth", "bbox/../x.pt", "other" + B + "x.pt", ".x.pt", ["2", 0]]:
+ self.assertEqual(vet1("H3FaceTrackCrop", detector=bad), "unsafe-path", bad)
+
+ def test_studio_workflows_pass_with_node_kinds(self):
+ """Every workflow Fuobe ships passes with the node classes' own kinds too (from Fuobe's recorded /object_info)."""
+ folder = os.path.join(PACK, "..", "..", "workflows", "comfyui")
+ info_file = os.path.join(folder, "object_info.subset.json")
+ if not os.path.exists(info_file):
+ self.skipTest("Fuobe's workflows aren't beside this copy of the pack")
+ with open(info_file, encoding="utf-8") as f:
+ info = {k: v for k, v in json.load(f).items() if isinstance(v, dict)}
+ kinds = NodeKinds(lambda cls: (info[cls].get("input") or {}, info[cls].get("output") or []) if cls in info else None)
+ checked = 0
+ for path in glob.glob(os.path.join(folder, "*.json")):
+ if os.path.basename(path) in ("requirements.json", "manifest.json", "object_info.subset.json"):
+ continue
+ with open(path, encoding="utf-8") as fh:
+ wf = json.load(fh)
+ if not isinstance(wf, dict) or not all(isinstance(n, dict) and "class_type" in n for n in wf.values()):
+ continue
+ checked += 1
+ self.assertIsNone(vet_graph(staged_like_the_studio(wf), SHIPPED, None, kinds), os.path.basename(path))
+ self.assertGreater(checked, 50)
+
+
class NodeListTest(unittest.TestCase):
def test_shipped_and_own(self):
shipped = shipped_nodes()
diff --git a/scripts/connect-nodes.mjs b/scripts/connect-nodes.mjs
index 1070bdfd..abccc0c8 100644
--- a/scripts/connect-nodes.mjs
+++ b/scripts/connect-nodes.mjs
@@ -1,15 +1,26 @@
#!/usr/bin/env node
// Writes Fuobe Connect's node allowlist (integrations/fuobe-connect/fuobe_connect/allowed_nodes.json): every node type
-// the studio's graphs use. Fuobe Connect refuses a studio's graph with any other node, so run this before a Fuobe Connect
-// release whenever a workflow or graph builder starts using a new node. tests/fuobe-connect-nodes.test.ts checks it.
+// the studio's graphs use, the node types whose outputs ComfyUI doesn't type-check, and the links the studio's graphs
+// make from those outputs or into a dropdown. Fuobe Connect refuses a studio's graph with any other node, or with any
+// other such link, so run this before a Fuobe Connect release whenever a workflow or graph builder starts using a new
+// node or a new link of that kind. tests/fuobe-connect-nodes.test.ts checks it.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import { studioNodes } from "./lib/studio-nodes.mjs";
+import { connectLinks, studioNodes } from "./lib/studio-nodes.mjs";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const CONNECT_NODES = "integrations/fuobe-connect/fuobe_connect/allowed_nodes.json";
const list = studioNodes(root);
-fs.writeFileSync(path.join(root, CONNECT_NODES), `${JSON.stringify({ nodes: list }, null, 1)}\n`);
-console.log(`Fuobe Connect: ${list.length} allowed node types -> ${CONNECT_NODES}`);
+const { loose, links } = connectLinks(root, list);
+const body = [
+ "{",
+ ` "nodes": ${JSON.stringify(list, null, 1).replace(/\n/g, "\n ")},`,
+ ` "loose": {\n${Object.entries(loose).map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(",\n")}\n },`,
+ ` "links": [\n${links.map((l) => ` ${JSON.stringify(l)}`).join(",\n")}\n ]`,
+ "}",
+].join("\n");
+JSON.parse(body);
+fs.writeFileSync(path.join(root, CONNECT_NODES), `${body}\n`);
+console.log(`Fuobe Connect: ${list.length} allowed node types, ${Object.keys(loose).length} untyped, ${links.length} links -> ${CONNECT_NODES}`);
diff --git a/scripts/lib/studio-nodes.mjs b/scripts/lib/studio-nodes.mjs
index 67ad4468..51a9106b 100644
--- a/scripts/lib/studio-nodes.mjs
+++ b/scripts/lib/studio-nodes.mjs
@@ -26,3 +26,66 @@ export function studioNodes(root) {
for (const extra of ["LoraLoader", "LoraLoaderModelOnly"]) nodes.add(extra);
return [...nodes].sort();
}
+
+// Outputs ComfyUI never checks the type of: any ("*"), match-typed and dropdown-typed ones. A link from one reaches
+// any input (a dropdown too, whose list ComfyUI checks only for a value the graph writes), so Fuobe Connect lets such a
+// link, and any link into a dropdown, feed only what Fuobe's own graphs feed that way.
+const LOOSE_TYPES = new Set(["*", "COMFY_MATCHTYPE_V3", "COMBO"]);
+const looseType = (t) => typeof t !== "string" || t.split(",").some((p) => LOOSE_TYPES.has(p.trim()));
+const isDropdown = (spec) => {
+ const t = Array.isArray(spec) ? spec[0] : spec;
+ return Array.isArray(t) || t === "COMBO" || t === "COMFY_DYNAMICCOMBO_V3";
+};
+/** An input's name with a trailing number made general: images.image1 and images.image2 are one kind of input. */
+export const inputKind = (key) => key.replace(/\d+$/, "#");
+
+/** The studio's graphs (API form): workflows/comfyui and the hand-built ones. */
+export function studioGraphs(root) {
+ const out = [];
+ for (const dir of ["workflows/comfyui", "scripts/comfy/hand-built"]) {
+ const at = path.join(root, dir);
+ if (!fs.existsSync(at)) continue;
+ for (const f of fs.readdirSync(at)) {
+ if (!f.endsWith(".json") || ["requirements.json", "manifest.json", "object_info.subset.json"].includes(f)) continue;
+ try {
+ const g = JSON.parse(fs.readFileSync(path.join(at, f), "utf8"));
+ if (g && typeof g === "object" && !Array.isArray(g)) out.push(g);
+ } catch {}
+ }
+ }
+ return out;
+}
+
+/**
+ * The node types (on `nodes`) with outputs ComfyUI doesn't type-check, by output slot, and every [source type, target
+ * type, input kind] that the studio's graphs link from such an output or into a dropdown. Types come from
+ * workflows/comfyui/object_info.subset.json; inside ComfyUI, Fuobe Connect also reads them from the node classes.
+ */
+export function connectLinks(root, nodes) {
+ const info = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/object_info.subset.json"), "utf8"));
+ const loose = {};
+ for (const n of nodes) {
+ const outs = info[n]?.output;
+ if (!Array.isArray(outs)) continue;
+ const slots = outs.flatMap((t, i) => (looseType(t) ? [i] : []));
+ if (slots.length) loose[n] = slots;
+ }
+ const dropdown = (cls, key) => {
+ const inputs = info[cls]?.input ?? {};
+ const spec = inputs.required?.[key] ?? inputs.optional?.[key];
+ return spec !== undefined && isDropdown(spec);
+ };
+ const links = new Set();
+ for (const g of studioGraphs(root)) {
+ for (const n of Object.values(g)) {
+ if (!n || typeof n !== "object" || typeof n.class_type !== "string") continue;
+ for (const [key, v] of Object.entries(n.inputs ?? {})) {
+ if (!Array.isArray(v) || v.length !== 2 || typeof v[0] !== "string" || !Number.isInteger(v[1])) continue;
+ const src = g[v[0]]?.class_type;
+ if (typeof src !== "string") continue;
+ if (loose[src]?.includes(v[1]) || dropdown(n.class_type, key)) links.add(JSON.stringify([src, n.class_type, inputKind(key)]));
+ }
+ }
+ }
+ return { loose, links: [...links].sort().map((l) => JSON.parse(l)) };
+}
diff --git a/tests/fuobe-connect-nodes.test.ts b/tests/fuobe-connect-nodes.test.ts
index 0a807c08..0dd636af 100644
--- a/tests/fuobe-connect-nodes.test.ts
+++ b/tests/fuobe-connect-nodes.test.ts
@@ -16,6 +16,21 @@ describe("Fuobe Connect's node list", () => {
expect(missing, "run node scripts/connect-nodes.mjs").toEqual([]);
});
+ it("holds every untyped output and every such link the studio's graphs make", async () => {
+ const { connectLinks, studioNodes } = await import("../scripts/lib/studio-nodes.mjs");
+ const root = process.cwd();
+ const shipped = JSON.parse(fs.readFileSync(path.join(root, "integrations/fuobe-connect/fuobe_connect/allowed_nodes.json"), "utf8")) as {
+ loose: Record<string, number[]>;
+ links: [string, string, string][];
+ };
+ const want = connectLinks(root, studioNodes(root)) as { loose: Record<string, number[]>; links: [string, string, string][] };
+ expect(shipped.loose, "run node scripts/connect-nodes.mjs").toEqual(want.loose);
+ const have = new Set(shipped.links.map((l) => l.join("|")));
+ expect(want.links.filter((l) => !have.has(l.join("|"))), "run node scripts/connect-nodes.mjs").toEqual([]);
+ // Fuobe's any-typed helpers are among them: a link from one may feed only what the studio's graphs feed.
+ for (const n of ["CreateList", "GetItemFromList", "VRAM_Debug", "ComfySwitchNode"]) expect(Object.keys(shipped.loose)).toContain(n);
+ });
+
it("never lists nodes that read any folder, fetch addresses or run code", () => {
const shipped = JSON.parse(fs.readFileSync(path.join(process.cwd(), "integrations/fuobe-connect/fuobe_connect/allowed_nodes.json"), "utf8")).nodes as string[];
for (const risky of ["LoadImagesFromFolderKJ", "LoadImageFromUrl", "Image Load", "Image Saver", "Text Load Line From File", "KJ_RunPython"]) expect(shipped).not.toContain(risky);