Compare commits

..
9 Commits
Author SHA1 Message Date
ausboss 9986ded109 Merge pull request #356 from ausboss/fix/cache-guard-version-order
Ask for a reload only when the pack is newer than the page
2026-11-14 18:00:18 -06:00
ausboss 197ac04a8c Ask for a reload only when the pack is newer than the page
The update guard asked for a reload whenever the server's version and the
page's differed. After the Manager switches the pack on disk, the server
keeps reporting the old version until ComfyUI restarts, so a reload in
between loads the new files and the message said the page was older when
it was newer.

Now the guard speaks only when the server's version is the newer one, and
versions compare part by part as numbers. A version that is not three
plain numbers, such as "unknown", stays silent.

A page newer than the server stays silent rather than asking for a
restart: from two version numbers it cannot be told apart from a downgrade
with the tab left open, which needs a reload, and the Manager already asks
for its own restart after a switch.
2026-11-14 17:47:11 -06:00
ausboss be2a2a1444 Merge pull request #355 from ausboss/release/2.26.2
Release 2.26.2
2026-11-14 10:58:10 -06:00
ausboss 76eb4fc7e7 Release 2.26.2 2026-11-14 10:57:05 -06:00
ausboss 057f2bd05a Keep refused file names, script addresses and held runs off the disk
Three findings from the Comfy Registry's review of 2.25.2, all still in
2.26.1:

- The change check of Load Image, Load Image + Pad, Image Crop + Rotate +
  Pad and both Video Crop + Rotate + Pad nodes handed a value its resolver
  had refused to os.stat and Path.resolve. stable_file_fingerprint now
  opens only a Path a resolver returned; a refused value is hashed as text.
- The script version tagging joined the request's address to the js folder
  and resolved it before checking it. It now looks the address up in a
  list of the pack's scripts made at startup.
- Save Image's keep route read the run's list from a JSON file in the temp
  folder, which takes uploads, and built the copy source from its
  extension, so a planted list could copy a server file into output. Runs
  now stay in memory (the last 256), held pictures are named from the
  token, their number and Save Image's own formats, must sit directly in
  the held folder, and a run holds at most 10,000 pictures.
2026-11-14 10:56:27 -06:00
ausboss 172252ab02 Merge pull request #353 from ausboss/release/2.26.1
Release 2.26.1
2026-11-14 07:09:37 -06:00
ausboss ebc81ea57e Release 2.26.1 2026-11-14 07:08:54 -06:00
ausboss bc235e96e5 Merge pull request #352 from ausboss/fix/no-home-path-expansion
Stop expanding ~ paths and opening a typed LaMa model path
2026-11-14 06:53:14 -06:00
ausboss 6572b49386 Stop expanding "~" paths and opening a typed LaMa model path
Image Folder compared a pasted "~/..." path after expanding it; only a
path written out in full is compared now. LaMa Inpaint resolved a typed
path when ComfyUI's folder list was missing; it only takes a name from
models/lama now. Neither could read outside ComfyUI's folders, but both
read like it to a code scan.
2026-11-14 06:28:13 -06:00
21 changed files with 423 additions and 50 deletions
+43
View File
@@ -2,6 +2,49 @@
All notable changes to ComfyUI-AusBoss are documented here.
## Unreleased
- **The "AusBoss was updated" message no longer asks for a reload by
mistake.** After the Manager switched the pack to another version, a
page reload before ComfyUI restarted brought up the message, telling you
the page was older than the pack when it was newer. A restart was what
was needed. Now the message only comes up when the pack really is newer
than the page, and versions such as 2.25.10 and 2.25.9 are compared as
numbers.
## 2.26.2 - 2026-11-14
- **Loaders never look up a file name they refused.** Before each run,
Load Image 🆎, Load Image + Pad 🆎, Image Crop + Rotate + Pad 🆎 and both
Video Crop + Rotate + Pad nodes check whether their file changed. When the
name was one they do not accept, such as a whole path or a network share,
that check still looked it up on disk. On Windows, looking up a share
contacts its server and hands it the computer's login. Now a refused name
is only compared as text.
- **The pack's scripts are found without looking up the address.** The pack
tags its scripts with a version as the browser asks for them. It found
each one by joining the address the browser sent to its own folder and
looking the result up on disk, and only then checked that the file was
its own. Now it looks the address up in a list of its scripts made when
ComfyUI starts, so no address reaches the disk.
- **Save Image's Save button copies only pictures it holds.** With Auto
save off, the list of a run's held pictures was a file in ComfyUI's temp
folder. That folder takes uploads, so a planted list could copy another
file on the server into the output folder. The list now stays in
ComfyUI's memory, and a held picture is found only by its run, its number
and one of Save Image's formats. The Save button works for the last 256
runs, up to 10,000 pictures each; held pictures still go when ComfyUI
restarts, as before.
## 2.26.1 - 2026-11-14
- **A path that starts with `~` is no longer expanded.** Image Folder used
to turn a pasted `~/...` path into a full one before checking that it sits
inside ComfyUI's folders; now only a path written out in full is checked.
LaMa Inpaint only opens a model from ComfyUI's `models/lama` list. Nothing
outside those folders could be read before either; this removes the code
that looked as if it could.
## 2.26.0 - 2026-11-14
- **Missing LoRAs show in ComfyUI's missing-models list.** When a workflow
+3 -3
View File
@@ -1,9 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.26.0">
<title>release: v2.26.0</title>
<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20" role="img" aria-label="release: v2.26.2">
<title>release: v2.26.2</title>
<path fill="#555" d="M0 0h48v20H0z"/>
<path fill="#00b4aa" d="M48 0h57v20H48z"/>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="24" y="14">release</text>
<text x="76.5" y="14">v2.26.0</text>
<text x="76.5" y="14">v2.26.2</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 425 B

After

Width:  |  Height:  |  Size: 425 B

+20 -1
View File
@@ -49,6 +49,25 @@ function askForReload(installed) {
}
}
// "2.26.2" -> [2, 26, 2]. Anything else, such as "unknown", is null.
function parseVersion(version) {
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(typeof version === "string" ? version : "");
return match ? match.slice(1).map(Number) : null;
}
// Only a server newer than the page means this tab runs old files. The page
// is newer when the Manager switched the pack on disk and the page was
// reloaded before ComfyUI restarted, and then a restart is what is needed.
// Two version numbers cannot tell that apart from a downgrade with the tab
// left open, which needs a reload, so in that case the guard says nothing.
function serverIsNewer(installed, running) {
const server = parseVersion(installed);
const page = parseVersion(running);
if (!server || !page) return false;
const step = server.findIndex((part, index) => part !== page[index]);
return step >= 0 && server[step] > page[step];
}
// The installed version this page already asked a reload for. A server that
// drops and comes back several times must not stack the same message.
let asked = null;
@@ -58,7 +77,7 @@ async function check() {
try {
const installed = (await (await api.fetchApi("/ausboss/pack_version")).json())?.version;
const running = await runningVersion();
if (!installed || installed === "unknown" || !running || installed === running || installed === asked) return;
if (!serverIsNewer(installed, running) || installed === asked) return;
asked = installed;
const listing = await (await api.fetchApi("/ausboss/pack_modules")).json();
await refreshModules(Array.isArray(listing?.modules) ? listing.modules : []);
+1 -1
View File
@@ -65,7 +65,7 @@ file's name. A caption on the `caption_text` input writes the paired `.txt`.
are saved under the name and folder set above, in the format picked,
with the workflow inside if **Embed workflow** is on. They wait in
ComfyUI's temp folder, which is emptied when ComfyUI restarts, so save
what you want before that.
what you want before that. The Save button works for the last 256 runs.
- **Preview steps** (`step_preview`, off by default): the switch left of
**preview** shows the picture while it is being made, one step at a time,
where the saved image goes, with a **STOP** button on the bar. Stop a run
+1 -1
View File
@@ -9,7 +9,7 @@ import { app } from "../../../scripts/app.js";
// Must match `version` in pyproject.toml — scripts/release_preflight.py
// enforces it. The backend serves its copy at /ausboss/pack_version; a
// mismatch means the browser cached JavaScript from an older install.
export const AUSBOSS_JS_VERSION = "2.26.0";
export const AUSBOSS_JS_VERSION = "2.26.2";
export const BRAND = "#00b4aa"; // AusBoss teal — keep node accents consistent.
export const BRAND_DARK = "#007f78";
+25 -5
View File
@@ -60,6 +60,26 @@ def add_module_version(source, token):
return _MODULE_IMPORT.sub(lambda m: f"{m.group(1)}{m.group(2)}{m.group(3)}?v={token}{m.group(2)}", source)
def list_served_scripts(js_root):
"""The pack's own scripts by their address below the js folder:
{"shared/index.mjs": <path>}. Made once at startup, so a request is
only looked up in it and the address a browser sends never reaches the
disk: no whole path, network share or ".." is ever opened. Links are
left out, and anything that resolves outside the js folder."""
root = Path(js_root).resolve()
scripts = {}
for path in sorted(root.rglob("*")):
try:
if path.suffix not in (".js", ".mjs") or path.is_symlink() or not path.is_file():
continue
if not path.resolve().is_relative_to(root):
continue
except OSError:
continue
scripts[path.relative_to(root).as_posix()] = path
return scripts
def make_revalidate_middleware(pack_name, js_root=None, token=None):
"""aiohttp middleware for this pack's scripts, nothing else touched.
@@ -69,7 +89,7 @@ def make_revalidate_middleware(pack_name, js_root=None, token=None):
from aiohttp import web
marker = f"/extensions/{pack_name}/"
root = Path(js_root).resolve() if js_root and token else None
scripts = list_served_scripts(js_root) if js_root and token else None
served = {}
def versioned(path):
@@ -90,15 +110,15 @@ def make_revalidate_middleware(pack_name, js_root=None, token=None):
def tagged_response(request):
"""The tagged script for this request, or None to let ComfyUI serve it."""
if root is None or request.method not in ("GET", "HEAD"):
if not scripts or request.method not in ("GET", "HEAD"):
return None
start = request.path.find(marker)
if start < 0 or not request.path.endswith((".js", ".mjs")):
return None
target = scripts.get(request.path[start + len(marker):])
if target is None:
return None
try:
target = (root / request.path[start + len(marker):]).resolve()
if not target.is_relative_to(root) or not target.is_file():
return None
found = versioned(target)
except (OSError, ValueError, UnicodeDecodeError):
return None
+3 -2
View File
@@ -82,9 +82,10 @@ def place_inside(folder, roots: dict) -> tuple[str, str] | None:
This compares text only. A path that is outside those folders is never
looked up on disk, and one on another machine is refused from its text."""
text = str(folder or "").strip().strip('"').replace("\\", "/")
if not looks_full(text) or text.startswith("//"):
# A "~" path is not expanded: only a path written out in full can match.
if not looks_full(text) or text.startswith("//") or text.startswith("~"):
return None
full = os.path.normpath(os.path.expanduser(text))
full = os.path.normpath(text)
for source, root in roots.items():
for base in {os.path.normpath(str(root)), os.path.realpath(str(root))}:
if full == base:
+45 -12
View File
@@ -6,18 +6,26 @@ that are wanted: they are copied into the output folder under the names the
node would have given them. Everything here works from names this module
made itself; the only thing a caller sends is the run's token and which
pictures to keep.
What a run holds (its settings, its count, what was kept) stays in this
process's memory, never in a file. ComfyUI's temp folder takes uploads, so a
list read back from there could be anyone's. The held pictures themselves
are named from the token, their number and one of the node's own formats,
and must still be in the held folder when they are copied.
"""
from __future__ import annotations
from collections import OrderedDict
from datetime import datetime
import json
from pathlib import Path
import re
import secrets
import shutil
import threading
from ._image_save_helpers import (
FORMAT_EXTENSIONS,
IMAGE_SAVE_LOCK,
existing_action,
name_stem,
@@ -34,6 +42,14 @@ from ._image_save_helpers import (
HELD_FOLDER = "ausboss_held"
_TOKEN = re.compile(r"^[0-9a-f]{16}$")
GONE = "These pictures are no longer held. Run the workflow again."
# The held pictures' formats: the extensions Save Image writes, nothing else.
HELD_EXTENSIONS = frozenset(FORMAT_EXTENSIONS.values())
# A run holds at most this many pictures, and the server remembers this many
# runs; the oldest is forgotten first and then says GONE.
MAX_HELD_PICTURES = 10000
MAX_HELD_RUNS = 256
_RUNS: "OrderedDict[str, dict]" = OrderedDict()
_RUNS_LOCK = threading.Lock()
def plan_destinations(settings: dict, count: int, now: datetime, root: Path, output_root: Path, picks=None):
@@ -88,15 +104,31 @@ def settle_destinations(planned, has_caption: bool, output_root: Path) -> list[s
def _held_name(token: str, index: int, extension: str) -> str:
if not _TOKEN.match(token) or extension not in HELD_EXTENSIONS or not 0 <= index < MAX_HELD_PICTURES:
raise ValueError("Save Image: that is not a picture it is holding.")
return f"{token}_{index:03d}.{extension}"
def _held_source(folder: Path, token: str, index: int, extension: str) -> Path:
"""A held picture's file, which must still sit directly in the held folder."""
source = folder / _held_name(token, index, extension)
if not source.is_file() or source.is_symlink() or source.resolve().parent != folder.resolve():
raise LookupError(GONE)
return source
def hold_pictures(temp_root, frames, settings: dict, encode) -> tuple[str, list[dict]]:
"""Write a run's pictures to the temp folder and remember how to name them.
`encode(path, frame)` writes one picture in the run's format. Returns
the run's token and the entries the node shows them from.
"""
frames = list(frames)
if len(frames) > MAX_HELD_PICTURES:
raise ValueError(
f"Save Image: {len(frames)} pictures are too many to hold (at most {MAX_HELD_PICTURES}). "
"Turn Auto save on to save them straight away."
)
folder = Path(temp_root) / HELD_FOLDER
folder.mkdir(parents=True, exist_ok=True)
token = secrets.token_hex(8)
@@ -105,8 +137,10 @@ def hold_pictures(temp_root, frames, settings: dict, encode) -> tuple[str, list[
name = _held_name(token, index, settings["extension"])
encode(folder / name, frame)
previews.append({"filename": name, "subfolder": HELD_FOLDER, "type": "temp"})
manifest = dict(settings, count=len(previews), kept={})
(folder / f"{token}.json").write_text(json.dumps(manifest), encoding="utf-8")
with _RUNS_LOCK:
_RUNS[token] = dict(settings, count=len(previews), kept={})
while len(_RUNS) > MAX_HELD_RUNS:
_RUNS.popitem(last=False)
return token, previews
@@ -119,16 +153,18 @@ def keep_pictures(temp_root, output_root, token, picks=None, now: datetime | Non
if not isinstance(token, str) or not _TOKEN.match(token):
raise ValueError("Save Image: that is not a run it is holding.")
folder = Path(temp_root) / HELD_FOLDER
manifest_path = folder / f"{token}.json"
if not manifest_path.is_file():
with _RUNS_LOCK:
manifest = _RUNS.get(token)
if manifest is None:
raise LookupError(GONE)
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
count = int(manifest["count"])
kept = {int(index): str(path) for index, path in dict(manifest.get("kept") or {}).items()}
kept = dict(manifest["kept"])
if picks is None:
wanted = list(range(count))
else:
if len(picks) > MAX_HELD_PICTURES:
raise ValueError("Save Image: that picture is not in this run.")
wanted = []
for pick in picks:
if isinstance(pick, bool) or not isinstance(pick, int) or not 0 <= pick < count:
@@ -151,17 +187,14 @@ def keep_pictures(temp_root, output_root, token, picks=None, now: datetime | Non
if action == "skip":
skipped.append(index)
continue
source = folder / _held_name(token, index, manifest["extension"])
if not source.is_file():
raise LookupError(GONE)
source = _held_source(folder, token, index, manifest["extension"])
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, path)
if has_caption:
sidecar_path(path).write_text(caption, encoding="utf-8")
kept[index] = path.resolve().relative_to(resolved_root).as_posix()
saved.append(index)
manifest["kept"] = {str(index): path for index, path in kept.items()}
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
manifest["kept"] = kept
return {
"count": count,
"saved": [{"index": index, "path": kept[index]} for index in saved],
+2 -5
View File
@@ -61,11 +61,8 @@ def list_lama_models() -> list[str]:
def resolve_lama_model(model_name: str) -> Path:
register_lama_model_folder()
if folder_paths is None:
path = Path(model_name).expanduser().resolve()
if path.is_file():
return path
else:
# Only a name from ComfyUI's lama model folder: a typed path is never opened.
if folder_paths is not None:
resolved = folder_paths.get_full_path(MODEL_FOLDER, model_name)
if resolved:
return Path(resolved).resolve()
+19 -11
View File
@@ -480,17 +480,25 @@ def transform_tensor_batch_chunked(
return output, mask, geometry
def stable_file_fingerprint(path: str | os.PathLike[str], inputs: dict[str, object]) -> str:
normalized_path = str(Path(path).resolve()).casefold()
try:
stat = os.stat(path)
file_state: dict[str, object] = {
"path": normalized_path,
"mtime_ns": stat.st_mtime_ns,
"size": stat.st_size,
}
except OSError:
file_state = {"path": normalized_path, "missing": True}
def stable_file_fingerprint(path: Path | None, inputs: dict[str, object]) -> str:
"""A key that changes when the inputs or the file do.
`path` is what resolve_input_path or resolve_video_path returned, or
None when they refused the value. Only such a path is ever looked at on
disk: a refused value is a string, and a string is only hashed, so a
whole path or a network share typed into a widget is never opened."""
if isinstance(path, Path):
try:
stat = os.stat(path)
file_state: dict[str, object] = {
"path": str(path).casefold(),
"mtime_ns": stat.st_mtime_ns,
"size": stat.st_size,
}
except OSError:
file_state = {"path": str(path).casefold(), "missing": True}
else:
file_state = {"unresolved": True}
payload = {"file": file_state, "inputs": inputs}
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
+1 -1
View File
@@ -168,7 +168,7 @@ class AusBossImageCropRotatePad:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
# Every widget value is already part of ComfyUI's cache key, so a
# changed transform or budget re-runs the node without this; the
+1 -1
View File
@@ -253,7 +253,7 @@ class AusBossLoadImage:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
return stable_file_fingerprint(path, {"image": image, **values})
+1 -1
View File
@@ -403,7 +403,7 @@ class AusBossLoadImagePad:
try:
path = resolve_input_path(image)
except Exception:
path = image or ""
path = None # refused: hashed by its text only, never opened
return stable_file_fingerprint(path, {"image": image, **values})
+2 -1
View File
@@ -152,7 +152,7 @@ class AusBossVideoCropRotatePad:
try:
path = resolve_video_path(source_mode, video, local_path)
except Exception:
path = local_path if source_mode == "local path" else video
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
resize = {name: values.get(name) for name in resize_inputs()}
return stable_file_fingerprint(
@@ -160,6 +160,7 @@ class AusBossVideoCropRotatePad:
{
"video": video,
"source_mode": source_mode,
"local_path": local_path,
"seek_mode": seek_mode,
"frame_index": int(frame_index),
"frame_time": round(float(frame_time), 6),
+2 -1
View File
@@ -395,7 +395,7 @@ class AusBossVideoCropRotatePadClip:
try:
path = resolve_video_path(source_mode, video, local_path)
except Exception:
path = local_path if source_mode == "local path" else video
path = None # refused: hashed by its text only, never opened
spec = spec_from_values(**values)
resize = {name: values.get(name) for name in resize_inputs()}
return stable_file_fingerprint(
@@ -403,6 +403,7 @@ class AusBossVideoCropRotatePadClip:
{
"video": video,
"source_mode": source_mode,
"local_path": local_path,
"start_seconds": round(float(start_seconds), 6),
"end_seconds": round(float(end_seconds), 6),
"every_nth": max(1, int(every_nth)),
+1 -1
View File
@@ -3,7 +3,7 @@ name = "ausboss-nodes"
# Manager/registry search matches against this text, so it names the actual
# nodes instead of describing the collection abstractly.
description = "ComfyUI-AusBoss (AusBoss nodes): image and video nodes with compact controls: Image and Video Crop + Rotate + Pad (frame or clip), Load Image, Load Image + Pad, Image Folder, Image Resize, Align Image, Image Size, Color Match, Image Compare A/B, Realign to Source (experimental), Save Image (PNG, WebP/JXL, captions), Load Video, Load Audio, Save Video, Select Frame, Frame Interpolate, Mask Refine, Mask by Name and Mask by Touch, LaMa Inpaint, Crop For Inpaint, Stitch Inpaint, Tiled Upscale and Tiled Upscale Stitch, FlashVSR Upscale, Edit Lock and Edit Lock Restore, LoRA Loader, Krea 2 Encode and Outpaint Model Patch, Latent Size, Layout Boxes, Seed, Select Every Nth, Split Batch, Merge Batches, Text, Text Lines, Prompt Variations, H3 Prompt Writer, Integer, Float, Math Expression, Show Text, Free Memory, Workflow Note, Workflow Note Tile, Callout, Callout Tile, Workflow Switches, Run Timer, and Step Preview. Example workflows for Qwen Image 2.1, Krea 2, Klein 9B and LTX 2.3."
version = "2.26.0"
version = "2.26.2"
# comfy-cli serializes this to JSON verbatim, so `file` publishes the literal
# string {"file": "LICENSE"} to the registry listing. `text` puts a readable
# name there instead. Both forms are supported; the LICENSE file is unchanged.
+36
View File
@@ -102,3 +102,39 @@ test("a server that does not answer keeps the page quiet", async (t) => {
await page.serverComesBack("2.7.0");
assert.equal(page.toasts.length, 1);
});
// The Manager switches the pack's files on disk, and the server keeps running
// the old version until ComfyUI restarts. A reload in between gives the page
// the new files: the page is newer than the server, and "press F5" is wrong.
test("a page newer than the server says nothing", async (t) => {
const page = await openPage(t, { running: "2.26.2", installed: "2.25.2" });
assert.deepEqual(page.toasts, []);
assert.deepEqual(page.refreshed, []);
await page.serverComesBack("2.26.2");
assert.deepEqual(page.toasts, [], "after the restart the two match");
});
test("versions compare as numbers, not as text", async (t) => {
const older = await openPage(t, { running: "2.25.10", installed: "2.25.9" });
assert.deepEqual(older.toasts, [], "2.25.9 is older than 2.25.10");
const newer = await openPage(t, { running: "2.25.9", installed: "2.25.10" });
assert.equal(newer.toasts.length, 1, "2.25.10 is newer than 2.25.9");
assert.match(newer.toasts[0].detail, /v2\.25\.10 is installed/);
});
test("an unknown or odd version says nothing", async (t) => {
for (const [running, installed] of [
["2.26.2", "unknown"],
["2.26.2", "2.27"],
["2.26.2", "2.27.0rc1"],
["2.26.2", "v2.27.0"],
["2.26.2", 3],
["unknown", "2.27.0"],
["dev", "2.27.0"],
[null, "2.27.0"],
]) {
const page = await openPage(t, { running, installed });
assert.deepEqual(page.toasts, [], `page ${running}, server ${installed}`);
assert.deepEqual(page.refreshed, [], `page ${running}, server ${installed}`);
}
});
+108
View File
@@ -0,0 +1,108 @@
"""A loader's change check never opens a value it refused.
ComfyUI calls a node's IS_CHANGED with the prompt's widget values before it
runs anything, and /prompt needs no login. The picture and video loaders
first hand the value to their resolver, which takes only a file named below
ComfyUI's input, output or temp folder. When the resolver refuses it, the
value is hashed as text and nothing else: on Windows, merely looking up a
network path ("//host/share/x.png") contacts that host and hands it the
server's login.
"""
from __future__ import annotations
import os
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._transform_engine import stable_file_fingerprint # noqa: E402
from nodes.node_image_crop_rotate_pad import AusBossImageCropRotatePad # noqa: E402
from nodes.node_load_image import AusBossLoadImage # noqa: E402
from nodes.node_load_image_pad import AusBossLoadImagePad # noqa: E402
from nodes.node_video_crop_rotate_pad import AusBossVideoCropRotatePad # noqa: E402
from nodes.node_video_crop_rotate_pad_clip import AusBossVideoCropRotatePadClip # noqa: E402
REFUSED = [
"//evil-host/share/photo.png",
"\\\\evil-host\\share\\photo.png",
"/evil-host/etc/photo.png",
"../../evil-host/photo.png",
]
class DiskWatch:
"""Records every stat and resolve of a path that names the evil host."""
def __init__(self):
self.touched = []
def __enter__(self):
real_stat, real_resolve = os.stat, Path.resolve
watch = self
def stat(path, *args, **kwargs):
if "evil-host" in str(path):
watch.touched.append(("stat", str(path)))
return real_stat(path, *args, **kwargs)
def resolve(self, *args, **kwargs):
if "evil-host" in str(self):
watch.touched.append(("resolve", str(self)))
return real_resolve(self, *args, **kwargs)
self._patches = [patch("os.stat", stat), patch.object(Path, "resolve", resolve)]
for item in self._patches:
item.start()
return self
def __exit__(self, *exc):
for item in reversed(self._patches):
item.stop()
class ChangeCheckTests(unittest.TestCase):
def assert_off_disk(self, call):
for value in REFUSED:
with self.subTest(value=value), DiskWatch() as watch:
first = call(value)
self.assertEqual(watch.touched, [])
# The text still counts: another refused value is another key.
self.assertNotEqual(first, call(value + "x"))
def test_picture_loaders(self):
for node in (AusBossLoadImage, AusBossLoadImagePad, AusBossImageCropRotatePad):
with self.subTest(node=node.__name__):
self.assert_off_disk(lambda value, node=node: node.IS_CHANGED(image=value))
def test_video_crop_nodes(self):
for node in (AusBossVideoCropRotatePad, AusBossVideoCropRotatePadClip):
for mode in ("input folder", "local path"):
with self.subTest(node=node.__name__, mode=mode):
self.assert_off_disk(
lambda value, node=node, mode=mode: node.IS_CHANGED(
video=value if mode == "input folder" else "",
source_mode=mode,
local_path=value if mode == "local path" else "",
seek_mode="frame index",
frame_index=0,
frame_time=0.0,
**({"start_seconds": 0.0, "end_seconds": 0.0} if node is AusBossVideoCropRotatePadClip else {}),
)
)
def test_the_fingerprint_opens_only_a_resolved_path(self):
with DiskWatch() as watch:
stable_file_fingerprint("//evil-host/share/photo.png", {})
stable_file_fingerprint(None, {})
self.assertEqual(watch.touched, [])
if __name__ == "__main__":
unittest.main()
+40
View File
@@ -7,6 +7,7 @@ import re
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
@@ -244,6 +245,45 @@ class VersionedServingTests(unittest.TestCase):
for path, (_status, body, _headers) in self.fetch(paths).items():
self.assertNotIn("?v=tok", body, path)
def test_an_address_never_reaches_the_disk(self):
# The request is unauthenticated: its address is only looked up in
# the list of scripts made at startup, never joined to a folder and
# resolved. On Windows, resolving "//host/share" contacts that host.
web = self.web
touched = []
async def handled(request):
return web.Response(text="from the handler", content_type="text/javascript")
async def run():
middleware = make_revalidate_middleware("ausboss-nodes", self.js, "tok")
real_resolve, real_stat = Path.resolve, os.stat
def resolve(path, *args, **kwargs):
if "evil-host" in str(path):
touched.append(str(path))
return real_resolve(path, *args, **kwargs)
def stat(path, *args, **kwargs):
if "evil-host" in str(path):
touched.append(str(path))
return real_stat(path, *args, **kwargs)
with patch.object(Path, "resolve", resolve), patch("os.stat", stat):
for path in [
"/extensions/ausboss-nodes//evil-host/share/x.mjs",
"/extensions/ausboss-nodes/%2F%2Fevil-host/share/x.mjs",
"/extensions/ausboss-nodes/%5C%5Cevil-host%5Cshare%5Cx.mjs",
"/extensions/ausboss-nodes/../../evil-host/x.mjs",
"/extensions/ausboss-nodes/%2e%2e/%2e%2e/evil-host/x.js",
"/extensions/ausboss-nodes/C:/evil-host/x.mjs",
]:
response = await middleware(self.make_request("GET", path), handled)
self.assertEqual(response.text, "from the handler", path)
asyncio.run(run())
self.assertEqual(touched, [])
def test_without_a_tag_the_files_are_served_as_before(self):
path = "/extensions/ausboss-nodes/shared/b.mjs"
status, body, headers = self.fetch([path], token=None)[path]
+5
View File
@@ -149,6 +149,11 @@ class ListingTests(FolderCase):
self.assertEqual(place_inside(str(self.root) + "/", roots), ("input", ""))
self.assertEqual(place_inside(str(roots["output"] / "set"), roots), ("output", "set"))
self.assertEqual(place_inside(f'"{self.root / "people"}"', roots), ("input", "people"), "quotes from a copied path")
# A "~" path is never expanded into a real one, and no node code does that.
self.assertIsNone(place_inside("~/ComfyUI/input/people", roots))
nodes_dir = Path(__file__).resolve().parents[1] / "nodes"
for source in nodes_dir.glob("*.py"):
self.assertNotIn("expanduser", source.read_text(encoding="utf-8"), source.name)
def test_a_whole_path_anywhere_else_is_not_a_place(self):
roots = {"input": self.root, "output": Path(self.temp.name) / "output"}
+64 -3
View File
@@ -1,17 +1,20 @@
from __future__ import annotations
from datetime import datetime
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if "nodes" in sys.modules and not hasattr(sys.modules["nodes"], "__path__"):
del sys.modules["nodes"]
from nodes._image_hold_helpers import GONE, HELD_FOLDER, hold_pictures, keep_pictures
from nodes import _image_hold_helpers # noqa: E402
from nodes._image_hold_helpers import GONE, HELD_FOLDER, hold_pictures, keep_pictures # noqa: E402
NOW = datetime(2026, 11, 10, 9, 30, 0)
@@ -99,12 +102,70 @@ class HoldTests(unittest.TestCase):
def test_a_folder_outside_the_output_folder_is_refused_at_the_click_too(self):
token, _ = self.hold(count=1)
manifest = self.temp / HELD_FOLDER / f"{token}.json"
manifest.write_text(manifest.read_text().replace('"output_dir": ""', '"output_dir": "../elsewhere"'))
_image_hold_helpers._RUNS[token]["output_dir"] = "../elsewhere"
with self.assertRaises(ValueError):
self.keep(token)
self.assertFalse((Path(self.box.name) / "elsewhere").exists())
def test_a_run_planted_in_the_temp_folder_is_not_a_run(self):
# ComfyUI's temp folder takes uploads, so a file there can be
# anyone's. A planted list naming a server file must copy nothing.
secret = Path(self.box.name) / "secret.txt"
secret.write_text("server secret")
held = self.temp / HELD_FOLDER
held.mkdir(exist_ok=True)
token = "a" * 16
planted = dict(
settings(extension="png/../../../secret.txt", output_dir="x/y"), count=1, kept={},
)
(held / f"{token}.json").write_text(json.dumps(planted))
(held / f"{token}_000.png").mkdir() # an upload's subfolder makes the ".." walk work
with self.assertRaises(LookupError):
self.keep(token)
self.assertEqual(list(self.output.rglob("*")), [])
def test_a_held_picture_is_named_only_from_the_token_number_and_format(self):
token, previews = self.hold(count=1)
for extension in ["png/../../x", "txt", "", "PNG"]:
with self.assertRaises(ValueError):
_image_hold_helpers._held_name(token, 0, extension)
_image_hold_helpers._RUNS[token]["extension"] = "png/../../../secret.txt"
with self.assertRaises(ValueError):
self.keep(token)
self.assertEqual(list(self.output.iterdir()), [])
def test_a_picture_swapped_for_a_link_is_not_copied(self):
token, previews = self.hold(count=1)
secret = Path(self.box.name) / "secret.txt"
secret.write_text("server secret")
picture = self.temp / HELD_FOLDER / previews[0]["filename"]
picture.unlink()
try:
picture.symlink_to(secret)
except (OSError, NotImplementedError):
self.skipTest("no symlinks here")
with self.assertRaises(LookupError):
self.keep(token)
self.assertEqual(list(self.output.iterdir()), [])
def test_counts_are_capped(self):
with patch.object(_image_hold_helpers, "MAX_HELD_PICTURES", 4):
with self.assertRaises(ValueError):
self.hold(count=5)
token, _ = self.hold(count=2)
with self.assertRaises(ValueError):
self.keep(token, [0] * 5)
self.assertEqual(list(self.output.iterdir()), [])
def test_old_runs_are_forgotten_first(self):
with patch.object(_image_hold_helpers, "MAX_HELD_RUNS", 2):
oldest, _ = self.hold(count=1)
self.hold(count=1)
newest, _ = self.hold(count=1)
with self.assertRaises(LookupError):
self.keep(oldest)
self.assertEqual(len(self.keep(newest)["saved"]), 1)
if __name__ == "__main__":
unittest.main()