Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@

Living log for the engine service side, _v0.1.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full.

## Hardening of the ComfyUI reads, the agent seal, the agent file writes, the library move and the Windows starter · after 2.8.4, unreleased (routers/comfyui.py status, last_graph, upscale_models_route, job, image; core/seal.py SEALED, EARLIER, VERSION, check, sign; services/agents.py _load; routers/mcp.py _convert, _run; routers/projects.py _free_beside, set_folder; services/agent_lookup.py shim_target, cmd_safe, start_argv, VERSION; setup/agents.py LOOKUP_HASHES)

- Kind: fix · logged 2026-11-29.
- **ComfyUI.** The GET routes that reach a ComfyUI server (`/status`, `/graph`, `/upscale-models`, `/job/{job}`, `/image`) attach the sign-in saved in Preferences > Plugins, and GETs pass `WindowKeyGuard`. Each now calls `window_key.require(request)`; the window already sends the key on every request. `upscale_models(target)` stays a plain function for `/upscale`, and the route is `upscale_models_route`.
- **Seal.** `SEALED` is `("policies", "allowed", "limits", "blocked")`. `check` returns `broken` for a seal that is there and does not match, whatever the values; before, it returned `unsealed` unless `allowed` or a policy was loosened, so a change to Blocked or to the folder limits stood with no note. A file sealed over the earlier three fields (`EARLIER`) reads as `earlier`, and `_load` saves it again so it carries the new seal.
- **Agent file writes.** `convert_file`, `export_image`, `save_project`, `export_mask`, `export_layer` and `timeline_render` wrote with `path.write_bytes(blob)` (and `dst.write_bytes(blob)`), which empties the file first. They now use `projects._write_atomic`, as the window's saves in `io.py` do.
- **Library move.** `set_folder` with `move` tried `name` and then `name (moved)`, and `shutil.copy2` replaced a `name (moved)` already there. Removed, quoted: `dst = new / src.name` / `if dst.exists():` / `dst = new / f"{src.stem} (moved){src.suffix}"`. `_free_beside` goes on to `(moved 2)` and on.
- **Windows starter (finder 1.0.2).** `start_argv` put `cmd.exe /c` in front of every .cmd or .bat. Removed, quoted: `return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words`. Now `shim_target` reads an npm shim and returns its node script with `node.exe` beside it (or `node` on PATH), or its .exe, and that is started directly. Otherwise `cmd_safe` refuses a word with a control character or `%`, and a line where one of `& | < > ^ ( )` is outside quotes in any of the ways cmd.exe may read it (as given, with its first and last quote taken off, and the arguments alone as a batch file's `%*` reads them). `CommandLineRefused` is an `OSError`, so the routes answer with their "could not start" message.
- **Shim shape.** `shim_target` takes only the npm shapes: a `%*` line that is `"%_prog%"`, `node` or the shim's own `node.exe` in front of one script, or one .exe alone in front of `%*`, in a file that sets nothing but `dp0`, `_prog` and `PATHEXT`. A launcher that sets its own variables, or hands `%*` to a program with a script before it, goes through `cmd_safe` instead of being started as the first .exe it names.
- **Seal version.** `sign` writes `sealVersion` (`VERSION`, 2) and seals it with the rest. `check` reads a file as `earlier` only when it has no `sealVersion`; a file that carries one is checked against the current seal alone, so it cannot be read as the earlier format, and any other version, or a version with no seal, is `broken`. A mark that is not 64 lowercase hex characters is `broken` before any comparison, and digests are compared as bytes, so an odd value in the file cannot raise. `agents._load` treats a file it cannot read, parse or check (anything but a missing file) as a broken seal, and a broken seal now also sets Blocked: outside agents blocked, `allowed` false, every `allow` policy `ask`.
- **Missing seal and the earlier format.** A file with no seal mark is `unsealed` only while the keychain holds no seal key and no versioned file has been sealed; once either is true it is `broken`. Removed, quoted: `return "broken" if versioned or loosened(stored) else "unsealed"`. `loosened` also counts outside agents not blocked (`blocked` false or missing) and folder limits that are empty or that the loader would change (not 1 to 32 non-blank paths). `sign`, and `check` on a current versioned file, record that a versioned file was sealed in the same keychain item as the key (`agents-seal`, now the key in hex followed by `:v2`; an item without `:` is the earlier layout and gains the mark on the next seal), so the key and the record cannot be changed apart; from then on `check` returns `broken` for the earlier format. An item that is there but cannot be read as a key counts as no key and recorded, so stored choices read as broken and the next save writes a new key, rather than the seal turning off. A refused write of the record keeps it in memory with the key still in use. A file accepted in the earlier format keeps Blocked on and `allowed` false until it is sealed again, since that seal never covered `blocked`; its policies and limits stand. `agents._load` seals it again at once, so the person turns Blocked off in Preferences if they had it off.
- **Tests stay out of the home folder.** `tests/conftest.py` points HOME, USERPROFILE, LOCALAPPDATA, APPDATA and the XDG folders at a temporary folder when it is imported, before any test module, and removes it at the end; `localgen.paths.DATA_DIR` is read at import, so a fixture would have been too late, and the default data folder (agents.json, generated pictures, model folders) was written into the person's own. The ffmpeg tests' `fake_release` set only XDG_DATA_HOME, which macOS and Windows ignore, so a stub ffmpeg went into the shared `formcut-binaries` folder and onto PATH for the later video tests; it now points every folder `ff.folder()` reads inside tmp_path, restores PATH, and checks the real folder is unchanged. `test_select_object`'s shared model folder is beside pytest's temporary folders instead of `~/.cache`. `tests/test_stand_in_home.py` checks the stand-in.
- **Command interpreter words.** `cmd_safe` no longer reads quoting: whenever cmd.exe still starts a program, any word, the program's path included, with one of `& | < > ^ ( ) ! % "` or a control character is refused, quoted or not, with or without spaces, and the message says to pass long text through standard input or a file. A shim whose `node` turns out to be a .cmd or .bat is not started directly. The finder stays 1.0.2; `LOOKUP_HASHES` records its new hash.
- Seen: the engine tests for each part, here on macOS. Not run: Windows.

## The rpm carries the launcher and the library check, as the deb does · 2.8.2 (src-tauri/tauri.conf.json `bundle.linux.rpm`)

- Kind: fix · logged 2026-11-26 · asked after a Linux tester's FormVis, installed from its rpm, closed right after starting.
Expand Down
117 changes: 99 additions & 18 deletions backend/app/core/seal.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,44 @@
import hashlib
import hmac
import json
import re
import secrets

SERVICE = "formvis"
ACCOUNT = "agents-seal"
FIELD = "seal"
SEALED = ("policies", "allowed", "limits")
_CACHE: dict = {"tried": False, "available": False, "key": None}
VERSION_FIELD = "sealVersion"
VERSION = 2
SEALED = ("policies", "allowed", "limits", "blocked", VERSION_FIELD)
EARLIER = ("policies", "allowed", "limits")
_MARK = re.compile(r"[0-9a-f]{64}")
_CACHE: dict = {"tried": False, "available": False, "key": None, "recorded": False}


def reset() -> None:
_CACHE.update(tried=False, available=False, key=None)
_CACHE.update(tried=False, available=False, key=None, recorded=False)


def _item(key_hex: str, recorded: bool) -> str:
"""The keychain item: the key in hex, followed by `:v2` once a versioned file has been sealed. The key and the record
are one item, so neither can be changed without the other. An item with no `:` is the layout from before the record
and reads as not recorded; anything after a `:` reads as recorded."""
return f"{key_hex}:v{VERSION}" if recorded else key_hex


def _parse(stored) -> tuple[bytes | None, bool]:
"""The key and whether a versioned file was sealed. An item that is there but is not a key in hex reads as no key
and recorded, so a damaged item leaves every stored choice broken rather than turning the seal off."""
if not stored:
return None, False
if not isinstance(stored, str):
return None, True
key_hex, colon, _ = stored.partition(":")
try:
key = bytes.fromhex(key_hex) if key_hex else None
except ValueError:
return None, True
return (key or None), bool(colon) or key is None


def _load(create: bool) -> bytes | None:
Expand All @@ -24,46 +51,100 @@ def _load(create: bool) -> bytes | None:

if isinstance(keyring.get_keyring(), (fail.Keyring, null.Keyring)):
raise RuntimeError("no keychain")
stored = keyring.get_password(SERVICE, ACCOUNT)
if not stored and create:
keyring.set_password(SERVICE, ACCOUNT, secrets.token_hex(32))
stored = keyring.get_password(SERVICE, ACCOUNT)
key = bytes.fromhex(stored) if stored else None
key, recorded = _parse(keyring.get_password(SERVICE, ACCOUNT))
if key is None and create:
keyring.set_password(SERVICE, ACCOUNT, _item(secrets.token_hex(32), recorded))
key, again = _parse(keyring.get_password(SERVICE, ACCOUNT))
recorded = recorded or again
except Exception:
_CACHE.update(available=False, key=None)
_CACHE.update(available=False, key=None, recorded=False)
return None
_CACHE.update(available=True, key=key)
_CACHE.update(available=True, key=key, recorded=_CACHE["recorded"] or recorded)
return key


def _record() -> None:
"""Notes in the keychain item, beside the key, that a versioned file has been sealed (an item in the earlier layout
gains the mark here). It is kept in memory even when the keychain refuses the write, with the key and the keychain
still in use, so this session never reads the earlier format again either."""
if _CACHE["recorded"]:
return
_CACHE["recorded"] = True
key = _CACHE["key"]
if key is None:
return
try:
import keyring

keyring.set_password(SERVICE, ACCOUNT, _item(key.hex(), True))
except Exception:
return



def available() -> bool:
_load(False)
return _CACHE["available"]


def digest(values: dict, key: bytes) -> str:
body = json.dumps({k: values.get(k) for k in SEALED}, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def digest(values: dict, key: bytes, fields: tuple = SEALED) -> str:
body = json.dumps({k: values.get(k) for k in fields}, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return hmac.new(key, body.encode("utf-8"), hashlib.sha256).hexdigest()


def _roots_kept(limits) -> bool:
"""Whether the stored folders are a list the loader keeps as it is: 1 to 32 folder paths, none of them blank."""
roots = limits.get("roots") if isinstance(limits, dict) else None
return isinstance(roots, list) and 0 < len(roots) <= 32 and all(isinstance(r, str) and r.strip() for r in roots)


def loosened(values: dict) -> bool:
"""Whether unsealed values would let more through than the restrictive ones: anything allowed, an allow policy,
outside agents not blocked (false or missing), or folders that are empty (anywhere) or that the loader would change."""
policies = values.get("policies") if isinstance(values.get("policies"), dict) else {}
return values.get("allowed") is True or any(v == "allow" for v in policies.values())
return (values.get("allowed") is True or any(v == "allow" for v in policies.values()) or values.get("blocked") is not True
or not _roots_kept(values.get("limits")))


def _matches(mark: str, values: dict, key: bytes, fields: tuple) -> bool:
return hmac.compare_digest(mark.encode("ascii"), digest(values, key, fields).encode("ascii"))


def check(stored: dict) -> str:
"""ok, unsealed (nothing loosened, so the values stand), broken, or unavailable (no keychain: the values stand)."""
"""ok, earlier (a file in the format from before the seal carried a version, to be sealed again; its blocked and
allowed values are not covered by that seal), unsealed (no seal, no seal key yet, no versioned file sealed before and
nothing loosened, so the values stand), broken (a seal that does not match, is not a 64 character hex mark, or has a
version other than this one; a version with no seal; no seal once a seal key exists or a versioned file was sealed;
no seal on loosened values; or the earlier format after a versioned file was sealed), or unavailable (no keychain:
the values stand). A file that carries a version is only ever checked against the current seal, so it can not be
passed off as the earlier format."""
key = _load(False)
if not _CACHE["available"]:
return "unavailable"
if not isinstance(stored, dict):
return "broken"
mark = stored.get(FIELD)
if key is not None and isinstance(mark, str) and hmac.compare_digest(mark, digest(stored, key)):
versioned = VERSION_FIELD in stored
if mark is None or mark == "":
return "broken" if versioned or key is not None or _CACHE["recorded"] or loosened(stored) else "unsealed"
if key is None or not isinstance(mark, str) or not _MARK.fullmatch(mark):
return "broken"
if versioned:
version = stored.get(VERSION_FIELD)
current = isinstance(version, int) and not isinstance(version, bool) and version == VERSION
if not (current and _matches(mark, stored, key, SEALED)):
return "broken"
_record()
return "ok"
return "broken" if loosened(stored) else "unsealed"
if _CACHE["recorded"]:
return "broken"
return "earlier" if _matches(mark, stored, key, EARLIER) else "broken"


def sign(values: dict) -> dict:
key = _load(True)
if key is None:
return {k: v for k, v in values.items() if k != FIELD}
return {**values, FIELD: digest(values, key)}
return {k: v for k, v in values.items() if k not in (FIELD, VERSION_FIELD)}
_record()
versioned = {**{k: v for k, v in values.items() if k != FIELD}, VERSION_FIELD: VERSION}
return {**versioned, FIELD: digest(versioned, key)}
19 changes: 14 additions & 5 deletions backend/app/routers/comfyui.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from fastapi import APIRouter, File, Form, HTTPException, Request, Response, UploadFile

from app.core import config
from app.core import config, window_key
from app.routers.terminal import require_local
from app.services import comfyui_auth, outbound

Expand Down Expand Up @@ -119,8 +119,9 @@ def recipe_file_delete(name: str, request: Request) -> dict:


@router.get("/status")
def status(target: str) -> dict:
def status(target: str, request: Request) -> dict:
"""Whether ComfyUI answers at `target`, and its version when it says."""
window_key.require(request)
base = _base(target)
try:
with _request(base + "/system_stats", timeout=3, probe=True) as r:
Expand All @@ -137,8 +138,9 @@ def status(target: str) -> dict:


@router.get("/graph")
def last_graph(target: str) -> dict:
def last_graph(target: str, request: Request) -> dict:
"""The graph of the newest job ComfyUI ran, in the API format its history keeps, to save as a recipe. 404 when it has run nothing."""
window_key.require(request)
base = _base(target)
try:
with _request(base + "/history?max_items=1", timeout=10) as r:
Expand Down Expand Up @@ -552,6 +554,11 @@ def run(target: str = Form(...), workflow: str = Form(...), items: str = Form("[


@router.get("/upscale-models")
def upscale_models_route(target: str, request: Request) -> dict:
window_key.require(request)
return upscale_models(target)


def upscale_models(target: str) -> dict:
"""The upscaler files ComfyUI lists in its upscale_models folder (.pth, .safetensors, .onnx and the rest it loads), and
whether it has the two nodes that run one."""
Expand Down Expand Up @@ -584,8 +591,9 @@ def upscale(target: str = Form(...), model: str = Form(...), image: UploadFile =


@router.get("/job/{job}")
def job(job: str, target: str) -> dict:
def job(job: str, target: str, request: Request) -> dict:
"""queued (with how many are ahead), running, done (with the output images) or failed."""
window_key.require(request)
base = _base(target)
try:
with _request(f"{base}/history/{urllib.parse.quote(job)}", timeout=5) as r:
Expand All @@ -611,8 +619,9 @@ def job(job: str, target: str) -> dict:


@router.get("/image")
def image(target: str, filename: str, subfolder: str = "") -> Response:
def image(target: str, filename: str, request: Request, subfolder: str = "") -> Response:
"""One output image, fetched through ComfyUI's /view (only from its output folder)."""
window_key.require(request)
base = _base(target)
q = urllib.parse.urlencode({"filename": filename, "subfolder": subfolder, "type": "output"})
try:
Expand Down
9 changes: 5 additions & 4 deletions backend/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from app import __version__
from app.services import agents, fal_run
from app.routers.mcp_pack import PACK_DECLARED, PACK_TOOLS, PACK_USE_WHEN
from app.routers.projects import _write_atomic
from app.routers.terminal import server_port

router = APIRouter()
Expand Down Expand Up @@ -849,7 +850,7 @@ def _convert(args: dict) -> dict:
blob = imaging.encode(png, fmt, int(round(float(args.get("quality", 0.92)) * 100)), int(args.get("dpi", 72)), None, options)
except imaging.DecodeError as exc:
raise ValueError(str(exc)) from exc
dst.write_bytes(blob)
_write_atomic(dst, blob)
return {"path": str(dst), "source": str(src), "format": fmt, "width": width, "height": height, "bytes": len(blob)}


Expand Down Expand Up @@ -1069,7 +1070,7 @@ async def _run(name: str, args: dict) -> dict:
if not data:
return out if out.get("isError") else _fail("formvis rendered nothing.")
blob = await asyncio.to_thread(base64.b64decode, data)
await asyncio.to_thread(path.write_bytes, blob)
await asyncio.to_thread(_write_atomic, path, blob)
return {"content": [{"type": "text", "text": f"Wrote {path} ({len(blob):,} bytes)."}], "structuredContent": {"path": str(path), "bytes": len(blob)}}
if name in ("export_mask", "export_layer"):
path = _path(args.get("path"), _FILES[name][0], False, args.get("overwrite"))
Expand All @@ -1078,7 +1079,7 @@ async def _run(name: str, args: dict) -> dict:
if not data:
return out if out.get("isError") else _fail("formvis gave nothing to write.")
blob = await asyncio.to_thread(base64.b64decode, data)
await asyncio.to_thread(path.write_bytes, blob)
await asyncio.to_thread(_write_atomic, path, blob)
return {"content": [{"type": "text", "text": f"Wrote {path} ({len(blob):,} bytes)."}], "structuredContent": {"path": str(path), "bytes": len(blob)}}
if name in ("save_project", "export_image"):
path = _path(args.get("path"), _FILES[name][0], False, args.get("overwrite"))
Expand All @@ -1100,7 +1101,7 @@ async def _run(name: str, args: dict) -> dict:
blob = await asyncio.to_thread(imaging.encode, blob, kind, int(round(float(args.get("quality", 0.92)) * 100)), int(args.get("dpi", 72)), None, dict(args.get("options") or {}))
except imaging.DecodeError as exc:
return _fail(str(exc))
await asyncio.to_thread(path.write_bytes, blob)
await asyncio.to_thread(_write_atomic, path, blob)
return {"content": [{"type": "text", "text": f"Wrote {path} ({len(blob):,} bytes)."}], "structuredContent": {"path": str(path), "bytes": len(blob)}}
except ValueError as exc:
return _fail(str(exc))
Expand Down
Loading
Loading