From 3361c8cd3e1c5b37945a73f4f8e06e5fd617557f Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:29:27 -0500 Subject: [PATCH 01/14] fix(comfyui): the ComfyUI reads that reach a server take the window key, as its writes do status, graph, upscale-models, job and image send the saved ComfyUI sign-in to the address they are given, so only the formvis window may ask for them. --- backend/app/routers/comfyui.py | 19 ++++++++++++++----- backend/tests/test_comfyui.py | 20 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/backend/app/routers/comfyui.py b/backend/app/routers/comfyui.py index 0c552fc8..265cfcf6 100644 --- a/backend/app/routers/comfyui.py +++ b/backend/app/routers/comfyui.py @@ -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 @@ -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: @@ -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: @@ -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.""" @@ -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: @@ -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: diff --git a/backend/tests/test_comfyui.py b/backend/tests/test_comfyui.py index d548cf8c..09a0ef44 100644 --- a/backend/tests/test_comfyui.py +++ b/backend/tests/test_comfyui.py @@ -54,3 +54,23 @@ def test_comfyui_not_running_or_a_bad_address(client): items = json.dumps([{"name": "x", "kind": "image"}]) assert client.post("/api/comfyui/send", data={"target": "http://127.0.0.1:9", "items": items}, files=[("files", ("a.png", png_bytes((4, 4)), "image/png"))]).status_code == 502 assert client.post("/api/comfyui/send", data={"target": "javascript:x", "items": items}, files=[("files", ("a.png", png_bytes((4, 4)), "image/png"))]).status_code == 422 + + +def test_comfyui_reads_with_a_target_need_the_window_key(bare): + server, base, seen = _stand_in() + hits = [] + handler = server.RequestHandlerClass + original = handler.do_GET + + def counted(self): + hits.append(self.path) + return original(self) + + handler.do_GET = counted + try: + for path, params in (("/api/comfyui/status", {}), ("/api/comfyui/graph", {}), ("/api/comfyui/upscale-models", {}), + ("/api/comfyui/job/j1", {}), ("/api/comfyui/image", {"filename": "a.png"})): + assert bare.get(path, params={"target": base, **params}).status_code == 403, path + assert hits == [] + finally: + server.shutdown() From 34bfc8ee2095b1cddb85a1ac3f1a982e9d9717f0 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:31:26 -0500 Subject: [PATCH 02/14] fix(agents): the saved agent choice seals Blocked too, and a seal that no longer matches is reported Blocked joins the sealed fields. A file whose seal does not match its values reads as changed outside formvis even when nothing in it was loosened, so a change to Blocked or to the agent folders is reported. A choice sealed before Blocked was sealed stands and is sealed again on load. --- backend/app/core/seal.py | 20 +++++++---- backend/app/services/agents.py | 3 ++ backend/tests/test_window_key.py | 61 ++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 6 deletions(-) diff --git a/backend/app/core/seal.py b/backend/app/core/seal.py index 3a686246..795fdd47 100644 --- a/backend/app/core/seal.py +++ b/backend/app/core/seal.py @@ -6,7 +6,8 @@ SERVICE = "formvis" ACCOUNT = "agents-seal" FIELD = "seal" -SEALED = ("policies", "allowed", "limits") +SEALED = ("policies", "allowed", "limits", "blocked") +EARLIER = ("policies", "allowed", "limits") _CACHE: dict = {"tried": False, "available": False, "key": None} @@ -41,8 +42,8 @@ def available() -> bool: 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() @@ -52,13 +53,20 @@ def loosened(values: dict) -> bool: def check(stored: dict) -> str: - """ok, unsealed (nothing loosened, so the values stand), broken, or unavailable (no keychain: the values stand).""" + """ok, earlier (sealed before Blocked was, to be sealed again), unsealed (no seal and nothing loosened, so the + values stand), broken (a seal that does not match, or no seal on loosened values), or unavailable (no keychain: the + values stand).""" key = _load(False) if not _CACHE["available"]: return "unavailable" mark = stored.get(FIELD) - if key is not None and isinstance(mark, str) and hmac.compare_digest(mark, digest(stored, key)): - return "ok" + if key is not None and isinstance(mark, str): + if hmac.compare_digest(mark, digest(stored, key)): + return "ok" + if hmac.compare_digest(mark, digest(stored, key, EARLIER)): + return "earlier" + if isinstance(mark, str) and mark: + return "broken" return "broken" if loosened(stored) else "unsealed" diff --git a/backend/app/services/agents.py b/backend/app/services/agents.py index 8340080e..4fde449a 100644 --- a/backend/app/services/agents.py +++ b/backend/app/services/agents.py @@ -54,6 +54,7 @@ def _load() -> None: return _seal["state"] = seal.check(data) broken = _seal["state"] == "broken" + earlier = _seal["state"] == "earlier" _policies.update({k: ("ask" if broken and v == "allow" else v) for k, v in (data.get("policies") or {}).items() if v in POLICIES}) _stored["allowed"] = False if broken else data.get("allowed") if isinstance(data.get("allowed"), bool) else None _stored["blocked"] = data.get("blocked") is True @@ -64,6 +65,8 @@ def _load() -> None: _limits[key] = saved[key] except (OSError, ValueError, AttributeError): return + if earlier: + _save() def _save() -> None: diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py index c2ffd95e..86d10db7 100644 --- a/backend/tests/test_window_key.py +++ b/backend/tests/test_window_key.py @@ -104,6 +104,8 @@ def _reload(agents): agents._loaded = False agents._policies.clear() agents._stored["allowed"] = None + agents._stored["blocked"] = False + agents._limits["roots"] = [] agents._seal["state"] = "unsealed" agents._load() @@ -155,3 +157,62 @@ def test_with_no_keychain_the_stored_choice_stands(tmp_path, monkeypatch): keyring.set_keyring(previous) seal.reset() _reload(agents) + + +def _with_memory_keychain(test): + def run(tmp_path, monkeypatch): + import keyring + from keyring.backend import KeyringBackend + + from app.services import agents + + class Memory(_Memory, KeyringBackend): + pass + + monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path)) + previous = keyring.get_keyring() + keyring.set_keyring(Memory()) + seal.reset() + try: + test(agents, tmp_path / "agents.json") + finally: + keyring.set_keyring(previous) + seal.reset() + _reload(agents) + return run + + +def _edit(path, change): + stored = json.loads(path.read_text()) + change(stored) + path.write_text(json.dumps(stored)) + + +@_with_memory_keychain +def test_a_hand_edit_that_lifts_blocked_is_caught(agents, path): + agents.set_blocked(True) + _reload(agents) + assert agents.state()["seal"] == "ok" and agents.state()["blocked"] is True + _edit(path, lambda s: s.update(blocked=False)) + _reload(agents) + assert agents.state()["sealBroken"] is True + + +@_with_memory_keychain +def test_a_hand_edit_of_the_agent_folders_is_caught(agents, path): + agents.set_limits({"roots": [str(path.parent / "work")]}) + _reload(agents) + assert agents.state()["seal"] == "ok" + _edit(path, lambda s: s["limits"].update(roots=[])) + _reload(agents) + assert agents.state()["sealBroken"] is True + + +@_with_memory_keychain +def test_a_choice_sealed_before_blocked_was_sealed_stands_and_is_sealed_again(agents, path): + agents.set_policy("Codex", "allow") + key = seal._load(False) + _edit(path, lambda s: s.update(seal=seal.digest(s, key, seal.EARLIER))) + _reload(agents) + assert agents.state()["seal"] == "ok" and agents.policy_of("Codex") == "allow" + assert json.loads(path.read_text())["seal"] == seal.digest(json.loads(path.read_text()), key) From 263b107a6b43f5c320e98ada2d8a5409fcf044c0 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:32:54 -0500 Subject: [PATCH 03/14] fix(mcp): the agent tools that write a file write it beside the target and rename it over, as the window's saves do export_image, save_project, export_mask, export_layer, timeline_render and convert_file no longer truncate the file they replace before the new one is complete, so a full disk or a stop part way leaves the earlier file. --- backend/app/routers/mcp.py | 9 ++++---- backend/tests/test_windows_review_fixes.py | 27 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index fa0a9a80..bde40381 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -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() @@ -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)} @@ -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")) @@ -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")) @@ -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)) diff --git a/backend/tests/test_windows_review_fixes.py b/backend/tests/test_windows_review_fixes.py index ae1dec2b..b9d17d29 100644 --- a/backend/tests/test_windows_review_fixes.py +++ b/backend/tests/test_windows_review_fixes.py @@ -90,3 +90,30 @@ def test_a_new_file_converts_with_no_window(tmp_path, monkeypatch): def test_convert_file_says_when_it_needs_the_window(): tool = next(t for t in M.TOOLS if t["name"] == "convert_file") assert "fails at once when no window is open" in tool["description"] + + +def test_a_write_that_fails_part_way_leaves_the_file_it_replaces(tmp_path, monkeypatch): + import errno + import pathlib + + from PIL import Image + + src, dst = tmp_path / "in.png", tmp_path / "out.jpg" + Image.new("RGB", (4, 3), (200, 10, 10)).save(src) + dst.write_bytes(b"the earlier picture") + + def full_disk(*_args, **_kwargs): + raise OSError(errno.ENOSPC, "No space left on device") + + def half_written(self, data): + with open(self, "wb") as out: + out.write(data[: len(data) // 2]) + full_disk() + + monkeypatch.setattr(pathlib.Path, "write_bytes", half_written) + monkeypatch.setattr(os, "fsync", full_disk) + monkeypatch.setattr(agents, "policy_of", lambda client: "allow") + out = asyncio.run(M._agent_call("test-agent", "convert_file", {"path": str(src), "output_path": str(dst), "overwrite": True})) + assert out["isError"] + assert dst.read_bytes() == b"the earlier picture" + assert sorted(p.name for p in tmp_path.iterdir()) == ["in.png", "out.jpg"] From 7800d493d2b5f38bbcee9aff60dbd9eb6d3b8292 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:34:04 -0500 Subject: [PATCH 04/14] fix(projects): moving the library picks a free name for each project whose name is taken there A project moved into a folder that already holds both its name and its (moved) name is now saved as (moved 2) and on, so no project there is replaced. --- backend/app/routers/projects.py | 13 ++++++++++--- backend/tests/test_library_move.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 backend/tests/test_library_move.py diff --git a/backend/app/routers/projects.py b/backend/app/routers/projects.py index fe25c702..b7709e73 100644 --- a/backend/app/routers/projects.py +++ b/backend/app/routers/projects.py @@ -254,6 +254,15 @@ class FolderBody(BaseModel): move: bool = False +def _free_beside(folder: Path, stem: str, suffix: str) -> Path: + """`stem` in `folder`, or "stem (moved)", "stem (moved 2)" and on, the first name no file there has.""" + for n in range(1, 1000): + dst = folder / (f"{stem}{suffix}" if n == 1 else f"{stem} (moved){suffix}" if n == 2 else f"{stem} (moved {n - 1}){suffix}") + if not dst.exists(): + return dst + raise HTTPException(status_code=409, detail=f"Too many projects named {stem} in that folder; nothing more was moved.") + + @router.put("/folder") def set_folder(body: FolderBody) -> dict: """The library moved to `folder` (empty: back to the default): made if missing and tested writable; with `move`, @@ -276,9 +285,7 @@ def set_folder(body: FolderBody) -> dict: if body.move and new.resolve() != old.resolve(): import shutil for src in sorted(p for s in (EXT, *OLD_EXTS) for p in old.glob(f"*{s}")): - dst = new / src.name - if dst.exists(): - dst = new / f"{src.stem} (moved){src.suffix}" + dst = _free_beside(new, src.stem, src.suffix) shutil.copy2(src, dst) if dst.stat().st_size != src.stat().st_size: raise HTTPException(status_code=500, detail=f"{src.name} did not copy whole; nothing more was moved.") diff --git a/backend/tests/test_library_move.py b/backend/tests/test_library_move.py new file mode 100644 index 00000000..eebcf824 --- /dev/null +++ b/backend/tests/test_library_move.py @@ -0,0 +1,19 @@ +"""Moving the library to a folder that already holds projects of the same names keeps every one of them.""" + +from app.core import config + + +def test_a_move_into_a_folder_with_the_same_names_keeps_each_project(client, tmp_path, monkeypatch): + monkeypatch.delenv("FORMVIS_LIBRARY_DIR", raising=False) + old = config.projects_dir() + old.mkdir(parents=True, exist_ok=True) + (old / "Poster.fvd").write_bytes(b"from this computer") + new = tmp_path / "Shared" + new.mkdir() + (new / "Poster.fvd").write_bytes(b"first") + (new / "Poster (moved).fvd").write_bytes(b"second") + r = client.put("/api/projects/folder", json={"folder": str(new), "move": True}) + assert r.status_code == 200 and r.json()["moved"] == 1 + assert {p.name: p.read_bytes() for p in new.iterdir()} == { + "Poster.fvd": b"first", "Poster (moved).fvd": b"second", "Poster (moved 2).fvd": b"from this computer"} + assert not (old / "Poster.fvd").exists() From 9cd73b868773c942f69e6d3b79ff304d1adbea4c Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:34:38 -0500 Subject: [PATCH 05/14] fix(library): a save to the library asks before replacing a project whose name differs only in letter case macOS and Windows file systems treat Poster and poster as one file, so Save to Library and Save a Copy now compare names without letter case before deciding whether to ask about replacing one. --- frontend/src/app.ts | 5 +++-- frontend/src/io/library-names.test.ts | 18 ++++++++++++++++++ frontend/src/io/library-names.ts | 4 ++++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 frontend/src/io/library-names.test.ts create mode 100644 frontend/src/io/library-names.ts diff --git a/frontend/src/app.ts b/frontend/src/app.ts index eaaea9c4..48f11b7f 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -13,6 +13,7 @@ import { DataSetsDialog, DefineVariablesDialog } from './ui/panels/variables-dia import { ArtboardPdfDialog, type ArtboardPdfSettings } from './ui/panels/artboard-pdf-dialog'; import { DEFAULT_LAYER_EXPORT, dataSetFiles, layerCompFiles, layerFileLoss, layerFiles, safeName, selectedLayerFiles, type LayerExportSettings } from './io/layer-export'; import { loadExportPrefs } from './io/export-prefs'; +import { libraryHas } from './io/library-names'; import { ExportPrefsDialog } from './ui/panels/export-prefs-dialog'; import { GuideDialog } from './ui/panels/guide-dialog'; import { EditGuidesDialog } from './ui/panels/guide-edit-dialog'; @@ -1432,7 +1433,7 @@ export function startApp(): void { name = await promptName(saveAs ? 'Save As' : 'Save to Library', p.libraryName ?? p.name, 'Save'); if (!name) return false; if (name !== p.libraryName) { - const taken = (await api.library().catch(() => [])).some((i) => i.name === name); + const taken = libraryHas(await api.library().catch(() => []), name, p.libraryName ?? null); if (taken && !(await confirmAction('Replace project?', `${name} already exists in the library.`, 'Replace', true))) return false; } } @@ -1518,7 +1519,7 @@ export function startApp(): void { return; } } - const taken = (await api.library().catch(() => [])).some((i) => i.name === name); + const taken = libraryHas(await api.library().catch(() => []), name); if (taken && !(await confirmAction('Replace project?', `${name} already exists in the library.`, 'Replace', true))) return; await engine.task(async () => { try { diff --git a/frontend/src/io/library-names.test.ts b/frontend/src/io/library-names.test.ts new file mode 100644 index 00000000..bd092a9e --- /dev/null +++ b/frontend/src/io/library-names.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { libraryHas } from './library-names'; + +const items = [{ name: 'Poster' }, { name: 'Café' }]; + +describe('library names', () => { + it('finds a project whose name differs only in letter case', () => { + expect(libraryHas(items, 'poster')).toBe(true); + expect(libraryHas(items, 'POSTER')).toBe(true); + expect(libraryHas(items, 'Café')).toBe(true); + expect(libraryHas(items, 'Flyer')).toBe(false); + }); + + it('does not count the document\'s own library project', () => { + expect(libraryHas(items, 'poster', 'Poster')).toBe(false); + expect(libraryHas(items, 'café', 'Poster')).toBe(true); + }); +}); diff --git a/frontend/src/io/library-names.ts b/frontend/src/io/library-names.ts new file mode 100644 index 00000000..f71e7b24 --- /dev/null +++ b/frontend/src/io/library-names.ts @@ -0,0 +1,4 @@ +export const sameLibraryName = (a: string, b: string): boolean => a.normalize('NFC').toLowerCase() === b.normalize('NFC').toLowerCase(); + +export const libraryHas = (items: ReadonlyArray<{ name: string }>, name: string, own: string | null = null): boolean => + items.some((i) => sameLibraryName(i.name, name) && !(own !== null && sameLibraryName(i.name, own))); From fd1953ed152ec59a290258a433daa31c374fd626 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:38:56 -0500 Subject: [PATCH 06/14] fix(agents): on Windows an npm shim starts its program directly, and cmd.exe gets only words it passes unchanged The finder is 1.0.2. A .cmd shim that npm wrote is started as the node script or program it names, so the words typed in the dock reach the program as typed. Any other .cmd or .bat still goes through cmd.exe, and a word with a control character, a %, an unmatched quote or one of & | < > ^ ( ) outside quotes is refused with a message. LOOKUP_HASHES records the new hash. --- backend/app/services/agent_lookup.py | 68 ++++++++++++++++++++++++++-- backend/tests/test_agent_lookup.py | 49 ++++++++++++++++++++ setup/agents.py | 2 +- 3 files changed, 115 insertions(+), 4 deletions(-) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba1..6cb574ab 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.0.2" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -359,13 +359,75 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class CommandLineRefused(OSError): + """A word the Windows command interpreter would not pass through to the program as it is.""" + + +_SHIM_TARGET = re.compile(r'"%(?:~dp0|dp0%)\\?([^"%\r\n]+?\.(?:js|cjs|mjs|exe))"', re.I) +_CMD_SPECIAL = frozenset("&|<>^()") +_CMD_REFUSED = re.compile(r"[\x00-\x1f\x7f%]") + + +def shim_target(shim: str, env: dict | None = None) -> list[str] | None: + """The program an npm .cmd shim runs (its script with node, or its .exe), so it can be started without the command + interpreter; None when the file is not such a shim or its target is missing.""" + env = os.environ if env is None else env + folder = Path(shim).parent + try: + text = Path(shim).read_text(encoding="utf-8", errors="replace")[:65536] + except OSError: + return None + for rel in _SHIM_TARGET.findall(text): + target = folder.joinpath(*[part for part in rel.replace("\\", "/").split("/") if part]) + if target.name.lower() == "node.exe" or not target.is_file(): + continue + if target.suffix.lower() == ".exe": + return [str(target)] + node = folder / "node.exe" + found = str(node) if node.is_file() else shutil.which("node", path=env.get("PATH", "")) + return [found, str(target)] if found else None + return None + + +def _cmd_unquoted(line: str) -> bool: + quoted = False + for ch in line: + if ch == '"': + quoted = not quoted + elif not quoted and ch in _CMD_SPECIAL: + return True + return False + + +def cmd_safe(words: list[str]) -> None: + """Raises CommandLineRefused unless every word reaches the program unchanged through cmd.exe /c and a batch file's %*: + no control characters and no %, and none of & | < > ^ ( ) outside quotes, read the ways cmd.exe may read the line.""" + for word in words: + if _CMD_REFUSED.search(word): + raise CommandLineRefused("A word for this program has a line break, a control character or %, which the Windows command interpreter would change.") + line = subprocess.list2cmdline(words) + readings = [line, subprocess.list2cmdline(words[1:])] + if line.startswith('"'): + last = line.rfind('"') + readings.append(line[1:last] + line[last + 1:]) + if any(_cmd_unquoted(reading) for reading in readings): + raise CommandLineRefused("A word for this program has an unmatched quote or one of & | < > ^ ( ) that the Windows command interpreter would act on.") + + def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux - (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + (exec, so the process is the program), directly on Windows. An npm .cmd shim is started as the node script or program + it names; any other .cmd or .bat goes through the command interpreter, only with words it passes through unchanged.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not words[0].lower().endswith((".cmd", ".bat")): + return words + direct = shim_target(words[0], env) + if direct: + return [*direct, *words[1:]] + cmd_safe(words) + return [env.get("COMSPEC") or "cmd.exe", "/c", *words] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/tests/test_agent_lookup.py b/backend/tests/test_agent_lookup.py index 4e986190..ef421cf4 100644 --- a/backend/tests/test_agent_lookup.py +++ b/backend/tests/test_agent_lookup.py @@ -164,3 +164,52 @@ def test_opening_a_tab_for_a_missing_or_broken_program_answers_with_the_sentence res = client.post("/api/terminal/agent", json={"kind": "antigravity"}) assert res.status_code == 404 and res.json()["detail"].startswith("Antigravity was not found. Looked in: PATH (/usr/bin:/bin:/usr/sbin:/sbin); ") assert set(agent_programs.PROGRAMS) == {"codex", "cursor", "antigravity"} and agent_programs.TABS == ("codex", "cursor", "antigravity") + + +NPM_SHIM = ('@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\nIF EXIST "%dp0%\\node.exe" (\r\n' + ' SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\n' + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %*\r\n') +TYPED = 'Remove the "red car & del /q *.png' + + +def test_on_windows_an_npm_shim_starts_its_script_with_node_and_no_command_interpreter(tmp_path): + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM) + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("") + node = tmp_path / "node.exe" + node.write_text("") + argv = agent_lookup.start_argv([str(shim), "--", TYPED], {"COMSPEC": "C:\\Windows\\cmd.exe"}, "win32") + assert argv == [str(node), str(script), "--", TYPED] + node.unlink() + elsewhere = tmp_path / "bin" + elsewhere.mkdir() + stand_in(elsewhere / "node") + assert agent_lookup.start_argv([str(shim), "--version"], {"PATH": str(elsewhere)}, "win32") == [str(elsewhere / "node"), str(script), "--version"] + + +def test_on_windows_an_old_style_shim_to_an_exe_starts_the_exe(tmp_path): + shim = tmp_path / "tool.cmd" + shim.write_text('@"%~dp0\\vendor\\tool.exe" %*\r\n') + (tmp_path / "vendor").mkdir() + (tmp_path / "vendor" / "tool.exe").write_text("") + assert agent_lookup.start_argv([str(shim), "a b"], {}, "win32") == [str(tmp_path / "vendor" / "tool.exe"), "a b"] + + +@pytest.mark.parametrize("word", [TYPED, "50% brighter", "two\nlines", "a&b", "x|y", " list[str]: LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51"} # the family's record: the SHA-256 of the shared finder at each of its versions +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "6afeb9842d8c3ea9bb6876697e1c9804a7e49f09c658d2ee5c6ed4213c6ba27d"} # the family's record: the SHA-256 of the shared finder at each of its versions def lookup_problems() -> list[str]: From e3c6f31df1b7216aba8bf25bb6519826242d5925 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:39:16 -0500 Subject: [PATCH 07/14] docs: the living logs record the ComfyUI, seal, file write, library and Windows starter fixes --- backend/HASHOUT_LOG.md | 10 ++++++++++ frontend/HASHOUT_LOG.md | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 9927a14d..b7c2d37f 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,16 @@ 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.3, unreleased (routers/comfyui.py status, last_graph, upscale_models_route, job, image; core/seal.py SEALED, EARLIER, check; 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. +- 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. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index dfe4863e..dd04223c 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,6 +2,12 @@ Living log for the frontend 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. +## A library save compares names without letter case · after 2.8.3, unreleased (io/library-names.ts sameLibraryName, libraryHas; app.ts saveCore, the Save a Copy path) + +- Kind: fix · logged 2026-11-29. +- macOS and Windows file systems treat `Poster.fvd` and `poster.fvd` as one file, and the engine's `/projects/save` with no base version replaces what is there. Removed from both places, quoted: `const taken = (await api.library().catch(() => [])).some((i) => i.name === name);`. Save to Library now uses `libraryHas(items, name, p.libraryName ?? null)` (the document's own project is not counted), and Save a Copy `libraryHas(items, name)`; both compare NFC lower case. +- Seen: `src/io/library-names.test.ts` and `tsc --noEmit`. Not seen in a window. + ## The menu bar's menus open under the bar and are at most three quarters of the window tall · _v2.8.3 (ui/menu.ts MENU_SHARE, MENU_PAD, menuCap, PopupMenu.floor, PopupMenu.openUnder, PopupMenu.openBeside, MenuBar.open) - Kind: fix · logged 2026-11-28 · a person on Linux reported that menus taller than the screen cover the File menu bar (File and View in a 1080-pixel window). From 5466076d1a84d82598a816e1ad603042020678fd Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:20:19 -0500 Subject: [PATCH 08/14] fix(agents): start a .cmd directly only when it has the npm shim shape A launcher that sets its own variables, or hands its arguments to a program with a script in front of them, is no longer started as the first .exe it names; it goes through the command interpreter checks instead. LOOKUP_HASHES records the finder's new hash. --- backend/HASHOUT_LOG.md | 1 + backend/app/services/agent_lookup.py | 28 +++++++++++++++++++--------- backend/tests/test_agent_lookup.py | 24 ++++++++++++++++++++++++ setup/agents.py | 2 +- 4 files changed, 45 insertions(+), 10 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index b7c2d37f..2ad830ec 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -10,6 +10,7 @@ Living log for the engine service side, _v0.1.0. Read the map and the TOC first; - **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. - 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`) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index 6cb574ab..209c9ec6 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -363,29 +363,39 @@ class CommandLineRefused(OSError): """A word the Windows command interpreter would not pass through to the program as it is.""" -_SHIM_TARGET = re.compile(r'"%(?:~dp0|dp0%)\\?([^"%\r\n]+?\.(?:js|cjs|mjs|exe))"', re.I) +_DP0 = r'"%(?:~dp0|dp0%)\\?([^"%\r\n]+?\.{ext})"' +_SHIM_SCRIPT = re.compile(r'(?:^|&)[ \t]*@?(?:"%_prog%"|node|"%(?:~dp0|dp0%)\\?node\.exe")[ \t]+' + _DP0.format(ext="(?:js|cjs|mjs)") + r'[ \t]+%\*[ \t\r]*$', re.I | re.M) +_SHIM_EXE = re.compile(r'(?:^|&)[ \t]*@?' + _DP0.format(ext="exe") + r'[ \t]+%\*[ \t\r]*$', re.I | re.M) +_SHIM_SETS = re.compile(r'\bset[ \t]+"?([A-Za-z_]\w*)=', re.I) +_SHIM_OWN_VARS = frozenset({"dp0", "_prog", "pathext"}) _CMD_SPECIAL = frozenset("&|<>^()") _CMD_REFUSED = re.compile(r"[\x00-\x1f\x7f%]") +def _beside(folder: Path, rel: str) -> Path: + return folder.joinpath(*[part for part in rel.replace("\\", "/").split("/") if part]) + + def shim_target(shim: str, env: dict | None = None) -> list[str] | None: """The program an npm .cmd shim runs (its script with node, or its .exe), so it can be started without the command - interpreter; None when the file is not such a shim or its target is missing.""" + interpreter; None when the file is not such a shim (it sets anything of its own, or hands %* to anything else) or + its target is missing.""" env = os.environ if env is None else env folder = Path(shim).parent try: text = Path(shim).read_text(encoding="utf-8", errors="replace")[:65536] except OSError: return None - for rel in _SHIM_TARGET.findall(text): - target = folder.joinpath(*[part for part in rel.replace("\\", "/").split("/") if part]) - if target.name.lower() == "node.exe" or not target.is_file(): - continue - if target.suffix.lower() == ".exe": - return [str(target)] + if any(name.lower() not in _SHIM_OWN_VARS for name in _SHIM_SETS.findall(text)): + return None + scripts = [_beside(folder, rel) for rel in _SHIM_SCRIPT.findall(text)] + exes = [_beside(folder, rel) for rel in _SHIM_EXE.findall(text)] + if scripts and not exes and len(set(scripts)) == 1 and scripts[0].is_file(): node = folder / "node.exe" found = str(node) if node.is_file() else shutil.which("node", path=env.get("PATH", "")) - return [found, str(target)] if found else None + return [found, str(scripts[0])] if found else None + if exes and not scripts and len(set(exes)) == 1 and exes[0].name.lower() != "node.exe" and exes[0].is_file(): + return [str(exes[0])] return None diff --git a/backend/tests/test_agent_lookup.py b/backend/tests/test_agent_lookup.py index ef421cf4..46f65b36 100644 --- a/backend/tests/test_agent_lookup.py +++ b/backend/tests/test_agent_lookup.py @@ -213,3 +213,27 @@ def test_on_windows_a_program_path_with_a_space_is_read_as_the_command_interpret with pytest.raises(agent_lookup.CommandLineRefused): agent_lookup.start_argv(["C:\\Users\\A B\\npm\\codex.cmd", "--", "red & blue"], {}, "win32") assert agent_lookup.start_argv(["C:\\Users\\A B\\npm\\codex.cmd", "--version"], {}, "win32")[-1] == "--version" + + +def test_on_windows_an_older_npm_shim_starts_its_script_with_node(tmp_path): + shim = tmp_path / "codex.cmd" + shim.write_text('@IF EXIST "%~dp0\\node.exe" (\r\n "%~dp0\\node.exe" "%~dp0\\node_modules\\@openai\\codex\\bin\\codex.js" %*\r\n' + ') ELSE (\r\n @SETLOCAL\r\n @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n node "%~dp0\\node_modules\\@openai\\codex\\bin\\codex.js" %*\r\n)\r\n') + script = tmp_path / "node_modules" / "@openai" / "codex" / "bin" / "codex.js" + script.parent.mkdir(parents=True) + script.write_text("") + (tmp_path / "node.exe").write_text("") + assert agent_lookup.start_argv([str(shim), TYPED], {}, "win32") == [str(tmp_path / "node.exe"), str(script), TYPED] + + +def test_on_windows_a_launcher_that_sets_its_own_variables_is_not_read_as_a_shim(tmp_path): + shim = tmp_path / "bin" / "agy.cmd" + shim.parent.mkdir() + shim.write_text('@echo off\r\nsetlocal\r\nset ELECTRON_RUN_AS_NODE=1\r\n"%~dp0..\\App.exe" "%~dp0..\\resources\\app\\out\\cli.js" %*\r\nendlocal\r\n') + (tmp_path / "App.exe").write_text("") + (tmp_path / "resources" / "app" / "out").mkdir(parents=True) + (tmp_path / "resources" / "app" / "out" / "cli.js").write_text("") + assert agent_lookup.shim_target(str(shim), {}) is None + assert agent_lookup.start_argv([str(shim), "--version"], {"COMSPEC": "C:\\Windows\\cmd.exe"}, "win32")[:2] == ["C:\\Windows\\cmd.exe", "/c"] + shim.write_text('@echo off\r\n"%~dp0..\\App.exe" "%~dp0..\\resources\\app\\out\\cli.js" %*\r\n') + assert agent_lookup.shim_target(str(shim), {}) is None diff --git a/setup/agents.py b/setup/agents.py index cd09bb76..e985983b 100755 --- a/setup/agents.py +++ b/setup/agents.py @@ -193,7 +193,7 @@ def dock_problems() -> list[str]: LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "6afeb9842d8c3ea9bb6876697e1c9804a7e49f09c658d2ee5c6ed4213c6ba27d"} # the family's record: the SHA-256 of the shared finder at each of its versions +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "39d837d87b04abab6a3439cf21be503a4f3a1516d1d9ef59e5cf29dc5caefd5e"} # the family's record: the SHA-256 of the shared finder at each of its versions def lookup_problems() -> list[str]: From 78b0c8aeff02cb4d875233847ba3b4f2db954cf0 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:20:19 -0500 Subject: [PATCH 09/14] fix(library): trim a name before checking whether the library has it The engine trims a library name before saving, so a name typed with a space at either end now asks before replacing the project it matches. --- frontend/HASHOUT_LOG.md | 2 +- frontend/src/io/library-names.test.ts | 1 + frontend/src/io/library-names.ts | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index dd04223c..d9051bcf 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -5,7 +5,7 @@ Living log for the frontend side, _v0.1.0. Read the map and the TOC first; entri ## A library save compares names without letter case · after 2.8.3, unreleased (io/library-names.ts sameLibraryName, libraryHas; app.ts saveCore, the Save a Copy path) - Kind: fix · logged 2026-11-29. -- macOS and Windows file systems treat `Poster.fvd` and `poster.fvd` as one file, and the engine's `/projects/save` with no base version replaces what is there. Removed from both places, quoted: `const taken = (await api.library().catch(() => [])).some((i) => i.name === name);`. Save to Library now uses `libraryHas(items, name, p.libraryName ?? null)` (the document's own project is not counted), and Save a Copy `libraryHas(items, name)`; both compare NFC lower case. +- macOS and Windows file systems treat `Poster.fvd` and `poster.fvd` as one file, and the engine's `/projects/save` with no base version replaces what is there. Removed from both places, quoted: `const taken = (await api.library().catch(() => [])).some((i) => i.name === name);`. Save to Library now uses `libraryHas(items, name, p.libraryName ?? null)` (the document's own project is not counted), and Save a Copy `libraryHas(items, name)`; both compare NFC lower case with the ends trimmed, as the engine trims a library name. - Seen: `src/io/library-names.test.ts` and `tsc --noEmit`. Not seen in a window. ## The menu bar's menus open under the bar and are at most three quarters of the window tall · _v2.8.3 (ui/menu.ts MENU_SHARE, MENU_PAD, menuCap, PopupMenu.floor, PopupMenu.openUnder, PopupMenu.openBeside, MenuBar.open) diff --git a/frontend/src/io/library-names.test.ts b/frontend/src/io/library-names.test.ts index bd092a9e..e6c73647 100644 --- a/frontend/src/io/library-names.test.ts +++ b/frontend/src/io/library-names.test.ts @@ -8,6 +8,7 @@ describe('library names', () => { expect(libraryHas(items, 'poster')).toBe(true); expect(libraryHas(items, 'POSTER')).toBe(true); expect(libraryHas(items, 'Café')).toBe(true); + expect(libraryHas(items, ' Poster ')).toBe(true); expect(libraryHas(items, 'Flyer')).toBe(false); }); diff --git a/frontend/src/io/library-names.ts b/frontend/src/io/library-names.ts index f71e7b24..185f7e44 100644 --- a/frontend/src/io/library-names.ts +++ b/frontend/src/io/library-names.ts @@ -1,4 +1,4 @@ -export const sameLibraryName = (a: string, b: string): boolean => a.normalize('NFC').toLowerCase() === b.normalize('NFC').toLowerCase(); +export const sameLibraryName = (a: string, b: string): boolean => a.trim().normalize('NFC').toLowerCase() === b.trim().normalize('NFC').toLowerCase(); export const libraryHas = (items: ReadonlyArray<{ name: string }>, name: string, own: string | null = null): boolean => items.some((i) => sameLibraryName(i.name, name) && !(own !== null && sameLibraryName(i.name, own))); From 4920592243a81c9ffed622562e0be3e2d20063c7 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 12:11:02 -0500 Subject: [PATCH 10/14] fix(agents): the seal carries a version, and a stored choice that cannot be checked blocks outside agents New seals write sealVersion and cover it, so a versioned file is only checked against the current seal and never read in the earlier format. A seal mark must be 64 hex characters before it is compared, as bytes. A file that cannot be read, parsed or checked is a broken seal, and a broken seal blocks outside agents, clears allowed and turns allow policies to ask. --- backend/app/core/seal.py | 41 ++++++++++----- backend/app/services/agents.py | 57 +++++++++++++++------ backend/tests/test_window_key.py | 88 +++++++++++++++++++++++++++++++- 3 files changed, 156 insertions(+), 30 deletions(-) diff --git a/backend/app/core/seal.py b/backend/app/core/seal.py index 795fdd47..2614504a 100644 --- a/backend/app/core/seal.py +++ b/backend/app/core/seal.py @@ -1,13 +1,17 @@ import hashlib import hmac import json +import re import secrets SERVICE = "formvis" ACCOUNT = "agents-seal" FIELD = "seal" -SEALED = ("policies", "allowed", "limits", "blocked") +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} @@ -52,26 +56,37 @@ def loosened(values: dict) -> bool: return values.get("allowed") is True or any(v == "allow" for v in policies.values()) +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, earlier (sealed before Blocked was, to be sealed again), unsealed (no seal and nothing loosened, so the - values stand), broken (a seal that does not match, or no seal on loosened values), 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), unsealed (no seal + 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; or no seal on loosened values), 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): - if hmac.compare_digest(mark, digest(stored, key)): - return "ok" - if hmac.compare_digest(mark, digest(stored, key, EARLIER)): - return "earlier" - if isinstance(mark, str) and mark: + versioned = VERSION_FIELD in stored + if mark is None or mark == "": + return "broken" if versioned or loosened(stored) else "unsealed" + if key is None or not isinstance(mark, str) or not _MARK.fullmatch(mark): return "broken" - return "broken" if loosened(stored) else "unsealed" + if versioned: + version = stored.get(VERSION_FIELD) + current = isinstance(version, int) and not isinstance(version, bool) and version == VERSION + return "ok" if current and _matches(mark, stored, key, SEALED) else "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)} + versioned = {**{k: v for k, v in values.items() if k != FIELD}, VERSION_FIELD: VERSION} + return {**versioned, FIELD: digest(versioned, key)} diff --git a/backend/app/services/agents.py b/backend/app/services/agents.py index 4fde449a..bf68c507 100644 --- a/backend/app/services/agents.py +++ b/backend/app/services/agents.py @@ -43,27 +43,54 @@ def _file(): return config.data_dir() / "agents.json" +def _restrict() -> None: + """The values a stored choice that cannot be read or checked leaves: outside agents blocked, nothing allowed without + asking, and the broken seal reported.""" + _seal["state"] = "broken" + for name, value in list(_policies.items()): + if value == "allow": + _policies[name] = "ask" + _stored["allowed"] = False + _stored["blocked"] = True + + +def _apply(data: dict) -> bool: + """Applies a stored choice; returns whether it is in the earlier seal format and should be sealed again.""" + if not isinstance(data, dict): + raise ValueError("the stored agent choice is not an object") + state = seal.check(data) + _seal["state"] = state + broken = state == "broken" + policies = data.get("policies") or {} + _policies.update({str(k): ("ask" if broken and v == "allow" else v) for k, v in policies.items() if v in POLICIES}) + _stored["allowed"] = False if broken else data.get("allowed") if isinstance(data.get("allowed"), bool) else None + _stored["blocked"] = True if broken else data.get("blocked") is True + saved = data.get("limits") or {} + _limits["roots"] = [str(r) for r in saved.get("roots", []) if isinstance(r, str) and r.strip()][:32] + for key, (low, high) in LIMIT_RANGES.items(): + if isinstance(saved.get(key), int) and low <= saved[key] <= high: + _limits[key] = saved[key] + return state == "earlier" + + def _load() -> None: + """Reads the stored choice once. No file is a first start (the defaults); a file that cannot be read, parsed or + checked is treated as a broken seal, with restrictive values.""" global _loaded if _loaded: return _loaded = True try: - data = json.loads(_file().read_text(encoding="utf-8")) - if not isinstance(data, dict): - return - _seal["state"] = seal.check(data) - broken = _seal["state"] == "broken" - earlier = _seal["state"] == "earlier" - _policies.update({k: ("ask" if broken and v == "allow" else v) for k, v in (data.get("policies") or {}).items() if v in POLICIES}) - _stored["allowed"] = False if broken else data.get("allowed") if isinstance(data.get("allowed"), bool) else None - _stored["blocked"] = data.get("blocked") is True - saved = data.get("limits") or {} - _limits["roots"] = [str(r) for r in saved.get("roots", []) if isinstance(r, str) and r.strip()][:32] - for key, (low, high) in LIMIT_RANGES.items(): - if isinstance(saved.get(key), int) and low <= saved[key] <= high: - _limits[key] = saved[key] - except (OSError, ValueError, AttributeError): + raw = _file().read_text(encoding="utf-8") + except FileNotFoundError: + return + except (OSError, ValueError): + _restrict() + return + try: + earlier = _apply(json.loads(raw)) + except Exception: + _restrict() return if earlier: _save() diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py index 86d10db7..48a7c2b7 100644 --- a/backend/tests/test_window_key.py +++ b/backend/tests/test_window_key.py @@ -1,3 +1,4 @@ +import contextlib import json import pytest @@ -100,6 +101,33 @@ def set_password(self, service, username, password): self.store[(service, username)] = password +@contextlib.contextmanager +def _memory_seal(): + import keyring + from keyring.backend import KeyringBackend + + class Memory(_Memory, KeyringBackend): + pass + + previous = keyring.get_keyring() + keyring.set_keyring(Memory()) + seal.reset() + try: + yield + finally: + keyring.set_keyring(previous) + seal.reset() + + +def _reload_clean(agents, folder): + for name in ("agents.json",): + target = folder / name + if target.exists(): + target.unlink() + agents._limits.update(text_chars=200_000, image_bytes=12 * 1024 * 1024) + _reload(agents) + + def _reload(agents): agents._loaded = False agents._policies.clear() @@ -212,7 +240,63 @@ def test_a_hand_edit_of_the_agent_folders_is_caught(agents, path): def test_a_choice_sealed_before_blocked_was_sealed_stands_and_is_sealed_again(agents, path): agents.set_policy("Codex", "allow") key = seal._load(False) - _edit(path, lambda s: s.update(seal=seal.digest(s, key, seal.EARLIER))) + _edit(path, lambda s: (s.pop(seal.VERSION_FIELD), s.update(seal=seal.digest(s, key, seal.EARLIER)))) _reload(agents) assert agents.state()["seal"] == "ok" and agents.policy_of("Codex") == "allow" - assert json.loads(path.read_text())["seal"] == seal.digest(json.loads(path.read_text()), key) + resealed = json.loads(path.read_text()) + assert resealed[seal.VERSION_FIELD] == seal.VERSION and resealed["seal"] == seal.digest(resealed, key) + + +@_with_memory_keychain +def test_a_versioned_choice_is_never_read_in_the_earlier_format(agents, path): + agents.set_policy("Codex", "allow") + key = seal._load(False) + _edit(path, lambda s: s.update(seal=seal.digest(s, key, seal.EARLIER))) + _reload(agents) + state = agents.state() + assert state["sealBroken"] is True and state["blocked"] is True and agents.policy_of("Codex") == "ask" + + +@pytest.mark.parametrize("version", [1, 3, "2", True, None]) +def test_a_seal_with_another_version_is_broken(version): + with _memory_seal(): + signed = seal.sign({"policies": {"Codex": "allow"}, "allowed": None, "limits": {}, "blocked": False}) + assert signed[seal.VERSION_FIELD] == seal.VERSION and seal.check(signed) == "ok" + assert seal.check({**signed, seal.VERSION_FIELD: version}) == "broken" + assert seal.check({k: v for k, v in signed.items() if k != seal.FIELD}) == "broken" + + +@pytest.mark.parametrize("mark", ["\u00e9" * 64, "A" * 64, "0" * 63, "g" * 64, 12, ["x"], {"a": 1}, True]) +def test_an_odd_seal_mark_is_broken_and_never_raises(mark): + with _memory_seal(): + signed = seal.sign({"policies": {}, "allowed": None, "limits": {}, "blocked": False}) + assert seal.check({**signed, seal.FIELD: mark}) == "broken" + earlier = {k: v for k, v in signed.items() if k != seal.VERSION_FIELD} + assert seal.check({**earlier, seal.FIELD: mark}) == "broken" + + +@pytest.mark.parametrize("text", ["{not json", "[1, 2]", '"text"', '{"policies": ["allow"]}', '{"policies": {"Codex": "allow"}, "limits": []}', + '{"seal": "\u00e9", "policies": {"Codex": "allow"}}', "\udcff"]) +def test_a_stored_choice_that_cannot_be_read_or_checked_blocks_outside_agents(tmp_path, monkeypatch, text): + from app.services import agents + + monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path)) + with _memory_seal(): + (tmp_path / "agents.json").write_text(text, encoding="utf-8", errors="surrogateescape") + try: + _reload(agents) + state = agents.state() + assert state["sealBroken"] is True and state["blocked"] is True and state["allowed"] is False + assert agents.blocked() is True and agents.policy_of("Codex") == "ask" + finally: + _reload_clean(agents, tmp_path) + + +def test_no_stored_choice_is_a_first_start_with_the_defaults(tmp_path, monkeypatch): + from app.services import agents + + monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path)) + with _memory_seal(): + _reload(agents) + state = agents.state() + assert state["sealBroken"] is False and state["blocked"] is False and state["allowed"] is None From 305a06841d79e5702f55deb2f8adf1d2b942ea33 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 12:11:03 -0500 Subject: [PATCH 11/14] fix(agents): through cmd.exe every word is held to one character rule, quoted or not When a program still starts through the Windows command interpreter, any word, its path included, with one of & | < > ^ ( ) ! % " or a control character is refused, with a message to pass long text through standard input or a file. The quote-based reading is gone. A shim whose node is itself a batch file is not started directly. LOOKUP_HASHES records the finder's new hash; the living log records both changes. --- backend/HASHOUT_LOG.md | 4 +++- backend/app/services/agent_lookup.py | 34 ++++++++-------------------- backend/tests/test_agent_lookup.py | 33 ++++++++++++++++++++------- setup/agents.py | 2 +- 4 files changed, 39 insertions(+), 34 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 2ad830ec..a88993ca 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ 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.3, unreleased (routers/comfyui.py status, last_graph, upscale_models_route, job, image; core/seal.py SEALED, EARLIER, check; 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) +## Hardening of the ComfyUI reads, the agent seal, the agent file writes, the library move and the Windows starter · after 2.8.3, 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`. @@ -11,6 +11,8 @@ Living log for the engine service side, _v0.1.0. Read the map and the TOC first; - **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`. +- **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`) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index 209c9ec6..8794f898 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -368,8 +368,7 @@ class CommandLineRefused(OSError): _SHIM_EXE = re.compile(r'(?:^|&)[ \t]*@?' + _DP0.format(ext="exe") + r'[ \t]+%\*[ \t\r]*$', re.I | re.M) _SHIM_SETS = re.compile(r'\bset[ \t]+"?([A-Za-z_]\w*)=', re.I) _SHIM_OWN_VARS = frozenset({"dp0", "_prog", "pathext"}) -_CMD_SPECIAL = frozenset("&|<>^()") -_CMD_REFUSED = re.compile(r"[\x00-\x1f\x7f%]") +_CMD_REFUSED = re.compile(r'[&|<>^()!%"\x00-\x1f\x7f]') def _beside(folder: Path, rel: str) -> Path: @@ -399,29 +398,16 @@ def shim_target(shim: str, env: dict | None = None) -> list[str] | None: return None -def _cmd_unquoted(line: str) -> bool: - quoted = False - for ch in line: - if ch == '"': - quoted = not quoted - elif not quoted and ch in _CMD_SPECIAL: - return True - return False - - def cmd_safe(words: list[str]) -> None: - """Raises CommandLineRefused unless every word reaches the program unchanged through cmd.exe /c and a batch file's %*: - no control characters and no %, and none of & | < > ^ ( ) outside quotes, read the ways cmd.exe may read the line.""" - for word in words: + """Raises CommandLineRefused unless every word, the program's path included, is free of the characters cmd.exe /c + or a batch file's %* may act on: & | < > ^ ( ) ! % " and control characters. Quotes do not protect a word there, so + no word is let through because it is quoted or has no spaces.""" + for index, word in enumerate(words): if _CMD_REFUSED.search(word): - raise CommandLineRefused("A word for this program has a line break, a control character or %, which the Windows command interpreter would change.") - line = subprocess.list2cmdline(words) - readings = [line, subprocess.list2cmdline(words[1:])] - if line.startswith('"'): - last = line.rfind('"') - readings.append(line[1:last] + line[last + 1:]) - if any(_cmd_unquoted(reading) for reading in readings): - raise CommandLineRefused("A word for this program has an unmatched quote or one of & | < > ^ ( ) that the Windows command interpreter would act on.") + what = "The path of this program" if index == 0 else "A word for this program" + raise CommandLineRefused(f"{what} has one of & | < > ^ ( ) ! % \" or a control character, which the Windows command " + "interpreter that starts it could change. Pass long or special text through standard input or a file " + "if the program supports it, or install the program so it starts without the command interpreter.") def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: @@ -434,7 +420,7 @@ def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) if not words[0].lower().endswith((".cmd", ".bat")): return words direct = shim_target(words[0], env) - if direct: + if direct and not direct[0].lower().endswith((".cmd", ".bat")): return [*direct, *words[1:]] cmd_safe(words) return [env.get("COMSPEC") or "cmd.exe", "/c", *words] diff --git a/backend/tests/test_agent_lookup.py b/backend/tests/test_agent_lookup.py index 46f65b36..e611eb5b 100644 --- a/backend/tests/test_agent_lookup.py +++ b/backend/tests/test_agent_lookup.py @@ -197,22 +197,39 @@ def test_on_windows_an_old_style_shim_to_an_exe_starts_the_exe(tmp_path): assert agent_lookup.start_argv([str(shim), "a b"], {}, "win32") == [str(tmp_path / "vendor" / "tool.exe"), "a b"] -@pytest.mark.parametrize("word", [TYPED, "50% brighter", "two\nlines", "a&b", "x|y", "", "caret^", "(group)", + "wow!", 'say "hi"', '"quoted & safe"', "make the sky blue & the sea green", "keep (this) as it is", + claude_code.inapp_mcp_config(8190)]) +def test_on_windows_a_word_with_a_command_interpreter_character_is_refused_quoted_or_not(word): + with pytest.raises(agent_lookup.CommandLineRefused, match="standard input or a file"): agent_lookup.start_argv(["C:\\npm\\codex.cmd", "--", word], {"COMSPEC": "C:\\Windows\\cmd.exe"}, "win32") -@pytest.mark.parametrize("word", ["make the sky blue & the sea green", "keep (this) as it is", 'one "two" & three', claude_code.inapp_mcp_config(8190), "plain"]) -def test_on_windows_words_the_command_interpreter_passes_unchanged_still_go_through_it(word): +@pytest.mark.parametrize("word", ["plain", "two words", "--flag=value", "C:\\Users\\A B\\file.txt", "a,b;c", "it's fine"]) +def test_on_windows_plain_words_still_go_through_the_command_interpreter(word): argv = agent_lookup.start_argv(["C:\\npm\\codex.cmd", "--", word], {"COMSPEC": "C:\\Windows\\cmd.exe"}, "win32") assert argv == ["C:\\Windows\\cmd.exe", "/c", "C:\\npm\\codex.cmd", "--", word] -def test_on_windows_a_program_path_with_a_space_is_read_as_the_command_interpreter_may_strip_its_quotes(): - with pytest.raises(agent_lookup.CommandLineRefused): - agent_lookup.start_argv(["C:\\Users\\A B\\npm\\codex.cmd", "--", "red & blue"], {}, "win32") +def test_on_windows_the_program_path_is_held_to_the_same_rule(): assert agent_lookup.start_argv(["C:\\Users\\A B\\npm\\codex.cmd", "--version"], {}, "win32")[-1] == "--version" + for path in ("C:\\Program Files (x86)\\tool\\tool.cmd", "C:\\100%\\tool.cmd", "C:\\a&b\\tool.bat"): + with pytest.raises(agent_lookup.CommandLineRefused, match="path of this program"): + agent_lookup.start_argv([path, "--version"], {}, "win32") + + +def test_on_windows_a_shim_whose_node_is_itself_a_batch_file_is_not_started_directly(tmp_path, monkeypatch): + shim = tmp_path / "codex.cmd" + shim.write_text(NPM_SHIM) + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("") + node_cmd = str(tmp_path / "elsewhere" / "node.cmd") + monkeypatch.setattr(agent_lookup.shutil, "which", lambda name, path=None: node_cmd if name == "node" else None) + assert agent_lookup.shim_target(str(shim), {}) == [node_cmd, str(script)] + with pytest.raises(agent_lookup.CommandLineRefused): + agent_lookup.start_argv([str(shim), "--", TYPED], {}, "win32") + assert agent_lookup.start_argv([str(shim), "--version"], {"COMSPEC": "cmd.exe"}, "win32") == ["cmd.exe", "/c", str(shim), "--version"] def test_on_windows_an_older_npm_shim_starts_its_script_with_node(tmp_path): diff --git a/setup/agents.py b/setup/agents.py index e985983b..9e7925db 100755 --- a/setup/agents.py +++ b/setup/agents.py @@ -193,7 +193,7 @@ def dock_problems() -> list[str]: LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "39d837d87b04abab6a3439cf21be503a4f3a1516d1d9ef59e5cf29dc5caefd5e"} # the family's record: the SHA-256 of the shared finder at each of its versions +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "c1fd039264c930cdf36394cf8a01d263b370625dee1ad00c83ff8876fe50df91"} # the family's record: the SHA-256 of the shared finder at each of its versions def lookup_problems() -> list[str]: From dc538599735c890db516a36f2f718ebff9f1c9c3 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 12:48:21 -0500 Subject: [PATCH 12/14] fix(agents): a missing seal reads as broken once the keychain has sealed, and the earlier format keeps Blocked on A stored choice with no seal mark stands only while the keychain holds no seal key and no versioned file has been sealed, and only when nothing is loosened; loosened now also counts outside agents not blocked and folder limits that are empty or that the loader would change. Sealing a versioned file is recorded in the keychain, and from then on the earlier format is refused. A file accepted in the earlier format, whose seal never covered blocked, keeps Blocked on and allowed false until it is sealed again. --- backend/HASHOUT_LOG.md | 1 + backend/app/core/seal.py | 58 +++++++++++++++---- backend/app/services/agents.py | 9 ++- backend/tests/test_window_key.py | 96 +++++++++++++++++++++++++++++++- docs/MANUAL.md | 5 +- 5 files changed, 150 insertions(+), 19 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index a88993ca..39854aba 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -12,6 +12,7 @@ Living log for the engine service side, _v0.1.0. Read the map and the TOC first; - **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 in the keychain (account `agents-seal-version`, `RECORD`) that a versioned file was sealed; from then on `check` returns `broken` for the earlier format. 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. - **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. diff --git a/backend/app/core/seal.py b/backend/app/core/seal.py index 2614504a..ec8f3e2c 100644 --- a/backend/app/core/seal.py +++ b/backend/app/core/seal.py @@ -6,17 +6,18 @@ SERVICE = "formvis" ACCOUNT = "agents-seal" +RECORD = "agents-seal-version" # kept in the keychain once a versioned file is sealed, so the earlier format is refused after FIELD = "seal" 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} +_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 _load(create: bool) -> bytes | None: @@ -34,13 +35,29 @@ def _load(create: bool) -> bytes | None: keyring.set_password(SERVICE, ACCOUNT, secrets.token_hex(32)) stored = keyring.get_password(SERVICE, ACCOUNT) key = bytes.fromhex(stored) if stored else None + recorded = bool(keyring.get_password(SERVICE, RECORD)) 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 that a versioned file has been sealed. It is kept in memory even when the keychain refuses + the write, so this session never reads the earlier format again either.""" + if _CACHE["recorded"]: + return + _CACHE["recorded"] = True + try: + import keyring + + keyring.set_password(SERVICE, RECORD, str(VERSION)) + except Exception: + return + + + def available() -> bool: _load(False) return _CACHE["available"] @@ -51,9 +68,18 @@ def digest(values: dict, key: bytes, fields: tuple = SEALED) -> str: 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: @@ -61,11 +87,13 @@ def _matches(mark: str, values: dict, key: bytes, fields: tuple) -> bool: def check(stored: dict) -> str: - """ok, earlier (a file in the format from before the seal carried a version, to be sealed again), unsealed (no seal - 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; or no seal on loosened values), 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.""" + """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" @@ -74,13 +102,18 @@ def check(stored: dict) -> str: mark = stored.get(FIELD) versioned = VERSION_FIELD in stored if mark is None or mark == "": - return "broken" if versioned or loosened(stored) else "unsealed" + 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 - return "ok" if current and _matches(mark, stored, key, SEALED) else "broken" + if not (current and _matches(mark, stored, key, SEALED)): + return "broken" + _record() + return "ok" + if _CACHE["recorded"]: + return "broken" return "earlier" if _matches(mark, stored, key, EARLIER) else "broken" @@ -88,5 +121,6 @@ def sign(values: dict) -> dict: key = _load(True) if key is None: 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)} diff --git a/backend/app/services/agents.py b/backend/app/services/agents.py index bf68c507..d41abb7e 100644 --- a/backend/app/services/agents.py +++ b/backend/app/services/agents.py @@ -55,16 +55,19 @@ def _restrict() -> None: def _apply(data: dict) -> bool: - """Applies a stored choice; returns whether it is in the earlier seal format and should be sealed again.""" + """Applies a stored choice; returns whether it is in the earlier seal format and should be sealed again. The earlier + seal does not cover blocked, so a file in that format keeps the restrictive values for blocked and allowed until it + is sealed again; its policies and limits, which that seal covers, stand.""" if not isinstance(data, dict): raise ValueError("the stored agent choice is not an object") state = seal.check(data) _seal["state"] = state broken = state == "broken" + restrict = broken or state == "earlier" policies = data.get("policies") or {} _policies.update({str(k): ("ask" if broken and v == "allow" else v) for k, v in policies.items() if v in POLICIES}) - _stored["allowed"] = False if broken else data.get("allowed") if isinstance(data.get("allowed"), bool) else None - _stored["blocked"] = True if broken else data.get("blocked") is True + _stored["allowed"] = False if restrict else data.get("allowed") if isinstance(data.get("allowed"), bool) else None + _stored["blocked"] = True if restrict else data.get("blocked") is True saved = data.get("limits") or {} _limits["roots"] = [str(r) for r in saved.get("roots", []) if isinstance(r, str) and r.strip()][:32] for key, (low, high) in LIMIT_RANGES.items(): diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py index 48a7c2b7..f8271966 100644 --- a/backend/tests/test_window_key.py +++ b/backend/tests/test_window_key.py @@ -236,17 +236,109 @@ def test_a_hand_edit_of_the_agent_folders_is_caught(agents, path): assert agents.state()["sealBroken"] is True +def _as_written_before_versions(path): + """Turns the stored choice into one sealed in the earlier format, by a keychain that never sealed a versioned file.""" + import keyring + + key = seal._load(False) + keyring.get_keyring().store.pop((seal.SERVICE, seal.RECORD), None) + seal.reset() + _edit(path, lambda s: (s.pop(seal.VERSION_FIELD), s.update(seal=seal.digest(s, key, seal.EARLIER)))) + return key + + @_with_memory_keychain def test_a_choice_sealed_before_blocked_was_sealed_stands_and_is_sealed_again(agents, path): agents.set_policy("Codex", "allow") - key = seal._load(False) - _edit(path, lambda s: (s.pop(seal.VERSION_FIELD), s.update(seal=seal.digest(s, key, seal.EARLIER)))) + key = _as_written_before_versions(path) _reload(agents) assert agents.state()["seal"] == "ok" and agents.policy_of("Codex") == "allow" resealed = json.loads(path.read_text()) assert resealed[seal.VERSION_FIELD] == seal.VERSION and resealed["seal"] == seal.digest(resealed, key) +@_with_memory_keychain +def test_a_choice_in_the_earlier_format_keeps_blocked_and_allowed_restrictive(agents, path): + agents.set_policy("Codex", "allow") + key = _as_written_before_versions(path) + _edit(path, lambda s: (s.update(blocked=False, allowed=True), s.update(seal=seal.digest(s, key, seal.EARLIER)))) + _reload(agents) + state = agents.state() + assert state["blocked"] is True and state["allowed"] is False and agents.policy_of("Codex") == "allow" + resealed = json.loads(path.read_text()) + assert resealed["blocked"] is True and resealed["allowed"] is False and seal.check(resealed) == "ok" + + +@_with_memory_keychain +def test_the_earlier_format_is_refused_once_a_versioned_choice_was_sealed(agents, path): + import keyring + + agents.set_policy("Codex", "allow") + assert keyring.get_keyring().store.get((seal.SERVICE, seal.RECORD)) + key = seal._load(False) + _edit(path, lambda s: (s.pop(seal.VERSION_FIELD), s.update(seal=seal.digest(s, key, seal.EARLIER)))) + seal.reset() + _reload(agents) + state = agents.state() + assert state["sealBroken"] is True and state["blocked"] is True and state["allowed"] is False + assert agents.policy_of("Codex") == "ask" + + +@_with_memory_keychain +def test_a_choice_with_its_seal_removed_is_broken_once_a_seal_key_exists(agents, path): + agents.set_blocked(True) + agents.set_limits({"roots": [str(path.parent / "work")]}) + _edit(path, lambda s: (s.pop(seal.FIELD), s.pop(seal.VERSION_FIELD))) + _reload(agents) + state = agents.state() + assert state["sealBroken"] is True and state["blocked"] is True and state["allowed"] is False + + +RESTRICTIVE = {"policies": {"Codex": "ask"}, "allowed": None, "limits": {"roots": ["/work"]}, "blocked": True} + + +def test_an_unsealed_choice_is_broken_once_a_seal_key_exists(): + import keyring + + with _memory_seal(): + keyring.set_password(seal.SERVICE, seal.ACCOUNT, "ab" * 32) + seal.reset() + assert seal.check(RESTRICTIVE) == "broken" + + +def test_an_unsealed_choice_is_broken_once_a_versioned_choice_was_sealed(): + import keyring + + with _memory_seal(): + keyring.set_password(seal.SERVICE, seal.RECORD, str(seal.VERSION)) + seal.reset() + assert seal.check(RESTRICTIVE) == "broken" + + +@pytest.mark.parametrize("change", [{"blocked": False}, {"blocked": None}, {"blocked": "yes"}, {"limits": {"roots": []}}, {"limits": {}}, + {"limits": {"roots": [" "]}}, {"limits": {"roots": "/work"}}, {"limits": {"roots": ["/work", 3]}}, + {"limits": {"roots": [f"/w{i}" for i in range(33)]}}, {"limits": None}]) +def test_an_unsealed_choice_that_lets_more_through_is_broken(change): + with _memory_seal(): + assert seal.check(RESTRICTIVE) == "unsealed" + assert seal.check({**RESTRICTIVE, **change}) == "broken" + without_blocked = {k: v for k, v in RESTRICTIVE.items() if k != "blocked"} + assert seal.check(without_blocked) == "broken" + + +def test_a_versioned_choice_that_checks_records_that_one_was_sealed(): + import keyring + + with _memory_seal(): + signed = seal.sign(RESTRICTIVE) + store = keyring.get_keyring().store + assert store.pop((seal.SERVICE, seal.RECORD)) == str(seal.VERSION) + seal.reset() + assert seal.check(signed) == "ok" and store[(seal.SERVICE, seal.RECORD)] == str(seal.VERSION) + earlier = {k: v for k, v in signed.items() if k != seal.VERSION_FIELD} + assert seal.check({**earlier, seal.FIELD: seal.digest(earlier, seal._load(False), seal.EARLIER)}) == "broken" + + @_with_memory_keychain def test_a_versioned_choice_is_never_read_in_the_earlier_format(agents, path): agents.set_policy("Codex", "allow") diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 62197c08..8246efba 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -627,8 +627,9 @@ other modes and depths its menu items are off, with the reason as their tooltip. - Only the formvis window can change what agents may do, answer their questions and approvals, or use the terminal dock: the engine gives the window a key when it starts and refuses those requests from anything else ("Only the formvis window can do this"). The saved choice is sealed; if the file is changed outside formvis, the choice reads as - Ask again and formvis says so once. formvis's own command line (`./formvis cli`, `./formvis headless`) is asked - about like any other outside agent. + Ask again and formvis says so once. A choice saved in the older sealed format is sealed again the first time a + newer formvis starts, with Outside agents set to Blocked; set it back in Preferences > Plugins if you had it open. + formvis's own command line (`./formvis cli`, `./formvis headless`) is asked about like any other outside agent. ## Terminal From 9c4958beb4c2c5fea89fd0a04f30220d0f772603 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 12:51:44 -0500 Subject: [PATCH 13/14] fix(agents): the seal key and the sealed-version record share one keychain item The record that a versioned file was sealed is kept beside the key in the agents-seal item (the key in hex followed by :v2), so the two cannot be changed apart; an item in the earlier layout gains the mark on the next seal. An item that cannot be read as a key counts as no key and recorded, so stored choices read as broken instead of the seal turning off, and a refused write of the record keeps it in memory with the key still in use. --- backend/HASHOUT_LOG.md | 2 +- backend/app/core/seal.py | 44 +++++++++++++++++------ backend/tests/test_window_key.py | 62 +++++++++++++++++++++++++++++--- 3 files changed, 92 insertions(+), 16 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 39854aba..9c6ece46 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -12,7 +12,7 @@ Living log for the engine service side, _v0.1.0. Read the map and the TOC first; - **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 in the keychain (account `agents-seal-version`, `RECORD`) that a versioned file was sealed; from then on `check` returns `broken` for the earlier format. 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. +- **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. - **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. diff --git a/backend/app/core/seal.py b/backend/app/core/seal.py index ec8f3e2c..16bf3be1 100644 --- a/backend/app/core/seal.py +++ b/backend/app/core/seal.py @@ -6,7 +6,6 @@ SERVICE = "formvis" ACCOUNT = "agents-seal" -RECORD = "agents-seal-version" # kept in the keychain once a versioned file is sealed, so the earlier format is refused after FIELD = "seal" VERSION_FIELD = "sealVersion" VERSION = 2 @@ -20,6 +19,28 @@ def reset() -> 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: if _CACHE["tried"] and (_CACHE["key"] is not None or not _CACHE["available"] or not create): return _CACHE["key"] @@ -30,12 +51,11 @@ 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 - recorded = bool(keyring.get_password(SERVICE, RECORD)) + 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, recorded=False) return None @@ -44,15 +64,19 @@ def _load(create: bool) -> bytes | None: def _record() -> None: - """Notes in the keychain that a versioned file has been sealed. It is kept in memory even when the keychain refuses - the write, so this session never reads the earlier format again either.""" + """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, RECORD, str(VERSION)) + keyring.set_password(SERVICE, ACCOUNT, _item(key.hex(), True)) except Exception: return diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py index f8271966..9e39fb52 100644 --- a/backend/tests/test_window_key.py +++ b/backend/tests/test_window_key.py @@ -241,7 +241,7 @@ def _as_written_before_versions(path): import keyring key = seal._load(False) - keyring.get_keyring().store.pop((seal.SERVICE, seal.RECORD), None) + keyring.get_keyring().store[(seal.SERVICE, seal.ACCOUNT)] = key.hex() seal.reset() _edit(path, lambda s: (s.pop(seal.VERSION_FIELD), s.update(seal=seal.digest(s, key, seal.EARLIER)))) return key @@ -274,8 +274,8 @@ def test_the_earlier_format_is_refused_once_a_versioned_choice_was_sealed(agents import keyring agents.set_policy("Codex", "allow") - assert keyring.get_keyring().store.get((seal.SERVICE, seal.RECORD)) key = seal._load(False) + assert keyring.get_keyring().store[(seal.SERVICE, seal.ACCOUNT)] == f"{key.hex()}:v{seal.VERSION}" _edit(path, lambda s: (s.pop(seal.VERSION_FIELD), s.update(seal=seal.digest(s, key, seal.EARLIER)))) seal.reset() _reload(agents) @@ -310,9 +310,11 @@ def test_an_unsealed_choice_is_broken_once_a_versioned_choice_was_sealed(): import keyring with _memory_seal(): - keyring.set_password(seal.SERVICE, seal.RECORD, str(seal.VERSION)) + keyring.set_password(seal.SERVICE, seal.ACCOUNT, f":v{seal.VERSION}") seal.reset() assert seal.check(RESTRICTIVE) == "broken" + signed = seal.sign(RESTRICTIVE) + assert seal.check(signed) == "ok" and keyring.get_password(seal.SERVICE, seal.ACCOUNT).endswith(f":v{seal.VERSION}") @pytest.mark.parametrize("change", [{"blocked": False}, {"blocked": None}, {"blocked": "yes"}, {"limits": {"roots": []}}, {"limits": {}}, @@ -332,9 +334,11 @@ def test_a_versioned_choice_that_checks_records_that_one_was_sealed(): with _memory_seal(): signed = seal.sign(RESTRICTIVE) store = keyring.get_keyring().store - assert store.pop((seal.SERVICE, seal.RECORD)) == str(seal.VERSION) + key_hex = seal._load(False).hex() + assert store[(seal.SERVICE, seal.ACCOUNT)] == f"{key_hex}:v{seal.VERSION}" + store[(seal.SERVICE, seal.ACCOUNT)] = key_hex seal.reset() - assert seal.check(signed) == "ok" and store[(seal.SERVICE, seal.RECORD)] == str(seal.VERSION) + assert seal.check(signed) == "ok" and store[(seal.SERVICE, seal.ACCOUNT)] == f"{key_hex}:v{seal.VERSION}" earlier = {k: v for k, v in signed.items() if k != seal.VERSION_FIELD} assert seal.check({**earlier, seal.FIELD: seal.digest(earlier, seal._load(False), seal.EARLIER)}) == "broken" @@ -392,3 +396,51 @@ def test_no_stored_choice_is_a_first_start_with_the_defaults(tmp_path, monkeypat _reload(agents) state = agents.state() assert state["sealBroken"] is False and state["blocked"] is False and state["allowed"] is None + + +def test_a_key_in_the_layout_before_the_record_still_seals_and_any_mark_reads_as_recorded(): + import keyring + + with _memory_seal(): + keyring.set_password(seal.SERVICE, seal.ACCOUNT, "ab" * 32) + seal.reset() + earlier = {k: v for k, v in RESTRICTIVE.items() if k != "blocked"} + assert seal.check({**earlier, seal.FIELD: seal.digest(earlier, bytes.fromhex("ab" * 32), seal.EARLIER)}) == "earlier" + keyring.set_password(seal.SERVICE, seal.ACCOUNT, "ab" * 32 + ":odd") + seal.reset() + assert seal.check({**earlier, seal.FIELD: seal.digest(earlier, bytes.fromhex("ab" * 32), seal.EARLIER)}) == "broken" + assert seal._load(False) == bytes.fromhex("ab" * 32) + + +def test_when_the_record_cannot_be_written_the_seal_stays_on_and_the_earlier_format_is_refused(): + import keyring + + with _memory_seal(): + signed = seal.sign(RESTRICTIVE) + key = seal._load(False) + backend = keyring.get_keyring() + backend.store[(seal.SERVICE, seal.ACCOUNT)] = key.hex() + seal.reset() + + def refuse(service, username, password): + raise RuntimeError("the keychain refused the write") + + backend.set_password = refuse + assert seal.check(signed) == "ok" + assert seal.available() is True and seal._load(False) == key + earlier = {k: v for k, v in signed.items() if k != seal.VERSION_FIELD} + assert seal.check({**earlier, seal.FIELD: seal.digest(earlier, key, seal.EARLIER)}) == "broken" + assert seal.check({k: v for k, v in RESTRICTIVE.items()}) == "broken" + + +@pytest.mark.parametrize("item", ["not hex", "zz" * 32 + ":v2", ":", "ab" * 31 + "a"]) +def test_a_damaged_keychain_item_keeps_the_seal_on_and_breaks_stored_choices(item): + import keyring + + with _memory_seal(): + keyring.set_password(seal.SERVICE, seal.ACCOUNT, item) + seal.reset() + assert seal.available() is True and seal.check(RESTRICTIVE) == "broken" + signed = seal.sign(RESTRICTIVE) + assert seal.check(signed) == "ok" + assert keyring.get_password(seal.SERVICE, seal.ACCOUNT).endswith(f":v{seal.VERSION}") From 7eec29105c6d21f5667871376f61fd1017ca8992 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 13:04:09 -0500 Subject: [PATCH 14/14] test: the engine tests run with a home folder of their own on every system conftest.py points HOME, USERPROFILE, LOCALAPPDATA, APPDATA and the XDG folders at a temporary folder before any test module is imported, since localgen.paths reads the data folder at import. The ffmpeg fixture set only XDG_DATA_HOME, which macOS and Windows ignore, so it wrote a stub ffmpeg into the shared folder and left it on PATH; it now redirects every folder ff.folder() reads into tmp_path, restores PATH and checks the real folder is unchanged. The shared model folder for the segmentation tests moves beside pytest's temporary folders. --- backend/HASHOUT_LOG.md | 1 + backend/tests/conftest.py | 32 ++++++++++++++++++++++++++++ backend/tests/test_ffmpeg_sources.py | 25 ++++++++++++++++++++-- backend/tests/test_select_object.py | 9 ++++---- backend/tests/test_stand_in_home.py | 24 +++++++++++++++++++++ 5 files changed, 85 insertions(+), 6 deletions(-) create mode 100644 backend/tests/test_stand_in_home.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 9c6ece46..caa5da29 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -13,6 +13,7 @@ Living log for the engine service side, _v0.1.0. Read the map and the TOC first; - **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. diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index a218e718..4d4b8b9d 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -1,12 +1,44 @@ import io import os +import shutil +import tempfile import time +from pathlib import Path import pytest from fastapi.testclient import TestClient from PIL import Image +HOME_VARIABLES = ("HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME") + + +def _stand_in_home() -> tuple[Path, dict]: + """Points the home folder and the per-user folders of macOS, Windows and Linux at a temporary folder, before any + test module is imported, so the default data folder (read once at import by localgen.paths), the shared ffmpeg + folder and anything else reached through the home folder never land in the person's own folders. A test that wants + another home sets HOME itself.""" + home = Path(tempfile.mkdtemp(prefix="formvis-tests-home-")).resolve() + places = {"HOME": home, "USERPROFILE": home, "LOCALAPPDATA": home / "AppData" / "Local", "APPDATA": home / "AppData" / "Roaming", + "XDG_DATA_HOME": home / ".local" / "share", "XDG_CONFIG_HOME": home / ".config", "XDG_CACHE_HOME": home / ".cache", + "XDG_STATE_HOME": home / ".local" / "state"} + before = {name: os.environ.get(name) for name in HOME_VARIABLES} + os.environ.update({name: str(places[name]) for name in HOME_VARIABLES}) + return home, before + + +STAND_IN_HOME, _HOME_BEFORE = _stand_in_home() + + +def pytest_unconfigure(config): + for name, value in _HOME_BEFORE.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + shutil.rmtree(STAND_IN_HOME, ignore_errors=True) + + @pytest.fixture(autouse=True) def fresh_secrets(monkeypatch): from app.services import secrets diff --git a/backend/tests/test_ffmpeg_sources.py b/backend/tests/test_ffmpeg_sources.py index c599e477..a2b202dd 100644 --- a/backend/tests/test_ffmpeg_sources.py +++ b/backend/tests/test_ffmpeg_sources.py @@ -1,6 +1,8 @@ import hashlib import io +import os import tarfile +from pathlib import Path import pytest @@ -29,11 +31,27 @@ def test_the_override_is_the_only_source(monkeypatch): assert ff.sources() == [f"https://mirror.example/ffmpeg/ffmpeg-lgpl-{ff.RELEASE}-{ff.host_triple()}.tar.gz"] +def _home_in(tmp_path: Path, monkeypatch) -> Path: + """Points every folder ff.folder() can use (the home folder, LOCALAPPDATA and XDG_DATA_HOME) inside tmp_path, so no + test writes into the person's own folders on any system.""" + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.setenv("LOCALAPPDATA", str(home / "AppData" / "Local")) + monkeypatch.setenv("XDG_DATA_HOME", str(home / ".local" / "share")) + monkeypatch.setattr(Path, "home", classmethod(lambda cls: home)) + return home + + @pytest.fixture() def fake_release(tmp_path, monkeypatch): + real = ff.folder() + before = sorted(real.iterdir()) if real.is_dir() else None + _home_in(tmp_path, monkeypatch) + assert tmp_path in ff.folder().parents name = f"ffmpeg-{ff.host_triple()}" good = b"#!/bin/sh\necho ffmpeg\n" - monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "share")) monkeypatch.delenv("FORMCUT_FFMPEG_RELEASE", raising=False) monkeypatch.setattr(ff, "FILES", {ff.host_triple(): ((name, hashlib.sha256(good).hexdigest()),)}) monkeypatch.setattr(ff, "SOURCES", ("https://new.example", "https://old.example")) @@ -47,7 +65,10 @@ def download(url, target): target.write_bytes(served[url.split("/")[2]]) monkeypatch.setattr(ff, "_download", download) - return name, good, served, asked + monkeypatch.setenv("PATH", os.environ.get("PATH", "")) + yield name, good, served, asked + assert tmp_path in ff.folder().parents + assert (sorted(real.iterdir()) if real.is_dir() else None) == before, f"a test wrote into {real}" def test_bytes_that_do_not_match_on_the_first_address_fall_back_to_the_second(fake_release): diff --git a/backend/tests/test_select_object.py b/backend/tests/test_select_object.py index 7c8d5de1..cf3279d8 100644 --- a/backend/tests/test_select_object.py +++ b/backend/tests/test_select_object.py @@ -1,7 +1,6 @@ import io import json import os -from pathlib import Path import pytest from PIL import Image, ImageDraw @@ -19,9 +18,11 @@ def need_sam_model(): @pytest.fixture(autouse=True) -def shared_models(monkeypatch): - # One verified checkpoint for every test run, not one per temporary data folder. - monkeypatch.setenv("FORMVIS_MODELS_DIR", os.environ.get("FORMVIS_MODELS_DIR") or str(Path.home() / ".cache" / "formvis-models")) +def shared_models(monkeypatch, tmp_path_factory): + # One verified checkpoint for every test in a run, not one per temporary data folder, kept beside pytest's own + # temporary folders rather than in the home folder. FORMVIS_MODELS_DIR points the tests at a folder already filled. + shared = tmp_path_factory.getbasetemp().parent / "formvis-models" + monkeypatch.setenv("FORMVIS_MODELS_DIR", os.environ.get("FORMVIS_MODELS_DIR") or str(shared)) def _scene() -> tuple[bytes, object, object]: diff --git a/backend/tests/test_stand_in_home.py b/backend/tests/test_stand_in_home.py new file mode 100644 index 00000000..f47215d7 --- /dev/null +++ b/backend/tests/test_stand_in_home.py @@ -0,0 +1,24 @@ +"""The tests run with a home folder of their own (conftest.py), so nothing they write lands in the person's folders.""" + +from pathlib import Path + +from app import ffmpeg_fetch as ff +from app.core import config +from tests.conftest import STAND_IN_HOME + + +def _inside(path: Path) -> bool: + return STAND_IN_HOME == path.resolve() or STAND_IN_HOME in path.resolve().parents + + +def test_the_home_folder_and_the_per_user_folders_are_the_stand_in(): + assert _inside(Path.home()) + assert _inside(config.platform_data_dir()) + assert _inside(ff.folder()) + + +def test_the_data_folder_read_at_import_is_inside_the_stand_in(): + from app.localgen import paths + + if not _inside(paths.DATA_DIR): + assert paths.DATA_DIR == config.data_dir() and config.data_dir_source() != "default", "the data folder read at import is the person's own"