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: see every link form, keep studios to checked requests, refuse held prompt ids

Adarsh03ac1fcbf6a5
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 5f430442..47af7268 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -19,8 +19,10 @@ README says how to install it and exactly what a trusted studio can do. It adds
**Direct mode.** ComfyUI turns away every other website. Fuobe Connect lets in only the studios that you trust. Each
studio is an exact https origin, and the default is `https://fuobe.com` with `https://www.fuobe.com`. You can name your
own studios, or `none`, in ComfyUI's settings or with `FUOBE_CONNECT_ORIGINS`. A trusted studio reaches the ComfyUI
-only at `127.0.0.1`, `::1` or `localhost`. Fuobe Connect checks each of its requests in Python, whatever the studio's
-page checked:
+only at `127.0.0.1`, `::1` or `localhost` (a network address too with `FUOBE_CONNECT_LAN=1`), never under another name
+that leads to the computer. Fuobe Connect turns away every other request of a trusted studio itself, even when ComfyUI
+runs with `--enable-cors-header` naming that studio, so with the pack the studio doesn't need that setting. Fuobe
+Connect checks each request it lets through in Python, whatever the studio's page checked:
- a workflow runs only when every node type is on the list the pack ships (`fuobe_connect/allowed_nodes.json`, written
by `node scripts/connect-nodes.mjs` from the same sources as the worker's list) or on the person's own list, and:
@@ -34,14 +36,18 @@ page checked:
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;
+ - a link names its node's output with a whole number from 0, as the studio's graphs write it. ComfyUI also takes
+ `true`, `false`, a number with a point or `-1` as an output; the pack sees those as links too, and refuses them;
- `VHS_VideoCombine` takes only a plain format name and plain-word settings (they go into ffmpeg's arguments), 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, 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
+- the studio sees, cancels, stops and downloads only its own prompts and their results; a prompt is its own only once
+ ComfyUI took it, never under an id that ComfyUI already holds in its queue or history; 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`.
+ out `custom_nodes` and `configs`. ComfyUI itself sends the live messages of a prompt queued without a client id to
+ every open socket, the studio's too.
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
diff --git a/integrations/fuobe-connect/README.md b/integrations/fuobe-connect/README.md
index 9acc9a05..579a44ef 100644
--- a/integrations/fuobe-connect/README.md
+++ b/integrations/fuobe-connect/README.md
@@ -27,8 +27,9 @@ phones, some other browsers), use pairing (below).
the Fuobe studios you trust. By default these are `https://fuobe.com` and `https://www.fuobe.com`. A studio's address
must start with `https://` (`http://` only for a studio on this computer, such as `http://localhost:3000`).
-A trusted studio reaches this ComfyUI only at `127.0.0.1`, `::1` or `localhost`, never at a network address. Its page
-can:
+A trusted studio reaches this ComfyUI only at `127.0.0.1`, `::1` or `localhost`. It never reaches it at a network
+address (unless you allow that, below) or under another name that leads to this computer, such as `127.0.0.1.nip.io`.
+Its page can:
- read ComfyUI's facts (`/system_stats`: version, GPU, memory, start options), its node list and the file lists of its
model folders, with each folder's place on disk (every folder ComfyUI lists, except `custom_nodes` and `configs`). In
@@ -60,6 +61,9 @@ can:
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`);
+ - a link must name its node's output with a whole number from 0 (`["4", 0]`), the way Fuobe's own workflows and
+ ComfyUI's page write it. ComfyUI also takes `true`, `false`, a number with a point (`0.0`) or `-1` as an output.
+ Fuobe Connect sees each of these as a link, and refuses it;
- `VHS_VideoCombine` puts its format's settings into ffmpeg's arguments, so each setting must be one plain word
(`yuv420p`, `hq`), and it takes a link only for its pictures, sound, batch, VAE and frame rate;
- the workflow may not give a node a JSON object (ComfyUI passes one on unchecked), except a 3D view's entries.
@@ -68,22 +72,31 @@ can:
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
+ `fuobe/<id>`). A prompt becomes the studio's only after ComfyUI takes it. Fuobe Connect refuses a prompt whose id
+ ComfyUI already has in its queue or its history, so a studio that learns the id of a prompt of yours can't take
+ that prompt over. In the queue, your own prompts show only as places in the line. It can't clear the queue or stop
your own work;
- download only the results that its own prompts' history lists;
-- 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. 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.
+- open ComfyUI's live socket only under a Fuobe client id (`fuobe-…`), never your own ComfyUI tab's. Note that
+ ComfyUI itself sends the live messages of a prompt queued without a client id (many scripts and API tools queue
+ that way) to every open socket, a studio's too: the prompt's id, its progress, its preview pictures, its errors and
+ the names of the files it saves. The studio still can't download those files or control that prompt. A prompt
+ queued from ComfyUI's own page carries that page's client id, and its messages go only to that page.
+
+A trusted studio can't reach the Manager's install calls, your user files or your settings: Fuobe Connect turns away
+every request of a trusted studio outside the list above itself, whatever ComfyUI's start options say. It can't read a
+file 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.
If ComfyUI runs with `--enable-cors-header` (an older Fuobe setup), ComfyUI's own check is off. Fuobe Connect then also
turns away every website except ComfyUI's own page, the site that the setting names and the trusted studios. This is
-what Fuobe's guard file did, so you can delete `fuobe_guard.py` and the setting.
+what Fuobe's guard file did, so you can delete `fuobe_guard.py` and the setting. A trusted studio gets only the checked
+requests above even when the setting names it, so a trusted studio doesn't need the setting. With
+`--enable-cors-header *` (every website) Fuobe Connect adds no check for other websites, but a trusted studio still
+gets only the checked requests.
## Choose your studios, or none
@@ -100,7 +113,8 @@ studio can't. Every check above applies to your nodes too: a workflow can't link
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`.
+runs with `--listen` at a network address, start ComfyUI with `FUOBE_CONNECT_LAN=1`. Its requests get the same checks
+there.
**A name for ComfyUI's page.** Fuobe Connect's own window works when you open ComfyUI at `127.0.0.1`, `localhost` or
an IP address. If you open it by a name (for example `comfy.local`, or a domain in front of it), set
diff --git a/integrations/fuobe-connect/fuobe_connect/graph.py b/integrations/fuobe-connect/fuobe_connect/graph.py
index 8020405b..c51d3e3f 100644
--- a/integrations/fuobe-connect/fuobe_connect/graph.py
+++ b/integrations/fuobe-connect/fuobe_connect/graph.py
@@ -21,6 +21,9 @@ A graph from a studio (a trusted page in direct mode, or the paired studio in pa
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 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 few inputs take only a link from one node type, or text of one shape (LINK_INPUTS, TEXT_INPUTS).
A result is downloaded only when this run's own history lists it. A model name the graph writes is checked by ComfyUI
@@ -300,8 +303,17 @@ def comfy_kinds(mappings) -> NodeKinds:
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)
+ """[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."""
+ 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."""
+ return type(v[1]) is int and 0 <= v[1] < 1000
def link_problem(graph: dict, cls: str, key: str, v, kinds: NodeKinds | None = None) -> str | None:
@@ -321,6 +333,8 @@ def input_problem(graph: dict, cls: str, key: str, v, kinds: NodeKinds | 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"
+ if is_link(v) and not plain_slot(v):
+ return "unsafe-graph"
links = LINK_INPUTS.get(cls, {}).get(key)
if is_link(v) and links is not None:
src = graph.get(v[0])
@@ -477,13 +491,14 @@ 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."""
+ """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."""
if isinstance(v, str):
yield v
elif isinstance(v, dict) and depth < 4:
for x in v.values():
yield from _strings(x, depth + 1)
- elif isinstance(v, list) and depth < 4 and not (len(v) == 2 and isinstance(v[0], str) and isinstance(v[1], int)):
+ elif isinstance(v, list) and depth < 4 and not (depth == 0 and is_link(v)):
for x in v:
yield from _strings(x, depth + 1)
diff --git a/integrations/fuobe-connect/fuobe_connect/middleware.py b/integrations/fuobe-connect/fuobe_connect/middleware.py
index 06f7c847..5e36deb6 100644
--- a/integrations/fuobe-connect/fuobe_connect/middleware.py
+++ b/integrations/fuobe-connect/fuobe_connect/middleware.py
@@ -8,17 +8,21 @@ is 127.0.0.1, ::1 or localhost) for a path a Fuobe run needs (origins.allowed).
- checks what the request asks for, here in Python, whatever the studio's own page checked (Studios.check): a prompt
runs only with the node types this pack ships (graph.py) and reads only files Fuobe sent; an upload goes only into
the input folder under a name Fuobe gives (fuobe_<id>.<ext>); a studio may take off, cancel, read or download only
- the prompts it queued and their results;
+ the prompts it queued and their results. A prompt counts as the studio's only once ComfyUI took it, and never under
+ an id that ComfyUI already holds (in its queue or its history: someone else's prompt);
- passes the request on without its Origin and Sec-Fetch-Site headers, so ComfyUI's own check sees what it sees for a
program on this computer, and adds Access-Control-Allow-Origin for that origin to the answer;
- shows the studio only its own prompts in the queue, the history and the job list, and never the names of the files
in your input folder (Studios.answer).
-Every other request goes on untouched, so ComfyUI's own check still turns away every other website.
+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.
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 a web page gets in only when the page is ComfyUI's own, the origin the setting
-names, or a trusted studio. With "--enable-cors-header *" (every site, the person's choice) it adds no check.
+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.
Pure aiohttp: the tests load it with ComfyUI's own middleware and nothing else.
"""
@@ -113,8 +117,12 @@ class Studios:
KEEP = 4096
- def __init__(self, nodes: Callable[[], Iterable[str]] | None = None):
+ 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."""
self.nodes = nodes or (lambda: frozenset())
+ self.held = held
self.prompts: OrderedDict[str, None] = OrderedDict()
self.files: OrderedDict[tuple, None] = OrderedDict()
@@ -197,7 +205,16 @@ class Studios:
return _refuse(REASONS[why], 400)
if self.own(pid):
return _refuse("That prompt id is taken", 400)
- self.add_prompt(pid)
+ if self.held is not None:
+ try:
+ taken = bool(self.held(pid))
+ except Exception:
+ logging.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")
+ return _refuse("That prompt id is taken", 400)
+ # The prompt becomes the studio's in answer(), once ComfyUI took it.
return None
async def _upload(self, request: web.Request) -> web.Response | None:
@@ -225,7 +242,7 @@ class Studios:
p = _bare(request.path)
if request.method == "POST":
if p == "/prompt":
- # An older ComfyUI names the prompt itself: that id is the studio's too.
+ # The id ComfyUI took the prompt under (the one the studio sent, or one an older ComfyUI chose).
try:
pid = json.loads(response.body).get("prompt_id")
except Exception:
@@ -290,6 +307,25 @@ class Studios:
return out
+def comfy_held(prompt_queue: Callable[[], object]) -> Callable[[str], bool]:
+ """Studios' `held`, from ComfyUI's own PromptQueue (`prompt_queue()` returns it): the id is in its history, or a
+ prompt with it runs or waits."""
+
+ def held(pid: str) -> bool:
+ q = prompt_queue()
+ try:
+ found = q.get_history(prompt_id=pid, map_function=lambda entry: True)
+ except TypeError: # a ComfyUI without map_function
+ found = q.get_history(prompt_id=pid)
+ if found:
+ return True
+ current = getattr(q, "get_current_queue_volatile", None) or q.get_current_queue
+ running, pending = current()
+ return any(isinstance(item, (list, tuple)) and len(item) > 1 and item[1] == pid for item in [*running, *pending])
+
+ return held
+
+
def _hide_inputs(info):
"""/object_info without the names of the files in your input folder (a loader's list keeps only Fuobe's own)."""
if not isinstance(info, dict):
@@ -326,6 +362,15 @@ def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | None
guard_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])
+ try:
+ named = flag_origin is not None and flag_origin in set(trusted())
+ except Exception:
+ named = False
+ if named:
+ logging.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,
+ )
studios = studios or Studios()
@web.middleware
@@ -333,29 +378,33 @@ def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | None
raw = request.headers.get("Origin")
if raw is not None:
origin = normalise(raw)
- here = lan or is_loopback(host_name(request.headers.get("Host")))
- if origin and here and origin in set(trusted()):
- if request.method == "OPTIONS":
- answer = preflight(request, origin)
- if answer is not None:
- return answer
- elif allowed(request.method, request.path, request.query_string):
- headers = request.headers.copy()
- headers.popall("Origin", None)
- headers.popall("Sec-Fetch-Site", None)
- headers[MARKER] = origin
- # One clone, read here and handed on: ComfyUI's handler reads the same body.
- clone = request.clone(headers=headers)
- response = await studios.check(clone)
- if response is None:
- response = await studios.answer(clone, await _pass(clone, handler))
- if isinstance(response, web.StreamResponse) and not response.prepared:
- response.headers.update(_cors_headers(origin))
- return response
- # A trusted site asking for anything else is any other website: ComfyUI decides (and turns it away).
- if guard_on and (origin is None or origin != flag_origin) and not same_host(raw, request.headers.get("Host")):
- if not (origin and origin in set(trusted())):
- _note(raw[:120])
+ host = request.headers.get("Host")
+ # A trusted studio, unless the page is ComfyUI's own (a studio listed at ComfyUI's own address).
+ if origin and origin in set(trusted()) and not same_host(raw, host):
+ if lan or is_loopback(host_name(host)):
+ if request.method == "OPTIONS":
+ answer = preflight(request, origin)
+ if answer is not None:
+ return answer
+ elif allowed(request.method, request.path, request.query_string):
+ headers = request.headers.copy()
+ headers.popall("Origin", None)
+ headers.popall("Sec-Fetch-Site", None)
+ headers[MARKER] = origin
+ # One clone, read here and handed on: ComfyUI's handler reads the same body.
+ clone = request.clone(headers=headers)
+ response = await studios.check(clone)
+ if response is None:
+ response = await studios.answer(clone, await _pass(clone, handler))
+ if isinstance(response, web.StreamResponse) and not response.prepared:
+ response.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.
+ 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])
return web.Response(status=403)
elif guard_on and request.headers.get("Sec-Fetch-Site", "").lower() in ("cross-site", "same-site"):
_note("another website")
diff --git a/integrations/fuobe-connect/fuobe_connect/origins.py b/integrations/fuobe-connect/fuobe_connect/origins.py
index d5c0667a..aa18efe8 100644
--- a/integrations/fuobe-connect/fuobe_connect/origins.py
+++ b/integrations/fuobe-connect/fuobe_connect/origins.py
@@ -6,7 +6,8 @@ A trusted site is a Fuobe studio: https://fuobe.com (and https://www.fuobe.com)
Only an exact origin counts (scheme, host and port), and only https, except a studio on this computer (http://localhost
or http://127.0.0.1, for development). A trusted site may use only the paths a Fuobe run needs (`allowed`); the
middleware then checks what each request asks for (middleware.py). It never reaches the Manager's install calls, your
-user files or your settings: those stay behind ComfyUI's own check, as for every other website.
+user files or your settings: the middleware turns away every other request of a trusted site itself, even when
+ComfyUI's own check is off (--enable-cors-header).
"""
from __future__ import annotations
diff --git a/integrations/fuobe-connect/fuobe_connect/plugin.py b/integrations/fuobe-connect/fuobe_connect/plugin.py
index 1374e756..36e23409 100644
--- a/integrations/fuobe-connect/fuobe_connect/plugin.py
+++ b/integrations/fuobe-connect/fuobe_connect/plugin.py
@@ -17,7 +17,7 @@ from aiohttp import web
from . import __version__
from .graph import NodeList, comfy_kinds
-from .middleware import MARKER, Studios, make_middleware
+from .middleware import MARKER, Studios, comfy_held, 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
log = logging.getLogger("fuobe_connect")
@@ -170,7 +170,8 @@ def install():
_state["store"] = store
# 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)
+ # A studio's prompt id is checked against ComfyUI's own queue and history (read when a prompt comes in).
+ studios = Studios(nodes, comfy_held(lambda: instance.prompt_queue))
_state["studios"] = studios
lan = os.environ.get("FUOBE_CONNECT_LAN") == "1"
try:
diff --git a/integrations/fuobe-connect/tests/comfy_stack.py b/integrations/fuobe-connect/tests/comfy_stack.py
index 9d13a649..3cab8465 100644
--- a/integrations/fuobe-connect/tests/comfy_stack.py
+++ b/integrations/fuobe-connect/tests/comfy_stack.py
@@ -110,7 +110,8 @@ def comfy_middleware() -> dict:
class Comfy:
- """What the stand-in ComfyUI keeps: its queue, its history, and what it was sent."""
+ """What the stand-in ComfyUI keeps: its queue, its history, and what it was sent. It also answers like ComfyUI's
+ PromptQueue (get_history, get_current_queue_volatile), the way Fuobe Connect reads it inside ComfyUI."""
def __init__(self, mint_ids: bool = False):
self.mint_ids = mint_ids
@@ -120,6 +121,19 @@ class Comfy:
self.posts: list = []
self.uploads: list = []
self.number = 0
+ # A /prompt answer of ComfyUI's own (status, body) instead of taking the prompt, for example a 400.
+ self.refuse: tuple | None = None
+
+ def get_history(self, prompt_id=None, max_items=None, offset=-1, map_function=None):
+ if prompt_id is None:
+ return dict(self.history)
+ if prompt_id not in self.history:
+ return {}
+ e = self.history[prompt_id]
+ return {prompt_id: map_function(e) if map_function else json.loads(json.dumps(e))}
+
+ def get_current_queue_volatile(self):
+ return list(self.queue_running), list(self.queue_pending)
def entry(self, pid: str, prompt: dict, files: list | None = None) -> dict:
self.number += 1
@@ -152,6 +166,8 @@ def build_app(cors_flag: str | None = None, fuobe_connect=None, extra_routes=Non
@routes.post("/prompt")
async def prompt(request):
body = await request.json()
+ if c.refuse is not None:
+ return web.json_response(c.refuse[1], status=c.refuse[0])
pid = str(uuid.uuid4()) if c.mint_ids or not body.get("prompt_id") else body.get("prompt_id")
c.posts.append(body)
if isinstance(body.get("prompt"), dict):
diff --git a/integrations/fuobe-connect/tests/test_graph.py b/integrations/fuobe-connect/tests/test_graph.py
index 43c6e730..70ca0b39 100644
--- a/integrations/fuobe-connect/tests/test_graph.py
+++ b/integrations/fuobe-connect/tests/test_graph.py
@@ -31,6 +31,7 @@ from fuobe_connect.graph import ( # noqa: E402
comfy_kinds,
graph_problem,
input_kind,
+ is_link,
may_download,
refusal,
run_prefix,
@@ -42,6 +43,28 @@ from fuobe_connect.graph import ( # noqa: E402
)
B = chr(92) # a backslash
+
+
+def comfy_is_link():
+ """ComfyUI's own is_link: from COMFYUI_DIR's comfy_execution/graph_utils.py when set (only that function is read),
+ else a copy of it."""
+ folder = os.environ.get("COMFYUI_DIR")
+ if folder:
+ import ast
+
+ with open(os.path.join(folder, "comfy_execution", "graph_utils.py"), encoding="utf-8") as f:
+ tree = ast.parse(f.read())
+ picked = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "is_link"]
+ ns: dict = {}
+ exec(compile(ast.Module(body=picked, type_ignores=[]), "comfyui/graph_utils.py", "exec"), ns)
+ return ns["is_link"]
+
+ def copy(obj):
+ if not isinstance(obj, list) or len(obj) != 2 or not isinstance(obj[0], str):
+ return False
+ return isinstance(obj[1], int) or isinstance(obj[1], float)
+
+ return copy
NODES = frozenset({"LoadImage", "SaveImage", "CLIPTextEncode", "Load3D", "VHS_LoadVideo", "LoadImagesFromFolderKJ", "LoadImageFromUrl", "Image Load", "Image Saver", "PrimitiveString"})
STAGED = ["fuobe_abcdefgh12.png", "fuobe_abcdefgh34.spz"]
@@ -448,6 +471,44 @@ 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."""
+ 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)
+ made = node("StringConcatenate", string_a="mine", string_b=".safetensors", delimiter="")
+ switch = node("ComfySwitchNode", switch=True, on_true=["1", 0], on_false=["1", 0])
+ video = {"images": ["9", 0], "format": "video/h264-mp4", "frame_rate": 24, "filename_prefix": "fuobe/x"}
+ for kinds in (None, KINDS):
+ # Slot 0: the link rules refuse these (the loose switch into a dropdown, a link into ffmpeg's arguments).
+ self.assertEqual(vet_graph(chain(made, switch, node("CheckpointLoaderSimple", ckpt_name=["2", 0])), SHIPPED, STAGED, kinds), "unsafe-graph")
+ self.assertEqual(vet_graph(chain(made, switch, node("VHS_VideoCombine", **video, pix_fmt=["2", 0])), SHIPPED, STAGED, kinds), "unsafe-graph")
+ for slot in (False, True, 0.0, 1.0, -1, 1000):
+ for target in (
+ node("CheckpointLoaderSimple", ckpt_name=["2", slot]),
+ node("LoraLoader", model=["8", 0], clip=["8", 1], lora_name=["2", slot]),
+ node("VHS_VideoCombine", **video, pix_fmt=["2", slot]),
+ node("VHS_VideoCombine", **{**video, "filename_prefix": ["2", slot]}),
+ node("VHS_VideoCombine", **{**video, "images": ["2", slot]}),
+ node("CLIPTextEncode", text=["2", slot], clip=["8", 0]),
+ node("KSampler", model=["2", slot], positive=["7", 0]),
+ node("LoadImage", image=["2", slot]),
+ ):
+ self.assertEqual(vet_graph(chain(made, switch, target), SHIPPED, STAGED, kinds), "unsafe-graph", (slot, target))
+ # Fuobe's own form still passes.
+ self.assertIsNone(vet_graph(chain(made, switch, node("KSampler", model=["2", 0], positive=["7", 0])), SHIPPED, STAGED, kinds))
+
+ 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 are
+ read like any other."""
+ for inner in (["//host/share/x", 0], ["C:" + B + "Users" + B + "x", False], ["/etc/passwd", 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."""
diff --git a/integrations/fuobe-connect/tests/test_middleware.py b/integrations/fuobe-connect/tests/test_middleware.py
index 9e0a564a..7ff94e0c 100644
--- a/integrations/fuobe-connect/tests/test_middleware.py
+++ b/integrations/fuobe-connect/tests/test_middleware.py
@@ -10,6 +10,7 @@ import asyncio
import json
import os
import sys
+import types
import unittest
import uuid
@@ -21,7 +22,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from comfy_stack import COMFY, Comfy, build_app # noqa: E402
from fuobe_connect import plugin # noqa: E402
-from fuobe_connect.middleware import MARKER, Studios, make_middleware # noqa: E402
+from fuobe_connect.middleware import MARKER, Studios, comfy_held, make_middleware # noqa: E402
from fuobe_connect.origins import allowed, normalise, parse_list, same_host, studio, trusted_origins # noqa: E402
PORT = int(os.environ.get("FUOBE_CONNECT_TEST_PORT", "3360"))
@@ -97,11 +98,33 @@ def with_connect(trusted=trusted_origins(None, None), cors_flag=None, comfy=None
plugin._state.clear()
plugin._state["store"] = FakeStore()
routes = [("GET", "/fuobe/connect", plugin.status), ("POST", "/fuobe/connect/studios", plugin.set_studios)]
- studios = Studios(lambda: NODES)
+ comfy = comfy or Comfy()
+ # The stand-in answers like ComfyUI's PromptQueue, which the plugin hands to Studios inside ComfyUI.
+ studios = Studios(lambda: NODES, comfy_held(lambda: comfy))
app, source = build_app(cors_flag, make_middleware(lambda: trusted, cors_flag, studios, lan), routes, comfy)
return app, source
+def comfy_prompt_queue():
+ """ComfyUI's own PromptQueue class, read from COMFYUI_DIR's execution.py (that class alone: nothing else of ComfyUI
+ is imported). None without COMFYUI_DIR."""
+ folder = os.environ.get("COMFYUI_DIR")
+ if not folder:
+ return None
+ import ast
+ import copy
+ import heapq
+ import threading
+ import typing
+
+ with open(os.path.join(folder, "execution.py"), encoding="utf-8") as f:
+ tree = ast.parse(f.read())
+ picked = [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "PromptQueue"]
+ ns = {"threading": threading, "heapq": heapq, "copy": copy, "MAXIMUM_HISTORY_SIZE": 10000, **{k: getattr(typing, k) for k in typing.__all__ if hasattr(typing, k)}}
+ exec(compile(ast.Module(body=picked, type_ignores=[]), "comfyui/execution.py", "exec"), ns)
+ return ns["PromptQueue"]
+
+
def run(coro):
return asyncio.run(coro)
@@ -367,6 +390,118 @@ 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."""
+
+ async def go():
+ comfy = Comfy()
+ done, running, waiting = (str(uuid.uuid4()) for _ in range(3))
+ yours = {"1": {"class_type": "SaveImage", "inputs": {"filename_prefix": "ComfyUI", "images": ["2", 0]}}}
+ comfy.entry(done, yours, [{"filename": "ComfyUI_00042_.png", "subfolder": "", "type": "output"}])
+ comfy.queue_running = [[1, running, yours, {}, ["1"]]]
+ comfy.queue_pending = [[2, waiting, yours, {}, ["1"]]]
+ app, _ = with_connect(comfy=comfy)
+ claim = {"9": {"class_type": "SaveImage", "inputs": {"filename_prefix": "fuobe/gen123abc", "images": ["8", 0]}}}
+ async with Server(app) as s:
+ for pid in (done, running, waiting):
+ status, h, data = await s.json("POST", "/prompt", body={"prompt": claim, "prompt_id": pid, "client_id": "fuobe-abcdefgh"})
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (400, FUOBE), pid)
+ self.assertEqual(data["error"]["type"], "fuobe_connect_refused")
+ self.assertEqual(comfy.posts, [])
+ status, _, data = await s.json("GET", f"/history/{done}")
+ self.assertEqual((status, data), (200, {}))
+ status, _, _ = await s.req("GET", "/view?filename=ComfyUI_00042_.png&subfolder=&type=output", browser(FUOBE))
+ self.assertEqual(status, 403)
+ status, _, _ = await s.json("GET", f"/api/jobs/{done}")
+ self.assertEqual(status, 404)
+ status, _, _ = await s.json("POST", "/interrupt", body={"prompt_id": running})
+ self.assertEqual(status, 403)
+ for path in ("/queue", "/history"):
+ status, _, _ = await s.json("POST", path, body={"delete": [waiting]})
+ self.assertEqual(status, 403, path)
+ status, _, _ = await s.json("POST", f"/api/jobs/{waiting}/cancel", body={})
+ self.assertEqual(status, 403)
+ status, _, data = await s.json("GET", "/queue")
+ self.assertEqual((data["queue_running"], data["queue_pending"]), ([[1, None, None, {}, []]], [[2, None, None, {}, []]]))
+
+ run(go())
+
+ def test_prompt_is_the_studios_once_comfyui_took_it(self):
+ """A prompt that ComfyUI refused never becomes the studio's, so a later prompt under that id isn't either."""
+
+ async def go():
+ comfy = Comfy()
+ app, _ = with_connect(comfy=comfy)
+ async with Server(app) as s:
+ pid = str(uuid.uuid4())
+ comfy.refuse = (400, {"error": {"type": "prompt_outputs_failed_validation"}})
+ status, _, _ = await s.json("POST", "/prompt", body={"prompt": graph(), "prompt_id": pid})
+ self.assertEqual(status, 400)
+ comfy.refuse = None
+ comfy.entry(pid, {"1": {"class_type": "SaveImage", "inputs": {"filename_prefix": "ComfyUI"}}}, [{"filename": "ComfyUI_00007_.png", "subfolder": "", "type": "output"}])
+ status, _, data = await s.json("GET", f"/history/{pid}")
+ self.assertEqual(data, {})
+ status, _, _ = await s.json("POST", "/interrupt", body={"prompt_id": pid})
+ self.assertEqual(status, 403)
+ # The id ComfyUI took is the studio's, and it can't be sent again.
+ mine = str(uuid.uuid4())
+ status, _, _ = await s.json("POST", "/prompt", body={"prompt": graph(), "prompt_id": mine})
+ self.assertEqual(status, 200)
+ status, _, _ = await s.json("POST", "/interrupt", body={"prompt_id": mine})
+ self.assertEqual(status, 200)
+ status, _, _ = await s.json("POST", "/prompt", body={"prompt": graph(), "prompt_id": mine})
+ self.assertEqual(status, 400)
+
+ run(go())
+
+ def test_prompt_id_check_that_fails_refuses(self):
+ def broken(pid):
+ raise RuntimeError("no queue")
+
+ studios = Studios(lambda: NODES, broken)
+ answer = studios._prompt({"prompt": graph(), "prompt_id": str(uuid.uuid4())})
+ self.assertEqual(answer.status, 503)
+ self.assertEqual(len(studios.prompts), 0)
+
+ def test_held_reads_comfyuis_queue(self):
+ """comfy_held against ComfyUI's own PromptQueue (with COMFYUI_DIR), else against the stand-in."""
+ cls = comfy_prompt_queue()
+ if cls is None:
+ comfy = Comfy()
+ held = comfy_held(lambda: comfy)
+ comfy.queue_pending = [[0, "a", {}, {}, []]]
+ self.assertTrue(held("a"))
+ comfy.queue_running, comfy.queue_pending = comfy.queue_pending, []
+ self.assertTrue(held("a"))
+ comfy.queue_running = []
+ comfy.entry("a", {})
+ self.assertTrue(held("a"))
+ self.assertFalse(held("b"))
+ else:
+ q = cls(types.SimpleNamespace(queue_updated=lambda: None))
+ held = comfy_held(lambda: q)
+ self.assertFalse(held("a"))
+ q.put((0, "a", {}, {}, [], {}))
+ self.assertTrue(held("a"))
+ _, i = q.get()
+ self.assertTrue(held("a"))
+ q.task_done(i, {"outputs": {}, "meta": {}}, None)
+ self.assertEqual(q.get_tasks_remaining(), 0)
+ self.assertTrue(held("a"))
+ self.assertFalse(held("b"))
+
+ # An older ComfyUI: get_history without map_function, and no get_current_queue_volatile.
+ class Older:
+ def get_history(self, prompt_id=None, max_items=None, offset=-1):
+ return {"c": {}} if prompt_id == "c" else {}
+
+ def get_current_queue(self):
+ return [[0, "d", {}, {}, []]], [[1, "e", {}, {}, []]]
+
+ older = comfy_held(Older)
+ self.assertEqual([older(x) for x in "cdef"], [True, True, True, False])
+
def test_older_comfyui_names_the_prompt(self):
async def go():
comfy = Comfy(mint_ids=True)
@@ -410,7 +545,7 @@ class DirectModeTest(unittest.TestCase):
# A simple GET that Chrome preflights only for Private Network Access.
status, h, _ = await s.req("OPTIONS", "/system_stats", browser(FUOBE, **{"Access-Control-Request-Method": "GET", "Access-Control-Request-Private-Network": "true"}))
self.assertEqual((status, h.get("Access-Control-Allow-Private-Network")), (204, "true"))
- # A header a run never sends: no preflight answer from Fuobe Connect, so ComfyUI's check refuses it.
+ # A header a run never sends: Fuobe Connect refuses the preflight.
status, h, _ = await s.req("OPTIONS", "/prompt", browser(FUOBE, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "x-custom"}))
self.assertEqual(status, 403)
self.assertNotIn("Access-Control-Allow-Origin", h)
@@ -562,6 +697,57 @@ 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."""
+
+ def form(name, kind):
+ f = aiohttp.FormData()
+ f.add_field("image", b"data", filename=name, content_type="image/png")
+ f.add_field("type", kind)
+ return f
+
+ async def go(flag, lan):
+ comfy = Comfy()
+ app, _ = with_connect(cors_flag=flag, comfy=comfy, lan=lan)
+ async with Server(app) as s:
+ unlisted = {"1": {"class_type": "SomeUnlistedNode", "inputs": {"path": "C:/Windows/x"}}}
+ for host in (f"127.0.0.1:{PORT}", f"localhost:{PORT}", f"127.0.0.1.nip.io:{PORT}", f"localtest.me:{PORT}"):
+ for method, path in [
+ ("POST", "/v2/manager/queue/install"),
+ ("POST", "/api/v2/manager/queue/install"),
+ ("GET", "/userdata/comfy.settings.json"),
+ ("POST", "/settings/Comfy.Server.LaunchArgs"),
+ ("POST", "/upload/mask"),
+ ("GET", "/internal/logs"),
+ ]:
+ status, h, _ = await s.req(method, path, browser(FUOBE, Host=host, **{"Content-Type": "application/json"}), data=b"{}" if method == "POST" else None)
+ self.assertEqual(status, 403, (flag, lan, host, path))
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+ status, h, _ = await s.req("OPTIONS", "/v2/manager/queue/install", browser(FUOBE, Host=host, **{"Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "content-type"}))
+ self.assertEqual(status, 403, (flag, lan, host))
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+ # The paths a run needs: checked here, or (this computer under another name) refused.
+ checked = lan or host.startswith(("127.0.0.1:", "localhost:"))
+ status, h, _ = await s.req("POST", "/prompt", browser(FUOBE, Host=host, **{"Content-Type": "application/json"}), data=prompt_body(unlisted))
+ self.assertEqual(status, 400 if checked else 403, (flag, lan, host))
+ async with s.session.post(BASE + "/upload/image", data=form("my_photo.png", "output"), headers=browser(FUOBE, Host=host)) as res:
+ self.assertEqual(res.status, 403, (flag, lan, host))
+ self.assertEqual(res.headers.get("Access-Control-Allow-Origin"), FUOBE if checked else None)
+ status, h, _ = await s.req("GET", "/system_stats", browser(FUOBE, Host=host))
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE) if checked else (403, None), (flag, lan, host))
+ self.assertEqual((comfy.posts, comfy.uploads), ([], []))
+ status, _, _ = await s.req("POST", "/prompt", browser(FUOBE, **{"Content-Type": "application/json"}), data=prompt_body())
+ self.assertEqual(status, 200)
+
+ for flag in (FUOBE, "https://www.fuobe.com", "*"):
+ for lan in (False, True):
+ run(go(flag, lan))
+ with self.assertLogs(level="WARNING") as logs:
+ with_connect(cors_flag=FUOBE)
+ self.assertTrue(any("isn't needed for that studio" in line for line in logs.output), logs.output)
+
def test_flag_that_isnt_an_origin(self):
"""--enable-cors-header with a value that isn't a full origin: a sandboxed page ("null") stays out."""
diff --git a/integrations/fuobe-connect/tests/test_plugin.py b/integrations/fuobe-connect/tests/test_plugin.py
index d41d6b86..6b2e2e6b 100644
--- a/integrations/fuobe-connect/tests/test_plugin.py
+++ b/integrations/fuobe-connect/tests/test_plugin.py
@@ -27,7 +27,7 @@ PACK = os.path.dirname(HERE)
sys.path.insert(0, HERE)
sys.path.insert(0, PACK)
-from comfy_stack import build_app # noqa: E402
+from comfy_stack import COMFY, build_app # noqa: E402
from fuobe_connect import plugin # noqa: E402
from fuobe_connect.store import access_list # noqa: E402
@@ -231,7 +231,8 @@ class FakeStudio:
def load_pack(user_dir: str):
"""ComfyUI's view of the world, as much of it as Fuobe Connect reads, then the pack itself."""
app, _ = build_app()
- instance = types.SimpleNamespace(app=app, routes=web.RouteTableDef())
+ # The stand-in's queue and history answer like ComfyUI's PromptQueue.
+ instance = types.SimpleNamespace(app=app, routes=web.RouteTableDef(), prompt_queue=app[COMFY])
server = types.ModuleType("server")
server.PromptServer = types.SimpleNamespace(instance=instance)
folder_paths = types.ModuleType("folder_paths")
@@ -270,6 +271,12 @@ class PluginTest(unittest.TestCase):
paths = {(r.method, r.path) for r in instance.routes}
for p in [("GET", "/fuobe/connect"), ("POST", "/fuobe/connect/pair"), ("POST", "/fuobe/connect/jobs")]:
self.assertIn(p, paths)
+ # A studio's prompt id is checked against ComfyUI's own queue and history.
+ studios = sys.modules["fuobe_connect_pack.fuobe_connect.plugin"]._state["studios"]
+ instance.prompt_queue.entry("0f0e0d0c-0000-4000-8000-000000000001", {})
+ instance.prompt_queue.queue_pending = [[1, "0f0e0d0c-0000-4000-8000-000000000002", {}, {}, []]]
+ self.assertEqual([studios.held(f"0f0e0d0c-0000-4000-8000-00000000000{i}") for i in (1, 2, 3)], [True, True, False])
+ instance.prompt_queue.queue_pending = []
instance.app.add_routes(instance.routes)
studio = FakeStudio()
file = os.path.join(user_dir, "fuobe-connect.json")