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: check every studio request on this computer before ComfyUI sees it

Adarsh73ffcc73051a
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index ea8802ef..f409580f 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -12,19 +12,34 @@ the studio over HTTPS, and neither opens a port. With no worker added and nothin
## Fuobe Connect (a person's own ComfyUI)
-Fuobe Connect is a ComfyUI custom node pack. Its code is in `integrations/fuobe-connect`, and its own README tells you
-how to install it. It adds no nodes.
+Fuobe Connect is a ComfyUI custom node pack. Its source is in `integrations/fuobe-connect`, and people install it
+from `https://github.com/workingprototype/ComfyUI-Fuobe-Connect` or from ComfyUI-Manager (`Fuobe Connect`). Its own
+README says how to install it and exactly what a trusted studio can do. It adds no nodes.
**Direct mode.** ComfyUI turns away every other website. Fuobe Connect lets in only the studios that you trust. Each
-studio is an exact origin, and the default is `https://fuobe.com`. You can add your own studio in ComfyUI's settings,
-or with `FUOBE_CONNECT_ORIGINS`. A trusted studio can use only what a run needs: ComfyUI's facts, model lists, queue
-and history, the run's results, uploads of its inputs, and its prompt. It cannot reach the Manager's install calls,
-your user files or your settings. Fuobe Connect answers the CORS and Private Network Access preflights for the trusted
-origins only. Every other website still meets ComfyUI's own check.
+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:
+
+- 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, no text
+ input names a path or an address, and every loader reads a Fuobe input (`fuobe_<id>.<ext>`);
+- an upload goes only into the input folder, under a Fuobe input name;
+- 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, and the node list hides the names of the person's input files.
+
+It cannot reach the Manager's install calls, the person's user files, settings, input files or own results. Fuobe
+Connect answers the CORS and Private Network Access preflights for the trusted origins only. Every other website still
+meets ComfyUI's own check.
You do not need a start flag or a guard file. In the studio, **Connect your GPU** finds ComfyUI after one browser
"Allow" prompt, and then connects.
+When a workflow or graph builder starts using a new node type, run `node scripts/connect-nodes.mjs` and ship the list
+with the next Fuobe Connect release (`tests/fuobe-connect-nodes.test.ts` fails until then). People with an older Fuobe
+Connect get a refusal that asks them to update it.
+
**Pairing mode.** Use pairing with Safari, phones, a blocked browser or a PC with no screen:
1. In ComfyUI, open **Extensions → Connect to Fuobe**. On a PC with no screen, start ComfyUI with
@@ -35,7 +50,9 @@ You do not need a start flag or a guard file. In the studio, **Connect your GPU*
gets a worker token (`fuobe_wkr_…`). The studio makes the token at that moment and keeps only its SHA-256 hash.
The token acts only as that person's own computer. The ComfyUI gets that person's jobs, and nobody else's. The jobs
-run with no Fuobe tab open. The person can disconnect the ComfyUI in Settings → Your GPU (`DELETE /api/gpu/paired/<id>`)
+run with no Fuobe tab open. Fuobe Connect pairs only with a studio the person trusts (or `https://fuobe.com`), and
+checks every job as in direct mode before ComfyUI sees it. If the poll answer names the approving account, ComfyUI
+shows it. The person can pause jobs in ComfyUI. The person can disconnect the ComfyUI in Settings → Your GPU (`DELETE /api/gpu/paired/<id>`)
or press Disconnect in ComfyUI (`POST /api/gpu/computer/unpair`). A disconnected token gets 401 at its next call.
## Workers (the owner's shared GPUs)
@@ -185,7 +202,8 @@ routes.
## Tests
-- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`)
+- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`,
+ `tests/fuobe-connect-nodes.test.ts`)
- `node tests/e2e/worker.mjs` and `node tests/e2e/fuobe-connect.mjs` (after `pnpm build`, or with `E2E_DEV=1`). These
use a stand-in ComfyUI and a stand-in `nvidia-smi` on ports 3361 and 3362. They never touch a real GPU or ComfyUI.
- `python -m unittest discover -s tests` in `integrations/fuobe-connect`
diff --git a/integrations/fuobe-connect/.comfyignore b/integrations/fuobe-connect/.comfyignore
new file mode 100644
index 00000000..fd7f63b3
--- /dev/null
+++ b/integrations/fuobe-connect/.comfyignore
@@ -0,0 +1,3 @@
+tests/
+.github/
+.gitignore
diff --git a/integrations/fuobe-connect/.github/workflows/publish.yml b/integrations/fuobe-connect/.github/workflows/publish.yml
new file mode 100644
index 00000000..0a86dfe3
--- /dev/null
+++ b/integrations/fuobe-connect/.github/workflows/publish.yml
@@ -0,0 +1,21 @@
+# Publishes Fuobe Connect to the Comfy Registry when pyproject.toml changes on main (a new version), or by hand.
+# Needs the repository secret REGISTRY_ACCESS_TOKEN: a publishing key of the "workingprototype" Registry publisher.
+name: Publish to the Comfy Registry
+on:
+ workflow_dispatch:
+ push:
+ branches: [main]
+ paths: [pyproject.toml]
+
+permissions:
+ contents: read
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ if: ${{ github.repository_owner == 'workingprototype' }}
+ steps:
+ - name: Publish
+ uses: Comfy-Org/publish-node-action@7578cdb0c1410f2515e6f9b1443c6859cab94f05 # 1.0.1
+ with:
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
diff --git a/integrations/fuobe-connect/.gitignore b/integrations/fuobe-connect/.gitignore
new file mode 100644
index 00000000..2f8c9c20
--- /dev/null
+++ b/integrations/fuobe-connect/.gitignore
@@ -0,0 +1,5 @@
+__pycache__/
+*.pyc
+*.tmp
+fuobe-connect.json
+fuobe-connect-nodes.json
diff --git a/integrations/fuobe-connect/README.md b/integrations/fuobe-connect/README.md
index 89b69a15..61ecc41e 100644
--- a/integrations/fuobe-connect/README.md
+++ b/integrations/fuobe-connect/README.md
@@ -17,47 +17,97 @@ git clone https://github.com/workingprototype/ComfyUI-Fuobe-Connect
Then restart ComfyUI.
-Then open Fuobe in Chrome, Edge or Firefox and choose **Connect your GPU**. Your browser asks once to let the page reach
-apps on this computer. Press **Allow**. Fuobe finds ComfyUI and connects.
+Then open Fuobe and choose **Connect your GPU**. Chrome and Edge ask once to let the page reach apps on this computer.
+Press **Allow**. Fuobe finds ComfyUI and connects. If your browser can't reach this computer from a website (Safari,
+phones, some other browsers), use pairing (below).
-## What it does
+## What a trusted studio can do
**Direct mode (the default).** ComfyUI turns away requests from every other website. Fuobe Connect adds one exception:
-the Fuobe studios you trust (`https://fuobe.com` unless you name others). For a trusted studio it:
-
-- answers the browser's CORS preflight and Chrome's Private Network Access preflight, for that exact origin only;
-- lets through only what a Fuobe run needs: ComfyUI's facts, its model lists, its queue and history, the run's
- results, uploading the run's inputs and queueing its prompt.
-
-A trusted studio cannot reach the Manager's install calls, your user files, your settings or your input folder. Every
-other website still meets ComfyUI's own check, unchanged. Nothing in ComfyUI's own files changes.
+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:
+
+- read ComfyUI's facts (`/system_stats`: version, GPU, memory, start options), its node list and its model lists. 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;
+- 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;
+ - no text input may name a path or an address: an absolute path, a drive letter, a network share, a `..` step, a
+ home folder, a URL, or a ComfyUI folder tag such as `name [output]`;
+ - every file loader must read a Fuobe input (`fuobe_<id>.<ext>`), never a file of yours.
+
+ A workflow that uses an installed node from the list can still do what that node does (for example, save into your
+ output folder);
+- 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;
+- 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, your settings, your input files or your
+own results. 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.
-**Pairing mode (for Safari, phones and PCs with no screen).** Some browsers do not let a website reach apps on your
-computer. In ComfyUI, open **Extensions → Connect to Fuobe** and press **Connect**. ComfyUI shows a short code. Open the
-link on any device, sign in to Fuobe and approve the code. From then on, ComfyUI gets that one person's jobs from the
-studio over HTTPS, and it runs them with no Fuobe tab open. It opens no port. The token belongs to you alone, so another
-person's jobs never reach your PC. To stop, press **Disconnect** in the same window, or remove the computer in Fuobe's
-settings.
+## Choose your studios, or none
-On a PC with no screen, start ComfyUI with `FUOBE_CONNECT_PAIR=1`. The code and the link then appear in ComfyUI's
-console.
+Open ComfyUI's **Settings → Fuobe Connect** and enter the studios that may use this ComfyUI, separated by commas, for
+example `https://studio.example.com`. Type `none` to let no website use this ComfyUI from the browser. Pairing still
+works.
+
+You can also set the environment variable `FUOBE_CONNECT_ORIGINS` before you start ComfyUI (`none` works there too).
+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.
+
+**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`.
-## Your own Fuobe studio
+**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
+`FUOBE_CONNECT_HOSTS=comfy.local` before you start ComfyUI. This keeps a website that points its own name at your
+computer out of the window's settings.
+
+## Pairing (for Safari, phones and PCs with no screen)
+
+In ComfyUI, open **Extensions → Connect to Fuobe**. You can give this computer a name. Press **Connect**. ComfyUI
+shows a short code. Open the link on any device, sign in to Fuobe and approve the code. Approve only a code that you
+see in your own ComfyUI. From then on, ComfyUI gets that one person's jobs from the studio over HTTPS, and it runs them
+with no Fuobe tab open. It opens no port. The token belongs to you alone, so another person's jobs never reach your PC.
+
+Pairing works only with a studio you trust, or with `https://fuobe.com`. Every job gets the same checks as in direct
+mode, before it reaches ComfyUI. The job's inputs leave the input folder when the job is done.
+
+The **Connect to Fuobe** window shows the studio, the account that approved the code (when the studio says), and the
+last jobs with their node types and times. **Pause jobs** stops this computer from taking new jobs. **Disconnect** tells
+the studio to forget this computer first. If the studio can't be reached, Fuobe Connect keeps trying every minute, and
+you can also remove the computer in Fuobe's settings.
+
+On a PC with no screen, start ComfyUI with `FUOBE_CONNECT_PAIR=1`. The code and the link then appear in ComfyUI's
+console. `FUOBE_CONNECT_SITE=https://studio.example.com` chooses the studio for that.
-To use a studio that you host yourself, open ComfyUI's **Settings → Fuobe Connect** and enter its address, for example
-`https://studio.example.com`. You can also set the environment variable
-`FUOBE_CONNECT_ORIGINS=https://studio.example.com` before you start ComfyUI. Separate several studios with commas. The
-first one is also the studio that pairing uses.
+**What pairing sends to the studio.** When you press Connect: this computer's name (the one you typed, else its
+network name), the GPU's name, its memory and ComfyUI's version. While paired, about every minute: the GPU's name and
+memory, the computer's memory, the operating system, ComfyUI's version, whether ComfyUI is the portable build, and the
+progress of a running job. Every five minutes: the file names in your `loras` folder (up to 20,000), so Fuobe can use
+your LoRAs. To stop sending the LoRA names, start ComfyUI with `FUOBE_CONNECT_LORAS=0`. After a job: its results, and
+for a failed job the error type and message, without the folders on this computer.
## Files
Fuobe Connect keeps one file, `fuobe-connect.json`, in ComfyUI's `user` folder. The file holds the studios that you
-trust and, after pairing, the studio's address and the token. Only your user account can read the file. ComfyUI does
-not serve this file to web pages.
+trust and, after pairing, the studio's address, the account and the token. Only your user account can read the file:
+mode 0600 on Linux and macOS, and on Windows an access list with only your account. ComfyUI does not serve this file to
+web pages.
## Tests
@@ -65,9 +115,10 @@ not serve this file to web pages.
python -m unittest discover -s tests
```
-The tests load ComfyUI's own origin check and run it behind Fuobe Connect over real HTTP on port 3360. Set
-`FUOBE_CONNECT_TEST_PORT` to choose another port. Set `COMFYUI_DIR` to a ComfyUI folder to read the middleware from that
-copy of ComfyUI. The tests need only `aiohttp`. They do not need models, a GPU or a running ComfyUI.
+The tests load ComfyUI's own origin check and run it behind Fuobe Connect over real HTTP on ports 3360, 3364, 3365
+and 3366. Set `FUOBE_CONNECT_TEST_PORT` to move them (the tests use that port and the three after it, +4 to +6). Set
+`COMFYUI_DIR` to a ComfyUI folder to read the middleware from that copy of ComfyUI. The tests need only `aiohttp`.
+They do not need models, a GPU or a running ComfyUI. The `tests` folder is not part of the published pack.
## Licence
diff --git a/integrations/fuobe-connect/fuobe_connect/agent.py b/integrations/fuobe-connect/fuobe_connect/agent.py
index f2cf7c03..0e18393a 100644
--- a/integrations/fuobe-connect/fuobe_connect/agent.py
+++ b/integrations/fuobe-connect/fuobe_connect/agent.py
@@ -1,44 +1,85 @@
"""Pairing mode: Fuobe Connect runs your Fuobe jobs on this ComfyUI with no browser tab, after one approval.
-For browsers that can't reach this computer from a website (Safari, Firefox in some setups, phones) and for PCs with no
-screen. It runs in its own thread with its own event loop, so ComfyUI's own work is never held up by it.
+For browsers that can't reach this computer from a website (Safari, phones, and other browsers in some setups) and for
+PCs with no screen. It runs in its own thread with its own event loop, so ComfyUI's own work is never held up by it.
1. "Connect to Fuobe" (ComfyUI's menu, or FUOBE_CONNECT_PAIR=1 on a PC with no screen) asks the studio for a short code.
+ The studio is one you trust (Settings → Fuobe Connect) or https://fuobe.com.
2. You open the studio's /connect page, signed in, and approve that code.
-3. This ComfyUI gets a token for you alone, kept in fuobe-connect.json, and runs your jobs (runner.py).
+3. This ComfyUI gets a token for you alone, kept in fuobe-connect.json, and runs your jobs (runner.py). The window shows
+ the account that approved it (when the studio says) and the last jobs, and can pause them.
-"Disconnect" in ComfyUI, or Disconnect in the studio's settings, ends it.
+"Disconnect" in ComfyUI tells the studio first; the token is forgotten here once the studio has it revoked. Disconnect in
+the studio's settings ends it too.
"""
from __future__ import annotations
import asyncio
import logging
+import os
+import re
import socket
import threading
import time
+from collections import deque
+from urllib.parse import urlsplit
import aiohttp
+from .graph import NodeList
from .net import Comfy, Site, site_base
from .runner import Runner, Unpaired
from .store import Store
log = logging.getLogger("fuobe_connect")
+CODE = re.compile(r"^[A-Z0-9]{2,8}(?:-[A-Z0-9]{2,8})?\Z")
+NAME = re.compile(r"^[^\x00-\x1f\x7f]{1,48}\Z")
+REVOKE_RETRY_S = 60
+
+
+def computer_name(name=None) -> str:
+ """The name this computer has on Fuobe: the one the person typed, else this computer's own name."""
+ if isinstance(name, str) and NAME.match(name.strip() or "x") and name.strip():
+ return name.strip()
+ own = (socket.gethostname() or "")[:48]
+ return own if NAME.match(own or "x") and own else "ComfyUI"
+
+
+def pairing_link(url, base: str) -> str:
+ """The studio's approval page: on the studio's own address, https (http only on this computer)."""
+ if not isinstance(url, str) or len(url) > 300:
+ raise RuntimeError("The studio's answer had no approval link")
+ try:
+ u = urlsplit(url)
+ same = site_base(f"{u.scheme}://{u.netloc}") == base
+ except ValueError:
+ same = False
+ if not same or u.username or u.password:
+ raise RuntimeError("The studio's approval link isn't on the studio's own address")
+ return url
+
class Agent:
- def __init__(self, store: Store, comfy_base: str, port: int, default_site: str):
+ def __init__(self, store: Store, comfy_base: str, port: int, default_site: str, nodes: NodeList | None = None, input_dir: str | None = None):
self.store = store
self.comfy_base = comfy_base
self.port = port
self.default_site = default_site
+ self.nodes = nodes or NodeList()
+ self.input_dir = input_dir
self.loop = asyncio.new_event_loop()
self.state = "unpaired"
self.message: str | None = None
self.pairing: dict | None = None
+ # The prompts Fuobe Connect queued on this ComfyUI, its jobs' prefixes, and the last jobs (shown in ComfyUI's window).
+ self.own: set[str] = set()
+ self.prefixes: set[str] = set()
+ self.recent: deque = deque(maxlen=20)
self._runner_task: asyncio.Future | None = None
self._pair_task: asyncio.Future | None = None
+ self._revoke_task: asyncio.Future | None = None
self._session: aiohttp.ClientSession | None = None
self._thread: threading.Thread | None = None
@@ -56,7 +97,10 @@ class Agent:
async def _boot(self):
self._session = aiohttp.ClientSession()
- if self.store.load().get("token"):
+ data = self.store.load()
+ if data.get("revokePending"):
+ self._start_revoke()
+ elif data.get("token"):
self._start_runner()
def call(self, coro):
@@ -66,11 +110,16 @@ class Agent:
# ------------------------------------------------------------------
# State
+ def paused(self) -> bool:
+ return bool(self.store.load().get("paused"))
+
def status(self) -> dict:
data = self.store.load()
- out = {"state": self.state, "message": self.message}
- if data.get("token"):
- out["paired"] = {"site": data.get("site"), "name": data.get("name"), "since": data.get("pairedAt")}
+ out = {"state": self.state, "message": self.message, "paused": bool(data.get("paused")), "jobs": list(self.recent)[::-1]}
+ if data.get("token") and not data.get("revokePending"):
+ out["paired"] = {"site": data.get("site"), "name": data.get("name"), "account": data.get("account"), "since": data.get("pairedAt")}
+ if data.get("revokePending"):
+ out["revokePending"] = data.get("site")
if self.pairing and self.state == "pairing":
out["pairing"] = {k: self.pairing[k] for k in ("code", "url", "expiresAt", "site")}
return out
@@ -81,11 +130,19 @@ class Agent:
if message:
log.info("[Fuobe Connect] %s", message)
+ def set_paused(self, paused: bool) -> dict:
+ self.store.update(paused=True if paused else None)
+ if self.store.load().get("token"):
+ self._set("paused" if paused else "connected", "Fuobe jobs are paused on this computer." if paused else "Your Fuobe jobs run on this ComfyUI again.")
+ return self.status()
+
# ------------------------------------------------------------------
# Pairing
- async def start_pairing(self, site: str | None = None) -> dict:
+ async def start_pairing(self, site: str | None = None, name: str | None = None) -> dict:
base = site_base(site or self.default_site)
+ if self.store.load().get("revokePending"):
+ raise RuntimeError("This ComfyUI is still telling the studio it disconnected. Try again in a minute.")
if self._pair_task and not self._pair_task.done():
self._pair_task.cancel()
comfy = Comfy(self._session, self.comfy_base)
@@ -96,27 +153,38 @@ class Agent:
facts = {k: v for k, v in {"device": dev.get("name"), "vramBytes": dev.get("vram_total"), "version": (stats.get("system") or {}).get("comfyui_version")}.items() if v}
except Exception:
pass
- a = await Site(self._session, base).pair_start(socket.gethostname()[:48] or "ComfyUI", facts)
+ a = await Site(self._session, base).pair_start(computer_name(name), facts)
if a.status != 200 or not a.body.get("code"):
- raise RuntimeError(a.body.get("error") or f"The studio answered HTTP {a.status}")
- self.pairing = {**a.body, "site": base}
- self._set("pairing", f"To connect this ComfyUI, open {a.body['url']} and approve the code {a.body['code']}.")
- self._pair_task = asyncio.ensure_future(self._poll(base, a.body["id"], a.body["secret"], a.body.get("pollMs") or 2000, a.body.get("expiresAt")))
+ raise RuntimeError(str(a.body.get("error") or f"The studio answered HTTP {a.status}")[:200])
+ code, pair_id, secret = a.body.get("code"), a.body.get("id"), a.body.get("secret")
+ if not (isinstance(code, str) and CODE.match(code) and isinstance(pair_id, str) and len(pair_id) <= 128 and isinstance(secret, str) and len(secret) <= 256):
+ raise RuntimeError("The studio's answer wasn't a pairing code")
+ url = pairing_link(a.body.get("url"), base)
+ poll_ms = a.body.get("pollMs") if isinstance(a.body.get("pollMs"), int) else 2000
+ expires = a.body.get("expiresAt") if isinstance(a.body.get("expiresAt"), int) else None
+ self.pairing = {"code": code, "url": url, "expiresAt": expires, "site": base}
+ self._set("pairing", f"To connect this ComfyUI, open {url} and approve the code {code}.")
+ self._pair_task = asyncio.ensure_future(self._poll(base, pair_id, secret, min(max(poll_ms, 1000), 30000), expires))
return self.status()
async def _poll(self, base: str, pair_id: str, secret: str, poll_ms: int, expires_at: int | None):
site = Site(self._session, base)
until = time.time() + 11 * 60
while time.time() < until:
- await asyncio.sleep(max(1.0, poll_ms / 1000))
+ await asyncio.sleep(poll_ms / 1000)
try:
a = await site.pair_poll(pair_id, secret)
except Exception:
continue
- if a.status == 200 and a.body.get("state") == "approved" and a.body.get("token"):
- self.store.update(site=base, token=a.body["token"], name=a.body.get("name"), workerId=a.body.get("workerId"), pairedAt=int(time.time() * 1000))
+ token = a.body.get("token")
+ if a.status == 200 and a.body.get("state") == "approved" and isinstance(token, str) and 16 <= len(token) <= 256:
+ account = a.body.get("account") if isinstance(a.body.get("account"), str) else None
+ name = a.body.get("name") if isinstance(a.body.get("name"), str) else None
+ worker = a.body.get("workerId") if isinstance(a.body.get("workerId"), str) else None
+ self.store.update(site=base, token=token, name=(name or "")[:48] or None, account=(account or "")[:80] or None, workerId=(worker or "")[:64] or None, pairedAt=int(time.time() * 1000), paused=None)
self.pairing = None
- self._set("connected", f"Connected to {base}. Your Fuobe jobs now run on this ComfyUI.")
+ who = f" as {account[:80]}" if account else ""
+ self._set("connected", f"Connected to {base}{who}. Your Fuobe jobs now run on this ComfyUI.")
self._start_runner()
return
if a.status == 404 or a.body.get("state") == "gone":
@@ -131,20 +199,51 @@ class Agent:
if self.state == "pairing":
self._set("unpaired", None)
+ async def _revoke(self, site: str, token: str) -> bool:
+ """Tell the studio to revoke the token. True when it is gone there (revoked now, or already unknown)."""
+ try:
+ a = await Site(self._session, site, token).call("POST", "/api/gpu/computer/unpair", {}, timeout=10)
+ except Exception:
+ return False
+ return a.status in (200, 401, 404)
+
async def unpair(self) -> dict:
- """Forget the token here, and tell the studio to forget it too (best effort)."""
+ """Stop running jobs, tell the studio to revoke the token, and forget it here once it did. If the studio can't be
+ reached, the token is kept (unused) and Fuobe Connect tries again every minute."""
data = self.store.load()
if self._runner_task and not self._runner_task.done():
self._runner_task.cancel()
- self.store.update(token=None, workerId=None, pairedAt=None)
- self._set("unpaired", "Disconnected from Fuobe.")
- if data.get("token") and data.get("site"):
- try:
- await Site(self._session, data["site"], data["token"]).call("POST", "/api/gpu/computer/unpair", {}, timeout=10)
- except Exception:
- pass
+ token, site = data.get("token"), data.get("site")
+ if not token or not site:
+ self.store.update(token=None, workerId=None, pairedAt=None, account=None, revokePending=None)
+ self._set("unpaired", None)
+ return self.status()
+ if await self._revoke(site, token):
+ self.store.update(token=None, workerId=None, pairedAt=None, account=None, revokePending=None)
+ self._set("unpaired", "Disconnected from Fuobe.")
+ else:
+ self.store.update(revokePending=True)
+ self._set("unpaired", "Stopped here. Fuobe couldn't be reached to forget this computer: Fuobe Connect keeps trying. You can also remove it in Fuobe's settings.")
+ self._start_revoke()
return self.status()
+ def _start_revoke(self):
+ if self._revoke_task and not self._revoke_task.done():
+ return
+ self._revoke_task = asyncio.ensure_future(self._revoke_loop())
+
+ async def _revoke_loop(self):
+ while True:
+ data = self.store.load()
+ if not data.get("revokePending") or not data.get("token") or not data.get("site"):
+ self.store.update(revokePending=None)
+ return
+ if await self._revoke(data["site"], data["token"]):
+ self.store.update(token=None, workerId=None, pairedAt=None, account=None, revokePending=None)
+ self._set("unpaired", "Disconnected from Fuobe.")
+ return
+ await asyncio.sleep(REVOKE_RETRY_S)
+
# ------------------------------------------------------------------
# Running jobs
@@ -158,15 +257,28 @@ class Agent:
while True:
data = self.store.load()
token, site = data.get("token"), data.get("site")
- if not token or not site:
+ if not token or not site or data.get("revokePending"):
return
device = f"connect-{(data.get('workerId') or 'here')}"[:64]
- runner = Runner(Site(self._session, site, token), Comfy(self._session, self.comfy_base), device, self.port, on_state=self._set)
+ runner = Runner(
+ Site(self._session, site, token),
+ Comfy(self._session, self.comfy_base),
+ device,
+ self.port,
+ on_state=self._set,
+ nodes=self.nodes,
+ own=self.own,
+ prefixes=self.prefixes,
+ input_dir=self.input_dir,
+ paused=self.paused,
+ on_job=self.recent.append,
+ loras=os.environ.get("FUOBE_CONNECT_LORAS", "1") != "0",
+ )
try:
await runner.run_forever()
backoff = 5
except Unpaired:
- self.store.update(token=None, workerId=None, pairedAt=None)
+ self.store.update(token=None, workerId=None, pairedAt=None, account=None)
self._set("unpaired", "This ComfyUI was disconnected from Fuobe. Press Connect to Fuobe to pair it again.")
return
except asyncio.CancelledError:
diff --git a/integrations/fuobe-connect/fuobe_connect/allowed_nodes.json b/integrations/fuobe-connect/fuobe_connect/allowed_nodes.json
new file mode 100644
index 00000000..a1a6276d
--- /dev/null
+++ b/integrations/fuobe-connect/fuobe_connect/allowed_nodes.json
@@ -0,0 +1,462 @@
+{
+ "nodes": [
+ "AILab_FeyNoBg",
+ "AILab_Qwen3ASRSubtitle",
+ "AILab_Qwen3TTSVoiceClone_Advanced",
+ "AILab_Qwen3TTSVoiceDesign_Advanced",
+ "AILab_VRMBG",
+ "AUSBOSS_NODES_CropForInpaint",
+ "AUSBOSS_NODES_ImageCropRotatePad",
+ "AUSBOSS_NODES_MaskByTouch",
+ "AUSBOSS_NODES_StitchInpaint",
+ "Add Subtitles To Frames",
+ "Apply Whisper",
+ "ApplyTextureToMesh",
+ "AuKGenerateEdit",
+ "AuKModelLoader",
+ "AudioAdjustVolume",
+ "AudioConcat",
+ "AudioEncoderEncode",
+ "AudioEncoderLoader",
+ "AudioMerge",
+ "BakeAmbientOcclusion",
+ "BakeNormalMapFromMesh",
+ "BakeTextureFromVoxel",
+ "BasicGuider",
+ "BasicScheduler",
+ "BatchImagesNode",
+ "BerniniConditioning",
+ "BlockSparseAttention",
+ "CFGGuider",
+ "CFGNorm",
+ "CFGOverride",
+ "CLIPLoader",
+ "CLIPTextEncode",
+ "CLIPTextEncodeFlux",
+ "CLIPVisionEncode",
+ "CLIPVisionLoader",
+ "Canny",
+ "CheckpointLoaderSimple",
+ "ClothesSegment",
+ "ColorTransfer",
+ "ComfyMathExpression",
+ "ComfyNumberConvert",
+ "ComfySwitchNode",
+ "ConcatenateVideo",
+ "ConditioningZeroOut",
+ "CorridorKey2",
+ "CreateCameraInfo",
+ "CreateList",
+ "CreateVideo",
+ "CropFuobeLive",
+ "CropMask",
+ "CustomCombo",
+ "DA3Inference",
+ "DA3Render",
+ "DBSLoader",
+ "DBSSeparate",
+ "DecimateMesh",
+ "DifferentialDiffusion",
+ "DownloadAndLoadWav2VecModel",
+ "DualCLIPLoader",
+ "DualModelGuider",
+ "EmptyAceStep1.5LatentAudio",
+ "EmptyAudio",
+ "EmptyFlux2LatentImage",
+ "EmptyHunyuanLatentVideo",
+ "EmptyHunyuanVideo15Latent",
+ "EmptyImage",
+ "EmptyLTXVLatentVideo",
+ "EmptyLatentAudio",
+ "EmptyLatentHunyuan3Dv2",
+ "EmptyLatentImage",
+ "EmptyMiniMaxMusic3LatentAudio",
+ "EmptyQwenImageLayeredLatentImage",
+ "EmptySD3LatentImage",
+ "EmptyTrellis2LatentStructure",
+ "EmptyYuE2LatentAudio",
+ "EndLoop",
+ "FL_ChatterboxDialogTTS",
+ "FL_ChatterboxMultilingualTTS",
+ "FL_ChatterboxVC",
+ "FeatherMask",
+ "File3DToSplat",
+ "Flux2Scheduler",
+ "FluxGuidance",
+ "FluxKontextImageScale",
+ "FluxKontextMultiReferenceLatentMethod",
+ "FrameInterpolate",
+ "FrameInterpolationModelLoader",
+ "GetImageRangeFromBatch",
+ "GetImageSize",
+ "GetImageSizeAndCount",
+ "GetItemFromList",
+ "GetMeshInfo",
+ "GetVideoComponents",
+ "GrowMask",
+ "GrowMaskWithBlur",
+ "H3AdaLNLoRAFix",
+ "H3AdvancedSwapPlan",
+ "H3CharacterSwapAssemble",
+ "H3CharacterSwapController",
+ "H3CharacterSwapExpandMask",
+ "H3CharacterSwapModels",
+ "H3CharacterSwapPrepareVideo",
+ "H3CharacterSwapRecoverMasks",
+ "H3CharacterSwapSelectSubject",
+ "H3CharacterSwapSettings",
+ "H3CharacterSwapShot",
+ "H3CharacterSwapWindowPlan",
+ "H3ClipShots",
+ "H3FaceChunks",
+ "H3FaceJoin",
+ "H3FaceMaskSAM",
+ "H3FaceStitch",
+ "H3FaceTrackCrop",
+ "H3FillShots",
+ "H3GreyMannequins",
+ "H3ObjectSwapPlan",
+ "H3PaintedEditArea",
+ "H3PeopleMask",
+ "H3RelayAppendWindow",
+ "H3RelayApplyEditMask",
+ "H3RelayApplyHistory",
+ "H3RelayExpandMask",
+ "H3RelayFinishWindows",
+ "H3RelayPrepareSource",
+ "H3RelayRecoverMasks",
+ "H3RelayReviewWindows",
+ "H3RelaySamplingMemory",
+ "H3RelaySelectMask",
+ "H3RelayTextMemory",
+ "H3RelayWindowInputs",
+ "H3RelayWindowPlan",
+ "H3RoleMask",
+ "H3SLAAttention",
+ "H3SoundtrackOrSilence",
+ "H3SourceSlice",
+ "H3SubjectPrompt",
+ "H3TrackCrops",
+ "H3TrackRoles",
+ "Hi3DLoadMesh",
+ "Hi3DModelLoader",
+ "Hi3DRefine",
+ "Hunyuan3Dv2Conditioning",
+ "HunyuanDependenciesLoader",
+ "HunyuanFoleySampler",
+ "HunyuanModelLoader",
+ "HunyuanVideo15ImageToVideo",
+ "INTConstant",
+ "Ideogram4Scheduler",
+ "IdolCamera",
+ "IdolPreprocessImage",
+ "IdolPruneSplat",
+ "ImageBatch",
+ "ImageBatchExtendWithOverlap",
+ "ImageBlur",
+ "ImageCompositeMasked",
+ "ImageCrop",
+ "ImageCropToMask",
+ "ImageDetailContrast",
+ "ImageFromBatch",
+ "ImageGridtoBatch",
+ "ImageInvert",
+ "ImageOnlyCheckpointLoader",
+ "ImagePadForOutpaint",
+ "ImageResizeKJv2",
+ "ImageSDRToHDR",
+ "ImageScale",
+ "ImageScaleBy",
+ "ImageScaleToMaxDimension",
+ "ImageScaleToTotalPixels",
+ "ImageStitch",
+ "ImageToMask",
+ "ImageUpscaleWithModel",
+ "IndexTTS2Simple",
+ "InpaintModelConditioning",
+ "InvertMask",
+ "JoinImageWithAlpha",
+ "JsonExtractString",
+ "KSampler",
+ "KSamplerAdvanced",
+ "KSamplerSelect",
+ "Kandinsky6AudioVAEDecode",
+ "Kandinsky6AudioVAELoader",
+ "Kandinsky6BeautifyPrompt",
+ "Kandinsky6EmptyLatent",
+ "Kandinsky6ImageToVideoAudio",
+ "Kandinsky6LatentUpscalerLoader",
+ "Kandinsky6RemoveReferenceLatent",
+ "Kandinsky6SRVAELoader",
+ "Kandinsky6Sampler",
+ "Kandinsky6TextEncode",
+ "Kandinsky6VSRUpscale",
+ "Krea2EditGroundedEncode",
+ "Krea2EditModelPatch",
+ "Krea2OstrisEditModelPatch",
+ "LTXAVTextEncoderLoader",
+ "LTXAddVideoICLoRAGuide",
+ "LTXICLoRALoaderModelOnly",
+ "LTXVAddGuide",
+ "LTXVAudioVAEDecode",
+ "LTXVAudioVAELoader",
+ "LTXVConcatAVLatent",
+ "LTXVConditioning",
+ "LTXVCropGuides",
+ "LTXVDualCFGGuider",
+ "LTXVEmptyLatentAudio",
+ "LTXVImgToVideoInplace",
+ "LTXVLatentUpsampler",
+ "LTXVPreprocess",
+ "LTXVScheduler",
+ "LTXVSeparateAVLatent",
+ "LTXVTiledFusionSampler",
+ "LatentBatchSeedBehavior",
+ "LatentConcat",
+ "LatentCut",
+ "LatentCutToBatch",
+ "LatentSyncNode",
+ "LatentUpscaleModelLoader",
+ "Load3D",
+ "LoadAudio",
+ "LoadBackgroundRemovalModel",
+ "LoadDA3Model",
+ "LoadImage",
+ "LoadImageFuobeLive",
+ "LoadImageMask",
+ "LoadMoGeModel",
+ "LoadVideo",
+ "LoadVideoDepthAnythingModel",
+ "LoraLoader",
+ "LoraLoaderModelOnly",
+ "MMAudioFeatureUtilsLoader",
+ "MMAudioModelLoader",
+ "MMAudioSampler",
+ "ManualSigmas",
+ "MaskComposite",
+ "MaskToImage",
+ "MelBandRoFormerModelLoader",
+ "MelBandRoFormerSampler",
+ "MeshSmoothNormals",
+ "MeshToFile3D",
+ "Metric3D-NormalMapPreprocessor",
+ "MiniMaxH3AddGuide",
+ "MiniMaxH3ChainAssemble",
+ "MiniMaxH3ChainContext",
+ "MiniMaxH3ChainCurrent",
+ "MiniMaxH3ChainLoopEnd",
+ "MiniMaxH3ChainLoopStart",
+ "MiniMaxH3ChainPlanModern",
+ "MiniMaxH3ChainReview",
+ "MiniMaxH3ChainSegmentSave",
+ "MiniMaxH3ContexLoopMaskSlice",
+ "MiniMaxH3ContexMaskedTarget",
+ "MiniMaxH3FantasticVideoEditLatent",
+ "MiniMaxH3GenerationProfile",
+ "MiniMaxH3ImageToVideo",
+ "MiniMaxH3LoopTrim",
+ "MiniMaxH3ReferenceToVideo",
+ "MiniMaxH3SigmaShift",
+ "MiniMaxH3SourceTimeline",
+ "MiniMaxH3TurboLoRA",
+ "MiniMaxH3TurboSampler",
+ "MiniMaxMusic3TextEncode",
+ "MoGeGeometryToFOV",
+ "MoGeInference",
+ "MoGePointMapToMesh",
+ "MoGeRender",
+ "ModelAttentionBackend",
+ "ModelPatchLoader",
+ "ModelSamplingAuraFlow",
+ "ModelSamplingFlux",
+ "ModelSamplingSD3",
+ "MultiTalkModelLoader",
+ "MultiTalkWav2VecEmbeds",
+ "NomasCameraPath",
+ "NomasWorldContinue",
+ "NomasWorldGenerate",
+ "NomasWorldPrompt",
+ "OpenH3LoadRefinedLatent",
+ "OpenH3RegenFastVAEDecode",
+ "OpenH3RegenFinish",
+ "OpenH3RegenLora",
+ "OpenH3RegenPrepareDraft",
+ "OpenH3RegenRefineLatent",
+ "OpenH3RegenSigmas",
+ "OpenH3RegenUpscale",
+ "OpenH3SaveRefinedLatent",
+ "OpticalFlowLoader",
+ "Orion4D_FXMax_DCTLToneMapper",
+ "PasteBackFuobeLive",
+ "Pixal3DConditioning",
+ "Pixal3DMultiViewConditioning",
+ "PreviewAny",
+ "PrimitiveBoolean",
+ "PrimitiveFloat",
+ "PrimitiveInt",
+ "PrimitiveStringMultiline",
+ "QWMComposite",
+ "QWMDetect",
+ "QWMFinal",
+ "QWMPrepare",
+ "QWMRefineMask",
+ "QWMResidualDetect",
+ "QuadrupleCLIPLoader",
+ "Qwen21EncodeFuobeLive",
+ "Qwen21ReferenceFuobeLive",
+ "QwenImage21Cache",
+ "QwenImageDiffsynthControlnet",
+ "REUSEEnhance",
+ "REUSELoader",
+ "RIFE VFI",
+ "RMBG",
+ "RTXTrueHDR",
+ "RTXVideoFrameGeneration",
+ "RTXVideoSuperResolution",
+ "RandomNoise",
+ "ReActorFaceSwap",
+ "RebatchImages",
+ "ReferenceLatent",
+ "ReferenceMultiLatent",
+ "RegexMatch",
+ "RegexReplace",
+ "RemeshMesh",
+ "RemoveBackground",
+ "RenderMesh",
+ "RenderSplat",
+ "RepeatImageBatch",
+ "RescaleCFG",
+ "ResizeImageMaskNode",
+ "ResizeImagesByLongerEdge",
+ "RotateMesh",
+ "SAM3_Detect",
+ "SAM3_TrackToMask",
+ "SAM3_VideoTrack",
+ "SAMLoader",
+ "SamplerCustom",
+ "SamplerCustomAdvanced",
+ "SamplerEulerAncestral",
+ "Save3DAdvanced",
+ "SaveAnimatedWEBP",
+ "SaveAudio",
+ "SaveAudioAdvanced",
+ "SaveAudioMP3",
+ "SaveGLB",
+ "SaveImage",
+ "SaveImageAdvanced",
+ "SaveImageFuobeLive",
+ "SaveSVGNode",
+ "SaveText",
+ "SaveVideo",
+ "SaveWEBM",
+ "SeedVR2Conditioning",
+ "SeedVR2PostProcessing",
+ "SeedVR2Preprocess",
+ "SelectCLIPDevice",
+ "SetLatentNoiseMask",
+ "SheetSage2AudioToABC",
+ "SkipLayerGuidanceDiTSimple",
+ "SolarRendererConditioning",
+ "SolarRendererLoraLoader",
+ "SolarRendererModel",
+ "SolarRendererSigmas",
+ "SolidMask",
+ "SplatToFile3D",
+ "SplatToMesh",
+ "SplitAudioChannels",
+ "SplitImageWithAlpha",
+ "SplitSigmas",
+ "StartLoop",
+ "StringConcatenate",
+ "StringFormat",
+ "StringReplace",
+ "TS_ImageToSVGStringColor_Vtracer",
+ "TS_SVGStringToSVGBytesIO",
+ "TextEncodeAceStepAudio1.5",
+ "TextEncodeFibo2",
+ "TextEncodeKrea2OstrisEdit",
+ "TextEncodeQwenImage21",
+ "TextEncodeQwenImageEditPlus",
+ "TextGenerate",
+ "TextOverlay",
+ "ThinkSoundFeatureUtilsLoader",
+ "ThinkSoundModelLoader",
+ "ThinkSoundSampler",
+ "ThresholdMask",
+ "Trellis2Conditioning",
+ "Trellis2ShapeStage",
+ "Trellis2TextureStage",
+ "Trellis2UpsampleStage",
+ "TrimAudioDuration",
+ "TrimVideoLatent",
+ "TripoSplatConditioning",
+ "TripoSplatPreprocessImage",
+ "UNETLoader",
+ "USOStyleReference",
+ "UnwrapMesh",
+ "UpscaleModelLoader",
+ "VAEDecode",
+ "VAEDecodeAudio",
+ "VAEDecodeAudioTiled",
+ "VAEDecodeHunyuan3D",
+ "VAEDecodeTiled",
+ "VAEDecodeTripoSplat",
+ "VAEEncode",
+ "VAEEncodeTiled",
+ "VAELoader",
+ "VHS_BatchManager",
+ "VHS_LoadAudioUpload",
+ "VHS_LoadVideo",
+ "VHS_SelectEveryNthImage",
+ "VHS_VideoCombine",
+ "VHS_VideoInfo",
+ "VHS_VideoInfoLoaded",
+ "VOIDInpaintConditioning",
+ "VOIDSampler",
+ "VOIDWarpedNoise",
+ "VOIDWarpedNoiseSource",
+ "VRAM_Debug",
+ "VaeDecodeShapeTrellis",
+ "VaeDecodeStructureTrellis2",
+ "VaeDecodeTextureTrellis",
+ "Video Slice",
+ "VideoDepthAnythingOutput",
+ "VideoDepthAnythingProcess",
+ "VideoLengthAdjuster",
+ "ViggleTurboLora",
+ "ViggleTurboSigmas",
+ "VoxCPM2_Clone",
+ "VoxCPM2_TTS",
+ "VoxelToMesh",
+ "Wan22FunControlToVideo",
+ "Wan22ImageToVideoLatent",
+ "WanAnimate2Cache",
+ "WanAnimate2ToVideo",
+ "WanCameraEmbedding",
+ "WanCameraImageToVideo",
+ "WanFirstLastFrameToVideo",
+ "WanImageToVideo",
+ "WanInfiniteTalkToVideo",
+ "WanMoveTrackToVideo",
+ "WanMoveTracksFromCoords",
+ "WanSoundImageToVideo",
+ "WanSoundImageToVideoExtend",
+ "WanUni3CControlnetApply",
+ "WanVaceToVideo",
+ "WanVideoBlockSwap",
+ "WanVideoClipVisionEncode",
+ "WanVideoDecode",
+ "WanVideoEncode",
+ "WanVideoImageToVideoMultiTalk",
+ "WanVideoLoraSelect",
+ "WanVideoModelLoader",
+ "WanVideoPassImagesFromSamples",
+ "WanVideoSampler",
+ "WanVideoTextEncodeCached",
+ "WanVideoVAELoader",
+ "YuE2GenerateABC",
+ "YuE2GenerateMusic",
+ "ZenImage21AdapterLoader",
+ "ZenImage21TextEncode"
+ ]
+}
diff --git a/integrations/fuobe-connect/fuobe_connect/graph.py b/integrations/fuobe-connect/fuobe_connect/graph.py
index c2f0fc9b..1b12a104 100644
--- a/integrations/fuobe-connect/fuobe_connect/graph.py
+++ b/integrations/fuobe-connect/fuobe_connect/graph.py
@@ -1,22 +1,47 @@
-"""Checks Fuobe Connect makes on its own, whatever the studio sends (the same ones the Fuobe tab makes):
+"""The checks Fuobe Connect makes itself, on this computer, whatever a studio sends.
-- a job's graph may read only the input files that job sent (no file of yours);
-- a result is downloaded only when this job's own prompt saved it.
+A graph from a studio (a trusted page in direct mode, or the paired studio in pairing mode) runs only when:
+
+- every node type is on the list that ships inside this pack (allowed_nodes.json: the nodes Fuobe's own workflows use),
+ plus the types you list yourself in fuobe-connect-nodes.json in ComfyUI's user folder. A studio can never add to it;
+- no text input names a path or an address: an absolute path, a drive letter, a network share, a ".." step, a home
+ folder, a URL, or one of ComfyUI's folder tags ("name [output]", "name [temp]");
+- 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 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.
Pure, so the tests run it alone.
"""
from __future__ import annotations
+import json
+import os
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}$")
-UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
+# The file types a run sends: pictures, clips, sound, 3D scenes, and plain data. Never a page, a script or a program.
+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()
+)
+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")
+CLIENT_ID = re.compile(r"^fuobe-[A-Za-z0-9_-]{4,72}\Z")
+# A run's filename prefix: fuobe/<generation id> (src/server/providers/comfyui.ts).
+PREFIX = re.compile(r"^fuobe/[A-Za-z0-9_-]{6,64}\Z")
FILE_LOADERS = {
"LoadImage": ["image"],
"LoadImageMask": ["image"],
"LoadImageOutput": ["image"],
+ "LoadImageFuobeLive": ["image"],
"LoadVideo": ["file"],
"LoadAudio": ["audio"],
"VHS_LoadVideo": ["video"],
@@ -25,13 +50,102 @@ FILE_LOADERS = {
"VHS_LoadAudioUpload": ["audio"],
"VHS_LoadImages": ["directory"],
"VHS_LoadImagesPath": ["directory"],
+ # AusBoss's Crop + Rotate + Pad loads the upload itself.
+ "AUSBOSS_NODES_ImageCropRotatePad": ["image"],
+ # Any Angle's saved 3D view: the scene file, and the picture entries (checked one by one below).
+ "Load3D": ["model_file"],
}
_FILEISH = re.compile(r"image|video|audio|file|path|directory", re.I)
+_PATHLIKE = [
+ re.compile(r"^[A-Za-z]:[\\/]"), # C:\ or C:/
+ re.compile(r"^\\\\"), # \\server\share, \\?\C:\
+ re.compile(r"^/(?!/)[^\s]*/"), # /etc/passwd
+ re.compile(r"^/(?!/)\S+\Z"), # /secret.png
+ re.compile(r"(^|[\\/])\.\.([\\/]|\Z)"), # a ".." step
+ re.compile(r"^~[\\/]"), # ~/
+ re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*://"), # a URL
+ re.compile(r"^file:", re.I),
+ re.compile(r"^blake3:", re.I), # ComfyUI's asset names reach any registered file
+ re.compile(r"\x00"),
+]
+_TAG = re.compile(r" \[(input|output|temp)\]\Z")
+
+
+def staged_name_ok(name) -> bool:
+ """A name Fuobe gives a file it sends: fuobe_<id>.<ext>, with a file type a run sends."""
+ return isinstance(name, str) and bool(INPUT_NAME.match(name)) and name.rsplit(".", 1)[1] in INPUT_EXTS
+
+
+def unsafe_text(v: str) -> bool:
+ """A text input that names a path, an address or a folder tag."""
+ return any(p.search(v) for p in _PATHLIKE)
+
+
+# ---------------------------------------------------------------------------
+# The node list
+
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+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))
+
+
+def own_nodes(user_dir: str | None) -> frozenset:
+ """The node types the person added in ComfyUI's user folder (a list, or {"nodes": [...]}); never from a studio."""
+ if not user_dir:
+ return frozenset()
+ try:
+ with open(os.path.join(user_dir, OWN_NODES_FILE), encoding="utf-8") as f:
+ data = json.load(f)
+ except (OSError, ValueError):
+ return frozenset()
+ items = data.get("nodes") if isinstance(data, dict) else data
+ return frozenset(n for n in items if isinstance(n, str)) if isinstance(items, list) else frozenset()
+
-def graph_problem(graph, staged: list[str]) -> str | None:
- """Every loader names one of this job's own inputs, or a value from another node. Else: what is wrong."""
- if not isinstance(graph, dict):
+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):
+ self.user_dir = user_dir
+ self.shipped = shipped_nodes()
+ self._mtime = None
+ self._own = frozenset()
+
+ def __call__(self) -> frozenset:
+ path = os.path.join(self.user_dir, OWN_NODES_FILE) if self.user_dir else None
+ try:
+ mtime = os.stat(path).st_mtime if path else None
+ except OSError:
+ mtime = None
+ if mtime != self._mtime:
+ self._mtime = mtime
+ self._own = own_nodes(self.user_dir) if mtime is not None else frozenset()
+ return self.shipped | self._own
+
+
+# ---------------------------------------------------------------------------
+# A graph
+
+
+def _staged(v, staged) -> bool:
+ """One of the run's own inputs (optionally tagged " [input]")."""
+ if not isinstance(v, str):
+ return False
+ name = v[: -len(" [input]")] if v.endswith(" [input]") else v
+ return staged_name_ok(name) and (staged is None or name in staged)
+
+
+def graph_problem(graph, staged: list[str] | None) -> str | None:
+ """Every file loader names one of this run's own inputs. `staged`: the run's input names (None: any name Fuobe
+ gives an input, for direct mode, where the pack doesn't know the run). Else: what is wrong."""
+ if not isinstance(graph, dict) or not graph:
return "No graph"
for node_id, node in graph.items():
if not isinstance(node, dict):
@@ -39,22 +153,77 @@ def graph_problem(graph, staged: list[str]) -> str | None:
cls = node.get("class_type") if isinstance(node.get("class_type"), str) else ""
inputs = node.get("inputs") if isinstance(node.get("inputs"), dict) else {}
keys = FILE_LOADERS.get(cls)
+ known = keys is not None
if keys is None:
keys = [k for k in inputs if _FILEISH.search(k)] if re.match(r"^(Load|VHS_Load)", cls) else []
for k in keys:
v = inputs.get(k)
- if v is None or isinstance(v, list):
+ if v is None:
continue
- if not isinstance(v, str) or re.sub(r" \[input\]$", "", v) not in staged:
+ if isinstance(v, list):
+ # The studio names its files as values; a loader fed by another node could be fed any name.
+ if known:
+ return f"Node {node_id} ({cls}) reads a file named by another node"
+ continue
+ if not _staged(v, staged):
+ return f"Node {node_id} ({cls}) reads a file this run didn't send"
+ if cls == "Load3D" and "image" in inputs:
+ pics = inputs["image"]
+ if isinstance(pics, dict):
+ for f, x in pics.items():
+ if f == "camera_info" or x in ("", None):
+ continue
+ if not _staged(x, staged):
+ return f"Node {node_id} ({cls}) reads a file this run didn't send"
+ elif pics not in ("", None):
return f"Node {node_id} ({cls}) reads a file this run didn't send"
return None
+def vet_graph(graph, allowed: frozenset | set, staged: list[str] | 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' for a loader that reads a file this run didn't send."""
+ if not isinstance(graph, dict) or not graph or len(graph) > 5000:
+ return "unsafe-graph"
+ for node in graph.values():
+ if not isinstance(node, dict) or not isinstance(node.get("class_type"), str) or node["class_type"] not in allowed:
+ return "unknown-node"
+ for node in graph.values():
+ inputs = node.get("inputs")
+ if inputs is None:
+ continue
+ if not isinstance(inputs, dict):
+ return "unsafe-graph"
+ for v in inputs.values():
+ for s in _strings(v):
+ if unsafe_text(s) or (_TAG.search(s) and not _staged(s, staged)):
+ return "unsafe-path"
+ if graph_problem(graph, staged):
+ return "unsafe-graph"
+ return None
+
+
+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."""
+ 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)):
+ for x in v:
+ yield from _strings(x, depth + 1)
+
+
+# ---------------------------------------------------------------------------
+# Results
+
+
def files_in(entries: list) -> list[dict]:
out = []
for e in entries or []:
outputs = e.get("outputs") if isinstance(e, dict) else None
- for ui in (outputs or {}).values():
+ for ui in (outputs or {}).values() if isinstance(outputs, dict) else []:
if not isinstance(ui, dict):
continue
for v in ui.values():
@@ -75,24 +244,123 @@ def safe_wanted(w: dict) -> bool:
"""A wanted file the server named: a plain file name in output or temp, no way out of the folder."""
name = w.get("filename")
sub = w.get("subfolder") or ""
- if not isinstance(name, str) or not name or re.search(r"[\\/]", name) or name in (".", ".."):
+ if not isinstance(name, str) or not name or re.search(r"[\\/]", name) or name in (".", "..") or _TAG.search(name) or unsafe_text(name):
return False
- if not isinstance(sub, str) or any(p == ".." for p in re.split(r"[\\/]", sub)):
+ if not isinstance(sub, str) or any(p == ".." for p in re.split(r"[\\/]", sub)) or sub.startswith(("/", "\\")) or re.match(r"^[A-Za-z]:", sub):
return False
return w.get("type") in ("output", "temp")
def has_prefix(prompt, prefix: str) -> bool:
- if not isinstance(prompt, dict):
+ if not isinstance(prompt, dict) or not isinstance(prefix, str) or not prefix:
return False
return any(isinstance(n, dict) and isinstance(n.get("inputs"), dict) and n["inputs"].get("filename_prefix") == prefix for n in prompt.values())
+def fuobe_prefixed(prompt) -> bool:
+ """A prompt that saves under Fuobe's own prefix (fuobe/<generation id>): one of Fuobe's runs."""
+ if not isinstance(prompt, dict):
+ return False
+ return any(
+ isinstance(n, dict) and isinstance(n.get("inputs"), dict) and isinstance(n["inputs"].get("filename_prefix"), str) and PREFIX.match(n["inputs"]["filename_prefix"])
+ for n in prompt.values()
+ )
+
+
+def run_prefix(prefix, graph) -> str | None:
+ """The run's prefix when it is Fuobe's form and this run's own graph saves under it; else None."""
+ if isinstance(prefix, str) and PREFIX.match(prefix) and has_prefix(graph, prefix):
+ return prefix
+ return None
+
+
+_ABS_PATH = re.compile(r"(?:[A-Za-z]:[\\/]|\\\\|(?<![\w.~-])/(?=[^\s/'\"]+/))[^\s'\"<>|]*")
+_LIST = re.compile(r"\s*not in \[.*", re.S)
+
+
+def scrub(text, limit: int = 300):
+ """ComfyUI's words without folders on this computer or lists of your files, cut short."""
+ if not isinstance(text, str):
+ return None
+ return _ABS_PATH.sub("<path>", _LIST.sub(" not in the list", text[: limit * 4]))[:limit]
+
+
+def _slim_status(status):
+ if not isinstance(status, dict):
+ return status
+ out = {k: status.get(k) for k in ("status_str", "completed") if k in status}
+ msgs = []
+ for m in status.get("messages") or []:
+ if not (isinstance(m, list) and len(m) == 2 and isinstance(m[0], str) and isinstance(m[1], dict)):
+ continue
+ d = m[1]
+ keep = {k: d[k] for k in ("prompt_id", "node_id", "node_type", "timestamp") if k in d}
+ if "exception_message" in d:
+ keep["exception_message"] = scrub(d.get("exception_message"), 600)
+ if "exception_type" in d:
+ keep["exception_type"] = scrub(d.get("exception_type"), 120)
+ msgs.append([m[0], keep])
+ out["messages"] = msgs[:50]
+ return out
+
+
def slim(e: dict) -> dict:
- """A history entry as the studio needs it: its status and outputs, not the whole graph again."""
+ """A history entry as the studio needs it: its status and outputs, not the whole graph again, and no traceback."""
p = e.get("prompt")
return {
"prompt": [p[0], p[1]] if isinstance(p, list) and len(p) >= 2 else None,
- "status": e.get("status"),
+ "status": _slim_status(e.get("status")),
"outputs": e.get("outputs"),
}
+
+
+def refusal(answer, sent: set | None = None) -> dict:
+ """ComfyUI's 400 answer to a prompt, as the studio needs it to say what was missing: the error types, the node
+ classes, and the values the graph itself sent, without lists of your files or folders on this computer."""
+ out: dict = {}
+ if not isinstance(answer, dict):
+ return out
+ err = answer.get("error")
+ if isinstance(err, dict):
+ e = {k: scrub(err.get(k), n) for k, n in (("type", 80), ("message", 300)) if isinstance(err.get(k), str)}
+ info = err.get("extra_info")
+ if isinstance(info, dict) and isinstance(info.get("class_type"), str):
+ e["extra_info"] = {"class_type": info["class_type"][:128]}
+ out["error"] = e
+ nodes = answer.get("node_errors")
+ if isinstance(nodes, dict):
+ slim_nodes = {}
+ for nid, n in list(nodes.items())[:24]:
+ if not isinstance(n, dict):
+ continue
+ errors = []
+ for x in (n.get("errors") or [])[:6]:
+ if not isinstance(x, dict):
+ continue
+ item = {k: scrub(x.get(k), 300) for k in ("type", "message", "details") if isinstance(x.get(k), str)}
+ info = x.get("extra_info") if isinstance(x.get("extra_info"), dict) else {}
+ extra = {}
+ if isinstance(info.get("input_name"), str):
+ extra["input_name"] = info["input_name"][:64]
+ got = info.get("received_value")
+ if isinstance(got, str) and len(got) <= 256 and (sent is None or got in sent):
+ extra["received_value"] = got
+ if extra:
+ item["extra_info"] = extra
+ errors.append(item)
+ slim_node = {"errors": errors}
+ if isinstance(n.get("class_type"), str):
+ slim_node["class_type"] = n["class_type"][:128]
+ slim_nodes[str(nid)[:32]] = slim_node
+ out["node_errors"] = slim_nodes
+ return out
+
+
+def graph_strings(graph) -> set:
+ """Every text a graph's nodes take."""
+ out = set()
+ for node in graph.values() if isinstance(graph, dict) else []:
+ if isinstance(node, dict) and isinstance(node.get("inputs"), dict):
+ for v in node["inputs"].values():
+ out.update(_strings(v))
+ return out
diff --git a/integrations/fuobe-connect/fuobe_connect/middleware.py b/integrations/fuobe-connect/fuobe_connect/middleware.py
index 10fba8b2..7179b7ca 100644
--- a/integrations/fuobe-connect/fuobe_connect/middleware.py
+++ b/integrations/fuobe-connect/fuobe_connect/middleware.py
@@ -1,12 +1,18 @@
"""The middleware that lets a trusted Fuobe studio use this ComfyUI from the browser, with no start flag.
ComfyUI turns away every request from another website (its origin check). This middleware runs before that check and
-handles exactly one case: a request from a trusted studio (an exact origin) for a path a Fuobe run needs
-(origins.allowed). For that request it:
+handles exactly one case: a request from a trusted studio (an exact origin) to this ComfyUI on this computer (the Host
+is 127.0.0.1, ::1 or localhost) for a path a Fuobe run needs (origins.allowed). For that request it:
- answers the browser's CORS preflight, and Chrome's Private Network Access preflight, for that origin only;
+- 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;
- 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.
+ 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.
@@ -19,12 +25,15 @@ Pure aiohttp: the tests load it with ComfyUI's own middleware and nothing else.
from __future__ import annotations
+import json
import logging
+from collections import OrderedDict
from typing import Callable, Iterable
from aiohttp import web
-from .origins import allowed, normalise, same_host
+from .graph import CLIENT_ID, FILE_LOADERS, UUID, fuobe_prefixed, files_in, staged_name_ok, vet_graph
+from .origins import allowed, host_name, is_loopback, normalise, same_host
ALLOW_METHODS = "GET, POST, OPTIONS"
# Set on a trusted studio's request as it goes on (and dropped from every incoming one), so Fuobe Connect's own status
@@ -79,19 +88,253 @@ async def _pass(request: web.Request, handler):
return await handler(request)
-def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | None = None):
+def _bare(path: str) -> str:
+ return path[4:] if path.startswith("/api/") else path
+
+
+def _refuse(message: str, status: int = 403) -> web.Response:
+ return web.json_response({"error": {"type": "fuobe_connect_refused", "message": message}}, status=status)
+
+
+# What a refused graph means, in words the studio shows the person.
+REASONS = {
+ "unknown-node": "Fuobe Connect on this computer doesn't run one of this workflow's node types. Update Fuobe Connect in ComfyUI-Manager, then retry.",
+ "unsafe-path": "Fuobe Connect refused this workflow: it names a folder, a file path or a web address on this computer.",
+ "unsafe-graph": "Fuobe Connect refused this workflow: it reads a file Fuobe didn't send.",
+}
+
+_PROMPT_KEYS = {"prompt", "prompt_id", "client_id", "extra_data", "front"}
+_UPLOAD_FIELDS = {"image", "type", "subfolder", "overwrite"}
+
+
+class Studios:
+ """What trusted studios did here: the prompts they queued (and a batch's later passes), and the result files their
+ prompts' history showed them. A studio may touch only those. Kept in memory: ComfyUI's queue and history are too."""
+
+ KEEP = 4096
+
+ def __init__(self, nodes: Callable[[], Iterable[str]] | None = None):
+ self.nodes = nodes or (lambda: frozenset())
+ self.prompts: OrderedDict[str, None] = OrderedDict()
+ self.files: OrderedDict[tuple, None] = OrderedDict()
+
+ @staticmethod
+ def _keep(d: OrderedDict, key):
+ d[key] = None
+ d.move_to_end(key)
+ while len(d) > Studios.KEEP:
+ d.popitem(last=False)
+
+ def own(self, pid) -> bool:
+ return isinstance(pid, str) and pid in self.prompts
+
+ def add_prompt(self, pid: str):
+ self._keep(self.prompts, pid)
+
+ def add_files(self, entry):
+ for f in files_in([entry]):
+ self._keep(self.files, (f["filename"], f.get("subfolder") or "", f["type"]))
+
+ def has_file(self, filename: str, subfolder: str, kind: str) -> bool:
+ return (filename, subfolder or "", kind or "output") in self.files
+
+ # ------------------------------------------------------------------
+ # Requests
+
+ async def check(self, request: web.Request) -> web.StreamResponse | None:
+ """None when the request may go on; else the answer instead of ComfyUI's."""
+ p = _bare(request.path)
+ if request.method == "POST":
+ if p == "/upload/image":
+ return await self._upload(request)
+ if p.startswith("/customnode/") or p.startswith("/v2/customnode/"):
+ return None
+ try:
+ body = await request.json()
+ except (ValueError, UnicodeDecodeError):
+ return _refuse("Not JSON", 400)
+ if p == "/prompt":
+ return self._prompt(body)
+ if p in ("/queue", "/history"):
+ ids = body.get("delete") if isinstance(body, dict) and set(body) == {"delete"} else None
+ if not isinstance(ids, list) or not ids or not all(self.own(i) for i in ids):
+ return _refuse("A studio may take off only its own prompts")
+ return None
+ if p == "/interrupt":
+ if not (isinstance(body, dict) and self.own(body.get("prompt_id"))):
+ return _refuse("A studio may stop only its own prompt")
+ return None
+ if p.startswith("/jobs/") and p.endswith("/cancel"):
+ return None if self.own(p.split("/")[2]) else _refuse("A studio may cancel only its own prompts")
+ return _refuse("Not a run's request")
+ if p.startswith("/history/"):
+ return None if self.own(p[9:]) else web.json_response({})
+ if p.startswith("/jobs/"):
+ return None if self.own(p[6:]) else web.json_response({"error": "Job not found"}, status=404)
+ if p == "/view":
+ q = request.query
+ if not self.has_file(q.get("filename", ""), q.get("subfolder", ""), q.get("type", "output")):
+ return _refuse("A studio may download only its own prompts' results")
+ return None
+
+ def _prompt(self, body) -> web.Response | None:
+ if not isinstance(body, dict) or set(body) - _PROMPT_KEYS:
+ return _refuse("Not a run's prompt", 400)
+ pid = body.get("prompt_id")
+ if not isinstance(pid, str) or not UUID.match(pid):
+ return _refuse("A run's prompt has its own id", 400)
+ cid = body.get("client_id")
+ if cid is not None and not (isinstance(cid, str) and CLIENT_ID.match(cid)):
+ return _refuse("Not a Fuobe client id", 400)
+ extra = body.get("extra_data")
+ if extra is not None and not (isinstance(extra, dict) and set(extra) <= {"preview_method"} and isinstance(extra.get("preview_method", ""), str)):
+ 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)
+ if why:
+ _note(f"a trusted studio: its workflow was refused ({why})")
+ return _refuse(REASONS[why], 400)
+ if self.own(pid):
+ return _refuse("That prompt id is taken", 400)
+ self.add_prompt(pid)
+ return None
+
+ async def _upload(self, request: web.Request) -> web.Response | None:
+ try:
+ form = await request.post()
+ except Exception:
+ return _refuse("Not an upload", 400)
+ if set(form.keys()) - _UPLOAD_FIELDS or len(form.getall("image", [])) != 1:
+ return _refuse("Not a run's upload")
+ image = form.get("image")
+ name = getattr(image, "filename", None)
+ if not staged_name_ok(name):
+ return _refuse("A studio may upload only a run's own inputs (fuobe_<id> pictures, clips and sound)")
+ if form.get("type", "input") not in ("", "input") or form.get("subfolder", "") != "":
+ return _refuse("A studio may upload only into the input folder")
+ return None
+
+ # ------------------------------------------------------------------
+ # Answers
+
+ async def answer(self, request: web.Request, response: web.StreamResponse) -> web.StreamResponse:
+ """The answer as a studio may see it."""
+ if not isinstance(response, web.Response) or response.status != 200:
+ return response
+ 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.
+ try:
+ pid = json.loads(response.body).get("prompt_id")
+ except Exception:
+ pid = None
+ if isinstance(pid, str) and len(pid) <= 64:
+ self.add_prompt(pid)
+ return response
+ if p == "/queue" or p == "/jobs" or p == "/history" or p.startswith("/history/") or p == "/object_info" or p.startswith("/object_info/"):
+ try:
+ data = json.loads(response.body if isinstance(response.body, (bytes, bytearray)) else response.text)
+ except Exception:
+ return _refuse("Fuobe Connect couldn't read ComfyUI's answer", 502)
+ if p == "/queue":
+ data = self._queue(data)
+ elif p == "/jobs":
+ data = self._jobs(data)
+ elif p.startswith("/history"):
+ data = self._history(data, single=p != "/history")
+ else:
+ data = _hide_inputs(data)
+ return web.json_response(data)
+ return response
+
+ def _history(self, data, single: bool):
+ if not isinstance(data, dict):
+ return {}
+ out = {}
+ for pid, entry in data.items():
+ prompt = entry.get("prompt") if isinstance(entry, dict) else None
+ mine = single or self.own(pid) or (isinstance(prompt, list) and len(prompt) > 2 and fuobe_prefixed(prompt[2]))
+ if mine and isinstance(pid, str):
+ if not single:
+ self.add_prompt(pid)
+ self.add_files(entry)
+ out[pid] = entry
+ return out
+
+ def _queue(self, data):
+ if not isinstance(data, dict):
+ return {}
+ out = {}
+ for k in ("queue_running", "queue_pending"):
+ items = []
+ for r in data.get(k) or []:
+ if not isinstance(r, list) or len(r) < 3:
+ continue
+ if self.own(r[1]) or fuobe_prefixed(r[2]):
+ if isinstance(r[1], str):
+ self.add_prompt(r[1])
+ items.append(r)
+ else:
+ # Someone else's prompt: only its place in the queue.
+ items.append([r[0], None, None, {}, []])
+ out[k] = items
+ return out
+
+ def _jobs(self, data):
+ if not isinstance(data, dict):
+ return {"jobs": []}
+ out = dict(data)
+ out["jobs"] = [j for j in data.get("jobs") or [] if isinstance(j, dict) and self.own(j.get("id"))]
+ return out
+
+
+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):
+ return info
+ for cls, spec in info.items():
+ inputs = spec.get("input") if isinstance(spec, dict) else None
+ if not isinstance(inputs, dict):
+ continue
+ for section in ("required", "optional"):
+ group = inputs.get(section)
+ if not isinstance(group, dict):
+ continue
+ for name, s in group.items():
+ if not isinstance(s, list) or not s:
+ continue
+ opts = s[1] if len(s) > 1 and isinstance(s[1], dict) else {}
+ if not (name in FILE_LOADERS.get(cls, ()) or any(opts.get(k) for k in ("image_upload", "video_upload", "audio_upload", "file_upload", "upload"))):
+ continue
+ keep = lambda x: isinstance(x, str) and staged_name_ok(x[:-8] if x.endswith(" [input]") else x) # noqa: E731
+ if isinstance(s[0], list):
+ s[0] = [x for x in s[0] if keep(x)]
+ if isinstance(opts.get("options"), list):
+ opts["options"] = [x for x in opts["options"] if keep(x)]
+ return info
+
+
+def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | None = None, studios: Studios | None = None, lan: bool = False):
"""`trusted`: the trusted origins now (read on each request, so a change applies at once).
- `cors_flag`: ComfyUI's --enable-cors-header value, when it was started with one."""
+ `cors_flag`: ComfyUI's --enable-cors-header value, when it was started with one.
+ `studios`: what trusted studios did here (with the node list their prompts are checked against).
+ `lan`: also serve a trusted studio when this ComfyUI is reached at a network address (FUOBE_CONNECT_LAN=1)."""
flag = (cors_flag or "").strip()
flag_origin = normalise(flag) if flag and flag != "*" else 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])
+ studios = studios or Studios()
@web.middleware
async def fuobe_connect(request: web.Request, handler):
raw = request.headers.get("Origin")
if raw is not None:
origin = normalise(raw)
- if origin and origin in set(trusted()):
+ 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:
@@ -101,12 +344,16 @@ def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | None
headers.popall("Origin", None)
headers.popall("Sec-Fetch-Site", None)
headers[MARKER] = origin
- response = await _pass(request.clone(headers=headers), handler)
+ # 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 != flag_origin and not same_host(raw, request.headers.get("Host")):
+ 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])
return web.Response(status=403)
@@ -122,4 +369,5 @@ def make_middleware(trusted: Callable[[], Iterable[str]], cors_flag: str | None
return await handler(request)
return await _pass(request, handler)
+ fuobe_connect.studios = studios
return fuobe_connect
diff --git a/integrations/fuobe-connect/fuobe_connect/net.py b/integrations/fuobe-connect/fuobe_connect/net.py
index b8bc4f37..7dee8d19 100644
--- a/integrations/fuobe-connect/fuobe_connect/net.py
+++ b/integrations/fuobe-connect/fuobe_connect/net.py
@@ -1,21 +1,31 @@
"""The two places Fuobe Connect talks to: the paired Fuobe studio (over HTTPS, with its token) and this ComfyUI itself
(on this computer, as a program: no browser headers, so ComfyUI's own checks treat it as it treats any local tool).
-Only aiohttp, which ComfyUI already has.
+Every answer from the studio is read with a size limit, and files go through a temporary file, so a broken or taken-over
+studio can't fill ComfyUI's memory. Only aiohttp, which ComfyUI already has.
"""
from __future__ import annotations
+import hashlib
+import io
import json
import ssl
+import tempfile
from dataclasses import dataclass
-from urllib.parse import urlencode, urlsplit
+from urllib.parse import quote, urlencode, urlsplit
import aiohttp
from . import __version__
+from .origins import is_loopback
USER_AGENT = f"FuobeConnect/{__version__}"
+# The most a studio's JSON answer may be.
+MAX_JSON = 4 * 2**20
+# A file is kept in memory up to this size, then on disk.
+SPOOL = 16 * 2**20
+CHUNK = 2**20
class SiteError(Exception):
@@ -25,6 +35,10 @@ class SiteError(Exception):
self.body = body or {}
+class TooBig(Exception):
+ """An answer larger than it may be."""
+
+
@dataclass
class Answer:
status: int
@@ -33,10 +47,64 @@ class Answer:
def site_base(site: str) -> str:
- u = urlsplit(site.strip())
- if u.scheme not in ("https", "http") or not u.hostname:
+ """The studio's origin. https only, except a studio on this computer (http://localhost, for development)."""
+ try:
+ u = urlsplit((site or "").strip())
+ u.port # noqa: B018 (a bad port raises here)
+ except ValueError:
raise ValueError("The studio's address must start with https://")
- return f"{u.scheme}://{u.netloc}"
+ if not u.hostname or u.username or u.password or u.scheme not in ("https", "http") or (u.scheme == "http" and not is_loopback(u.hostname)):
+ raise ValueError("The studio's address must start with https://")
+ return f"{u.scheme}://{u.netloc.lower()}"
+
+
+def seg(value) -> str:
+ """One path segment, quoted: an id can never add a step or a query."""
+ return quote(str(value), safe="")
+
+
+async def read_capped(res: aiohttp.ClientResponse, limit: int) -> bytes:
+ length = res.headers.get("Content-Length")
+ if length and length.isdigit() and int(length) > limit:
+ raise TooBig(f"The answer is {length} bytes, more than {limit}")
+ out = bytearray()
+ while True:
+ chunk = await res.content.read(CHUNK)
+ if not chunk:
+ return bytes(out)
+ out += chunk
+ if len(out) > limit:
+ raise TooBig(f"The answer is more than {limit} bytes")
+
+
+async def spool(res: aiohttp.ClientResponse, limit: int):
+ """The answer's body in memory, or in a temporary file once it is large, with its size and SHA-256. Raises TooBig
+ past `limit`."""
+ length = res.headers.get("Content-Length")
+ if length and length.isdigit() and int(length) > limit:
+ raise TooBig(f"The file is {length} bytes, more than {limit}")
+ f = io.BytesIO()
+ h = hashlib.sha256()
+ size = 0
+ try:
+ while True:
+ chunk = await res.content.read(CHUNK)
+ if not chunk:
+ break
+ size += len(chunk)
+ if size > limit:
+ raise TooBig(f"The file is more than {limit} bytes")
+ h.update(chunk)
+ if isinstance(f, io.BytesIO) and size > SPOOL:
+ disk = tempfile.TemporaryFile()
+ disk.write(f.getvalue())
+ f = disk
+ f.write(chunk)
+ except BaseException:
+ f.close()
+ raise
+ f.seek(0)
+ return f, size, h.hexdigest()
class Site:
@@ -55,24 +123,28 @@ class Site:
h.update(extra)
return h
- async def call(self, method: str, path: str, body=None, headers: dict | None = None, data: bytes | None = None, timeout: float = 60) -> Answer:
- kwargs = {"headers": self._headers(headers), "timeout": aiohttp.ClientTimeout(total=timeout)}
+ async def call(self, method: str, path: str, body=None, headers: dict | None = None, data=None, timeout: float = 60) -> Answer:
+ kwargs = {"headers": self._headers(headers), "timeout": aiohttp.ClientTimeout(total=timeout), "allow_redirects": False}
if body is not None:
kwargs["data"] = json.dumps(body)
kwargs["headers"]["Content-Type"] = "application/json"
elif data is not None:
kwargs["data"] = data
async with self.session.request(method, self.base + path, **kwargs) as res:
- text = await res.text()
try:
+ text = (await read_capped(res, MAX_JSON)).decode("utf-8", "replace")
parsed = json.loads(text) if text else {}
- except ValueError:
+ except (ValueError, TooBig):
parsed = {}
return Answer(res.status, parsed if isinstance(parsed, dict) else {}, dict(res.headers))
- async def read(self, path: str, headers: dict | None = None) -> tuple[int, bytes, dict]:
- async with self.session.get(self.base + path, headers=self._headers(headers), timeout=aiohttp.ClientTimeout(total=600)) as res:
- return res.status, await res.read(), dict(res.headers)
+ async def fetch_file(self, path: str, limit: int, headers: dict | None = None):
+ """(status, temporary file or None, size, sha256, headers). The file is at most `limit` bytes."""
+ async with self.session.get(self.base + path, headers=self._headers(headers), timeout=aiohttp.ClientTimeout(total=600), allow_redirects=False) as res:
+ if res.status != 200:
+ return res.status, None, 0, "", dict(res.headers)
+ f, size, sha = await spool(res, limit)
+ return res.status, f, size, sha, dict(res.headers)
# Pairing (no token yet).
async def pair_start(self, name: str, facts: dict) -> Answer:
@@ -116,7 +188,8 @@ class Comfy:
parsed = {}
return res.status, parsed if isinstance(parsed, dict) else {}
- async def upload_input(self, name: str, data: bytes, content_type: str) -> int:
+ async def upload_input(self, name: str, data, content_type: str) -> int:
+ """`data`: bytes or an open file. Always into the input folder, under the run's own name."""
form = aiohttp.FormData()
form.add_field("image", data, filename=name, content_type=content_type or "application/octet-stream")
form.add_field("type", "input")
@@ -125,10 +198,14 @@ class Comfy:
await res.read()
return res.status
- async def view(self, filename: str, subfolder: str, kind: str) -> bytes | None:
+ async def view(self, filename: str, subfolder: str, kind: str, limit: int = 64 * 2**30):
+ """A result in a temporary file (memory, then disk) and its size, or (None, 0)."""
q = urlencode({"filename": filename, "subfolder": subfolder, "type": kind})
async with self.session.get(f"{self.base}/view?{q}", **self._kw(600)) as res:
- return await res.read() if res.status == 200 else None
+ if res.status != 200:
+ return None, 0
+ f, size, _ = await spool(res, limit)
+ return f, size
def ws_url(self, client_id: str) -> str:
return self.base.replace("http", "ws", 1) + "/ws?" + urlencode({"clientId": client_id})
diff --git a/integrations/fuobe-connect/fuobe_connect/origins.py b/integrations/fuobe-connect/fuobe_connect/origins.py
index 393b2649..7eec78b3 100644
--- a/integrations/fuobe-connect/fuobe_connect/origins.py
+++ b/integrations/fuobe-connect/fuobe_connect/origins.py
@@ -2,18 +2,22 @@
Pure (no ComfyUI imports), so the tests load it on its own.
-A trusted site is a Fuobe studio: https://fuobe.com unless you name others. Only an exact origin counts (scheme, host
-and port). A trusted site may use only what a Fuobe run needs: the facts about this ComfyUI, its queue and history,
-its results, uploading a run's inputs and queueing its prompt. It never reaches the Manager's install calls, your
-user files or settings: those stay behind ComfyUI's own check, as for every other website.
+A trusted site is a Fuobe studio: https://fuobe.com (and https://www.fuobe.com) unless you name others, or none at all.
+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.
"""
from __future__ import annotations
+import ipaddress
import re
from urllib.parse import parse_qs, urlsplit
DEFAULT_STUDIOS = ("https://fuobe.com",)
+# What the person types to trust no website (pairing still works).
+NONE = "none"
# A site that is also reached under "www.".
_WWW_TWINS = {"fuobe.com"}
@@ -45,19 +49,66 @@ def normalise(origin: str | None) -> str | None:
return f"{u.scheme}://{host}"
+def is_loopback(host: str | None) -> bool:
+ """127.0.0.1, ::1 or localhost (a host name, without a port)."""
+ if not host:
+ return False
+ h = host.strip().lower().strip("[]").rstrip(".")
+ if h == "localhost":
+ return True
+ try:
+ return ipaddress.ip_address(h).is_loopback
+ except ValueError:
+ return False
+
+
+def is_ip(host: str | None) -> bool:
+ try:
+ ipaddress.ip_address((host or "").strip().strip("[]"))
+ return True
+ except ValueError:
+ return False
+
+
+def host_name(host_header: str | None) -> str | None:
+ """The host of a Host header ('127.0.0.1:8188' -> '127.0.0.1', '[::1]:8188' -> '::1')."""
+ try:
+ return urlsplit("//" + (host_header or "").strip()).hostname
+ except ValueError:
+ return None
+
+
+def studio(origin: str | None) -> str | None:
+ """A studio's origin: https, or http only on this computer (a studio in development). None for anything else."""
+ o = normalise(origin)
+ if not o:
+ return None
+ u = urlsplit(o)
+ if u.scheme == "http" and not is_loopback(u.hostname):
+ return None
+ return o
+
+
def parse_list(text: str | list | tuple | None) -> list[str]:
- """A comma- or space-separated list (or a list) of origins: the valid ones, in order, without repeats."""
+ """A comma- or space-separated list (or a list) of studios: the valid ones, in order, without repeats."""
if text is None:
return []
items = text if isinstance(text, (list, tuple)) else re.split(r"[\s,]+", str(text))
out: list[str] = []
for item in items:
- o = normalise(item) if isinstance(item, str) else None
+ o = studio(item) if isinstance(item, str) else None
if o and o not in out:
out.append(o)
return out
+def says_none(text) -> bool:
+ """The person's 'none': trust no website."""
+ if isinstance(text, (list, tuple)):
+ return len(text) == 0 or (len(text) == 1 and says_none(text[0]))
+ return isinstance(text, str) and text.strip().lower() == NONE
+
+
def with_twins(origins: list[str]) -> list[str]:
out = list(origins)
for o in origins:
@@ -70,8 +121,13 @@ def with_twins(origins: list[str]) -> list[str]:
def trusted_origins(env_value: str | None, configured: str | list | None) -> tuple[str, ...]:
- """FUOBE_CONNECT_ORIGINS when set, else the configured studios, else https://fuobe.com."""
+ """FUOBE_CONNECT_ORIGINS when set, else the configured studios, else https://fuobe.com. 'none' (or an empty saved
+ list) in either: no website."""
for source in (env_value, configured):
+ if source is None or (isinstance(source, str) and not source.strip()):
+ continue
+ if says_none(source):
+ return ()
found = parse_list(source)
if found:
return tuple(with_twins(found))
@@ -79,49 +135,89 @@ def trusted_origins(env_value: str | None, configured: str | list | None) -> tup
# ---------------------------------------------------------------------------
-# What a trusted site may use (ComfyUI answers each path with and without "/api" in front).
+# What a trusted site may use (ComfyUI answers each path with and without "/api" in front). The middleware checks the
+# body or the answer of several of these (middleware.py).
+_UUID = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
_GET = re.compile(
- r"^/(?:"
+ r"/(?:"
r"system_stats|object_info(?:/[^/]{1,128})?|models(?:/[A-Za-z0-9_.-]{1,64})?|embeddings|queue|features"
- r"|history(?:/[0-9a-f-]{36})?|jobs(?:/[0-9a-f-]{36})?|view|ws"
+ rf"|history(?:/{_UUID})?|jobs(?:/{_UUID})?|view|ws"
r"|experiment/models(?:/[A-Za-z0-9_.-]{1,64})?"
r"|(?:v2/)?manager/(?:version|queue/status)|(?:v2/)?customnode/installed"
- r"|fuobe/connect|fuobe/guard"
- r")$"
+ r"|fuobe/connect|fuobe/guard|fuobe/live"
+ r")"
)
_POST = re.compile(
- r"^/(?:upload/image|prompt|queue|interrupt|jobs/[0-9a-f-]{36}/cancel|(?:v2/)?customnode/import_fail_info(?:_bulk)?)$"
+ rf"/(?:upload/image|prompt|queue|history|interrupt|jobs/{_UUID}/cancel|(?:v2/)?customnode/import_fail_info(?:_bulk)?)"
)
+_TAG = re.compile(r" \[[a-z]+\]\Z")
def _bare(path: str) -> str:
return path[4:] if path.startswith("/api/") else path
+def view_ok(query: str) -> bool:
+ """A /view of a result: output or temp, a plain file name (no folder tag, no asset name), no way out of the folder."""
+ q = parse_qs(query, keep_blank_values=True)
+ if set(q) - {"filename", "subfolder", "type"} or any(len(v) != 1 for v in q.values()):
+ return False
+ name = q.get("filename", [""])[0]
+ sub = q.get("subfolder", [""])[0]
+ if q.get("type", ["output"])[0] not in ("output", "temp"):
+ return False
+ if not name or name in (".", "..") or re.search(r"[\\/\x00]", name) or _TAG.search(name) or name.lower().startswith("blake3:"):
+ return False
+ if "\x00" in sub or sub.startswith(("/", "\\")) or re.match(r"^[A-Za-z]:", sub) or any(p == ".." for p in re.split(r"[\\/]", sub)):
+ return False
+ return True
+
+
+def ws_ok(query: str) -> bool:
+ """The live socket, under a Fuobe client id only (never the id of your own ComfyUI tab)."""
+ q = parse_qs(query, keep_blank_values=True)
+ ids = q.get("clientId", [])
+ return set(q) == {"clientId"} and len(ids) == 1 and bool(re.fullmatch(r"fuobe-[A-Za-z0-9_-]{4,72}", ids[0]))
+
+
+def history_list_ok(query: str) -> bool:
+ """/history only as the last few prompts (max_items), the way a run follows a batch."""
+ q = parse_qs(query, keep_blank_values=True)
+ return set(q) == {"max_items"} and len(q["max_items"]) == 1 and bool(re.fullmatch(r"[0-9]{1,3}", q["max_items"][0]))
+
+
def allowed(method: str, path: str, query: str = "") -> bool:
- """May a trusted site send this? (`query`: the raw query string; /view is only for results.)"""
+ """May a trusted site send this? (`query`: the raw query string.)"""
p = _bare(path)
m = method.upper()
if m in ("GET", "HEAD"):
- if not _GET.match(p):
+ if not _GET.fullmatch(p):
return False
if p == "/view":
- q = parse_qs(query, keep_blank_values=True)
- return q.get("type", ["output"])[0] in ("output", "temp")
+ return view_ok(query)
+ if p == "/ws":
+ return ws_ok(query)
+ if p == "/history":
+ return history_list_ok(query)
return True
if m == "POST":
- return bool(_POST.match(p))
+ return bool(_POST.fullmatch(p))
return False
+def _port(scheme: str, port: int | None) -> int | None:
+ return port if port is not None else _DEFAULT_PORTS.get(scheme)
+
+
def same_host(origin: str, host: str | None) -> bool:
- """The page is ComfyUI's own (the origin's host and port are the Host header's)."""
+ """The page is ComfyUI's own: the origin's host and port are the Host header's (a missing port is the scheme's
+ usual one, so http://localhost is port 80, not ComfyUI's 8188)."""
try:
o = urlsplit(origin)
h = urlsplit("//" + (host or "").strip().lower())
- if not o.hostname or not h.hostname or o.hostname.lower() != h.hostname:
+ if o.scheme not in _DEFAULT_PORTS or not o.hostname or not h.hostname or o.hostname.lower() != h.hostname:
return False
- return o.port is None or h.port is None or o.port == h.port
+ return _port(o.scheme, o.port) == _port(o.scheme, h.port)
except ValueError:
return False
diff --git a/integrations/fuobe-connect/fuobe_connect/plugin.py b/integrations/fuobe-connect/fuobe_connect/plugin.py
index 94b7de9b..bfade5a0 100644
--- a/integrations/fuobe-connect/fuobe_connect/plugin.py
+++ b/integrations/fuobe-connect/fuobe_connect/plugin.py
@@ -7,14 +7,17 @@ files changes.
from __future__ import annotations
+import asyncio
import logging
import os
+import re
from aiohttp import web
from . import __version__
-from .middleware import make_middleware, MARKER
-from .origins import normalise, parse_list, same_host, trusted_origins
+from .graph import NodeList
+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
log = logging.getLogger("fuobe_connect")
@@ -27,12 +30,49 @@ def trusted() -> tuple[str, ...]:
return trusted_origins(os.environ.get("FUOBE_CONNECT_ORIGINS"), configured)
-def _own_page(request: web.Request) -> bool:
- """A call from ComfyUI's own page, or from a program on this computer: never from a trusted studio or any website."""
+def pairing_sites() -> list[str]:
+ """The studios this ComfyUI may pair with: the trusted ones, Fuobe's own, and FUOBE_CONNECT_SITE."""
+ sites = list(trusted()) + with_twins(list(DEFAULT_STUDIOS))
+ env = studio(os.environ.get("FUOBE_CONNECT_SITE"))
+ if env:
+ sites.append(env)
+ return sites
+
+
+def own_hosts() -> set[str]:
+ """Host names (besides this computer's own and IP addresses) that ComfyUI's own page is opened at:
+ FUOBE_CONNECT_HOSTS, for a ComfyUI you reach by a name (comfy.local, or a domain in front of it)."""
+ return {h.strip().lower().rstrip(".") for h in re.split(r"[\s,]+", os.environ.get("FUOBE_CONNECT_HOSTS", "")) if h.strip()}
+
+
+def _own_page(request: web.Request, post: bool = False) -> bool:
+ """A call from ComfyUI's own page, or from a program on this computer: never from a trusted studio or any website.
+
+ The Host must be this computer (127.0.0.1, ::1, localhost), an IP address, or a name in FUOBE_CONNECT_HOSTS: a page
+ whose own name was pointed at this computer (DNS rebinding) has neither. The Origin, when there is one, is that
+ Host with the same port; the browser's Sec-Fetch-Site, when sent, says same-origin; a change is JSON."""
if request.headers.get(MARKER):
return False
+ host = host_name(request.headers.get("Host"))
+ if not host or not (is_loopback(host) or is_ip(host) or host.lower().rstrip(".") in own_hosts()):
+ return False
origin = request.headers.get("Origin")
- return origin is None or same_host(origin, request.headers.get("Host"))
+ if origin is not None and not same_host(origin, request.headers.get("Host")):
+ return False
+ site = request.headers.get("Sec-Fetch-Site")
+ if site is not None and site.lower() not in ("same-origin", "none" if not post else "same-origin"):
+ return False
+ if post and request.content_type != "application/json":
+ return False
+ return True
+
+
+async def _json(request: web.Request) -> dict:
+ try:
+ body = await request.json()
+ except (ValueError, UnicodeDecodeError):
+ return {}
+ return body if isinstance(body, dict) else {}
async def status(request: web.Request) -> web.Response:
@@ -40,51 +80,73 @@ async def status(request: web.Request) -> web.Response:
base = {"connect": 1, "version": __version__, "guard": 1}
if not _own_page(request):
return web.json_response(base)
+ store = _state.get("store")
agent = _state.get("agent")
- return web.json_response({**base, "studios": list(trusted()), "fromEnv": bool(os.environ.get("FUOBE_CONNECT_ORIGINS")), **(agent.status() if agent else {"state": "off"})})
+ from_env = bool(os.environ.get("FUOBE_CONNECT_ORIGINS"))
+ saved = store.load().get("studios") if store else None
+ return web.json_response(
+ {
+ **base,
+ "studios": list(trusted()),
+ "setting": NONE if says_none(saved) else ", ".join(saved) if isinstance(saved, list) else None,
+ "fromEnv": from_env,
+ "pairSites": pairing_sites(),
+ **(agent.status() if agent else {"state": "off"}),
+ }
+ )
async def set_studios(request: web.Request) -> web.Response:
- """POST /fuobe/connect/studios {studios: "https://a, https://b"}: the studios that may use this ComfyUI."""
- if not _own_page(request):
+ """POST /fuobe/connect/studios {studios: "https://a, https://b" | "none"}: the studios that may use this ComfyUI from
+ the browser ("none": no website; pairing still works)."""
+ if not _own_page(request, post=True):
return web.Response(status=403)
- body = await request.json()
- studios = parse_list(body.get("studios") if isinstance(body, dict) else None)
- if not studios:
- return web.json_response({"error": "Name at least one studio, like https://fuobe.com"}, status=400)
- _state["store"].update(studios=studios)
- return web.json_response({"studios": list(trusted())})
+ raw = (await _json(request)).get("studios")
+ if says_none(raw):
+ _state["store"].update(studios=[])
+ else:
+ studios = parse_list(raw)
+ if not studios:
+ return web.json_response({"error": "Name a studio like https://fuobe.com, or type none for no website. A studio's address starts with https://."}, status=400)
+ _state["store"].update(studios=studios)
+ return web.json_response({"studios": list(trusted()), "fromEnv": bool(os.environ.get("FUOBE_CONNECT_ORIGINS"))})
async def pair(request: web.Request) -> web.Response:
- """POST /fuobe/connect/pair {site?}: a code to approve on the studio."""
- if not _own_page(request):
+ """POST /fuobe/connect/pair {site?, name?}: a code to approve on the studio. Only a studio this ComfyUI may pair with."""
+ if not _own_page(request, post=True):
return web.Response(status=403)
agent = _state.get("agent")
+ body = await _json(request)
+ sites = pairing_sites()
+ site = studio(body.get("site")) if body.get("site") is not None else (sites[0] if sites else None)
+ if not site or site not in sites:
+ return web.json_response({"error": "Pair only with a studio you trust: add it in Settings → Fuobe Connect first."}, status=400)
try:
- body = await request.json()
- except ValueError:
- body = {}
- site = normalise((body or {}).get("site")) if isinstance(body, dict) else None
- try:
- fut = agent.call(agent.start_pairing(site or trusted()[0]))
- import asyncio
-
+ fut = agent.call(agent.start_pairing(site, body.get("name") if isinstance(body.get("name"), str) else None))
return web.json_response(await asyncio.wrap_future(fut))
except Exception as e:
- return web.json_response({"error": str(e)}, status=502)
+ return web.json_response({"error": str(e)[:200]}, status=502)
async def unpair(request: web.Request) -> web.Response:
- if not _own_page(request):
+ if not _own_page(request, post=True):
return web.Response(status=403)
- import asyncio
-
agent = _state["agent"]
agent.cancel_pairing()
return web.json_response(await asyncio.wrap_future(agent.call(agent.unpair())))
+async def set_jobs(request: web.Request) -> web.Response:
+ """POST /fuobe/connect/jobs {paused: bool}: pause or resume Fuobe jobs on this computer."""
+ if not _own_page(request, post=True):
+ return web.Response(status=403)
+ paused = (await _json(request)).get("paused")
+ if not isinstance(paused, bool):
+ return web.json_response({"error": "Send paused: true or false"}, status=400)
+ return web.json_response(_state["agent"].set_paused(paused))
+
+
def install():
"""Called once when ComfyUI loads this custom node."""
import folder_paths
@@ -102,10 +164,15 @@ def install():
app = instance.app
if any(getattr(m, "__name__", "") == "fuobe_connect" for m in app.middlewares):
return
- store = Store(folder_paths.get_user_directory())
+ user_dir = folder_paths.get_user_directory()
+ store = Store(user_dir)
_state["store"] = store
+ nodes = NodeList(user_dir)
+ studios = Studios(nodes)
+ _state["studios"] = studios
+ lan = os.environ.get("FUOBE_CONNECT_LAN") == "1"
try:
- app.middlewares.insert(0, make_middleware(trusted, getattr(args, "enable_cors_header", None)))
+ app.middlewares.insert(0, make_middleware(trusted, getattr(args, "enable_cors_header", None), studios, lan))
except RuntimeError:
log.warning("[Fuobe Connect] ComfyUI had already started, so Fuobe Connect is off. Restart ComfyUI.")
return
@@ -113,14 +180,29 @@ def install():
instance.routes.post("/fuobe/connect/studios")(set_studios)
instance.routes.post("/fuobe/connect/pair")(pair)
instance.routes.post("/fuobe/connect/unpair")(unpair)
+ instance.routes.post("/fuobe/connect/jobs")(set_jobs)
+
+ for source in (os.environ.get("FUOBE_CONNECT_ORIGINS"), store.load().get("studios")):
+ items = source if isinstance(source, list) else re.split(r"[\s,]+", source or "")
+ for item in items:
+ if isinstance(item, str) and item.strip() and not says_none(item) and normalise(item) and not studio(item):
+ log.warning("[Fuobe Connect] %s isn't trusted: a studio's address starts with https:// (http only on this computer).", item[:120])
port = int(getattr(args, "port", 8188) or 8188)
- agent = Agent(store, loopback_base(getattr(args, "listen", None), port, bool(getattr(args, "tls_keyfile", None))), port, trusted()[0])
+ try:
+ input_dir = folder_paths.get_input_directory()
+ except Exception:
+ input_dir = None
+ sites = pairing_sites()
+ agent = Agent(store, loopback_base(getattr(args, "listen", None), port, bool(getattr(args, "tls_keyfile", None))), port, sites[0], nodes, input_dir)
_state["agent"] = agent
agent.start()
- log.info("[Fuobe Connect] %s can use this ComfyUI from the browser.", ", ".join(trusted()))
+ if trusted():
+ log.info("[Fuobe Connect] %s can use this ComfyUI from the browser.", ", ".join(trusted()))
+ else:
+ log.info("[Fuobe Connect] No website may use this ComfyUI from the browser (studios: none).")
if os.environ.get("FUOBE_CONNECT_PAIR") == "1" and not store.load().get("token"):
# A PC with no screen: the code and the address go to ComfyUI's console.
- agent.call(agent.start_pairing(os.environ.get("FUOBE_CONNECT_SITE") or trusted()[0]))
+ agent.call(agent.start_pairing(studio(os.environ.get("FUOBE_CONNECT_SITE")) or sites[0]))
elif not store.load().get("token"):
log.info("[Fuobe Connect] To run Fuobe jobs here with no browser tab open: ComfyUI menu → Extensions → Connect to Fuobe.")
diff --git a/integrations/fuobe-connect/fuobe_connect/runner.py b/integrations/fuobe-connect/fuobe_connect/runner.py
index 43e7622a..f1bed54a 100644
--- a/integrations/fuobe-connect/fuobe_connect/runner.py
+++ b/integrations/fuobe-connect/fuobe_connect/runner.py
@@ -5,23 +5,42 @@ here, claim the person's next job, send its inputs and its exact graph to this C
upload the results the studio asks for. It decides nothing about a result. Only that person's jobs reach it: the studio
picks them by the token, which belongs to one person.
-A job's graph may read only the files that job sent, and a result is uploaded only when this job's own prompt saved it
-(graph.py). One job at a time.
+Before a job runs, Fuobe Connect checks it here, whatever the studio says (graph.py): every node type is on the list
+this pack ships (plus your own fuobe-connect-nodes.json), no text input names a path or an address, the inputs have the
+names Fuobe gives its files, and every loader reads one of them. Every id the studio sends is checked before it goes
+into an address. Only the prompts this runner queued are followed, taken off or read back, and a result is uploaded only
+when this job's own prompt (or its batch's passes, under the job's own fuobe/<id> prefix) saved it. One job at a time.
+Pausing (ComfyUI's Connect to Fuobe window) stops it taking new jobs.
"""
from __future__ import annotations
import asyncio
-import hashlib
import json
import logging
+import os
+import re
import time
import uuid
import aiohttp
-from .graph import graph_problem, has_prefix, may_download, safe_wanted, slim, UUID
-from .net import Comfy, Site
+from .graph import (
+ PREFIX,
+ TASK_ID,
+ UUID,
+ NodeList,
+ graph_strings,
+ has_prefix,
+ may_download,
+ refusal,
+ run_prefix,
+ safe_wanted,
+ slim,
+ staged_name_ok,
+ vet_graph,
+)
+from .net import Comfy, Site, TooBig, seg
log = logging.getLogger("fuobe_connect")
@@ -31,6 +50,13 @@ POLL_S = 1.0
PROGRESS_EVERY_S = 0.5
PART_BYTES = 16 * 2**20
SAVE_WAIT_S = 60 * 60
+# The most one input may be when the studio doesn't say its size.
+MAX_INPUT = 4 * 2**30
+SEND_TRIES = 3
+MAX_INPUTS = 64
+
+SHA256 = re.compile(r"^[0-9a-f]{64}\Z")
+LEASE = re.compile(r"^[A-Za-z0-9_-]{16,128}\Z")
class Stopped(Exception):
@@ -48,8 +74,28 @@ def _retry_after(headers: dict) -> float:
return 2.0
+def _small_int(n) -> bool:
+ return isinstance(n, int) and not isinstance(n, bool) and 0 <= n < 1000
+
+
class Runner:
- def __init__(self, site: Site, comfy: Comfy, device: str, port: int, on_state=None, sleep=asyncio.sleep, clock=time.monotonic):
+ def __init__(
+ self,
+ site: Site,
+ comfy: Comfy,
+ device: str,
+ port: int,
+ on_state=None,
+ sleep=asyncio.sleep,
+ clock=time.monotonic,
+ nodes=None,
+ own: set | None = None,
+ prefixes: set | None = None,
+ input_dir: str | None = None,
+ paused=None,
+ on_job=None,
+ loras: bool = True,
+ ):
self.site = site
self.comfy = comfy
self.device = device
@@ -70,6 +116,20 @@ class Runner:
self.ws_task: asyncio.Task | None = None
self.ws_open = False
self.comfy_ok = False
+ # What this ComfyUI may run (the shipped list and the person's own file).
+ self.nodes = nodes or NodeList()
+ # The prompts Fuobe Connect queued on this ComfyUI (kept by the agent across runners), and the jobs' prefixes.
+ self.own = own if own is not None else set()
+ self.prefixes = prefixes if prefixes is not None else set()
+ self.input_dir = input_dir
+ self.paused = paused or (lambda: False)
+ self.on_job = on_job or (lambda record: None)
+ self.share_loras = loras
+
+ def _own(self, pid: str):
+ if len(self.own) > 4096:
+ self.own.clear()
+ self.own.add(pid)
# ------------------------------------------------------------------
# This ComfyUI
@@ -102,7 +162,7 @@ class Runner:
f["os"] = str(system["os"])[:40]
if isinstance(system.get("embedded_python"), bool):
f["portable"] = system["embedded_python"]
- if loras:
+ if loras and self.share_loras:
try:
names = await self.comfy.get_json("/models/loras")
if isinstance(names, list):
@@ -129,7 +189,7 @@ class Runner:
continue
d = m.get("data") if isinstance(m, dict) and isinstance(m.get("data"), dict) else {}
pid = d.get("prompt_id")
- if not isinstance(pid, str):
+ if not isinstance(pid, str) or pid not in self.own:
continue
cur = self.events.setdefault(pid, {"nodesDone": 0})
t = m.get("type")
@@ -143,6 +203,9 @@ class Runner:
self.ws_open = False
async def where(self, prompt_id: str, prefix: str | None = None) -> dict:
+ if not UUID.match(prompt_id):
+ return {"s": "absent"}
+ pid = seg(prompt_id)
if self.jobs_api is None:
try:
await self.comfy.get_json("/api/jobs")
@@ -150,7 +213,7 @@ class Runner:
except Exception:
self.jobs_api = False
if self.jobs_api:
- status, j = await self.comfy.get_status(f"/api/jobs/{prompt_id}")
+ status, j = await self.comfy.get_status(f"/api/jobs/{pid}")
if status == 404:
return await self.where_by_queue(prompt_id) if prefix else {"s": "absent"}
if status != 200:
@@ -160,9 +223,9 @@ class Runner:
return {"s": "running"}
if st == "pending":
return await self.where_by_queue(prompt_id)
- entry = (await self.comfy.get_json(f"/history/{prompt_id}")).get(prompt_id)
+ entry = (await self.comfy.get_json(f"/history/{pid}")).get(prompt_id)
return {"s": "done", "entry": entry} if entry else {"s": "absent"}
- entry = (await self.comfy.get_json(f"/history/{prompt_id}")).get(prompt_id)
+ entry = (await self.comfy.get_json(f"/history/{pid}")).get(prompt_id)
if entry and ((entry.get("status") or {}).get("completed") or (entry.get("status") or {}).get("status_str")):
return {"s": "done", "entry": entry}
return await self.where_by_queue(prompt_id)
@@ -176,7 +239,7 @@ class Runner:
for i, r in enumerate(pending):
if len(r) > 1 and r[1] == prompt_id:
return {"s": "pending", "ahead": i + len(running)}
- entry = (await self.comfy.get_json(f"/history/{prompt_id}")).get(prompt_id)
+ entry = (await self.comfy.get_json(f"/history/{seg(prompt_id)}")).get(prompt_id)
return {"s": "done", "entry": entry} if entry else {"s": "absent"}
# ------------------------------------------------------------------
@@ -186,7 +249,7 @@ class Runner:
until = self.clock() + 120
tries = 0
while True:
- a = await self.site.call("POST", f"/api/gpu/computer/tasks/{t['id']}/report", event, headers={"X-Fuobe-Lease": t["lease"]})
+ a = await self.site.call("POST", f"/api/gpu/computer/tasks/{seg(t['id'])}/report", event, headers={"X-Fuobe-Lease": t["lease"]})
if a.status == 200:
return a.body
if a.status == 401:
@@ -206,7 +269,8 @@ class Runner:
due = now - self.facts_at > 60
loras = due and now - self.loras_at > 300
read = await self.facts(loras) if due else (await self.look() and {})
- body: dict = {"device": self.device, "port": self.port, "ready": read is not None}
+ paused = bool(self.paused())
+ body: dict = {"device": self.device, "port": self.port, "ready": read is not None and not paused}
if due and read:
self.facts_at = now
if loras:
@@ -219,7 +283,7 @@ class Runner:
item = {"task": task_id}
if j.get("position") is not None:
item["position"] = j["position"]
- ev = self.events.get(j.get("promptId", ""))
+ ev = self.events.get(j.get("promptId") or "")
if j["phase"] == "running" and ev:
item.update({k: ev[k] for k in ("value", "max", "nodesDone") if ev.get(k) is not None})
running.append(item)
@@ -232,46 +296,55 @@ class Runner:
raise Unpaired()
if a.status != 200:
self.runner = False
- self.on_state("waiting", a.body.get("error") or f"The studio answered HTTP {a.status}")
+ self.on_state("waiting", a.body.get("error") if isinstance(a.body.get("error"), str) else f"The studio answered HTTP {a.status}")
return None
for s in stopped:
self.stopped_done.discard(s)
self.runner = bool(a.body.get("runner"))
- if not self.comfy_ok:
+ if paused:
+ self.on_state("paused", "Fuobe jobs are paused on this computer.")
+ elif not self.comfy_ok:
self.on_state("comfy-down", "ComfyUI isn't answering here.")
elif self.runner:
self.on_state("connected", None)
else:
self.on_state("elsewhere", "Another computer runs your Fuobe jobs now.")
- for s in a.body.get("stops") or []:
- asyncio.ensure_future(self.take_off(s))
+ for s in (a.body.get("stops") or [])[:50]:
+ if isinstance(s, dict):
+ asyncio.ensure_future(self.take_off(s))
return a.body
+ async def _cancel(self, pid: str):
+ if self.jobs_api is not False:
+ status, _ = await self.comfy.post_json(f"/api/jobs/{seg(pid)}/cancel", {})
+ if status == 404:
+ self.jobs_api = False
+ if self.jobs_api is False:
+ await self.comfy.post_json("/queue", {"delete": [pid]})
+ q = await self.comfy.get_json("/queue")
+ if any(len(r) > 1 and r[1] == pid for r in q.get("queue_running") or []):
+ await self.comfy.post_json("/interrupt", {"prompt_id": pid})
+
async def take_off(self, s: dict):
+ """Take a job's prompt off this ComfyUI (only one this runner queued) and its batch's later passes (only under a
+ prefix of a job this runner ran), then tell the studio."""
task_id = s.get("task")
pid = s.get("promptId")
- if not isinstance(task_id, str) or task_id in self.stopping or not isinstance(pid, str) or not UUID.match(pid):
+ if not isinstance(task_id, str) or not TASK_ID.match(task_id) or task_id in self.stopping or not isinstance(pid, str) or not UUID.match(pid):
return
self.stopping.add(task_id)
try:
- if self.jobs_api is not False:
- status, _ = await self.comfy.post_json(f"/api/jobs/{pid}/cancel", {})
- if status == 404:
- self.jobs_api = False
- if self.jobs_api is False:
- await self.comfy.post_json("/queue", {"delete": [pid]})
- q = await self.comfy.get_json("/queue")
- if any(len(r) > 1 and r[1] == pid for r in q.get("queue_running") or []):
- await self.comfy.post_json("/interrupt", {"prompt_id": pid})
+ if pid in self.own:
+ await self._cancel(pid)
prefix = s.get("prefix")
- if isinstance(prefix, str) and prefix:
+ if isinstance(prefix, str) and PREFIX.match(prefix) and prefix in self.prefixes:
for _ in range(5):
q = await self.comfy.get_json("/queue")
- ids = [str(r[1]) for r in (q.get("queue_running") or []) + (q.get("queue_pending") or []) if len(r) > 2 and has_prefix(r[2], prefix)]
+ ids = [str(r[1]) for r in (q.get("queue_running") or []) + (q.get("queue_pending") or []) if len(r) > 2 and has_prefix(r[2], prefix) and isinstance(r[1], str) and UUID.match(r[1])]
if not ids:
break
for i in ids:
- await self.comfy.post_json(f"/api/jobs/{i}/cancel", {})
+ await self.comfy.post_json(f"/api/jobs/{seg(i)}/cancel", {})
await self.sleep(1)
self.stopped_done.add(task_id)
except Exception as e:
@@ -283,7 +356,7 @@ class Runner:
j["phase"] = "failed"
async def claim_and_run(self) -> bool:
- if not self.alive or not self.runner or not await self.look():
+ if not self.alive or not self.runner or self.paused() or not await self.look():
return False
running = [k for k, j in self.jobs.items() if j["phase"] not in ("done", "failed")]
a = await self.site.call("POST", "/api/gpu/computer/claim", {"device": self.device, "running": running})
@@ -302,7 +375,8 @@ class Runner:
raise
except Exception as e:
log.warning("[Fuobe Connect] A job stopped here: %s", e)
- self.jobs.pop(t["id"], None)
+ if isinstance(t.get("id"), str):
+ self.jobs.pop(t["id"], None)
return True
# ------------------------------------------------------------------
@@ -315,14 +389,59 @@ class Runner:
for k in done[:-6]:
self.jobs.pop(k, None)
+ def vet(self, t: dict) -> str | None:
+ """Why this job may not run here (the worker program's reasons), or None."""
+ if not isinstance(t.get("promptId"), str) or not UUID.match(t["promptId"]):
+ return "unsafe-graph"
+ inputs = t.get("inputs") if t.get("inputs") is not None else []
+ if not isinstance(inputs, list) or len(inputs) > MAX_INPUTS:
+ return "unsafe-graph"
+ names: list[str] = []
+ for i in inputs:
+ if not isinstance(i, dict) or not _small_int(i.get("n")) or not staged_name_ok(i.get("name")) or i["name"] in names:
+ return "unsafe-graph"
+ if not isinstance(i.get("sha256"), str) or not SHA256.match(i["sha256"]):
+ return "unsafe-graph"
+ size = i.get("size")
+ if size is not None and not (isinstance(size, int) and 0 <= size <= MAX_INPUT):
+ return "input-too-big"
+ names.append(i["name"])
+ 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)
+
+ def _record(self, t: dict, why: str | None) -> dict:
+ graph = t.get("graph") if isinstance(t.get("graph"), dict) else {}
+ kinds = sorted({n["class_type"] for n in graph.values() if isinstance(n, dict) and isinstance(n.get("class_type"), str)})
+ rec = {"at": int(time.time() * 1000), "nodes": [k[:64] for k in kinds[:40]], "more": max(0, len(kinds) - 40), "state": f"refused ({why})" if why else "running"}
+ try:
+ self.on_job(rec)
+ except Exception:
+ pass
+ return rec
+
async def run(self, t: dict):
- resume = t.get("resume")
+ if not isinstance(t.get("id"), str) or not TASK_ID.match(t["id"]) or not isinstance(t.get("lease"), str) or not LEASE.match(t["lease"]):
+ log.warning("[Fuobe Connect] The studio sent a job with a bad id; skipped it.")
+ return
+ resume = t.get("resume") if t.get("resume") in ("collecting", "running", "queued") else None
self._job(t, phase={"collecting": "saving", "running": "running", "queued": "queued"}.get(resume, "sending"), promptId=t.get("promptId"))
+ why = self.vet(t)
+ rec = self._record(t, why)
try:
- names = [i["name"] for i in t.get("inputs") or []]
- if graph_problem(t.get("graph"), names):
- await self.report(t, {"event": "failed", "reason": "unsafe-graph"})
+ if why:
+ await self.report(t, {"event": "failed", "reason": why})
return self._job(t, phase="failed")
+ names = [i["name"] for i in t.get("inputs") or []]
+ t = {**t, "prefix": run_prefix(t.get("prefix"), t["graph"])}
+ if t["prefix"]:
+ if len(self.prefixes) > 4096:
+ self.prefixes.clear()
+ self.prefixes.add(t["prefix"])
+ # A prompt this ComfyUI's Fuobe Connect didn't queue (it restarted): start the job again.
+ if resume in ("running", "queued") and t["promptId"] not in self.own:
+ resume = None
entries = None
wanted = t.get("wanted")
phase = resume or "sending"
@@ -333,6 +452,8 @@ class Runner:
return
self._socket()
done = await self.follow(t)
+ if done == "refused":
+ return self._job(t, phase="failed")
if done == "gone":
a = await self.report(t, {"event": "gone"})
if a.get("state") != "sending":
@@ -349,14 +470,31 @@ class Runner:
if entries is None:
entries = await self.own_entries(t)
await self.collect(t, wanted, entries, t.get("received") or [])
+ if self.jobs.get(t["id"], {}).get("phase") == "done":
+ self.clean_inputs(names)
except Stopped:
self._job(t, phase="failed")
+ finally:
+ rec["state"] = rec["state"] if why else self.jobs.get(t["id"], {}).get("phase", "stopped")
+
+ def clean_inputs(self, names: list[str]):
+ """A finished job's inputs leave this computer's input folder (only Fuobe's own fuobe_<id> files)."""
+ if not self.input_dir:
+ return
+ for name in names:
+ if staged_name_ok(name):
+ try:
+ os.remove(os.path.join(self.input_dir, name))
+ except OSError:
+ pass
async def own_entries(self, t: dict) -> list:
- try:
- own = (await self.comfy.get_json(f"/history/{t['promptId']}")).get(t["promptId"])
- except Exception:
- own = None
+ own = None
+ if t["promptId"] in self.own:
+ try:
+ own = (await self.comfy.get_json(f"/history/{seg(t['promptId'])}")).get(t["promptId"])
+ except Exception:
+ own = None
passes = []
if t.get("prefix"):
try:
@@ -381,57 +519,85 @@ class Runner:
await self.sleep(3)
async def send_job(self, t: dict) -> bool:
- self._job(t, phase="sending")
- try:
- there = await self.where(t["promptId"])
- except Exception:
- there = None
- if there and there["s"] != "absent":
- await self.report(t, {"event": "sent", "promptId": t["promptId"]})
- return True
- if there is None:
+ """Send the job's inputs and prompt, a few times when ComfyUI stops answering partway. False: it failed (and the
+ studio was told)."""
+ for attempt in range(SEND_TRIES):
+ self._job(t, phase="sending")
+ try:
+ there = await self.where(t["promptId"])
+ except Exception:
+ there = None
+ if there and there["s"] != "absent":
+ if t["promptId"] not in self.own:
+ # A prompt with this id that Fuobe Connect didn't queue here: never someone else's.
+ await self.report(t, {"event": "failed", "reason": "unsafe-graph"})
+ self._job(t, phase="failed")
+ return False
+ await self.report(t, {"event": "sent", "promptId": t["promptId"]})
+ return True
+ if there is None:
+ await self.wait_for_comfy(t)
+ sent = await self._send_once(t)
+ if sent is not None:
+ return sent
await self.wait_for_comfy(t)
+ await self.sleep(2 * (attempt + 1))
+ await self.report(t, {"event": "failed", "reason": "comfy-error"})
+ self._job(t, phase="failed")
+ return False
+
+ async def _fail(self, t: dict, event: dict) -> bool:
+ await self.report(t, event)
+ self._job(t, phase="failed")
+ return False
+
+ async def _send_once(self, t: dict) -> bool | None:
+ """True: sent. False: failed (the studio was told). None: ComfyUI stopped answering; try again."""
for inp in t.get("inputs") or []:
- status, data, headers = await self.site.read(f"/api/gpu/computer/tasks/{t['id']}/inputs/{inp['n']}", headers={"X-Fuobe-Lease": t["lease"]})
+ size = inp.get("size")
+ try:
+ status, f, got, sha, _ = await self.site.fetch_file(
+ f"/api/gpu/computer/tasks/{seg(t['id'])}/inputs/{int(inp['n'])}",
+ size if isinstance(size, int) else MAX_INPUT,
+ headers={"X-Fuobe-Lease": t["lease"]},
+ )
+ except TooBig:
+ return await self._fail(t, {"event": "failed", "reason": "input-changed"})
if status == 401:
raise Unpaired()
if status in (404, 409):
raise Stopped()
- if status != 200:
+ if status != 200 or f is None:
raise RuntimeError(f"The studio answered HTTP {status} for a file")
- if hashlib.sha256(data).hexdigest() != inp.get("sha256"):
- await self.report(t, {"event": "failed", "reason": "input-changed"})
- self._job(t, phase="failed")
- return False
try:
- up = await self.comfy.upload_input(inp["name"], data, inp.get("contentType") or "application/octet-stream")
- except Exception:
- await self.wait_for_comfy(t)
- return await self.send_job(t)
+ if sha != inp.get("sha256"):
+ return await self._fail(t, {"event": "failed", "reason": "input-changed"})
+ try:
+ up = await self.comfy.upload_input(inp["name"], f, inp.get("contentType") if isinstance(inp.get("contentType"), str) else "application/octet-stream")
+ except Exception:
+ return None
+ finally:
+ f.close()
if up != 200:
- await self.report(t, {"event": "failed", "reason": "input-too-big" if up == 413 else "comfy-error", "status": up})
- self._job(t, phase="failed")
- return False
+ return await self._fail(t, {"event": "failed", "reason": "input-too-big" if up == 413 else "comfy-error", "status": up})
body = {"prompt": t["graph"], "prompt_id": t["promptId"], "client_id": self.client_id}
if t.get("preview"):
body["extra_data"] = {"preview_method": "auto"}
+ self._own(t["promptId"])
try:
status, answer = await self.comfy.post_json("/prompt", body)
except Exception:
- await self.wait_for_comfy(t)
- return await self.send_job(t)
+ return None
if status == 400:
- await self.report(t, {"event": "refused", "status": 400, "body": answer})
- self._job(t, phase="failed")
- return False
- if status != 200 or not isinstance(answer.get("prompt_id"), str):
- await self.report(t, {"event": "failed", "reason": "comfy-error", "status": status})
- self._job(t, phase="failed")
- return False
- if answer["prompt_id"] != t["promptId"]:
- t["promptId"] = answer["prompt_id"]
- self._job(t, promptId=t["promptId"])
- ev = {"event": "sent", "promptId": answer["prompt_id"]}
+ return await self._fail(t, {"event": "refused", "status": 400, "body": refusal(answer, graph_strings(t["graph"]))})
+ pid = answer.get("prompt_id")
+ if status != 200 or not isinstance(pid, str) or not UUID.match(pid):
+ return await self._fail(t, {"event": "failed", "reason": "comfy-error", "status": status})
+ self._own(pid)
+ if pid != t["promptId"]:
+ t["promptId"] = pid
+ self._job(t, promptId=pid)
+ ev = {"event": "sent", "promptId": pid}
if isinstance(answer.get("number"), (int, float)):
ev["number"] = answer["number"]
await self.report(t, ev)
@@ -476,7 +642,11 @@ class Runner:
if a.get("stop"):
raise Stopped()
if a.get("follow"):
- following = a["follow"]
+ # Only this job's own batch: the prefix its own graph saves under.
+ if not t.get("prefix") or a["follow"] != t["prefix"]:
+ await self.report(t, {"event": "failed", "reason": "unsafe-graph"})
+ return "refused"
+ following = t["prefix"]
continue
return {"entries": [w["entry"]], "answer": a}
ev = self.events.get(t["promptId"]) or {}
@@ -496,37 +666,45 @@ class Runner:
async def collect(self, t: dict, wanted: list, entries: list, received: list):
self._job(t, phase="saving")
- for w in wanted:
- got = next((r for r in received if r.get("n") == w.get("n")), None)
+ for w in wanted if isinstance(wanted, list) else []:
+ if not isinstance(w, dict) or not _small_int(w.get("n")):
+ await self.report(t, {"event": "failed", "reason": "output-missing"})
+ return self._job(t, phase="failed")
+ got = next((r for r in received if isinstance(r, dict) and r.get("n") == w.get("n")), None)
if got and got.get("done"):
continue
if not safe_wanted(w) or not may_download(w, entries):
await self.report(t, {"event": "failed", "reason": "output-missing"})
return self._job(t, phase="failed")
- data = await self.comfy.view(w["filename"], w.get("subfolder") or "", w["type"])
- if data is None:
+ f, size = await self.comfy.view(w["filename"], w.get("subfolder") or "", w["type"])
+ if f is None:
await self.report(t, {"event": "failed", "reason": "output-missing"})
return self._job(t, phase="failed")
- offset = (got or {}).get("bytes") or 0
- if offset > 0:
- s = await self.site.call("GET", f"/api/gpu/computer/tasks/{t['id']}/outputs/{w['n']}", headers={"X-Fuobe-Lease": t["lease"]})
- offset = s.body.get("received", 0) if s.status == 200 else 0
- if not await self.upload(t, w, data, offset):
- return self._job(t, phase="failed")
+ try:
+ offset = (got or {}).get("bytes") or 0
+ if offset > 0:
+ s = await self.site.call("GET", f"/api/gpu/computer/tasks/{seg(t['id'])}/outputs/{int(w['n'])}", headers={"X-Fuobe-Lease": t["lease"]})
+ offset = s.body.get("received", 0) if s.status == 200 else 0
+ if not await self.upload(t, w, f, size, int(offset) if isinstance(offset, int) and 0 <= offset <= size else 0):
+ return self._job(t, phase="failed")
+ finally:
+ f.close()
self._job(t, phase="done")
- async def upload(self, t: dict, w: dict, data: bytes, offset: int) -> bool:
+ async def upload(self, t: dict, w: dict, f, total: int, offset: int) -> bool:
+ """Send a result to the studio in parts, from the temporary file `f` (`total` bytes), starting at `offset`."""
fails = 0
until = self.clock() + SAVE_WAIT_S
- total = len(data)
+ path = f"/api/gpu/computer/tasks/{seg(t['id'])}/outputs/{int(w['n'])}"
while offset < total or total == 0:
if not self.alive:
raise Stopped()
- part = data[offset : offset + PART_BYTES]
+ f.seek(offset)
+ part = f.read(PART_BYTES)
try:
a = await self.site.call(
"PUT",
- f"/api/gpu/computer/tasks/{t['id']}/outputs/{w['n']}?offset={offset}&total={total}",
+ f"{path}?offset={offset}&total={total}",
data=part,
headers={"X-Fuobe-Lease": t["lease"], "Content-Type": "application/octet-stream"},
timeout=600,
@@ -534,7 +712,8 @@ class Runner:
except Exception:
a = None
if a and a.status == 200:
- offset = int(a.body.get("received", offset))
+ got = a.body.get("received", offset)
+ offset = got if isinstance(got, int) and 0 <= got <= total else offset
fails = 0
if a.body.get("done"):
return True
@@ -547,12 +726,13 @@ class Runner:
if a and a.status == 401:
raise Unpaired()
if a and a.status == 409:
- s = await self.site.call("GET", f"/api/gpu/computer/tasks/{t['id']}/outputs/{w['n']}", headers={"X-Fuobe-Lease": t["lease"]})
+ s = await self.site.call("GET", path, headers={"X-Fuobe-Lease": t["lease"]})
if s.status != 200:
return False
if s.body.get("done"):
return True
- offset = int(s.body.get("received", 0))
+ got = s.body.get("received", 0)
+ offset = got if isinstance(got, int) and 0 <= got <= total else 0
fails += 1
if fails >= 3:
try:
diff --git a/integrations/fuobe-connect/fuobe_connect/store.py b/integrations/fuobe-connect/fuobe_connect/store.py
index 302bb207..3070e12e 100644
--- a/integrations/fuobe-connect/fuobe_connect/store.py
+++ b/integrations/fuobe-connect/fuobe_connect/store.py
@@ -1,22 +1,117 @@
"""Fuobe Connect's own small file: the studios this ComfyUI trusts, and its pairing (the studio and its token).
-It lives in ComfyUI's user folder, beside (not inside) the folder ComfyUI serves as user data, and only this Windows
-or Unix user may read it.
+It lives in ComfyUI's user folder, beside (not inside) the folder ComfyUI serves as user data. Only your own user
+account may read it: mode 0600 on Linux and macOS, and on Windows an access list that names only your account (no
+inherited entries), set before the token is written.
"""
from __future__ import annotations
import json
+import logging
import os
import threading
FILE_NAME = "fuobe-connect.json"
+log = logging.getLogger("fuobe_connect")
+
+
+def _current_user_sid() -> str | None:
+ """This Windows account's SID, as text (S-1-5-21-...)."""
+ import ctypes
+ from ctypes import wintypes
+
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE
+ advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
+ advapi32.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
+ advapi32.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)]
+ kernel32.LocalFree.argtypes = [ctypes.c_void_p]
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ TOKEN_QUERY = 0x0008
+ TOKEN_USER = 1
+ token = wintypes.HANDLE()
+ if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), TOKEN_QUERY, ctypes.byref(token)):
+ return None
+ try:
+ need = wintypes.DWORD(0)
+ advapi32.GetTokenInformation(token, TOKEN_USER, None, 0, ctypes.byref(need))
+ buf = ctypes.create_string_buffer(need.value)
+ if not advapi32.GetTokenInformation(token, TOKEN_USER, buf, need, ctypes.byref(need)):
+ return None
+ sid_ptr = ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p))[0]
+ text = wintypes.LPWSTR()
+ if not advapi32.ConvertSidToStringSidW(sid_ptr, ctypes.byref(text)):
+ return None
+ try:
+ return text.value
+ finally:
+ kernel32.LocalFree(text)
+ finally:
+ kernel32.CloseHandle(token)
+
+
+def owner_only(path: str) -> bool:
+ """Windows: give the file one access entry, full control for this account, and no inherited ones. True when set."""
+ if os.name != "nt":
+ return False
+ import ctypes
+ from ctypes import wintypes
+
+ sid = _current_user_sid()
+ if not sid:
+ return False
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.ULONG)]
+ advapi32.SetFileSecurityW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.c_void_p]
+ kernel32.LocalFree.argtypes = [ctypes.c_void_p]
+ sd = ctypes.c_void_p()
+ # D:P = a protected access list (nothing inherited from the folder); one entry: full access (FA) for this account.
+ if not advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW(f"D:P(A;;FA;;;{sid})", 1, ctypes.byref(sd), None):
+ return False
+ try:
+ DACL_SECURITY_INFORMATION = 0x00000004
+ PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
+ return bool(advapi32.SetFileSecurityW(path, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, sd))
+ finally:
+ kernel32.LocalFree(sd)
+
+
+def access_list(path: str) -> str | None:
+ """Windows: the file's access list as SDDL text (for the tests and a check)."""
+ if os.name != "nt":
+ return None
+ import ctypes
+ from ctypes import wintypes
+
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ advapi32.GetFileSecurityW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
+ advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW.argtypes = [ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(wintypes.LPWSTR), ctypes.POINTER(wintypes.ULONG)]
+ kernel32.LocalFree.argtypes = [ctypes.c_void_p]
+ DACL = 0x00000004
+ need = wintypes.DWORD(0)
+ advapi32.GetFileSecurityW(path, DACL, None, 0, ctypes.byref(need))
+ buf = ctypes.create_string_buffer(need.value)
+ if not advapi32.GetFileSecurityW(path, DACL, buf, need, ctypes.byref(need)):
+ return None
+ text = wintypes.LPWSTR()
+ if not advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW(buf, 1, DACL, ctypes.byref(text), None):
+ return None
+ try:
+ return text.value
+ finally:
+ kernel32.LocalFree(text)
+
class Store:
def __init__(self, folder: str):
self.path = os.path.join(folder, FILE_NAME)
self._lock = threading.Lock()
+ self._warned = False
def load(self) -> dict:
try:
@@ -37,12 +132,26 @@ class Store:
data[k] = v
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
tmp = self.path + ".tmp"
- fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
- with os.fdopen(fd, "w", encoding="utf-8") as f:
- json.dump(data, f, indent=2)
- os.replace(tmp, self.path)
try:
- os.chmod(self.path, 0o600)
+ os.remove(tmp)
except OSError:
pass
+ # A new file of our own (never one someone placed there), private before anything is written to it.
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o600)
+ try:
+ if os.name == "nt" and not owner_only(tmp) and not self._warned:
+ self._warned = True
+ log.warning("[Fuobe Connect] Couldn't make %s private to your Windows account.", self.path)
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ fd = None
+ json.dump(data, f, indent=2)
+ finally:
+ if fd is not None:
+ os.close(fd)
+ os.replace(tmp, self.path)
+ if os.name != "nt":
+ try:
+ os.chmod(self.path, 0o600)
+ except OSError:
+ pass
return data
diff --git a/integrations/fuobe-connect/pyproject.toml b/integrations/fuobe-connect/pyproject.toml
index 8f2e3018..2402c76b 100644
--- a/integrations/fuobe-connect/pyproject.toml
+++ b/integrations/fuobe-connect/pyproject.toml
@@ -1,16 +1,20 @@
[project]
-name = "comfyui-fuobe-connect"
-description = "Use this ComfyUI from Fuobe with one install: no start flag, no extra file. Trusts only the Fuobe studios you name, keeps ComfyUI's own check for every other website, and can pair with your Fuobe account for Safari, phones and PCs with no screen."
+name = "fuobe-connect"
+description = "Use this ComfyUI from Fuobe with one install: no start flag, no extra file. Trusts only the Fuobe studios you name, checks every workflow they send against the node list it ships, keeps ComfyUI's own check for every other website, and can pair with your Fuobe account for Safari, phones and PCs with no screen."
version = "1.0.0"
license = { file = "LICENSE" }
+requires-python = ">=3.9"
+# aiohttp comes with ComfyUI: naming it here could make ComfyUI-Manager change ComfyUI's own copy.
dependencies = []
+classifiers = ["Operating System :: OS Independent"]
[project.urls]
Repository = "https://github.com/workingprototype/ComfyUI-Fuobe-Connect"
-Documentation = "https://github.com/workingprototype/Fuobe/blob/main/docs/gpu-workers.md"
+Documentation = "https://github.com/workingprototype/ComfyUI-Fuobe-Connect#readme"
+"Bug Tracker" = "https://github.com/workingprototype/ComfyUI-Fuobe-Connect/issues"
[tool.comfy]
PublisherId = "workingprototype"
DisplayName = "Fuobe Connect"
-Icon = ""
+requires-comfyui = ">=0.3.0"
includes = []
diff --git a/integrations/fuobe-connect/tests/comfy_stack.py b/integrations/fuobe-connect/tests/comfy_stack.py
index 41c68795..9d13a649 100644
--- a/integrations/fuobe-connect/tests/comfy_stack.py
+++ b/integrations/fuobe-connect/tests/comfy_stack.py
@@ -6,7 +6,8 @@ torch are needed). Without it, a copy of ComfyUI 0.42's origin check is used. Ei
ComfyUI's PromptServer builds it: [cache_control, deprecation_warning] then the CORS middleware when started with
--enable-cors-header, else the origin check. Fuobe Connect then goes in front, as in ComfyUI.
-The routes answer like ComfyUI's, with fixed values: enough to see who gets in.
+The routes answer like ComfyUI's, from a small in-memory queue and history (Comfy): enough to see who gets in and what
+they see.
"""
from __future__ import annotations
@@ -19,6 +20,7 @@ import os
import socket
import urllib
import urllib.parse
+import uuid
from aiohttp import web
@@ -107,11 +109,40 @@ def comfy_middleware() -> dict:
return _from_comfyui(folder) if folder else _copy()
-def build_app(cors_flag: str | None = None, fuobe_connect=None, extra_routes=None) -> tuple[web.Application, str]:
+class Comfy:
+ """What the stand-in ComfyUI keeps: its queue, its history, and what it was sent."""
+
+ def __init__(self, mint_ids: bool = False):
+ self.mint_ids = mint_ids
+ self.history: dict = {}
+ self.queue_running: list = []
+ self.queue_pending: list = []
+ self.posts: list = []
+ self.uploads: list = []
+ self.number = 0
+
+ def entry(self, pid: str, prompt: dict, files: list | None = None) -> dict:
+ self.number += 1
+ e = {
+ "prompt": [self.number, pid, prompt, {"client_id": "x"}, ["9"]],
+ "outputs": {"9": {"images": files if files is not None else [{"filename": f"{pid[:8]}_00001_.png", "subfolder": "fuobe", "type": "output"}]}},
+ "status": {"status_str": "success", "completed": True, "messages": []},
+ }
+ self.history[pid] = e
+ return e
+
+
+# Where build_app keeps the stand-in's Comfy on the app.
+COMFY = web.AppKey("comfy", Comfy) if hasattr(web, "AppKey") else "comfy"
+
+
+def build_app(cors_flag: str | None = None, fuobe_connect=None, extra_routes=None, comfy: Comfy | None = None) -> tuple[web.Application, str]:
ns = comfy_middleware()
middlewares = [ns["cache_control"], ns["deprecation_warning"]]
middlewares.append(ns["create_cors_middleware"](cors_flag) if cors_flag else ns["create_origin_only_middleware"]())
app = web.Application(middlewares=middlewares)
+ c = comfy or Comfy()
+ app[COMFY] = c
routes = web.RouteTableDef()
@routes.get("/system_stats")
@@ -121,11 +152,75 @@ 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()
- return web.json_response({"prompt_id": body.get("prompt_id"), "number": 1})
+ 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):
+ c.entry(pid, body["prompt"])
+ return web.json_response({"prompt_id": pid, "number": 1})
+
+ @routes.get("/history")
+ async def history(request):
+ return web.json_response(c.history)
+
+ @routes.get("/history/{pid}")
+ async def history_one(request):
+ pid = request.match_info["pid"]
+ return web.json_response({pid: c.history[pid]} if pid in c.history else {})
+
+ @routes.post("/history")
+ async def history_post(request):
+ c.posts.append(("history", await request.json()))
+ return web.json_response({})
+
+ @routes.get("/queue")
+ async def queue(request):
+ return web.json_response({"queue_running": c.queue_running, "queue_pending": c.queue_pending})
+
+ @routes.post("/queue")
+ async def queue_post(request):
+ c.posts.append(("queue", await request.json()))
+ return web.json_response({})
+
+ @routes.post("/interrupt")
+ async def interrupt(request):
+ c.posts.append(("interrupt", await request.read()))
+ return web.json_response({})
+
+ @routes.get("/api/jobs")
+ async def jobs(request):
+ return web.json_response({"jobs": [{"id": pid, "status": "completed"} for pid in c.history], "has_more": False})
+
+ @routes.get("/api/jobs/{pid}")
+ async def job(request):
+ pid = request.match_info["pid"]
+ return web.json_response({"id": pid, "status": "completed"}) if pid in c.history else web.json_response({"error": "not found"}, status=404)
+
+ @routes.post("/api/jobs/{pid}/cancel")
+ async def cancel(request):
+ c.posts.append(("cancel", request.match_info["pid"]))
+ return web.json_response({"cancelled": True})
+
+ @routes.post("/upload/image")
+ async def upload(request):
+ post = await request.post()
+ image = post.get("image")
+ data = image.file.read() if hasattr(image, "file") else b""
+ c.uploads.append({"name": getattr(image, "filename", None), "type": post.get("type"), "subfolder": post.get("subfolder"), "bytes": len(data)})
+ return web.json_response({"name": getattr(image, "filename", None), "subfolder": "", "type": post.get("type", "input")})
+
+ @routes.get("/object_info")
+ async def object_info(request):
+ return web.json_response(
+ {
+ "LoadImage": {"input": {"required": {"image": [["holiday.png", "fuobe_abcdefgh12.png", "sub/me.jpg"], {"image_upload": True}]}}},
+ "LoadAudio": {"input": {"required": {"audio": ["COMBO", {"options": ["voice memo.wav", "fuobe_abcdefgh12.wav"], "audio_upload": True}]}}},
+ "CheckpointLoaderSimple": {"input": {"required": {"ckpt_name": [["model.safetensors"], {}]}}},
+ }
+ )
@routes.get("/view")
async def view(request):
- return web.Response(body=b"\x89PNG\r\n\x1a\nfake", content_type="image/png")
+ return web.Response(body=bytes([137]) + b"PNG fake", content_type="image/png")
@routes.get("/userdata/{file}")
async def userdata(request):
@@ -149,7 +244,8 @@ def build_app(cors_flag: str | None = None, fuobe_connect=None, extra_routes=Non
# ComfyUI answers every route under /api too.
api = web.RouteTableDef()
for r in routes:
- api.route(r.method, "/api" + r.path)(r.handler)
+ if not r.path.startswith("/api/"):
+ api.route(r.method, "/api" + r.path)(r.handler)
app.add_routes(api)
app.add_routes(routes)
if fuobe_connect is not None:
diff --git a/integrations/fuobe-connect/tests/pair_and_run.py b/integrations/fuobe-connect/tests/pair_and_run.py
index d39e507e..fc12eb4f 100644
--- a/integrations/fuobe-connect/tests/pair_and_run.py
+++ b/integrations/fuobe-connect/tests/pair_and_run.py
@@ -1,6 +1,10 @@
-"""Fuobe Connect's pairing and job runner outside ComfyUI, for the end-to-end test (tests/e2e/fuobe-connect.mjs in the
-Fuobe repo): it asks the studio for a code, prints it as one JSON line, waits for the approval, then runs that person's
-jobs on the ComfyUI at --comfy until it is stopped (or unpaired).
+"""Test-only: Fuobe Connect's pairing and job runner outside ComfyUI, for the end-to-end test (tests/e2e/fuobe-connect.mjs
+in the Fuobe repo), against a stand-in studio on this computer. It asks the studio for a code, prints it as one JSON
+line, waits for the approval, then runs that person's jobs on the ComfyUI at --comfy until it is stopped (or unpaired).
+
+It prints the worker token only when FUOBE_CONNECT_TEST_PRINT_TOKEN=1 (the end-to-end test needs it, with a throwaway
+studio); otherwise only its last four characters. A token to start with comes from FUOBE_CONNECT_TOKEN, never from the
+command line (where other programs on this computer could read it). Not part of the published pack.
python tests/pair_and_run.py --site http://127.0.0.1:3361 --comfy http://127.0.0.1:3362
"""
@@ -39,7 +43,8 @@ async def main(site_url: str, comfy_url: str, name: str, token: str | None):
p = await site.pair_poll(a.body["id"], a.body["secret"])
if p.status == 200 and p.body.get("state") == "approved":
token = p.body["token"]
- say(event="paired", workerId=p.body["workerId"], token=token)
+ shown = token if os.environ.get("FUOBE_CONNECT_TEST_PRINT_TOKEN") == "1" else f"…{token[-4:]}"
+ say(event="paired", workerId=p.body["workerId"], token=shown)
break
if p.status == 404:
say(event="gone")
@@ -58,6 +63,5 @@ if __name__ == "__main__":
ap.add_argument("--site", required=True)
ap.add_argument("--comfy", required=True)
ap.add_argument("--name", default="test-pc")
- ap.add_argument("--token")
args = ap.parse_args()
- sys.exit(asyncio.run(main(args.site, args.comfy, args.name, args.token)))
+ sys.exit(asyncio.run(main(args.site, args.comfy, args.name, os.environ.get("FUOBE_CONNECT_TOKEN") or None)))
diff --git a/integrations/fuobe-connect/tests/test_graph.py b/integrations/fuobe-connect/tests/test_graph.py
new file mode 100644
index 00000000..ad7a5549
--- /dev/null
+++ b/integrations/fuobe-connect/tests/test_graph.py
@@ -0,0 +1,239 @@
+"""Fuobe Connect's own graph checks (graph.py), alone: the node list, path-like text, the loaders, and what goes back
+to the studio."""
+
+from __future__ import annotations
+
+import glob
+import json
+import os
+import re
+import sys
+import tempfile
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+PACK = os.path.dirname(HERE)
+sys.path.insert(0, PACK)
+
+from fuobe_connect import __version__ # noqa: E402
+from fuobe_connect.graph import ( # noqa: E402
+ OWN_NODES_FILE,
+ NodeList,
+ graph_problem,
+ may_download,
+ refusal,
+ run_prefix,
+ safe_wanted,
+ shipped_nodes,
+ slim,
+ staged_name_ok,
+ vet_graph,
+)
+
+B = chr(92) # a backslash
+NODES = frozenset({"LoadImage", "SaveImage", "CLIPTextEncode", "Load3D", "VHS_LoadVideo", "LoadImagesFromFolderKJ", "LoadImageFromUrl", "Image Load", "Image Saver", "PrimitiveString"})
+STAGED = ["fuobe_abcdefgh12.png", "fuobe_abcdefgh34.spz"]
+
+
+def g(*nodes) -> dict:
+ return {str(i + 1): n for i, n in enumerate(nodes)}
+
+
+def node(cls, **inputs) -> dict:
+ return {"class_type": cls, "inputs": inputs}
+
+
+class NamesTest(unittest.TestCase):
+ def test_staged_names(self):
+ for ok in ["fuobe_abcdefgh12.png", "fuobe_ABC-def_1234.mp4", "fuobe_abcdefgh12.spz", "fuobe_abcdefgh12.wav"]:
+ 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)
+
+
+class VetTest(unittest.TestCase):
+ def test_unknown_node(self):
+ self.assertEqual(vet_graph(g(node("KJ_RunPython", code="import os")), NODES, STAGED), "unknown-node")
+ self.assertEqual(vet_graph(g({"inputs": {}}), NODES, STAGED), "unknown-node")
+ self.assertEqual(vet_graph({}, NODES, STAGED), "unsafe-graph")
+ self.assertEqual(vet_graph("x", NODES, STAGED), "unsafe-graph")
+
+ def test_path_like_text(self):
+ for v in [
+ "C:/Users/me/Pictures",
+ "C:" + B + "Users" + B + "me",
+ B + B + "server" + B + "share",
+ "/etc/passwd",
+ "/secret.png",
+ "../../secret.png",
+ "fuobe/" + ".." + "/x",
+ "~/.ssh/id_rsa",
+ "http://192.168.1.1/admin",
+ "https://example.com/x.png",
+ "file:///etc/passwd",
+ "blake3:0123456789abcdef",
+ "ComfyUI_00001_.png [output]",
+ "preview.png [temp]",
+ "holiday.png [input]",
+ ]:
+ self.assertEqual(vet_graph(g(node("CLIPTextEncode", text=v)), NODES, STAGED), "unsafe-path", v)
+ # Ordinary words, a staged input with its folder tag, a Fuobe prefix, a model in a subfolder: fine.
+ for v in ["a red door", "wait.. what?", "...", "fuobe/gen123abc", "flux/model.safetensors", "1/2 cup", "fuobe_abcdefgh12.png [input]"]:
+ self.assertIsNone(vet_graph(g(node("CLIPTextEncode", text=v)), NODES, STAGED), v)
+
+ def test_nodes_that_read_or_fetch(self):
+ """Nodes from common packs that read any folder, fetch a URL or write anywhere: refused by the list, and by the
+ path check when the person added them to their own list."""
+ risky = [
+ node("LoadImagesFromFolderKJ", folder="C:/Users/me/Pictures"),
+ node("LoadImageFromUrl", url="http://192.168.1.1/admin"),
+ node("Image Load", image_path="C:/ProgramData/x.png"),
+ node("Image Saver", path="C:/ProgramData/Microsoft/Windows/Start Menu", images=["1", 0]),
+ ]
+ for n in risky:
+ self.assertEqual(vet_graph(g(n), frozenset({"SaveImage"}), STAGED), "unknown-node", n)
+ self.assertEqual(vet_graph(g(n), NODES, STAGED), "unsafe-path", n)
+
+ def test_loaders_read_only_this_runs_files(self):
+ self.assertIsNone(vet_graph(g(node("LoadImage", image="fuobe_abcdefgh12.png")), NODES, STAGED))
+ self.assertIsNone(vet_graph(g(node("LoadImage", image="fuobe_abcdefgh12.png [input]")), NODES, STAGED))
+ for bad in [
+ node("LoadImage", image="my_photo.png"),
+ node("LoadImage", image="fuobe_zzzzzzzz99.png"), # a Fuobe name, but not this run's
+ node("LoadImage", image=["2", 0]), # a name another node works out
+ node("VHS_LoadVideo", video="clip.mp4"),
+ node("Load3D", model_file="3d/scene.spz"),
+ node("Load3D", model_file="fuobe_abcdefgh34.spz", image={"image": "secret.png", "camera_info": {}}),
+ ]:
+ self.assertEqual(vet_graph(g(bad, node("PrimitiveString", value="x")), NODES, STAGED), "unsafe-graph", bad)
+ self.assertIsNone(vet_graph(g(node("Load3D", model_file="fuobe_abcdefgh34.spz", image={"image": "fuobe_abcdefgh12.png", "mask": "", "camera_info": {"x": 1}})), NODES, STAGED))
+ # Direct mode doesn't know the run: any name Fuobe gives an input.
+ self.assertIsNone(graph_problem(g(node("LoadImage", image="fuobe_zzzzzzzz99.png")), None))
+ self.assertIsNotNone(graph_problem(g(node("LoadImage", image="my_photo.png")), None))
+
+ def test_studio_workflows_pass(self):
+ """Every workflow Fuobe ships uses only listed nodes and no path-like text (when the pack is inside Fuobe)."""
+ folder = os.path.join(PACK, "..", "..", "workflows", "comfyui")
+ files = [f for f in glob.glob(os.path.join(folder, "*.json")) if os.path.basename(f) not in ("requirements.json", "manifest.json", "object_info.subset.json")]
+ if not files:
+ self.skipTest("Fuobe's workflows aren't beside this copy of the pack")
+ nodes = shipped_nodes()
+ checked = 0
+ for f in files:
+ with open(f, 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
+ # Their loaders still name placeholder files (the studio stages the real ones), so only these two reasons.
+ self.assertNotIn(vet_graph(wf, nodes, None), ("unknown-node", "unsafe-path"), os.path.basename(f))
+ self.assertGreater(checked, 50)
+
+
+class NodeListTest(unittest.TestCase):
+ def test_shipped_and_own(self):
+ shipped = shipped_nodes()
+ self.assertIn("LoadImage", shipped)
+ self.assertIn("SaveImage", shipped)
+ self.assertNotIn("LoadImagesFromFolderKJ", shipped)
+ with tempfile.TemporaryDirectory() as d:
+ nodes = NodeList(d)
+ self.assertEqual(nodes(), shipped)
+ with open(os.path.join(d, OWN_NODES_FILE), "w", encoding="utf-8") as f:
+ json.dump({"nodes": ["MyOwnNode"]}, f)
+ self.assertIn("MyOwnNode", nodes())
+ os.remove(os.path.join(d, OWN_NODES_FILE))
+ self.assertNotIn("MyOwnNode", nodes())
+
+
+class ResultsTest(unittest.TestCase):
+ def test_wanted(self):
+ self.assertTrue(safe_wanted({"filename": "a.png", "subfolder": "fuobe", "type": "output"}))
+ for w in [
+ {"filename": "a.png", "subfolder": "", "type": "input"},
+ {"filename": "../a.png", "subfolder": "", "type": "output"},
+ {"filename": "a.png [input]", "subfolder": "", "type": "output"},
+ {"filename": "blake3:abc", "subfolder": "", "type": "output"},
+ {"filename": "a.png", "subfolder": "..", "type": "output"},
+ {"filename": "a.png", "subfolder": "/etc", "type": "output"},
+ {"filename": "a.png", "subfolder": "C:/x", "type": "output"},
+ ]:
+ self.assertFalse(safe_wanted(w), w)
+ entries = [{"outputs": {"9": {"images": [{"filename": "a.png", "subfolder": "fuobe", "type": "output"}]}}}]
+ self.assertTrue(may_download({"filename": "a.png", "subfolder": "fuobe", "type": "output"}, entries))
+ self.assertFalse(may_download({"filename": "b.png", "subfolder": "fuobe", "type": "output"}, entries))
+
+ def test_prefix(self):
+ graph = g(node("SaveImage", filename_prefix="fuobe/gen123abc"))
+ self.assertEqual(run_prefix("fuobe/gen123abc", graph), "fuobe/gen123abc")
+ # The person's own prefix, or one this run's graph doesn't save under: none.
+ self.assertIsNone(run_prefix("ComfyUI", g(node("SaveImage", filename_prefix="ComfyUI"))))
+ self.assertIsNone(run_prefix("fuobe/other12345", graph))
+ self.assertIsNone(run_prefix("fuobe/../x", graph))
+
+ def test_slim_drops_traceback_and_folders(self):
+ e = {
+ "prompt": [1, "p", {"big": "graph"}, {}, []],
+ "outputs": {"9": {"images": []}},
+ "status": {"status_str": "error", "completed": False, "messages": [["execution_error", {"node_id": "4", "node_type": "X", "exception_message": "No file C:" + B + "Users" + B + "alice" + B + "ComfyUI" + B + "x.png", "traceback": ["File C:/ComfyUI/nodes.py"]}]]},
+ }
+ s = slim(e)
+ self.assertEqual(s["prompt"], [1, "p"])
+ msg = s["status"]["messages"][0][1]
+ self.assertNotIn("traceback", msg)
+ self.assertNotIn("alice", msg["exception_message"])
+ self.assertEqual(msg["node_type"], "X")
+
+ def test_refusal_keeps_what_the_studio_needs(self):
+ answer = {
+ "error": {"type": "prompt_outputs_failed_validation", "message": "Prompt outputs failed validation", "details": "x", "extra_info": {}},
+ "node_errors": {
+ "4": {
+ "class_type": "CheckpointLoaderSimple",
+ "dependent_outputs": ["9"],
+ "errors": [
+ {
+ "type": "value_not_in_list",
+ "message": "Value not in list",
+ "details": "ckpt_name: 'flux.safetensors' not in ['my_private_model.safetensors', 'another.ckpt']",
+ "extra_info": {"input_name": "ckpt_name", "received_value": "flux.safetensors", "input_config": [["my_private_model.safetensors"]]},
+ }
+ ],
+ }
+ },
+ }
+ r = refusal(answer, {"flux.safetensors"})
+ text = json.dumps(r)
+ self.assertNotIn("my_private_model", text)
+ self.assertNotIn("another.ckpt", text)
+ self.assertEqual(r["node_errors"]["4"]["class_type"], "CheckpointLoaderSimple")
+ err = r["node_errors"]["4"]["errors"][0]
+ self.assertIn("not in list", err["message"])
+ self.assertEqual(err["extra_info"], {"input_name": "ckpt_name", "received_value": "flux.safetensors"})
+ # A value the graph didn't send isn't echoed.
+ self.assertNotIn("received_value", refusal(answer, {"other"})["node_errors"]["4"]["errors"][0]["extra_info"])
+ missing = refusal({"error": {"type": "missing_node_type", "message": "Node 'Foo' not found. The custom node may not be installed.", "extra_info": {"class_type": "Foo", "node_id": "3"}}})
+ self.assertEqual(missing["error"]["extra_info"], {"class_type": "Foo"})
+
+
+class PackageTest(unittest.TestCase):
+ def test_one_version(self):
+ with open(os.path.join(PACK, "pyproject.toml"), encoding="utf-8") as f:
+ text = f.read()
+ self.assertEqual(re.search(r'^version = "([^"]+)"', text, re.M).group(1), __version__)
+
+ def test_registry_metadata(self):
+ with open(os.path.join(PACK, "pyproject.toml"), encoding="utf-8") as f:
+ text = f.read()
+ name = re.search(r'^name = "([^"]+)"', text, re.M).group(1)
+ self.assertNotIn("comfyui", name.lower())
+ self.assertNotRegex(text, r'Icon = ""')
+ self.assertIn("requires-python", text)
+ self.assertIn("requires-comfyui", text)
+ with open(os.path.join(PACK, ".comfyignore"), encoding="utf-8") as f:
+ ignored = f.read().split()
+ self.assertIn("tests/", ignored)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/integrations/fuobe-connect/tests/test_middleware.py b/integrations/fuobe-connect/tests/test_middleware.py
index ef4cbaeb..6dfb733c 100644
--- a/integrations/fuobe-connect/tests/test_middleware.py
+++ b/integrations/fuobe-connect/tests/test_middleware.py
@@ -1,15 +1,17 @@
"""Fuobe Connect's middleware in front of ComfyUI's own (tests/comfy_stack.py), over real HTTP on this computer.
-Run: python -m unittest discover -s tests (from integrations/fuobe-connect). FUOBE_CONNECT_TEST_PORT picks the port
-(3360 by default); COMFYUI_DIR=<a ComfyUI folder> reads ComfyUI's own middleware from it.
+Run: python -m unittest discover -s tests (from the pack's folder). FUOBE_CONNECT_TEST_PORT picks the port (3360 by
+default); COMFYUI_DIR=<a ComfyUI folder> reads ComfyUI's own middleware from it.
"""
from __future__ import annotations
import asyncio
+import json
import os
import sys
import unittest
+import uuid
import aiohttp
from aiohttp import web
@@ -17,21 +19,36 @@ from aiohttp import web
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from comfy_stack import build_app # noqa: E402
+from comfy_stack import COMFY, Comfy, build_app # noqa: E402
from fuobe_connect import plugin # noqa: E402
-from fuobe_connect.middleware import MARKER, make_middleware # noqa: E402
-from fuobe_connect.origins import allowed, normalise, parse_list, trusted_origins # noqa: E402
+from fuobe_connect.middleware import MARKER, Studios, 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"))
BASE = f"http://127.0.0.1:{PORT}"
FUOBE = "https://fuobe.com"
EVIL = "https://evil.example"
+NODES = frozenset({"CheckpointLoaderSimple", "CLIPTextEncode", "KSampler", "VAEDecode", "SaveImage", "LoadImage", "EmptyLatentImage", "PreviewImage"})
def browser(origin: str, site: str = "cross-site", **extra) -> dict:
return {"Origin": origin, "Sec-Fetch-Site": site, "Sec-Fetch-Mode": "cors", **extra}
+def graph(**extra) -> dict:
+ g = {
+ "4": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "model.safetensors"}},
+ "6": {"class_type": "CLIPTextEncode", "inputs": {"text": "a red door", "clip": ["4", 1]}},
+ "9": {"class_type": "SaveImage", "inputs": {"filename_prefix": "fuobe/gen123abc", "images": ["8", 0]}},
+ }
+ g.update(extra)
+ return g
+
+
+def prompt_body(g=None, **extra) -> bytes:
+ return json.dumps({"prompt": g or graph(), "prompt_id": str(uuid.uuid4()), "client_id": "fuobe-abcdefgh", **extra}).encode()
+
+
class Server:
def __init__(self, app: web.Application):
self.app = app
@@ -51,6 +68,14 @@ class Server:
async with self.session.request(method, BASE + path, headers=headers or {}, **kw) as res:
return res.status, dict(res.headers), await res.read()
+ async def json(self, method: str, path: str, origin: str = FUOBE, body=None):
+ status, h, raw = await self.req(method, path, browser(origin, **({"Content-Type": "application/json"} if body is not None else {})), data=json.dumps(body).encode() if body is not None else None)
+ try:
+ data = json.loads(raw) if raw else None
+ except ValueError:
+ data = None
+ return status, h, data
+
class FakeStore:
def __init__(self, data=None):
@@ -60,15 +85,20 @@ class FakeStore:
return dict(self.data)
def update(self, **c):
- self.data.update({k: v for k, v in c.items() if v is not None})
+ for k, v in c.items():
+ if v is None:
+ self.data.pop(k, None)
+ else:
+ self.data[k] = v
return self.data
-def with_connect(trusted=trusted_origins(None, None), cors_flag=None):
+def with_connect(trusted=trusted_origins(None, None), cors_flag=None, comfy=None, lan=False):
plugin._state.clear()
plugin._state["store"] = FakeStore()
routes = [("GET", "/fuobe/connect", plugin.status), ("POST", "/fuobe/connect/studios", plugin.set_studios)]
- app, source = build_app(cors_flag, make_middleware(lambda: trusted, cors_flag), routes)
+ studios = Studios(lambda: NODES)
+ app, source = build_app(cors_flag, make_middleware(lambda: trusted, cors_flag, studios, lan), routes, comfy)
return app, source
@@ -84,19 +114,70 @@ class OriginsTest(unittest.TestCase):
for bad in ["fuobe.com", "https://fuobe.com/path", "javascript:alert(1)", "null", "", "https://[email protected]", "ftp://fuobe.com"]:
self.assertIsNone(normalise(bad), bad)
+ def test_studios_are_https(self):
+ self.assertEqual(studio("https://studio.example.com"), "https://studio.example.com")
+ self.assertEqual(studio("http://localhost:3001"), "http://localhost:3001")
+ self.assertEqual(studio("http://127.0.0.1:3001"), "http://127.0.0.1:3001")
+ self.assertIsNone(studio("http://studio.example.com"))
+ self.assertIsNone(studio("http://192.168.1.5:3000"))
+ self.assertEqual(parse_list("http://studio.example.com, https://fuobe.com"), ["https://fuobe.com"])
+
def test_trusted(self):
self.assertEqual(trusted_origins(None, None), ("https://fuobe.com", "https://www.fuobe.com"))
self.assertEqual(trusted_origins("https://studio.example.com", ["https://fuobe.com"]), ("https://studio.example.com",))
self.assertEqual(trusted_origins(None, "https://a.example, https://b.example:8443"), ("https://a.example", "https://b.example:8443"))
self.assertEqual(parse_list("nonsense"), [])
+ # "none", or a saved empty list: no website at all.
+ self.assertEqual(trusted_origins("none", None), ())
+ self.assertEqual(trusted_origins(None, []), ())
+ self.assertEqual(trusted_origins(None, "none"), ())
+ self.assertEqual(trusted_origins("", None), ("https://fuobe.com", "https://www.fuobe.com"))
def test_allowed_paths(self):
- for m, p in [("GET", "/system_stats"), ("GET", "/api/system_stats"), ("POST", "/prompt"), ("POST", "/upload/image"), ("GET", "/ws"), ("GET", "/history/0f0e0d0c-0000-4000-8000-000000000000"), ("POST", "/api/jobs/0f0e0d0c-0000-4000-8000-000000000000/cancel"), ("GET", "/v2/customnode/installed")]:
- self.assertTrue(allowed(m, p), p)
- for m, p in [("GET", "/userdata/comfy.settings.json"), ("POST", "/v2/manager/queue/install"), ("POST", "/history"), ("POST", "/fuobe/connect/studios"), ("POST", "/fuobe/connect/pair"), ("DELETE", "/prompt"), ("GET", "/internal/logs")]:
- self.assertFalse(allowed(m, p), p)
- self.assertFalse(allowed("GET", "/view", "filename=a.png&type=input&subfolder="))
+ uid = "0f0e0d0c-0000-4000-8000-000000000000"
+ for m, p, q in [("GET", "/system_stats", ""), ("GET", "/api/system_stats", ""), ("POST", "/prompt", ""), ("POST", "/upload/image", ""), ("GET", "/ws", "clientId=fuobe-abcdefgh"), ("GET", f"/history/{uid}", ""), ("GET", "/history", "max_items=64"), ("POST", f"/api/jobs/{uid}/cancel", ""), ("GET", "/v2/customnode/installed", ""), ("POST", "/history", "")]:
+ self.assertTrue(allowed(m, p, q), p)
+ for m, p, q in [("GET", "/userdata/comfy.settings.json", ""), ("POST", "/v2/manager/queue/install", ""), ("POST", "/fuobe/connect/studios", ""), ("POST", "/fuobe/connect/pair", ""), ("DELETE", "/prompt", ""), ("GET", "/internal/logs", ""), ("GET", "/history", ""), ("GET", "/history", "max_items=64&offset=0"), ("GET", "/history/not-a-uuid", "")]:
+ self.assertFalse(allowed(m, p, q), p)
+
+ def test_paths_match_whole(self):
+ # Python's "$" also matches before a final newline: the lists match the whole path.
+ self.assertFalse(allowed("GET", "/system_stats\n"))
+ self.assertFalse(allowed("GET", "/history/0f0e0d0c-0000-4000-8000-000000000000\n"))
+ self.assertFalse(allowed("POST", "/prompt\n"))
+
+ def test_view_only_results(self):
self.assertTrue(allowed("GET", "/view", "filename=a.png&type=output&subfolder="))
+ self.assertTrue(allowed("GET", "/view", "filename=a.png&type=temp&subfolder=fuobe"))
+ for q in [
+ "filename=a.png&type=input&subfolder=",
+ # ComfyUI reads a " [input]" tag on the name before the type.
+ "filename=photo.png%20%5Binput%5D&type=output&subfolder=",
+ "filename=photo.png%20[input]&type=output",
+ "filename=photo.png%20[output]&type=temp",
+ "filename=blake3:0123abcd&type=output",
+ "filename=a.png&type=output&subfolder=..",
+ "filename=a.png&type=output&subfolder=fuobe/../..",
+ "filename=a.png&type=output&subfolder=/etc",
+ "filename=a.png&type=output&subfolder=C:/Users",
+ "filename=../a.png&type=output",
+ "filename=a.png&type=output&channel=a",
+ ]:
+ self.assertFalse(allowed("GET", "/view", q), q)
+
+ def test_ws_only_fuobe_ids(self):
+ self.assertTrue(allowed("GET", "/ws", "clientId=fuobe-abcdefgh"))
+ self.assertTrue(allowed("GET", "/ws", "clientId=fuobe-live-0123456789abcdef"))
+ for q in ["", "clientId=0123456789abcdef0123456789abcdef", "clientId=fuobe-abc", "clientId=fuobe-abcdefgh&x=1"]:
+ self.assertFalse(allowed("GET", "/ws", q), q)
+
+ def test_same_host_ports(self):
+ self.assertTrue(same_host("http://127.0.0.1:8188", "127.0.0.1:8188"))
+ # A page on port 80 isn't ComfyUI's own page on 8188.
+ self.assertFalse(same_host("http://localhost", "localhost:8188"))
+ self.assertFalse(same_host("http://127.0.0.1", "127.0.0.1:8188"))
+ self.assertTrue(same_host("http://localhost", "localhost"))
+ self.assertTrue(same_host("https://comfy.example", "comfy.example:443"))
class WithoutConnectTest(unittest.TestCase):
@@ -125,14 +206,179 @@ class DirectModeTest(unittest.TestCase):
self.assertIn(b"comfyui_version", body)
status, h, _ = await s.req("GET", "/api/system_stats", browser("https://www.fuobe.com"))
self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, "https://www.fuobe.com"))
- status, h, body = await s.req("POST", "/prompt", browser(FUOBE, **{"Content-Type": "application/json"}), data=b'{"prompt_id":"p1"}')
- self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE))
- self.assertIn(b"p1", body)
- status, h, _ = await s.req("GET", "/view?filename=a.png&subfolder=&type=output", browser(FUOBE))
+ pid = str(uuid.uuid4())
+ status, h, data = await s.json("POST", "/prompt", body={"prompt": graph(), "prompt_id": pid, "client_id": "fuobe-abcdefgh", "extra_data": {"preview_method": "auto"}})
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (200, FUOBE), data)
+ self.assertEqual(data["prompt_id"], pid)
+ # Its own prompt's history, then its result.
+ status, _, data = await s.json("GET", f"/history/{pid}")
+ self.assertEqual(list(data), [pid])
+ f = data[pid]["outputs"]["9"]["images"][0]
+ status, _, _ = await s.req("GET", f"/view?filename={f['filename']}&subfolder={f['subfolder']}&type=output", browser(FUOBE))
self.assertEqual(status, 200)
run(go())
+ def test_prompt_is_checked_here(self):
+ """Whatever the studio's own page checked: the pack checks every prompt in Python."""
+
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ refused = {
+ "a node this pack doesn't ship": graph(**{"10": {"class_type": "Image Load", "inputs": {"image_path": "C:/Users/me/secret.png"}}}),
+ "an absolute path": graph(**{"10": {"class_type": "SaveImage", "inputs": {"filename_prefix": "/etc/cron.d/x", "images": ["8", 0]}}}),
+ "a Windows path": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "C:\\Users\\me\\x.png", "clip": ["4", 1]}}}),
+ "a URL": graph(**{"6": {"class_type": "CLIPTextEncode", "inputs": {"text": "http://192.168.1.1/admin", "clip": ["4", 1]}}}),
+ "a .. step": graph(**{"10": {"class_type": "SaveImage", "inputs": {"filename_prefix": "../../startup", "images": ["8", 0]}}}),
+ "a file of yours": graph(**{"10": {"class_type": "LoadImage", "inputs": {"image": "holiday.png"}}}),
+ "your output": graph(**{"10": {"class_type": "LoadImage", "inputs": {"image": "ComfyUI_00001_.png [output]"}}}),
+ "a name from another node": graph(**{"10": {"class_type": "LoadImage", "inputs": {"image": ["6", 0]}}}),
+ }
+ for why, g in refused.items():
+ status, h, data = await s.json("POST", "/prompt", body={"prompt": g, "prompt_id": str(uuid.uuid4())})
+ self.assertEqual(status, 400, why)
+ self.assertEqual(h.get("Access-Control-Allow-Origin"), FUOBE)
+ self.assertEqual(data["error"]["type"], "fuobe_connect_refused", why)
+ for why, body in {
+ "no prompt id": {"prompt": graph()},
+ "a prompt id that isn't a UUID": {"prompt": graph(), "prompt_id": "../manager/reboot"},
+ "another client's socket": {"prompt": graph(), "prompt_id": str(uuid.uuid4()), "client_id": "0123456789abcdef"},
+ "an unknown field": {"prompt": graph(), "prompt_id": str(uuid.uuid4()), "number": -1},
+ "extra data a run never sends": {"prompt": graph(), "prompt_id": str(uuid.uuid4()), "extra_data": {"extra_pnginfo": {}}},
+ }.items():
+ status, _, _ = await s.json("POST", "/prompt", body=body)
+ self.assertEqual(status, 400, why)
+ self.assertEqual(app[COMFY].posts, [])
+ # Its own staged input is fine.
+ status, _, _ = await s.json("POST", "/prompt", body={"prompt": graph(**{"10": {"class_type": "LoadImage", "inputs": {"image": "fuobe_abcdefgh12.png"}}}), "prompt_id": str(uuid.uuid4())})
+ self.assertEqual(status, 200)
+
+ run(go())
+
+ def test_upload_only_run_inputs(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+
+ async def up(name, **fields):
+ form = aiohttp.FormData()
+ form.add_field("image", b"data", filename=name, content_type="image/png")
+ for k, v in fields.items():
+ form.add_field(k, v)
+ async with s.session.post(BASE + "/upload/image", data=form, headers=browser(FUOBE)) as res:
+ return res.status
+
+ self.assertEqual(await up("fuobe_abcdefgh12.png", type="input", overwrite="true"), 200)
+ self.assertEqual(app[COMFY].uploads[-1], {"name": "fuobe_abcdefgh12.png", "type": "input", "subfolder": None, "bytes": 4})
+ for name, fields in [
+ ("my_photo.png", {"type": "input", "overwrite": "true"}),
+ ("fuobe_abcdefgh12.html", {"type": "input"}),
+ ("fuobe_abcdefgh12.svg", {"type": "input"}),
+ ("fuobe_abcdefgh12.png", {"type": "output"}),
+ ("fuobe_abcdefgh12.png", {"type": "temp"}),
+ ("fuobe_abcdefgh12.png", {"type": "input", "subfolder": "../../custom_nodes"}),
+ ("fuobe_abcdefgh12.png", {"type": "input", "original_ref": "{}"}),
+ ]:
+ self.assertEqual(await up(name, **fields), 403, (name, fields))
+ self.assertEqual(len(app[COMFY].uploads), 1)
+
+ run(go())
+
+ def test_studio_sees_only_its_own_prompts(self):
+ async def go():
+ comfy = Comfy()
+ yours = str(uuid.uuid4())
+ comfy.entry(yours, {"1": {"class_type": "SaveImage", "inputs": {"filename_prefix": "ComfyUI"}}}, [{"filename": "ComfyUI_00001_.png", "subfolder": "", "type": "output"}])
+ batch = str(uuid.uuid4())
+ comfy.entry(batch, {"1": {"class_type": "SaveImage", "inputs": {"filename_prefix": "fuobe/gen123abc"}}}, [{"filename": "gen123abc_00002_.png", "subfolder": "fuobe", "type": "output"}])
+ running = str(uuid.uuid4())
+ comfy.queue_running = [[1, running, {"1": {"class_type": "SaveImage", "inputs": {"filename_prefix": "ComfyUI"}}}, {"client_id": "my-own-tab"}, ["1"]]]
+ app, _ = with_connect(comfy=comfy)
+ async with Server(app) as s:
+ # Your prompt's history and its file: not the studio's.
+ status, _, data = await s.json("GET", f"/history/{yours}")
+ self.assertEqual((status, data), (200, {}))
+ status, _, _ = await s.req("GET", "/view?filename=ComfyUI_00001_.png&subfolder=&type=output", browser(FUOBE))
+ self.assertEqual(status, 403)
+ status, _, data = await s.json("GET", f"/api/jobs/{yours}")
+ self.assertEqual(status, 404)
+ # The last prompts: only Fuobe's (a batch's passes under fuobe/<id>).
+ status, _, data = await s.json("GET", "/history?max_items=64")
+ self.assertEqual(list(data), [batch])
+ status, _, _ = await s.req("GET", "/view?filename=gen123abc_00002_.png&subfolder=fuobe&type=output", browser(FUOBE))
+ self.assertEqual(status, 200)
+ status, _, data = await s.json("GET", "/api/jobs")
+ self.assertEqual([j["id"] for j in data["jobs"]], [batch])
+ # The queue: your prompt keeps its place, with nothing else about it.
+ status, _, data = await s.json("GET", "/queue")
+ self.assertEqual(data["queue_running"], [[1, None, None, {}, []]])
+ # The bare history list is not for studios.
+ status, _, _ = await s.req("GET", "/history", browser(FUOBE))
+ self.assertEqual(status, 403)
+ # ComfyUI's own page still sees everything.
+ status, _, raw = await s.req("GET", "/history", {"Origin": BASE, "Sec-Fetch-Site": "same-origin"})
+ self.assertEqual(set(json.loads(raw)), {yours, batch})
+
+ run(go())
+
+ def test_studio_controls_only_its_own_prompts(self):
+ async def go():
+ comfy = Comfy()
+ yours = str(uuid.uuid4())
+ app, _ = with_connect(comfy=comfy)
+ async with Server(app) as s:
+ mine = str(uuid.uuid4())
+ status, _, _ = await s.json("POST", "/prompt", body={"prompt": graph(), "prompt_id": mine})
+ self.assertEqual(status, 200)
+ for body in [{"clear": True}, {"delete": [yours]}, {"delete": [mine], "clear": True}, {"delete": []}]:
+ status, _, _ = await s.json("POST", "/queue", body=body)
+ self.assertEqual(status, 403, body)
+ status, _, _ = await s.json("POST", "/queue", body={"delete": [mine]})
+ self.assertEqual(status, 200)
+ status, _, _ = await s.json("POST", "/history", body={"delete": [mine]})
+ self.assertEqual(status, 200)
+ status, _, _ = await s.json("POST", "/history", body={"clear": True})
+ self.assertEqual(status, 403)
+ status, _, _ = await s.json("POST", "/interrupt", body={})
+ self.assertEqual(status, 403)
+ status, _, _ = await s.json("POST", "/interrupt", body={"prompt_id": yours})
+ self.assertEqual(status, 403)
+ status, _, _ = await s.json("POST", "/interrupt", body={"prompt_id": mine})
+ self.assertEqual(status, 200)
+ status, _, _ = await s.json("POST", f"/api/jobs/{yours}/cancel", body={})
+ self.assertEqual(status, 403)
+ status, _, _ = await s.json("POST", f"/api/jobs/{mine}/cancel", body={})
+ self.assertEqual(status, 200)
+ self.assertEqual([p for p in comfy.posts if isinstance(p, tuple) and p[0] == "cancel"], [("cancel", mine)])
+
+ run(go())
+
+ def test_older_comfyui_names_the_prompt(self):
+ async def go():
+ comfy = Comfy(mint_ids=True)
+ app, _ = with_connect(comfy=comfy)
+ async with Server(app) as s:
+ status, _, data = await s.json("POST", "/prompt", body={"prompt": graph(), "prompt_id": str(uuid.uuid4())})
+ self.assertEqual(status, 200)
+ status, _, data = await s.json("GET", f"/history/{data['prompt_id']}")
+ self.assertEqual(len(data), 1)
+
+ run(go())
+
+ def test_input_names_stay_hidden(self):
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ status, _, data = await s.json("GET", "/object_info")
+ self.assertEqual(data["LoadImage"]["input"]["required"]["image"][0], ["fuobe_abcdefgh12.png"])
+ self.assertEqual(data["LoadAudio"]["input"]["required"]["audio"][1]["options"], ["fuobe_abcdefgh12.wav"])
+ self.assertEqual(data["CheckpointLoaderSimple"]["input"]["required"]["ckpt_name"][0], ["model.safetensors"])
+ status, _, raw = await s.req("GET", "/object_info")
+ self.assertIn(b"holiday.png", raw)
+
+ run(go())
+
def test_preflights(self):
async def go():
app, _ = with_connect()
@@ -177,11 +423,40 @@ class DirectModeTest(unittest.TestCase):
run(go())
+ def test_only_this_computer(self):
+ """A trusted studio reaches the ComfyUI on this computer, not one at a network address (unless LAN is on)."""
+
+ async def go():
+ app, _ = with_connect()
+ async with Server(app) as s:
+ for host in [f"192.168.1.5:{PORT}", f"comfy.local:{PORT}"]:
+ status, h, _ = await s.req("GET", "/system_stats", browser(FUOBE, Host=host))
+ self.assertEqual(status, 403, host)
+ self.assertNotIn("Access-Control-Allow-Origin", h)
+ for host in [f"localhost:{PORT}", f"127.0.0.1:{PORT}"]:
+ status, _, _ = await s.req("GET", "/system_stats", browser(FUOBE, Host=host))
+ self.assertEqual(status, 200, host)
+ app, _ = with_connect(lan=True)
+ async with Server(app) as s:
+ status, _, _ = await s.req("GET", "/system_stats", browser(FUOBE, Host=f"192.168.1.5:{PORT}"))
+ self.assertEqual(status, 200)
+
+ run(go())
+
+ def test_no_studio_when_none(self):
+ async def go():
+ app, _ = with_connect(trusted=trusted_origins(None, "none"))
+ async with Server(app) as s:
+ status, _, _ = await s.req("GET", "/system_stats", browser(FUOBE))
+ self.assertEqual(status, 403)
+
+ run(go())
+
def test_studio_reaches_only_what_a_run_needs(self):
async def go():
app, _ = with_connect()
async with Server(app) as s:
- for method, path in [("GET", "/userdata/comfy.settings.json"), ("POST", "/v2/manager/queue/install"), ("POST", "/fuobe/connect/studios"), ("GET", "/view?filename=a.png&subfolder=&type=input")]:
+ for method, path in [("GET", "/userdata/comfy.settings.json"), ("POST", "/v2/manager/queue/install"), ("POST", "/fuobe/connect/studios"), ("GET", "/view?filename=a.png&subfolder=&type=input"), ("GET", "/view?filename=a.png%20[input]&subfolder=&type=output")]:
status, h, _ = await s.req(method, path, browser(FUOBE, **{"Content-Type": "application/json"}), data=b'{"studios":"https://evil.example"}' if method == "POST" else None)
self.assertEqual(status, 403, path)
self.assertNotIn("Access-Control-Allow-Origin", h)
@@ -195,7 +470,7 @@ class DirectModeTest(unittest.TestCase):
async def go():
app, _ = with_connect()
async with Server(app) as s:
- status, h, _ = await s.req("POST", "/prompt", {"Origin": BASE, "Sec-Fetch-Site": "same-origin", "Content-Type": "application/json"}, data=b"{}")
+ status, h, _ = await s.req("POST", "/prompt", {"Origin": BASE, "Sec-Fetch-Site": "same-origin", "Content-Type": "application/json"}, data=b'{"prompt": {"1": {"class_type": "Anything", "inputs": {"path": "C:/x"}}}}')
self.assertEqual(status, 200)
self.assertNotIn("Access-Control-Allow-Origin", h)
status, _, _ = await s.req("GET", "/userdata/x")
@@ -207,13 +482,15 @@ class DirectModeTest(unittest.TestCase):
async def go():
app, _ = with_connect()
async with Server(app) as s:
- async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId=abc12345", headers=browser(FUOBE, **{"Sec-Fetch-Mode": "websocket"})) as ws:
+ async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId=fuobe-abc12345", headers=browser(FUOBE, **{"Sec-Fetch-Mode": "websocket"})) as ws:
msg = await ws.receive(timeout=5)
self.assertIn("status", msg.data)
- with self.assertRaises(aiohttp.WSServerHandshakeError) as e:
- async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId=abc12345", headers=browser(EVIL, **{"Sec-Fetch-Mode": "websocket"})):
- pass
- self.assertEqual(e.exception.status, 403)
+ # Your own ComfyUI tab's socket can't be taken over.
+ for origin, cid in [(FUOBE, "abc12345"), (EVIL, "fuobe-abc12345")]:
+ with self.assertRaises(aiohttp.WSServerHandshakeError) as e:
+ async with s.session.ws_connect(f"ws://127.0.0.1:{PORT}/ws?clientId={cid}", headers=browser(origin, **{"Sec-Fetch-Mode": "websocket"})):
+ pass
+ self.assertEqual(e.exception.status, 403)
run(go())
@@ -266,6 +543,23 @@ class WithCorsFlagTest(unittest.TestCase):
self.assertEqual(status, 403)
status, _, _ = await s.req("POST", "/prompt", {"Sec-Fetch-Site": "cross-site"}, data=b"{}")
self.assertEqual(status, 403)
+ # A page on another port of this computer isn't ComfyUI's own page.
+ status, _, _ = await s.req("POST", "/prompt", {"Origin": "http://127.0.0.1"}, data=b"{}")
+ self.assertEqual(status, 403)
+
+ run(go())
+
+ 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."""
+
+ async def go():
+ app, _ = with_connect(cors_flag="localhost:8080")
+ async with Server(app) as s:
+ for origin in ["null", EVIL]:
+ status, _, _ = await s.req("POST", "/prompt", {"Origin": origin, "Content-Type": "text/plain"}, data=b"{}")
+ self.assertEqual(status, 403, origin)
+ status, _, _ = await s.req("POST", "/prompt", {"Origin": BASE}, data=b"{}")
+ self.assertEqual(status, 200)
run(go())
diff --git a/integrations/fuobe-connect/tests/test_plugin.py b/integrations/fuobe-connect/tests/test_plugin.py
index 6df78131..d41d6b86 100644
--- a/integrations/fuobe-connect/tests/test_plugin.py
+++ b/integrations/fuobe-connect/tests/test_plugin.py
@@ -1,7 +1,9 @@
"""Fuobe Connect as ComfyUI loads it: __init__.py run against a stand-in of ComfyUI's server module (its PromptServer
-with ComfyUI's own middleware, tests/comfy_stack.py), then pairing through ComfyUI's page with a stand-in studio.
+with ComfyUI's own middleware, tests/comfy_stack.py), then pairing through ComfyUI's page with a stand-in studio. And
+the checks that keep its own small API to ComfyUI's own page.
-Ports: FUOBE_CONNECT_TEST_PORT + 5 for the ComfyUI stand-in, + 6 for the studio stand-in (3365 and 3366 by default).
+Ports: FUOBE_CONNECT_TEST_PORT + 4 for the page checks, + 5 for the ComfyUI stand-in, + 6 for the studio stand-in
+(3364, 3365 and 3366 by default).
"""
from __future__ import annotations
@@ -15,6 +17,7 @@ import tempfile
import time
import types
import unittest
+from unittest import mock
import aiohttp
from aiohttp import web
@@ -22,13 +25,168 @@ from aiohttp import web
HERE = os.path.dirname(os.path.abspath(__file__))
PACK = os.path.dirname(HERE)
sys.path.insert(0, HERE)
+sys.path.insert(0, PACK)
from comfy_stack import build_app # noqa: E402
+from fuobe_connect import plugin # noqa: E402
+from fuobe_connect.store import access_list # noqa: E402
BASE_PORT = int(os.environ.get("FUOBE_CONNECT_TEST_PORT", "3360"))
+PAGE_PORT = BASE_PORT + 4
COMFY_PORT = BASE_PORT + 5
SITE_PORT = BASE_PORT + 6
SITE = f"http://127.0.0.1:{SITE_PORT}"
+PAGE = f"http://127.0.0.1:{PAGE_PORT}"
+
+
+class FakeStore:
+ def __init__(self, data=None):
+ self.data = data or {}
+
+ def load(self):
+ return dict(self.data)
+
+ def update(self, **c):
+ for k, v in c.items():
+ if v is None:
+ self.data.pop(k, None)
+ else:
+ self.data[k] = v
+ return self.data
+
+
+class FakeAgent:
+ def __init__(self):
+ self.paired_with = []
+ self.paused = None
+
+ def call(self, coro):
+ import concurrent.futures
+
+ fut = concurrent.futures.Future()
+ try:
+ coro.send(None)
+ except StopIteration as e:
+ fut.set_result(e.value)
+ return fut
+
+ async def start_pairing(self, site, name=None):
+ self.paired_with.append((site, name))
+ return {"state": "pairing"}
+
+ def set_paused(self, paused):
+ self.paused = paused
+ return {"paused": paused}
+
+ def cancel_pairing(self):
+ pass
+
+ def status(self):
+ return {"state": "unpaired"}
+
+
+class OwnPageTest(unittest.TestCase):
+ """Only ComfyUI's own page (or a program here) changes the studios, pairs, or pauses: never a page whose own name
+ was pointed at this computer, a page on another port, or another website."""
+
+ def setUp(self):
+ self.env = mock.patch.dict(os.environ, {}, clear=False)
+ self.env.start()
+ for k in ("FUOBE_CONNECT_ORIGINS", "FUOBE_CONNECT_HOSTS", "FUOBE_CONNECT_SITE"):
+ os.environ.pop(k, None)
+ self.addCleanup(self.env.stop)
+ plugin._state.clear()
+ plugin._state["store"] = FakeStore()
+ self.agent = plugin._state["agent"] = FakeAgent()
+ self.addCleanup(plugin._state.clear)
+
+ def serve(self, test):
+ async def go():
+ app = web.Application()
+ app.router.add_get("/fuobe/connect", plugin.status)
+ app.router.add_post("/fuobe/connect/studios", plugin.set_studios)
+ app.router.add_post("/fuobe/connect/pair", plugin.pair)
+ app.router.add_post("/fuobe/connect/jobs", plugin.set_jobs)
+ runner = web.AppRunner(app)
+ await runner.setup()
+ await web.TCPSite(runner, "127.0.0.1", PAGE_PORT).start()
+ try:
+ async with aiohttp.ClientSession() as s:
+
+ async def req(method, path, headers=None, body=None, raw=None):
+ h = dict(headers or {})
+ data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None)
+ if body is not None and "Content-Type" not in h:
+ h["Content-Type"] = "application/json"
+ async with s.request(method, PAGE + path, headers=h, data=data) as res:
+ return res.status, await res.json(content_type=None) if res.status != 403 else None
+
+ await test(req)
+ finally:
+ await runner.cleanup()
+
+ asyncio.run(go())
+
+ def test_rebinding_and_other_pages(self):
+ async def test(req):
+ own = {"Origin": PAGE, "Sec-Fetch-Site": "same-origin"}
+ status, body = await req("GET", "/fuobe/connect", own)
+ self.assertIn("studios", body)
+ # A page at attacker.example whose name now points at 127.0.0.1: same Origin and Host, still not ComfyUI's page.
+ rebound = {"Host": f"attacker.example:{PAGE_PORT}", "Origin": f"http://attacker.example:{PAGE_PORT}", "Sec-Fetch-Site": "same-origin"}
+ status, body = await req("GET", "/fuobe/connect", rebound)
+ self.assertNotIn("studios", body)
+ for path, b in [("/fuobe/connect/studios", {"studios": "https://attacker.example"}), ("/fuobe/connect/pair", {"site": "https://attacker.example"}), ("/fuobe/connect/jobs", {"paused": False})]:
+ status, _ = await req("POST", path, rebound, b)
+ self.assertEqual(status, 403, path)
+ # A page on port 80 of this computer, another website, a form post: not ComfyUI's page either.
+ for headers in [
+ {"Origin": "http://127.0.0.1", "Host": f"127.0.0.1:{PAGE_PORT}"},
+ {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"},
+ {"Origin": PAGE, "Sec-Fetch-Site": "cross-site"},
+ ]:
+ status, _ = await req("POST", "/fuobe/connect/studios", headers, {"studios": "https://evil.example"})
+ self.assertEqual(status, 403, headers)
+ status, _ = await req("POST", "/fuobe/connect/studios", {"Origin": PAGE, "Content-Type": "text/plain"}, raw=b'{"studios":"https://evil.example"}')
+ self.assertEqual(status, 403)
+ self.assertNotIn("studios", plugin._state["store"].data)
+ # A name the person lists is ComfyUI's own page.
+ os.environ["FUOBE_CONNECT_HOSTS"] = "comfy.local"
+ status, body = await req("GET", "/fuobe/connect", {"Host": f"comfy.local:{PAGE_PORT}", "Origin": f"http://comfy.local:{PAGE_PORT}"})
+ self.assertIn("studios", body)
+
+ self.serve(test)
+
+ def test_studios_setting(self):
+ async def test(req):
+ own = {"Origin": PAGE, "Sec-Fetch-Site": "same-origin"}
+ status, body = await req("POST", "/fuobe/connect/studios", own, {"studios": "http://studio.example.com"})
+ self.assertEqual(status, 400)
+ status, body = await req("POST", "/fuobe/connect/studios", own, {"studios": "https://studio.example.com, http://localhost:3001"})
+ self.assertEqual(body["studios"], ["https://studio.example.com", "http://localhost:3001"])
+ status, body = await req("POST", "/fuobe/connect/studios", own, {"studios": "none"})
+ self.assertEqual((status, body["studios"]), (200, []))
+ self.assertEqual(plugin.trusted(), ())
+ status, body = await req("GET", "/fuobe/connect", own)
+ self.assertEqual((body["studios"], body["setting"]), ([], "none"))
+ # Pairing still works with no trusted website: with Fuobe's own studio.
+ self.assertEqual(body["pairSites"][0], "https://fuobe.com")
+
+ self.serve(test)
+
+ def test_pairs_only_with_a_trusted_studio(self):
+ async def test(req):
+ own = {"Origin": PAGE, "Sec-Fetch-Site": "same-origin"}
+ for site in ["https://attacker.example", "http://fuobe.com", "javascript:alert(1)"]:
+ status, _ = await req("POST", "/fuobe/connect/pair", own, {"site": site})
+ self.assertEqual(status, 400, site)
+ status, _ = await req("POST", "/fuobe/connect/pair", own, {"name": "Studio PC"})
+ self.assertEqual(status, 200)
+ self.assertEqual(self.agent.paired_with, [("https://fuobe.com", "Studio PC")])
+ status, body = await req("POST", "/fuobe/connect/jobs", own, {"paused": True})
+ self.assertEqual((status, self.agent.paused), (200, True))
+
+ self.serve(test)
class FakeStudio:
@@ -37,6 +195,8 @@ class FakeStudio:
def __init__(self):
self.polls = 0
self.calls: list[str] = []
+ self.url = None
+ self.unpair_status = 200
self.app = web.Application()
self.app.router.add_post("/api/gpu/pair/start", self.start)
self.app.router.add_post("/api/gpu/pair/poll", self.poll)
@@ -48,13 +208,13 @@ class FakeStudio:
self.calls.append("start")
body = await request.json()
self.name = body.get("name")
- return web.json_response({"id": "pair-1", "secret": "s" * 64, "code": "ABCD-EFGH", "url": f"{SITE}/connect?code=ABCD-EFGH", "expiresAt": 0, "pollMs": 1000})
+ return web.json_response({"id": "pair-1", "secret": "s" * 64, "code": "ABCD-EFGH", "url": self.url or f"{SITE}/connect?code=ABCD-EFGH", "expiresAt": 0, "pollMs": 1000})
async def poll(self, request):
self.polls += 1
if self.polls < 2:
return web.json_response({"state": "waiting"})
- return web.json_response({"state": "approved", "token": "fuobe_wkr_" + "T" * 43, "workerId": "w1", "name": self.name})
+ return web.json_response({"state": "approved", "token": "fuobe_wkr_" + "T" * 43, "workerId": "w1", "name": self.name, "account": "a***@example.com"})
async def beat(self, request):
self.calls.append(f"beat:{request.headers.get('Authorization', '')[:20]}")
@@ -64,8 +224,8 @@ class FakeStudio:
return web.Response(status=204)
async def unpair(self, request):
- self.calls.append("unpair")
- return web.json_response({"ok": True})
+ self.calls.append(f"unpair:{self.unpair_status}")
+ return web.json_response({"ok": self.unpair_status == 200}, status=self.unpair_status)
def load_pack(user_dir: str):
@@ -76,6 +236,7 @@ def load_pack(user_dir: str):
server.PromptServer = types.SimpleNamespace(instance=instance)
folder_paths = types.ModuleType("folder_paths")
folder_paths.get_user_directory = lambda: user_dir
+ folder_paths.get_input_directory = lambda: os.path.join(user_dir, "input")
cli_args = types.ModuleType("comfy.cli_args")
cli_args.args = types.SimpleNamespace(port=COMFY_PORT, listen="127.0.0.1", enable_cors_header=None, tls_keyfile=None)
comfy = types.ModuleType("comfy")
@@ -90,17 +251,28 @@ def load_pack(user_dir: str):
class PluginTest(unittest.TestCase):
+ def setUp(self):
+ folder = tempfile.TemporaryDirectory(prefix="fuobe-connect-user-")
+ self.addCleanup(folder.cleanup)
+ self.user_dir = folder.name
+ for patcher in (mock.patch.dict(os.environ), mock.patch.dict(sys.modules)):
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
def test_loads_into_comfyui_and_pairs(self):
- user_dir = tempfile.mkdtemp(prefix="fuobe-connect-user-")
+ user_dir = self.user_dir
module, instance = load_pack(user_dir)
+ agent_module = sys.modules["fuobe_connect_pack.fuobe_connect.agent"]
+ agent_module.REVOKE_RETRY_S = 0.3
self.assertEqual(module.NODE_CLASS_MAPPINGS, {})
self.assertEqual(module.WEB_DIRECTORY, "./web")
self.assertEqual(getattr(instance.app.middlewares[0], "__name__", ""), "fuobe_connect")
paths = {(r.method, r.path) for r in instance.routes}
- self.assertIn(("GET", "/fuobe/connect"), paths)
- self.assertIn(("POST", "/fuobe/connect/pair"), paths)
+ for p in [("GET", "/fuobe/connect"), ("POST", "/fuobe/connect/pair"), ("POST", "/fuobe/connect/jobs")]:
+ self.assertIn(p, paths)
instance.app.add_routes(instance.routes)
studio = FakeStudio()
+ file = os.path.join(user_dir, "fuobe-connect.json")
async def go():
runners = []
@@ -112,37 +284,68 @@ class PluginTest(unittest.TestCase):
try:
async with aiohttp.ClientSession() as s:
base = f"http://127.0.0.1:{COMFY_PORT}"
- async with s.get(f"{base}/fuobe/connect") as res:
- st = await res.json()
+ page = {"Origin": base, "Sec-Fetch-Site": "same-origin"}
+
+ async def status():
+ async with s.get(f"{base}/fuobe/connect") as res:
+ return await res.json()
+
+ st = await status()
self.assertEqual(st["studios"], [SITE])
self.assertEqual(st["state"], "unpaired")
# The studio itself can't start a pairing, or change the studios.
async with s.post(f"{base}/fuobe/connect/pair", json={}, headers={"Origin": SITE, "Sec-Fetch-Site": "cross-site"}) as res:
self.assertEqual(res.status, 403)
+ # An approval link that isn't on the studio's own address is refused.
+ studio.url = "javascript:alert(1)"
+ async with s.post(f"{base}/fuobe/connect/pair", json={}, headers=page) as res:
+ self.assertEqual(res.status, 502)
+ self.assertIn("approval link", (await res.json())["error"])
+ studio.url = None
# ComfyUI's own page can.
- async with s.post(f"{base}/fuobe/connect/pair", json={}, headers={"Origin": base}) as res:
+ async with s.post(f"{base}/fuobe/connect/pair", json={"name": "Studio PC"}, headers=page) as res:
body = await res.json()
self.assertEqual(res.status, 200, body)
self.assertEqual(body["pairing"]["code"], "ABCD-EFGH")
+ self.assertEqual(studio.name, "Studio PC")
deadline = time.time() + 15
while time.time() < deadline:
- async with s.get(f"{base}/fuobe/connect") as res:
- st = await res.json()
+ st = await status()
if st.get("paired") and any(c.startswith("beat:Bearer fuobe_wkr_") for c in studio.calls):
break
await asyncio.sleep(0.3)
self.assertEqual(st["paired"]["site"], SITE)
+ # The account that approved it, as the studio names it.
+ self.assertEqual(st["paired"]["account"], "a***@example.com")
self.assertTrue(any(c.startswith("beat:Bearer fuobe_wkr_") for c in studio.calls), studio.calls)
- with open(os.path.join(user_dir, "fuobe-connect.json"), encoding="utf-8") as f:
+ with open(file, encoding="utf-8") as f:
saved = json.load(f)
self.assertTrue(saved["token"].startswith("fuobe_wkr_"))
- if os.name != "nt":
- self.assertEqual(os.stat(os.path.join(user_dir, "fuobe-connect.json")).st_mode & 0o777, 0o600)
- async with s.post(f"{base}/fuobe/connect/unpair", json={}, headers={"Origin": base}) as res:
+ if os.name == "nt":
+ acl = access_list(file)
+ self.assertRegex(acl, r"^D:P\(A;;FA;;;S-1-[0-9-]+\)$")
+ else:
+ self.assertEqual(os.stat(file).st_mode & 0o777, 0o600)
+ # Pause and resume.
+ async with s.post(f"{base}/fuobe/connect/jobs", json={"paused": True}, headers=page) as res:
+ self.assertTrue((await res.json())["paused"])
+ async with s.post(f"{base}/fuobe/connect/jobs", json={"paused": False}, headers=page) as res:
+ self.assertFalse((await res.json())["paused"])
+ # Disconnect while the studio can't answer: the token stays (unused) until the studio has revoked it.
+ studio.unpair_status = 503
+ async with s.post(f"{base}/fuobe/connect/unpair", json={}, headers=page) as res:
st = await res.json()
self.assertNotIn("paired", st)
- self.assertIn("unpair", studio.calls)
- with open(os.path.join(user_dir, "fuobe-connect.json"), encoding="utf-8") as f:
+ self.assertEqual(st["revokePending"], SITE)
+ with open(file, encoding="utf-8") as f:
+ self.assertIn("token", json.load(f))
+ studio.unpair_status = 200
+ deadline = time.time() + 10
+ while time.time() < deadline and "revokePending" in await status():
+ await asyncio.sleep(0.2)
+ self.assertIn("unpair:503", studio.calls)
+ self.assertIn("unpair:200", studio.calls)
+ with open(file, encoding="utf-8") as f:
self.assertNotIn("token", json.load(f))
finally:
for r in runners:
diff --git a/integrations/fuobe-connect/tests/test_runner.py b/integrations/fuobe-connect/tests/test_runner.py
new file mode 100644
index 00000000..4cf7caaf
--- /dev/null
+++ b/integrations/fuobe-connect/tests/test_runner.py
@@ -0,0 +1,282 @@
+"""The paired runner (runner.py) with a stand-in studio and a stand-in ComfyUI, in memory: what it refuses, which ids
+reach an address, and what it reads back or takes off."""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import io
+import os
+import sys
+import tempfile
+import unittest
+import uuid
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from fuobe_connect.net import Answer, TooBig # noqa: E402
+from fuobe_connect.runner import SEND_TRIES, Runner, Stopped # noqa: E402
+
+NODES = frozenset({"LoadImage", "SaveImage", "CLIPTextEncode"})
+DATA = b"picture"
+SHA = hashlib.sha256(DATA).hexdigest()
+LEASE = "a" * 64
+
+
+class FakeSite:
+ def __init__(self, answers=None, file=DATA):
+ self.calls: list = []
+ self.answers = answers or {}
+ self.file = file
+
+ async def call(self, method, path, body=None, headers=None, data=None, timeout=60):
+ self.calls.append((method, path, body))
+ for key, a in self.answers.items():
+ if key in path and (body or {}).get("event") in (None, a.get("_event", (body or {}).get("event"))):
+ return Answer(200, {k: v for k, v in a.items() if k != "_event"}, {})
+ return Answer(200, {}, {})
+
+ async def fetch_file(self, path, limit, headers=None):
+ self.calls.append(("FILE", path, limit))
+ if len(self.file) > limit:
+ raise TooBig("big")
+ return 200, io.BytesIO(self.file), len(self.file), hashlib.sha256(self.file).hexdigest(), {}
+
+ def events(self):
+ return [c[2] for c in self.calls if c[0] == "POST" and c[1].endswith("/report")]
+
+
+class FakeComfy:
+ def __init__(self, upload_fails=False, history=None, queue=None):
+ self.calls: list = []
+ self.upload_fails = upload_fails
+ self.history = history or {}
+ self.queue = queue or {"queue_running": [], "queue_pending": []}
+ self.session = None
+ self._ssl = None
+
+ async def get_json(self, path, timeout=30):
+ self.calls.append(("GET", path))
+ if path == "/system_stats":
+ return {"system": {}, "devices": []}
+ if path == "/api/jobs":
+ raise RuntimeError("no jobs api")
+ if path == "/queue":
+ return self.queue
+ if path.startswith("/history/"):
+ pid = path[9:]
+ return {pid: self.history[pid]} if pid in self.history else {}
+ if path.startswith("/history?"):
+ return self.history
+ return {}
+
+ async def get_status(self, path):
+ self.calls.append(("GET", path))
+ return 404, None
+
+ async def post_json(self, path, body, timeout=60):
+ self.calls.append(("POST", path, body))
+ if path == "/prompt":
+ self.history[body["prompt_id"]] = {"prompt": [1, body["prompt_id"], body["prompt"]], "outputs": {"9": {"images": [{"filename": "gen_00001_.png", "subfolder": "fuobe", "type": "output"}]}}, "status": {"completed": True, "status_str": "success"}}
+ return 200, {"prompt_id": body["prompt_id"], "number": 1}
+ return 200, {}
+
+ async def upload_input(self, name, data, content_type):
+ self.calls.append(("UPLOAD", name))
+ if self.upload_fails:
+ raise ConnectionResetError("ComfyUI went away")
+ return 200
+
+ async def view(self, filename, subfolder, kind, limit=0):
+ self.calls.append(("VIEW", filename, subfolder, kind))
+ return io.BytesIO(b"result"), 6
+
+
+async def no_sleep(_s):
+ return None
+
+
+def task(**patch) -> dict:
+ t = {
+ "id": "task_abcdefgh1234",
+ "lease": LEASE,
+ "promptId": str(uuid.uuid4()),
+ "prefix": "fuobe/gen123abc",
+ "graph": {
+ "1": {"class_type": "LoadImage", "inputs": {"image": "fuobe_abcdefgh12.png"}},
+ "9": {"class_type": "SaveImage", "inputs": {"filename_prefix": "fuobe/gen123abc", "images": ["1", 0]}},
+ },
+ "inputs": [{"n": 0, "name": "fuobe_abcdefgh12.png", "size": len(DATA), "sha256": SHA, "contentType": "image/png"}],
+ }
+ t.update(patch)
+ return t
+
+
+def runner(site=None, comfy=None, **kw) -> Runner:
+ return Runner(site or FakeSite(), comfy or FakeComfy(), "connect-test", 8188, sleep=no_sleep, nodes=lambda: NODES, **kw)
+
+
+def run(coro):
+ return asyncio.run(coro)
+
+
+class VetTest(unittest.TestCase):
+ def refused(self, t, reason):
+ site = FakeSite()
+ comfy = FakeComfy()
+ jobs = []
+ run(runner(site, comfy, on_job=jobs.append).run(t))
+ self.assertEqual(site.events(), [{"event": "failed", "reason": reason}], t)
+ self.assertFalse([c for c in comfy.calls if c[0] in ("UPLOAD", "POST")], "nothing reached ComfyUI")
+ self.assertTrue(jobs and jobs[0]["state"].startswith("refused"))
+
+ def test_refusals(self):
+ self.refused(task(graph={"1": {"class_type": "KJ_RunPython", "inputs": {"code": "x"}}}), "unknown-node")
+ self.refused(task(graph={"1": {"class_type": "CLIPTextEncode", "inputs": {"text": "C:/Users/me/x.png"}}}), "unsafe-path")
+ self.refused(task(graph={"1": {"class_type": "LoadImage", "inputs": {"image": "my_photo.png"}}}), "unsafe-graph")
+ # The studio's input names: only Fuobe's own, each once, with a file type a run sends.
+ for name in ["my_photo.png", "fuobe_abcdefgh12.html", "ComfyUI_00001_.png [output]"]:
+ t = task()
+ t["inputs"][0]["name"] = name
+ t["graph"]["1"]["inputs"]["image"] = name
+ self.refused(t, "unsafe-graph")
+ t = task()
+ t["inputs"].append(dict(t["inputs"][0], n=1))
+ self.refused(t, "unsafe-graph")
+ self.refused(task(promptId="../manager/reboot"), "unsafe-graph")
+ t = task()
+ t["inputs"][0]["n"] = "0/../../x"
+ self.refused(t, "unsafe-graph")
+
+ def test_bad_task_id_is_skipped(self):
+ site = FakeSite()
+ run(runner(site).run(task(id="../../api/settings")))
+ run(runner(site).run(task(lease="x\r\nX-Evil: 1")))
+ self.assertEqual(site.calls, [])
+
+
+class RunTest(unittest.TestCase):
+ def test_a_job_runs_and_uploads_its_own_result(self):
+ site = FakeSite({"/report": {"_event": "finished", "wanted": [{"n": 0, "filename": "gen_00001_.png", "subfolder": "fuobe", "type": "output"}]}, "/outputs/0": {"received": 6, "done": True}})
+ comfy = FakeComfy()
+ with tempfile.TemporaryDirectory() as d:
+ with open(os.path.join(d, "fuobe_abcdefgh12.png"), "wb") as f:
+ f.write(DATA)
+ with open(os.path.join(d, "keep.png"), "wb") as f:
+ f.write(DATA)
+ r = runner(site, comfy, input_dir=d)
+ t = task()
+ run(r.run(t))
+ self.assertEqual(r.jobs[t["id"]]["phase"], "done")
+ self.assertIn(t["promptId"], r.own)
+ # The job's own input leaves the input folder; nothing else does.
+ self.assertEqual(sorted(os.listdir(d)), ["keep.png"])
+ self.assertIn(("VIEW", "gen_00001_.png", "fuobe", "output"), comfy.calls)
+ self.assertTrue(any(c[0] == "PUT" and c[1].startswith("/api/gpu/computer/tasks/task_abcdefgh1234/outputs/0?") for c in site.calls))
+
+ def test_follow_only_its_own_batch(self):
+ """A studio can't point the runner at your own results with another prefix (ComfyUI's default 'ComfyUI')."""
+ yours = str(uuid.uuid4())
+ comfy = FakeComfy(history={yours: {"prompt": [1, yours, {"9": {"class_type": "SaveImage", "inputs": {"filename_prefix": "ComfyUI"}}}], "outputs": {"9": {"images": [{"filename": "ComfyUI_00001_.png", "subfolder": "", "type": "output"}]}}}})
+ site = FakeSite({"/report": {"_event": "finished", "follow": "ComfyUI"}})
+ r = runner(site, comfy)
+ t = task()
+ run(r.run(t))
+ self.assertIn({"event": "failed", "reason": "unsafe-graph"}, site.events())
+ self.assertFalse(any(c[0] == "VIEW" for c in comfy.calls))
+ self.assertFalse(any(e.get("event") == "passes" for e in site.events()))
+
+ def test_resume_reads_only_its_own_prompts(self):
+ """Collecting a prompt this runner never queued: its history isn't read, so nothing of yours is uploaded."""
+ yours = str(uuid.uuid4())
+ comfy = FakeComfy(history={yours: {"prompt": [1, yours, {}], "outputs": {"9": {"images": [{"filename": "mine.png", "subfolder": "", "type": "output"}]}}}})
+ site = FakeSite()
+ r = runner(site, comfy)
+ run(r.run(task(promptId=yours, resume="collecting", wanted=[{"n": 0, "filename": "mine.png", "subfolder": "", "type": "output"}])))
+ self.assertNotIn(("GET", f"/history/{yours}"), comfy.calls)
+ self.assertFalse(any(c[0] == "VIEW" for c in comfy.calls))
+ self.assertIn({"event": "failed", "reason": "output-missing"}, site.events())
+
+ def test_a_prompt_id_already_in_use_isnt_followed(self):
+ yours = str(uuid.uuid4())
+ comfy = FakeComfy(history={yours: {"prompt": [1, yours, {}], "outputs": {}, "status": {"completed": True}}})
+ site = FakeSite()
+ run(runner(site, comfy).run(task(promptId=yours)))
+ self.assertEqual(site.events(), [{"event": "failed", "reason": "unsafe-graph"}])
+
+ def test_retries_end(self):
+ """A ComfyUI that answers but keeps failing uploads: a few tries, then comfy-error (no endless retry)."""
+ site = FakeSite()
+ comfy = FakeComfy(upload_fails=True)
+ r = runner(site, comfy)
+ run(r.run(task()))
+ self.assertEqual(len([c for c in comfy.calls if c[0] == "UPLOAD"]), SEND_TRIES)
+ self.assertEqual(site.events()[-1], {"event": "failed", "reason": "comfy-error"})
+
+ def test_input_bigger_than_said(self):
+ site = FakeSite(file=DATA * 10)
+ run(runner(site).run(task()))
+ self.assertEqual(site.events(), [{"event": "failed", "reason": "input-changed"}])
+
+ def test_refused_answer_is_slimmed(self):
+ class Refusing(FakeComfy):
+ async def post_json(self, path, body, timeout=60):
+ return 400, {"error": {"type": "prompt_outputs_failed_validation", "message": "x"}, "node_errors": {"4": {"class_type": "CheckpointLoaderSimple", "errors": [{"message": "Value not in list", "details": "ckpt_name: 'a' not in ['secret.safetensors']", "extra_info": {"received_value": "a"}}]}}}
+
+ site = FakeSite()
+ run(runner(site, Refusing()).run(task()))
+ ev = site.events()[-1]
+ self.assertEqual(ev["event"], "refused")
+ self.assertNotIn("secret.safetensors", str(ev))
+
+ def test_paused_takes_no_job(self):
+ site = FakeSite()
+ r = runner(site, paused=lambda: True)
+ r.runner = True
+ self.assertFalse(run(r.claim_and_run()))
+ self.assertFalse(any("/claim" in c[1] for c in site.calls))
+
+
+class TakeOffTest(unittest.TestCase):
+ def test_only_its_own_prompts(self):
+ yours = str(uuid.uuid4())
+ mine = str(uuid.uuid4())
+ pass_id = str(uuid.uuid4())
+ comfy = FakeComfy(queue={"queue_running": [[1, yours, {"9": {"inputs": {"filename_prefix": "ComfyUI"}}}]], "queue_pending": [[2, pass_id, {"9": {"inputs": {"filename_prefix": "fuobe/gen123abc"}}}]]})
+ r = runner(FakeSite(), comfy)
+ run(r.take_off({"task": "task_1", "promptId": yours, "prefix": "ComfyUI"}))
+ self.assertFalse([c for c in comfy.calls if c[0] == "POST"])
+ r.own.add(mine)
+ r.jobs_api = False
+ r.prefixes.add("fuobe/gen123abc")
+ comfy.queue = {"queue_running": [], "queue_pending": [[2, pass_id, {"9": {"inputs": {"filename_prefix": "fuobe/gen123abc"}}}]]}
+
+ async def go():
+ async def drop(_s):
+ comfy.queue = {"queue_running": [], "queue_pending": []}
+
+ r.sleep = drop
+ await r.take_off({"task": "task_2", "promptId": mine, "prefix": "fuobe/gen123abc"})
+
+ run(go())
+ posted = [c[1] for c in comfy.calls if c[0] == "POST"]
+ self.assertIn("/queue", posted) # its own prompt (no jobs API here)
+ self.assertIn(f"/api/jobs/{pass_id}/cancel", posted)
+ self.assertFalse(any(yours in p for p in posted))
+ self.assertIn("task_2", r.stopped_done)
+
+ def test_bad_ids(self):
+ comfy = FakeComfy()
+ r = runner(FakeSite(), comfy)
+ run(r.take_off({"task": "../x", "promptId": str(uuid.uuid4())}))
+ run(r.take_off({"task": "t1", "promptId": "../../manager/reboot"}))
+ self.assertEqual(comfy.calls, [])
+
+
+class StoppedTest(unittest.TestCase):
+ def test_stopped_is_an_exception(self):
+ self.assertTrue(issubclass(Stopped, Exception))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/integrations/fuobe-connect/web/fuobe_connect.js b/integrations/fuobe-connect/web/fuobe_connect.js
index 65c969bc..2a9ae990 100644
--- a/integrations/fuobe-connect/web/fuobe_connect.js
+++ b/integrations/fuobe-connect/web/fuobe_connect.js
@@ -1,15 +1,41 @@
// Fuobe Connect in ComfyUI's page: a setting for the studios that may use this ComfyUI, and "Connect to Fuobe"
// (pairing: a short code you approve on the studio, for Safari, phones and PCs with no screen).
+// Every value from the studio or the server goes into the page as text, never as markup.
import { app } from "../../scripts/app.js";
+import { api } from "../../scripts/api.js";
-const get = async () => (await fetch("/fuobe/connect", { cache: "no-store" })).json();
+const SETTING = "FuobeConnect.Studios";
+const DEFAULT_STUDIO = "https://fuobe.com";
+
+const call = (path, init) => (api?.fetchApi ? api.fetchApi(path, init) : fetch(path, init));
+const get = async () => {
+ const res = await call("/fuobe/connect", { cache: "no-store" });
+ if (!res.ok) throw new Error(`Fuobe Connect answered HTTP ${res.status}`);
+ return res.json();
+};
const post = async (path, body) => {
- const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}) });
+ const res = await call(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}) });
const json = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
return json;
};
+function toast(severity, detail) {
+ const t = app.extensionManager?.toast;
+ if (t?.add) t.add({ severity, summary: "Fuobe Connect", detail, life: 6000 });
+ else (severity === "error" ? console.warn : console.info)("[Fuobe Connect]", detail);
+}
+
+/** A link from the studio, opened only when it is on that studio's own address. */
+function sameSite(url, site) {
+ try {
+ const u = new URL(url);
+ return (u.protocol === "https:" || u.protocol === "http:") && u.origin === new URL(site).origin;
+ } catch {
+ return false;
+ }
+}
+
function el(tag, attrs = {}, ...children) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
@@ -31,14 +57,30 @@ function close() {
dialog = null;
}
+const when = (ms) => {
+ try {
+ return new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
+ } catch {
+ return "";
+ }
+};
+
function render(box, s) {
box.replaceChildren();
- const line = (text, style = {}) => box.append(el("p", { style: { margin: "0 0 10px", ...style } }, text));
+ const line = (text, style = {}) => box.append(el("p", { style: { margin: "0 0 10px", ...style } }, String(text ?? "")));
+ const small = { fontSize: "12px", opacity: "0.75" };
const button = (label, onclick, primary) =>
el(
"button",
{
- onclick,
+ onclick: async (e) => {
+ e.target.disabled = true;
+ try {
+ await onclick(e);
+ } catch (err) {
+ render(box, { ...s, message: String(err?.message || err) });
+ }
+ },
style: {
marginRight: "8px",
padding: "6px 12px",
@@ -51,42 +93,75 @@ function render(box, s) {
},
label,
);
+ const jobs = () => {
+ if (!s.jobs?.length) return;
+ box.append(el("p", { style: { margin: "12px 0 4px", fontWeight: "600" } }, "Last jobs"));
+ const list = el("ul", { style: { margin: "0", padding: "0 0 0 16px", maxHeight: "160px", overflowY: "auto", ...small } });
+ for (const j of s.jobs.slice(0, 10)) {
+ const nodes = (j.nodes ?? []).slice(0, 6).join(", ") + ((j.nodes?.length ?? 0) > 6 || j.more ? ", …" : "");
+ list.append(el("li", { style: { marginBottom: "4px" } }, `${when(j.at)} · ${j.state} · ${nodes}`));
+ }
+ box.append(list);
+ };
+ if (s.revokePending) {
+ line(`Stopped here. Telling ${s.revokePending} to forget this computer…`, { fontWeight: "600" });
+ line("You can also remove this computer in Fuobe's settings.", small);
+ box.append(button("Close", close));
+ return;
+ }
if (s.paired && s.state !== "unpaired") {
line(`Connected to ${s.paired.site}.`, { fontWeight: "600" });
- line(s.state === "connected" ? "Your Fuobe jobs run on this ComfyUI, even with no Fuobe tab open." : s.message || "Waiting for the studio…");
+ if (s.paired.account) line(`Approved by ${s.paired.account}.`);
+ if (s.paired.name) line(`This computer is “${s.paired.name}” on Fuobe.`, small);
+ line(s.paused ? "Fuobe jobs are paused on this computer." : s.state === "connected" ? "Your Fuobe jobs run on this ComfyUI, even with no Fuobe tab open." : s.message || "Waiting for the studio…");
box.append(
+ button(s.paused ? "Resume jobs" : "Pause jobs", async () => render(box, await post("/fuobe/connect/jobs", { paused: !s.paused }))),
button("Disconnect", async () => {
await post("/fuobe/connect/unpair");
render(box, await get());
}),
button("Close", close),
);
+ jobs();
return;
}
if (s.state === "pairing" && s.pairing) {
line("Approve this code on Fuobe, signed in:");
- box.append(el("p", { style: { fontSize: "28px", letterSpacing: "4px", fontFamily: "monospace", margin: "4px 0 12px" } }, s.pairing.code));
- box.append(button("Open Fuobe to approve", () => window.open(s.pairing.url, "_blank", "noopener"), true), button("Cancel", async () => {
- await post("/fuobe/connect/unpair");
- close();
- }));
- line(`Or open ${s.pairing.url} on any device.`, { marginTop: "10px", fontSize: "12px", opacity: "0.75" });
+ box.append(el("p", { style: { fontSize: "28px", letterSpacing: "4px", fontFamily: "monospace", margin: "4px 0 12px" } }, String(s.pairing.code ?? "")));
+ const ok = sameSite(s.pairing.url, s.pairing.site);
+ if (ok) box.append(button("Open Fuobe to approve", () => window.open(s.pairing.url, "_blank", "noopener,noreferrer"), true));
+ box.append(
+ button("Cancel", async () => {
+ await post("/fuobe/connect/unpair");
+ close();
+ }),
+ );
+ if (ok) line(`Or open ${s.pairing.url} on any device.`, { marginTop: "10px", ...small });
+ line("Only approve a code you see here, on your own Fuobe account.", small);
return;
}
line("Run your Fuobe jobs on this ComfyUI, with no browser tab open. Useful for Safari, phones and PCs with no screen.");
- if (s.message) line(s.message, { fontSize: "12px", opacity: "0.75" });
- const site = s.studios?.[0] ?? "https://fuobe.com";
+ if (s.message) line(s.message, small);
+ const site = s.pairSites?.[0] ?? s.studios?.[0] ?? DEFAULT_STUDIO;
+ const name = el("input", { type: "text", maxlength: "48", placeholder: "This computer's name (optional)", style: { width: "100%", boxSizing: "border-box", margin: "0 0 10px", padding: "6px 8px", borderRadius: "6px", border: "1px solid #666", background: "transparent", color: "inherit" } });
+ box.append(name);
+ let host = site;
+ try {
+ host = new URL(site).host;
+ } catch {}
box.append(
- button(`Connect to ${new URL(site).host}`, async (e) => {
- e.target.disabled = true;
- try {
- render(box, await post("/fuobe/connect/pair", { site }));
- } catch (err) {
- render(box, { ...s, message: String(err.message || err) });
- }
- }, true),
+ button(`Connect to ${host}`, async () => render(box, await post("/fuobe/connect/pair", { site, ...(name.value.trim() && { name: name.value.trim() }) })), true),
button("Close", close),
);
+ jobs();
+}
+
+async function refresh(box) {
+ try {
+ render(box, await get());
+ } catch (err) {
+ box.replaceChildren(el("p", { style: { margin: "0 0 10px" } }, `Fuobe Connect isn't answering: ${String(err?.message || err)}`));
+ }
}
async function open() {
@@ -97,32 +172,65 @@ async function open() {
{
role: "dialog",
"aria-label": "Fuobe Connect",
- style: { position: "fixed", top: "80px", right: "24px", zIndex: "10000", width: "360px", maxWidth: "calc(100vw - 48px)", padding: "16px", borderRadius: "10px", background: "var(--comfy-menu-bg, #222)", color: "var(--fg-color, #ddd)", boxShadow: "0 8px 30px rgba(0,0,0,.4)", font: "14px system-ui, sans-serif" },
+ style: { position: "fixed", top: "80px", right: "24px", zIndex: "10000", width: "380px", maxWidth: "calc(100vw - 48px)", padding: "16px", borderRadius: "10px", background: "var(--comfy-menu-bg, #222)", color: "var(--fg-color, #ddd)", boxShadow: "0 8px 30px rgba(0,0,0,.4)", font: "14px system-ui, sans-serif" },
},
el("p", { style: { margin: "0 0 10px", fontWeight: "700" } }, "Fuobe Connect"),
box,
);
document.body.append(dialog);
- render(box, await get());
- timer = setInterval(async () => dialog && render(box, await get()), 2000);
+ await refresh(box);
+ timer = setInterval(() => {
+ // Don't redraw while the person types a name.
+ if (dialog && !box.contains(document.activeElement)) refresh(box).catch(() => {});
+ }, 2000);
+}
+
+// The setting shows what Fuobe Connect really uses; a change it refuses is put back, with a note.
+let syncing = false;
+const settings = () => app.extensionManager?.setting;
+const shown = (s) => (s.setting ?? (s.studios?.length ? s.studios.filter((o) => !/^https:\/\/www\./.test(o) || !s.studios.includes(o.replace("://www.", "://"))).join(", ") : "none"));
+
+async function sync() {
+ try {
+ const s = await get();
+ if (s.fromEnv) toast("info", `FUOBE_CONNECT_ORIGINS is set, so these studios are used: ${(s.studios ?? []).join(", ") || "none"}. The setting changes nothing until it is removed.`);
+ const value = shown(s);
+ const st = settings();
+ if (st?.get && st?.set && st.get(SETTING) !== value) {
+ syncing = true;
+ try {
+ await st.set(SETTING, value);
+ } finally {
+ syncing = false;
+ }
+ }
+ } catch {}
}
app.registerExtension({
name: "Fuobe.Connect",
settings: [
{
- id: "FuobeConnect.Studios",
+ id: SETTING,
category: ["Fuobe Connect", "Studios", "Studios"],
name: "Fuobe studios that may use this ComfyUI",
- tooltip: "Their pages may use this ComfyUI from your browser (to run their jobs). Separate several with commas. Every other website stays out.",
+ tooltip: "Their pages may use this ComfyUI from your browser, to run their jobs: https addresses, separated by commas. Type none to let no website in (pairing still works). Every other website stays out.",
type: "text",
- defaultValue: "https://fuobe.com",
+ defaultValue: DEFAULT_STUDIO,
onChange: (value, old) => {
- if (old === undefined || value === old) return;
- post("/fuobe/connect/studios", { studios: value }).catch((e) => console.warn("[Fuobe Connect]", e));
+ if (syncing || old === undefined || value === old) return;
+ post("/fuobe/connect/studios", { studios: value })
+ .then((s) => toast("success", s.studios?.length ? `Trusted: ${s.studios.join(", ")}` : "No website may use this ComfyUI from the browser."))
+ .catch((e) => {
+ toast("error", String(e?.message || e));
+ sync();
+ });
},
},
],
commands: [{ id: "FuobeConnect.Open", label: "Connect to Fuobe", icon: "pi pi-link", function: open }],
menuCommands: [{ path: ["Extensions"], commands: ["FuobeConnect.Open"] }],
+ async setup() {
+ await sync();
+ },
});
diff --git a/scripts/build-worker.mjs b/scripts/build-worker.mjs
index 436b9b64..e29105de 100644
--- a/scripts/build-worker.mjs
+++ b/scripts/build-worker.mjs
@@ -9,6 +9,7 @@ import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
+import { studioNodes } from "./lib/studio-nodes.mjs";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const out = path.join(root, "bin/lib/worker/dist");
@@ -26,26 +27,7 @@ for (const name of SOURCES) {
fs.writeFileSync(path.join(out, `${name}.mjs`), `// Built from src/lib/${name}.ts by scripts/build-worker.mjs. Don't edit.\n${js}`);
}
-// The node allowlist.
-const index = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/requirements.json"), "utf8"));
-const nodes = new Set();
-for (const wf of Object.values(index.workflows)) {
- for (const c of wf.core) nodes.add(c);
- for (const cs of Object.values(wf.packs)) for (const c of cs) nodes.add(c);
-}
-for (const f of fs.readdirSync(path.join(root, "workflows/comfyui"))) {
- if (!f.endsWith(".json") || f === "requirements.json" || f === "manifest.json") continue;
- try {
- const g = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui", f), "utf8"));
- for (const n of Object.values(g)) if (n && typeof n === "object" && typeof n.class_type === "string") nodes.add(n.class_type);
- } catch {}
-}
-// What the graph builders add on their own (LoRA loaders, video joins, overlays…).
-const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : /\.tsx?$/.test(e.name) ? [path.join(dir, e.name)] : []));
-for (const file of [...walk(path.join(root, "src/lib")), ...walk(path.join(root, "src/server"))]) {
- for (const m of fs.readFileSync(file, "utf8").matchAll(/class_type: "([^"]+)"/g)) nodes.add(m[1]);
-}
-for (const extra of ["LoraLoader", "LoraLoaderModelOnly"]) nodes.add(extra);
-const list = [...nodes].sort();
+// The node allowlist (the same list Fuobe Connect ships: scripts/connect-nodes.mjs).
+const list = studioNodes(root);
fs.writeFileSync(path.join(out, "allowed-nodes.json"), `${JSON.stringify({ built: "scripts/build-worker.mjs", nodes: list }, null, 1)}\n`);
console.log(`worker: ${SOURCES.length} modules, ${list.length} allowed node types -> ${path.relative(root, out)}`);
diff --git a/scripts/connect-nodes.mjs b/scripts/connect-nodes.mjs
new file mode 100644
index 00000000..1070bdfd
--- /dev/null
+++ b/scripts/connect-nodes.mjs
@@ -0,0 +1,15 @@
+#!/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.
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { 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}`);
diff --git a/scripts/lib/studio-nodes.mjs b/scripts/lib/studio-nodes.mjs
new file mode 100644
index 00000000..67ad4468
--- /dev/null
+++ b/scripts/lib/studio-nodes.mjs
@@ -0,0 +1,28 @@
+// Every node type the studio's workflows and graph builders use. The worker program (scripts/build-worker.mjs) and
+// Fuobe Connect (scripts/connect-nodes.mjs) each freeze this list into what they ship: a graph with any other node is
+// refused on the person's computer, and the studio can't add to the list.
+import fs from "node:fs";
+import path from "node:path";
+
+export function studioNodes(root) {
+ const index = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui/requirements.json"), "utf8"));
+ const nodes = new Set();
+ for (const wf of Object.values(index.workflows)) {
+ for (const c of wf.core) nodes.add(c);
+ for (const cs of Object.values(wf.packs)) for (const c of cs) nodes.add(c);
+ }
+ for (const f of fs.readdirSync(path.join(root, "workflows/comfyui"))) {
+ if (!f.endsWith(".json") || f === "requirements.json" || f === "manifest.json") continue;
+ try {
+ const g = JSON.parse(fs.readFileSync(path.join(root, "workflows/comfyui", f), "utf8"));
+ for (const n of Object.values(g)) if (n && typeof n === "object" && typeof n.class_type === "string") nodes.add(n.class_type);
+ } catch {}
+ }
+ // What the graph builders add on their own (LoRA loaders, video joins, overlays…).
+ const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : /\.tsx?$/.test(e.name) ? [path.join(dir, e.name)] : []));
+ for (const file of [...walk(path.join(root, "src/lib")), ...walk(path.join(root, "src/server"))]) {
+ for (const m of fs.readFileSync(file, "utf8").matchAll(/class_type: "([^"]+)"/g)) nodes.add(m[1]);
+ }
+ for (const extra of ["LoraLoader", "LoraLoaderModelOnly"]) nodes.add(extra);
+ return [...nodes].sort();
+}
diff --git a/tests/e2e/fuobe-connect.mjs b/tests/e2e/fuobe-connect.mjs
index 468fa5bd..f9c77239 100644
--- a/tests/e2e/fuobe-connect.mjs
+++ b/tests/e2e/fuobe-connect.mjs
@@ -57,7 +57,9 @@ const fake = spawn(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE
const clients = [];
/** Fuobe Connect's runner as its own process: its JSON lines, one by one. */
function connect(name, token) {
- const p = spawn(python, [path.join(root, "integrations/fuobe-connect/tests/pair_and_run.py"), "--site", SITE, "--comfy", FAKE, "--name", name, ...(token ? ["--token", token] : [])], { stdio: ["ignore", "pipe", "pipe"] });
+ // The helper prints the worker token only when asked (this studio is a throwaway one), and takes one from the environment.
+ const env = { ...process.env, FUOBE_CONNECT_TEST_PRINT_TOKEN: "1", ...(token ? { FUOBE_CONNECT_TOKEN: token } : {}) };
+ const p = spawn(python, [path.join(root, "integrations/fuobe-connect/tests/pair_and_run.py"), "--site", SITE, "--comfy", FAKE, "--name", name], { stdio: ["ignore", "pipe", "pipe"], env });
clients.push(p);
const lines = [];
let err = "";
diff --git a/tests/fuobe-connect-nodes.test.ts b/tests/fuobe-connect-nodes.test.ts
new file mode 100644
index 00000000..0a807c08
--- /dev/null
+++ b/tests/fuobe-connect-nodes.test.ts
@@ -0,0 +1,23 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+/**
+ * Fuobe Connect (integrations/fuobe-connect) refuses a studio's graph with a node type that isn't on the list it ships.
+ * That list must hold every node the studio's workflows and graph builders use, or those runs fail on people's
+ * computers. When this fails: node scripts/connect-nodes.mjs, and ship the list with the next Fuobe Connect release.
+ */
+describe("Fuobe Connect's node list", () => {
+ it("holds every node type the studio uses", async () => {
+ const { 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")).nodes as string[];
+ const missing = (studioNodes(root) as string[]).filter((n) => !shipped.includes(n));
+ expect(missing, "run node scripts/connect-nodes.mjs").toEqual([]);
+ });
+
+ 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);
+ });
+});