From ea7738246f60c02a8da864d6962d026533b43191 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:48:23 -0500 Subject: [PATCH 01/12] fix: escape recovered titles and session names before showing them The restore bar on the home screen and the Connections list in Settings built their rows as markup from text that comes from a saved journal or another program. Both now go through escapeHtml, as the home cards already did. --- frontend/src/ui/settings-popout.ts | 5 +++-- frontend/src/ui/start-screen.ts | 2 +- tests/test_shown_text_escaped.py | 35 ++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 tests/test_shown_text_escaped.py diff --git a/frontend/src/ui/settings-popout.ts b/frontend/src/ui/settings-popout.ts index d533d2cb..7ad71015 100644 --- a/frontend/src/ui/settings-popout.ts +++ b/frontend/src/ui/settings-popout.ts @@ -6,6 +6,7 @@ import { t } from "../i18n"; import { localizeElement, text } from "../i18n/text"; import { icon } from "./icons"; +import { escapeHtml } from "./safe-text"; import type { ProjectEngine } from "../engine/project"; import type { MediaBin } from "../engine/media"; import { ACCENTS, PROFILES, apply, read, setAccent, setTheme } from "./appearance"; @@ -446,7 +447,7 @@ export function installSettingsPopout(engine: ProjectEngine, bin: MediaBin, open const row = document.createElement("div"); row.className = "panel-row"; const last = session.operations.at(-1)?.method ?? ""; - row.innerHTML = `${session.name}${session.agent ? ` · ${session.agent}` : ""}${session.operations.length} ${t("conn.calls")}${last ? ` · ${last}` : ""}`; + row.innerHTML = `${escapeHtml(String(session.name))}${session.agent ? ` · ${escapeHtml(String(session.agent))}` : ""}${session.operations.length} ${t("conn.calls")}${last ? ` · ${escapeHtml(String(last))}` : ""}`; sessionList.append(row); } } catch { @@ -467,7 +468,7 @@ export function installSettingsPopout(engine: ProjectEngine, bin: MediaBin, open const row = document.createElement("div"); row.className = "panel-row"; const percent = Math.round(job.progress * 100); - row.innerHTML = `${job.kind} · ${t("conn.status." + job.status) || job.status}${job.status === "running" ? ` ${percent}%` : ""}`; + row.innerHTML = `${escapeHtml(String(job.kind))} · ${escapeHtml(String(t("conn.status." + job.status) || job.status))}${job.status === "running" ? ` ${percent}%` : ""}`; if (job.status === "running") { const stop = document.createElement("button"); stop.className = "tool-chip"; diff --git a/frontend/src/ui/start-screen.ts b/frontend/src/ui/start-screen.ts index 11c713e1..f4f3db51 100644 --- a/frontend/src/ui/start-screen.ts +++ b/frontend/src/ui/start-screen.ts @@ -266,7 +266,7 @@ export function buildStartScreen(engine: ProjectEngine, bin: MediaBin): HTMLElem fresh.className = "restore-bar"; fresh.dataset.ref = "restore"; fresh.dataset.key = newest.key; - fresh.innerHTML = `${t("save.recover")}: ${newest.title || t("start.new")}`; + fresh.innerHTML = `${t("save.recover")}: ${escapeHtml(String(newest.title || t("start.new")))}`; fresh.querySelector("[data-restore]")!.addEventListener("click", () => void (async () => { if (await restoreJournal(engine, newest.key)) { void clearJournal(newest.key); diff --git a/tests/test_shown_text_escaped.py b/tests/test_shown_text_escaped.py new file mode 100644 index 00000000..98b2430e --- /dev/null +++ b/tests/test_shown_text_escaped.py @@ -0,0 +1,35 @@ +"""Text that reaches the window from a saved file or another program is escaped before it is shown as markup.""" + +import os +import re + +UI = os.path.join(os.path.dirname(__file__), "..", "frontend", "src", "ui") + + +def _read(name): + with open(os.path.join(UI, name), encoding="utf-8") as handle: + return handle.read() + + +def _markup_lines(source, marker): + return [line for line in source.splitlines() if "innerHTML" in line and marker in line] + + +def test_the_restore_bar_escapes_the_recovered_project_title(): + source = _read("start-screen.ts") + lines = _markup_lines(source, "newest.title") + assert lines, "the restore bar line moved; update this test" + for line in lines: + assert not re.search(r"\$\{\s*newest\.title", line), line + assert "escapeHtml(String(newest.title" in line, line + + +def test_connections_escape_session_names_agents_and_job_kinds(): + source = _read("settings-popout.ts") + assert 'import { escapeHtml } from "./safe-text";' in source + for field in ("session.name", "session.agent", "last", "job.kind"): + lines = [line for line in source.splitlines() if "innerHTML" in line and re.search(rf"\b{re.escape(field)}\b", line)] + assert lines, field + for line in lines: + assert not re.search(rf"\$\{{\s*{re.escape(field)}\s*\}}", line), (field, line) + assert f"escapeHtml(String({field}))" in line, (field, line) From 76425a0da5d57fbe2ac4a2e61497a5eec6c421e0 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:48:56 -0500 Subject: [PATCH 02/12] fix: collect files into a new folder instead of over an earlier collection Collect Files reused / when it was already there, so a second project of the same title replaced the first collection's footage and .fmc. A folder already present is now left alone and the collection goes to <title> 2, <title> 3 and so on, as files of the same name already were. --- backend/app/project_files.py | 10 +++++++--- tests/test_project_files.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/backend/app/project_files.py b/backend/app/project_files.py index 4e248fe9..db74b063 100644 --- a/backend/app/project_files.py +++ b/backend/app/project_files.py @@ -185,14 +185,18 @@ def collect(project_id: str, folder: Path, report=lambda *_: None, cancelled=lam """Collect Files, as After Effects does: <folder>/<title>/<title>.fmc with a copy of every file its clips use in Footage/ beside it, the .fmc pointing at those copies (by path and relative to it), so the folder can be moved, zipped or handed over whole. The project itself stays kept where it was; the collected .fmc is a copy of it. - Two files of the same name are told apart (a number added); a file missing now is listed, not copied.""" + Two files of the same name are told apart (a number added), and so is a folder of that name already there, which is + never written into; a file missing now is listed, not copied.""" project = store.get_project(project_id) if project is None: raise HTTPException(404, "project not found") title = "".join(ch for ch in str(project.get("title") or "Untitled") if ch not in '/\\:*?"<>|').strip() or "Untitled" - root = Path(folder).expanduser() / title + parent = Path(folder).expanduser() + root, number = parent / title, 2 + while root.exists(): + root, number = parent / f"{title} {number}", number + 1 footage = root / "Footage" - footage.mkdir(parents=True, exist_ok=True) + footage.mkdir(parents=True) where = root / f"{title}{SUFFIX}" table = media_table(project, where) used: set[str] = set() diff --git a/tests/test_project_files.py b/tests/test_project_files.py index 6fc88344..ba74cbc0 100644 --- a/tests/test_project_files.py +++ b/tests/test_project_files.py @@ -189,3 +189,18 @@ def test_save_and_the_start_screen_offer_project_files(): assert '["collect", "file.collect"]' in menu and "/api/project-files/collect" in bar assert "ev.shiftKey ? saveAs() : doSave(true)" in bar and "offered.has(result.id)" in bar assert 'fromFile.dataset.act = "open-file"' in home and "project.file ?" in home + + +def test_collecting_again_to_the_same_place_keeps_the_first_collection(tmp_path): + one = linking.link_path(_clip(tmp_path / "Card A", "C0001.mp4")) + two = linking.link_path(_clip(tmp_path / "Card B", "C0001.mp4", source="mandelbrot")) + store.save_project(_project(one["id"], "C0001.mp4", "p-first")) + store.save_project(_project(two["id"], "C0001.mp4", "p-second")) + first = project_files.collect("p-first", tmp_path / "Desktop") + kept = (tmp_path / "Desktop" / "Launch" / "Footage" / "C0001.mp4").read_bytes() + second = project_files.collect("p-second", tmp_path / "Desktop") + assert first["folder"] == str(tmp_path / "Desktop" / "Launch") + assert second["folder"] == str(tmp_path / "Desktop" / "Launch 2") + assert (tmp_path / "Desktop" / "Launch" / "Footage" / "C0001.mp4").read_bytes() == kept + assert json.loads((tmp_path / "Desktop" / "Launch" / "Launch.fmc").read_text())["project"]["id"] == "p-first" + assert json.loads((tmp_path / "Desktop" / "Launch 2" / "Launch.fmc").read_text())["project"]["id"] == "p-second" From 832515c360b075511083d6537c8b2940da396fb0 Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sat, 28 Nov 2026 20:50:19 -0500 Subject: [PATCH 03/12] fix: keep project ids from a .fmc file to plain names A project id is joined into the record, cover and delete paths, and opening a .fmc file took whatever id it held. One check, store.safe_id (no folder separator, no leading dot), now guards opening a file, the cover routes, the home screen's cover drawing and deleting a project's record, as it already guarded writing the records. --- backend/app/project_files.py | 2 ++ backend/app/projects.py | 8 ++++++-- backend/app/store.py | 11 +++++++++-- tests/test_project_files.py | 22 ++++++++++++++++++++++ 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/backend/app/project_files.py b/backend/app/project_files.py index db74b063..2f92efe7 100644 --- a/backend/app/project_files.py +++ b/backend/app/project_files.py @@ -137,6 +137,8 @@ def open_file(path: Path) -> dict: project = document["project"] if not project.get("id"): raise HTTPException(400, f"{path.name} holds no project id") + if not isinstance(project["id"], str) or not store.safe_id(project["id"]): + raise HTTPException(400, f"{path.name} holds a project id formcut cannot keep") existing = store.get_project(project["id"]) project = {**project, "revision": int(existing.get("revision", 0)) if existing else 0} saved = store._save_project(project) # the file is the word on it; the file itself is not written back yet diff --git a/backend/app/projects.py b/backend/app/projects.py index 7e8bf1f3..7bfe7a00 100644 --- a/backend/app/projects.py +++ b/backend/app/projects.py @@ -84,8 +84,10 @@ def _ensure_cover(record: dict) -> None: the home screen looked like while covers were only made on request. """ project_id = str(record.get("id") or "") + if not store.safe_id(project_id): + return path = COVERS / f"{project_id}.jpg" - if not project_id or path.is_file(): + if path.is_file(): return document = record.get("document") or {} if not document.get("timelines"): @@ -120,7 +122,7 @@ def project_summaries() -> list[dict]: @router.get("/{project_id}/cover") def project_cover(project_id: str): path = COVERS / f"{project_id}.jpg" - if not path.is_file(): + if not store.safe_id(project_id) or not path.is_file(): raise HTTPException(status_code=404, detail="no cover") return FileResponse(path, media_type="image/jpeg") @@ -133,6 +135,8 @@ def set_project_cover(project_id: str, body: dict) -> None: from .render_api import FrameRenderer from .render_document import validate_document + if not store.safe_id(project_id): + raise HTTPException(status_code=400, detail="bad project id") document = validate_document(body.get("project") or {}) COVERS.mkdir(parents=True, exist_ok=True) renderer = FrameRenderer(document, 480) diff --git a/backend/app/store.py b/backend/app/store.py index 195b5a61..ca0b96d8 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -15,6 +15,12 @@ _record_texts: dict[str, str] = {} +def safe_id(project_id) -> bool: + """An id that names a file inside formcut's own folders: no folder separator, nothing that starts with a dot.""" + value = str(project_id or "") + return bool(value) and "/" not in value and "\\" not in value and not value.startswith(".") and "\0" not in value + + def _read() -> list[dict]: """projects.json; when it is missing or damaged, the projects' own records (the latest word on each, a deleted project's gone with it), else its backup (one save behind), else none.""" @@ -44,7 +50,7 @@ def _write(projects: list[dict]) -> None: RECORDS_DIR.mkdir(parents=True, exist_ok=True) for project in projects: project_id = str(project.get("id") or "") - if not project_id or "/" in project_id or "\\" in project_id or project_id.startswith("."): + if not safe_id(project_id): continue text = json.dumps(project) if _record_texts.get(project_id) != text: @@ -110,6 +116,7 @@ def delete_project(project_id: str) -> bool: if len(remaining) == len(projects): return False _write(remaining) - (RECORDS_DIR / f"{project_id}.json").unlink(missing_ok=True) # deleted: not to be rebuilt + if safe_id(project_id): + (RECORDS_DIR / f"{project_id}.json").unlink(missing_ok=True) # deleted: not to be rebuilt _record_texts.pop(project_id, None) return True diff --git a/tests/test_project_files.py b/tests/test_project_files.py index ba74cbc0..5a0ec67d 100644 --- a/tests/test_project_files.py +++ b/tests/test_project_files.py @@ -204,3 +204,25 @@ def test_collecting_again_to_the_same_place_keeps_the_first_collection(tmp_path) assert (tmp_path / "Desktop" / "Launch" / "Footage" / "C0001.mp4").read_bytes() == kept assert json.loads((tmp_path / "Desktop" / "Launch" / "Launch.fmc").read_text())["project"]["id"] == "p-first" assert json.loads((tmp_path / "Desktop" / "Launch 2" / "Launch.fmc").read_text())["project"]["id"] == "p-second" + + +@pytest.mark.parametrize("project_id", ["../../outside", "..\\..\\outside", ".hidden", "a/b"]) +def test_a_project_file_whose_id_is_not_a_plain_name_is_not_opened(tmp_path, project_id): + from fastapi import HTTPException + + path = tmp_path / "shared.fmc" + document = {"format": project_files.FORMAT, "version": project_files.VERSION, "project": {**_project("0" * 32, "x", project_id)}} + path.write_text(json.dumps(document), encoding="utf-8") + with pytest.raises(HTTPException) as refused: + project_files.open_file(path) + assert refused.value.status_code == 400 + assert store.get_project(project_id) is None + + +def test_cover_paths_stay_in_the_covers_folder(client): + from app import projects + + assert not store.safe_id("..\\outside") and not store.safe_id("../outside") and store.safe_id("p-collect") + assert client.put("/api/projects/..%5Coutside/cover", json={"project": {}, "time": 0}).status_code == 400 + projects._ensure_cover({"id": "../outside", "document": {"timelines": [{}]}}) + assert not (projects.COVERS.parent / "outside.jpg").exists() From 652179f4bf864eb8d47167ebe905c95517babf85 Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sat, 28 Nov 2026 20:52:47 -0500 Subject: [PATCH 04/12] fix: count only real loopback names as this computer in the request guard The guard accepted the test client's host names, testserver and testclient, as loopback in every build. The engine now knows only localhost and loopback addresses; the test suite adds the test client's names in conftest. --- backend/app/security.py | 2 +- tests/conftest.py | 19 +++++++++++++++++++ tests/test_family_guard.py | 9 +++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/backend/app/security.py b/backend/app/security.py index d09d901e..cb564882 100644 --- a/backend/app/security.py +++ b/backend/app/security.py @@ -9,7 +9,7 @@ def loopback(value: str) -> bool: - if value in ("localhost", "testclient", "testserver"): + if value == "localhost": return True try: return ipaddress.ip_address(value).is_loopback diff --git a/tests/conftest.py b/tests/conftest.py index c7717e53..0857d72d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -115,6 +115,25 @@ def bare(client): _clients_made_as_the_window_carry_the_key() +def _test_clients_count_as_this_computer() -> None: + """The test client sends from "testclient" to "testserver" unless told otherwise; the engine itself knows only + real loopback names, so the suite adds those two here. The engine's own check stays as security.loopback.__wrapped__.""" + import functools + + from app import security + + real = security.loopback + + @functools.wraps(real) + def loopback(value: str) -> bool: + return value in ("testclient", "testserver") or real(value) + + security.loopback = loopback + + +_test_clients_count_as_this_computer() + + def pytest_sessionfinish(session, exitstatus): import shutil diff --git a/tests/test_family_guard.py b/tests/test_family_guard.py index 23e8b401..9da9ad99 100644 --- a/tests/test_family_guard.py +++ b/tests/test_family_guard.py @@ -125,3 +125,12 @@ def test_websocket_from_the_own_origin_is_accepted(client): with client.websocket_connect(f"{WS}?ticket={ticket}", headers={"host": f"127.0.0.1:{PORT}", "origin": OWN}) as ws: ws.send_json({"jsonrpc": "2.0", "id": 1, "method": "no.such.method"}) assert ws.receive_json()["id"] == 1 + + +@pytest.mark.parametrize("name", ["testserver", "testclient", "testserver.", "intranet"]) +def test_only_real_loopback_names_count_as_this_computer(name): + from app import security + + engine_check = security.loopback.__wrapped__ + assert not engine_check(name) + assert engine_check("localhost") and engine_check("127.0.0.1") and engine_check("::1") From edc2373afab595e2a4825d08cd9bc6f94f93166f Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sun, 29 Nov 2026 08:54:58 -0500 Subject: [PATCH 05/12] test: send the mounted-interface check from a loopback address The check runs the engine in a child process without the suite's conftest, so the test client's own host names are no longer taken as this computer there. It now addresses the engine as 127.0.0.1, as the desktop app does. --- tests/test_interface_mount.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_interface_mount.py b/tests/test_interface_mount.py index 4f99a040..cfb247b9 100644 --- a/tests/test_interface_mount.py +++ b/tests/test_interface_mount.py @@ -28,7 +28,7 @@ def test_with_the_interface_mounted_the_apps_own_routes_answer(tmp_path): script = """ from fastapi.testclient import TestClient from app.main import app -client = TestClient(app) +client = TestClient(app, base_url="http://127.0.0.1:8123", client=("127.0.0.1", 50000)) print(client.get("/api/packages").status_code, client.get("/api/locales").status_code, client.get("/api/diagnostics").status_code, client.get("/").status_code) """ From c8492ce87dfa3c014fe569d22885ca22f77542bf Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sun, 29 Nov 2026 10:04:46 -0500 Subject: [PATCH 06/12] fix: accept only plain project ids and keep their files in their folders A project id is joined into the record, cover and delete paths. The check refused separators and a leading dot, but still let through a Windows drive prefix such as C:x, device names such as CON, and other characters formcut never puts in an id. store.safe_id now accepts only the ids formcut issues (letters, digits, - and _, up to 64), and store.id_path also confirms that the joined file resolves inside its folder, so a link that leads out of the folder is not followed. Recovery keys are matched whole, so a key with a trailing newline is refused as well. --- backend/app/projects.py | 18 +++++----- backend/app/recovery.py | 4 +-- backend/app/store.py | 35 +++++++++++++----- tests/test_project_files.py | 3 +- tests/test_project_ids.py | 72 +++++++++++++++++++++++++++++++++++++ 5 files changed, 111 insertions(+), 21 deletions(-) create mode 100644 tests/test_project_ids.py diff --git a/backend/app/projects.py b/backend/app/projects.py index 7bfe7a00..c353c7dc 100644 --- a/backend/app/projects.py +++ b/backend/app/projects.py @@ -83,11 +83,8 @@ def _ensure_cover(record: dict) -> None: Four cards showing the same film icon tell a person nothing, which is what the home screen looked like while covers were only made on request. """ - project_id = str(record.get("id") or "") - if not store.safe_id(project_id): - return - path = COVERS / f"{project_id}.jpg" - if path.is_file(): + path = store.id_path(COVERS, record.get("id"), ".jpg") + if path is None or path.is_file(): return document = record.get("document") or {} if not document.get("timelines"): @@ -121,8 +118,8 @@ def project_summaries() -> list[dict]: @router.get("/{project_id}/cover") def project_cover(project_id: str): - path = COVERS / f"{project_id}.jpg" - if not store.safe_id(project_id) or not path.is_file(): + path = store.id_path(COVERS, project_id, ".jpg") + if path is None or not path.is_file(): raise HTTPException(status_code=404, detail="no cover") return FileResponse(path, media_type="image/jpeg") @@ -135,16 +132,17 @@ def set_project_cover(project_id: str, body: dict) -> None: from .render_api import FrameRenderer from .render_document import validate_document - if not store.safe_id(project_id): + COVERS.mkdir(parents=True, exist_ok=True) + path = store.id_path(COVERS, project_id, ".jpg") + if path is None: raise HTTPException(status_code=400, detail="bad project id") document = validate_document(body.get("project") or {}) - COVERS.mkdir(parents=True, exist_ok=True) renderer = FrameRenderer(document, 480) try: pixels = renderer.frame(max(0.0, float(body.get("time") or 0))) finally: renderer.close() - Image.fromarray(pixels[:, :, :3]).save(COVERS / f"{project_id}.jpg", quality=80) + Image.fromarray(pixels[:, :, :3]).save(path, quality=80) @router.patch("/{project_id}", status_code=200) diff --git a/backend/app/recovery.py b/backend/app/recovery.py index 83ea3d6f..f3b39d1a 100644 --- a/backend/app/recovery.py +++ b/backend/app/recovery.py @@ -19,11 +19,11 @@ router = APIRouter(prefix="/api/recovery", tags=["recovery"]) RECOVERY_DIR = DATA_DIR / "recovery" -_KEY = re.compile(r"^[A-Za-z0-9_-]{1,64}$") +_KEY = re.compile(r"[A-Za-z0-9_-]{1,64}") def _path(key: str): - if not _KEY.match(key): + if not isinstance(key, str) or not _KEY.fullmatch(key): raise HTTPException(status_code=400, detail="bad key") return RECOVERY_DIR / f"{key}.json" diff --git a/backend/app/store.py b/backend/app/store.py index ca0b96d8..fdfe93bc 100644 --- a/backend/app/store.py +++ b/backend/app/store.py @@ -1,7 +1,9 @@ import contextlib import json +import re import threading import time +from pathlib import Path from .durable import read_json, set_aside, write_json from .paths import DATA_DIR @@ -15,10 +17,25 @@ _record_texts: dict[str, str] = {} +_PLAIN_ID = re.compile(r"[A-Za-z0-9_-]{1,64}") +_DEVICE_NAMES = re.compile(r"(?i)(con|prn|aux|nul|com[0-9]|lpt[0-9])") + + def safe_id(project_id) -> bool: - """An id that names a file inside formcut's own folders: no folder separator, nothing that starts with a dot.""" - value = str(project_id or "") - return bool(value) and "/" not in value and "\\" not in value and not value.startswith(".") and "\0" not in value + """An id of the kind formcut issues (letters, digits, - and _, as a uuid's hex is), so it names one file of its own + inside formcut's folders on every system: no separator, drive, dot or device name.""" + return type(project_id) is str and bool(_PLAIN_ID.fullmatch(project_id)) and not _DEVICE_NAMES.fullmatch(project_id) + + +def id_path(folder: Path, project_id, suffix: str) -> Path | None: + """The file kept for a project id in folder, or None when the id is not a plain one or the file is not in folder.""" + if not safe_id(project_id): + return None + path = Path(folder) / f"{project_id}{suffix}" + try: + return path if path.resolve().parent == Path(folder).resolve() else None + except (OSError, RuntimeError): + return None def _read() -> list[dict]: @@ -49,12 +66,13 @@ def _write(projects: list[dict]) -> None: write_json(PROJECTS_FILE, projects) RECORDS_DIR.mkdir(parents=True, exist_ok=True) for project in projects: - project_id = str(project.get("id") or "") - if not safe_id(project_id): + project_id = project.get("id") + record = id_path(RECORDS_DIR, project_id, ".json") + if record is None: continue text = json.dumps(project) if _record_texts.get(project_id) != text: - write_json(RECORDS_DIR / f"{project_id}.json", project, indent=None, keep_backup=False) + write_json(record, project, indent=None, keep_backup=False) _record_texts[project_id] = text @@ -116,7 +134,8 @@ def delete_project(project_id: str) -> bool: if len(remaining) == len(projects): return False _write(remaining) - if safe_id(project_id): - (RECORDS_DIR / f"{project_id}.json").unlink(missing_ok=True) # deleted: not to be rebuilt + record = id_path(RECORDS_DIR, project_id, ".json") + if record is not None: + record.unlink(missing_ok=True) # deleted: not to be rebuilt _record_texts.pop(project_id, None) return True diff --git a/tests/test_project_files.py b/tests/test_project_files.py index 5a0ec67d..60351408 100644 --- a/tests/test_project_files.py +++ b/tests/test_project_files.py @@ -206,7 +206,7 @@ def test_collecting_again_to_the_same_place_keeps_the_first_collection(tmp_path) assert json.loads((tmp_path / "Desktop" / "Launch 2" / "Launch.fmc").read_text())["project"]["id"] == "p-second" -@pytest.mark.parametrize("project_id", ["../../outside", "..\\..\\outside", ".hidden", "a/b"]) +@pytest.mark.parametrize("project_id", ["../../outside", "..\\..\\outside", ".hidden", "a/b", "C:outside", "CON", "two words", 7]) def test_a_project_file_whose_id_is_not_a_plain_name_is_not_opened(tmp_path, project_id): from fastapi import HTTPException @@ -226,3 +226,4 @@ def test_cover_paths_stay_in_the_covers_folder(client): assert client.put("/api/projects/..%5Coutside/cover", json={"project": {}, "time": 0}).status_code == 400 projects._ensure_cover({"id": "../outside", "document": {"timelines": [{}]}}) assert not (projects.COVERS.parent / "outside.jpg").exists() + diff --git a/tests/test_project_ids.py b/tests/test_project_ids.py new file mode 100644 index 00000000..ade4d7b6 --- /dev/null +++ b/tests/test_project_ids.py @@ -0,0 +1,72 @@ +"""Project ids name files inside formcut's own folders only when they are ids of the kind formcut issues.""" + +import os +import uuid + +import pytest +from app import recovery, store +from fastapi import HTTPException + + +@pytest.mark.parametrize("project_id", [uuid.uuid4().hex, "p-first", "bare_2", "a" * 64]) +def test_ids_formcut_issues_are_plain(project_id): + assert store.safe_id(project_id) + + +class _Named(str): + def __str__(self): + return "../outside" + + +@pytest.mark.parametrize( + "project_id", + [ + "", + "C:x", + "c:..", + "CON", + "nul", + "Com1", + "lpt9", + "a b", + "a.b", + "a" * 65, + "ok\n", + "ok\x00", + "caf\u00e9", + "../x", + "a\\b", + None, + 7, + ["x"], + _Named("ok"), + ], +) +def test_other_ids_are_not(project_id): + assert not store.safe_id(project_id) + + +def test_the_file_for_an_id_is_in_its_folder(tmp_path): + folder = tmp_path / "covers" + folder.mkdir() + assert store.id_path(folder, "p-one", ".jpg") == folder / "p-one.jpg" + assert store.id_path(folder, "C:outside", ".jpg") is None + assert store.id_path(folder, "CON", ".json") is None + + +@pytest.mark.skipif(os.name != "posix", reason="links need developer mode on Windows") +def test_a_linked_file_that_leads_out_of_the_folder_is_not_used(tmp_path): + folder = tmp_path / "covers" + folder.mkdir() + outside = tmp_path / "elsewhere.jpg" + outside.write_bytes(b"kept") + (folder / "linked.jpg").symlink_to(outside) + assert store.id_path(folder, "linked", ".jpg") is None + assert outside.read_bytes() == b"kept" + + +@pytest.mark.parametrize("key", ["ok\n", "ok\x00", "../x", ""]) +def test_a_recovery_key_is_a_plain_id_with_nothing_after_it(key): + with pytest.raises(HTTPException): + recovery._path(key) + assert recovery._path("unsaved") == recovery.RECOVERY_DIR / "unsaved.json" From 5b48aab2147c5e2034504fb469dac113a51e4c5a Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sun, 29 Nov 2026 10:04:56 -0500 Subject: [PATCH 07/12] fix: make each collected folder new, never one reached through a link Collect Files checked whether <title> was there and then made its folders with parents allowed, so a link standing under that name, or a folder made in between, was still written into. The destination folder is now made with a single mkdir that fails when anything has the name, and the next free "<title> N" is taken instead. --- backend/app/project_files.py | 11 ++++++++--- tests/test_project_files.py | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/backend/app/project_files.py b/backend/app/project_files.py index 2f92efe7..05f1689f 100644 --- a/backend/app/project_files.py +++ b/backend/app/project_files.py @@ -194,11 +194,16 @@ def collect(project_id: str, folder: Path, report=lambda *_: None, cancelled=lam raise HTTPException(404, "project not found") title = "".join(ch for ch in str(project.get("title") or "Untitled") if ch not in '/\\:*?"<>|').strip() or "Untitled" parent = Path(folder).expanduser() + parent.mkdir(parents=True, exist_ok=True) root, number = parent / title, 2 - while root.exists(): - root, number = parent / f"{title} {number}", number + 1 + while True: + try: + root.mkdir() + break + except FileExistsError: + root, number = parent / f"{title} {number}", number + 1 footage = root / "Footage" - footage.mkdir(parents=True) + footage.mkdir() where = root / f"{title}{SUFFIX}" table = media_table(project, where) used: set[str] = set() diff --git a/tests/test_project_files.py b/tests/test_project_files.py index 60351408..17d3b251 100644 --- a/tests/test_project_files.py +++ b/tests/test_project_files.py @@ -227,3 +227,19 @@ def test_cover_paths_stay_in_the_covers_folder(client): projects._ensure_cover({"id": "../outside", "document": {"timelines": [{}]}}) assert not (projects.COVERS.parent / "outside.jpg").exists() + +def test_collecting_where_a_link_or_a_file_has_the_title_goes_to_a_new_folder(tmp_path): + clip = linking.link_path(_clip(tmp_path / "Card", "C0001.mp4")) + store.save_project(_project(clip["id"], "C0001.mp4", "p-linked")) + desk = tmp_path / "Desktop" + desk.mkdir() + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + (desk / "Launch").symlink_to(elsewhere) + (desk / "Launch 2").write_text("kept", encoding="utf-8") + (desk / "Launch 3").symlink_to(tmp_path / "not-there") + collected = project_files.collect("p-linked", desk) + assert collected["folder"] == str(desk / "Launch 4") + assert list(elsewhere.iterdir()) == [] + assert (desk / "Launch 2").read_text(encoding="utf-8") == "kept" + assert not (tmp_path / "not-there").exists() From cceb0729befae051940e599c3381d000eaf325e6 Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sun, 29 Nov 2026 10:04:56 -0500 Subject: [PATCH 08/12] fix: start a .cmd agent shim on Windows without the command interpreter An agent program installed by npm or pnpm is a .cmd shim, and it was run through cmd.exe /c, which reads %, quotes and & | < > ^ in the arguments (a first message for a Claude Code tab among them) as its own syntax. The shared finder (agent_lookup 1.0.2) now reads the shim and runs what it points at directly: the program, or node and its script. Only when the shim cannot be followed does it use the interpreter, and then it refuses any argument with a control character, %, ! or a quote, and & | < > ^ or brackets in a word that is not quoted. A batch file name in any case or with a trailing dot is treated the same way. The new version's hash is recorded in setup/agents.py. --- backend/app/agent_lookup.py | 50 ++++++++++++++++- setup/agents.py | 1 + tests/test_windows_start.py | 108 ++++++++++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 3 deletions(-) create mode 100644 tests/test_windows_start.py diff --git a/backend/app/agent_lookup.py b/backend/app/agent_lookup.py index ea34eba1..70eb57d9 100644 --- a/backend/app/agent_lookup.py +++ b/backend/app/agent_lookup.py @@ -15,6 +15,7 @@ from __future__ import annotations +import errno import os import re import shutil @@ -26,7 +27,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 +360,56 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +_SHIM_TARGET = re.compile(r'"%~?dp0%?\\?([^"%]+)"\s+%\*') +_CMD_NEVER = re.compile(r'[\x00-\x1f\x7f%!"]') +_CMD_UNQUOTED = re.compile(r"[&|<>^()]") + + +def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | None: + """What a package manager's .cmd shim runs (the program, or node and its script), read from the shim, so it can be + started directly instead of through the command interpreter; None when the shim says nothing this can follow.""" + shim = Path(shim) + try: + text = shim.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + found = _SHIM_TARGET.findall(text) + if not found: + return None + target = shim.parent / found[-1].strip().replace("\\", os.sep).lstrip(os.sep) + kind = target.suffix.lower() + if not target.is_file() or kind not in (".exe", ".js", ".cjs", ".mjs"): + return None + if kind == ".exe": + return [str(target)] + beside = shim.parent / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=(env or os.environ).get("PATH")) + return [node, str(target)] if node else None + + +def cmd_words(words: list[str]) -> list[str]: + """Words for the command interpreter's /c line, refused when the interpreter would read one as more than text: a + control character, %, ! or a quote in any word, or &, |, <, >, ^ or a bracket in a word that is not quoted.""" + for word in words: + quoted = word == "" or " " in word or "\t" in word + if _CMD_NEVER.search(word) or (not quoted and _CMD_UNQUOTED.search(word)): + raise OSError(errno.EINVAL, "an argument holds characters the Windows command interpreter would not pass on as text") + return words + + 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; a .cmd or .bat runs what it points at directly when it is + a package manager's shim, else through the command interpreter with only words it passes on as text.""" 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().rstrip(". ").endswith((".cmd", ".bat")): + return words + direct = shim_target(words[0], env) + if direct: + return [*direct, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/c", *cmd_words(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/setup/agents.py b/setup/agents.py index 79003354..b3f65896 100755 --- a/setup/agents.py +++ b/setup/agents.py @@ -73,6 +73,7 @@ def dock_problems(folder: Path = DOCK_DIR) -> list[str]: LOOKUP_HASHES = { "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", + "1.0.2": "59542bdef506af6e2efab9a5f34c7df897bb34fc968612830c3fb6b25dc3454b", } diff --git a/tests/test_windows_start.py b/tests/test_windows_start.py new file mode 100644 index 00000000..02394897 --- /dev/null +++ b/tests/test_windows_start.py @@ -0,0 +1,108 @@ +"""How an agent program installed as a .cmd shim is started on Windows: what the shim points at, run directly, or the +command interpreter with only words it passes on as text.""" + +import pytest +from app import agent_lookup + +NPM_SHIM = r"""@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\node_modules\@anthropic-ai\claude-code\cli.js" %* +""" + +ENV = {"COMSPEC": "C:\\Windows\\system32\\cmd.exe", "PATH": ""} + + +def _npm(tmp_path, node_beside=True): + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + if node_beside: + (tmp_path / "node.exe").write_bytes(b"") + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + return shim, script + + +def test_an_npm_shim_runs_node_and_its_script_directly(tmp_path): + shim, script = _npm(tmp_path) + prompt = 'fix the "title" & 100% of it!\nthen stop' + assert agent_lookup.start_argv([shim, prompt], ENV, "win32") == [str(tmp_path / "node.exe"), str(script), prompt] + + +@pytest.mark.parametrize("name", ["agent.cmd.", "agent.CMD", "agent.bat .", "agent.Bat"]) +def test_a_batch_file_name_in_any_case_or_with_a_trailing_dot_is_still_a_batch_file(name): + assert agent_lookup.start_argv([f"C:\\tools\\{name}", "--version"], ENV, "win32")[:2] == [ENV["COMSPEC"], "/c"] + with pytest.raises(OSError): + agent_lookup.start_argv([f"C:\\tools\\{name}", "a&b"], ENV, "win32") + + +def test_a_shim_that_points_at_a_program_runs_it(tmp_path): + program = tmp_path / "bin" / "agent.exe" + program.parent.mkdir() + program.write_bytes(b"") + shim = tmp_path / "agent.cmd" + shim.write_text('@"%~dp0\\bin\\agent.exe" %*\n', encoding="utf-8") + assert agent_lookup.start_argv([shim, "-p", "a&b"], ENV, "win32") == [str(program), "-p", "a&b"] + + +def _plain(tmp_path): + batch = tmp_path / "agent.bat" + batch.write_text("@echo off\nrem started some other way\n", encoding="utf-8") + return str(batch) + + +def test_a_batch_file_it_cannot_follow_goes_through_the_interpreter_with_plain_words(tmp_path): + batch = _plain(tmp_path) + words = [batch, "--version", "say hello & wave", "(in quotes) ^ <fine>", ""] + assert agent_lookup.start_argv(words, ENV, "win32") == [ENV["COMSPEC"], "/c", *words] + + +@pytest.mark.parametrize( + "word", + [ + "a&b", + "a|b", + "a>b", + "a<b", + "a^b", + "(a)", + "50%", + "%PATH%", + "two words 50%", + 'say "hi"', + "hi!", + "one\ntwo", + "tab\x1b", + "nul\x00", + "del\x7f", + ], +) +def test_words_the_interpreter_would_read_as_more_than_text_are_refused(tmp_path, word): + with pytest.raises(OSError) as refused: + agent_lookup.start_argv([_plain(tmp_path), word], ENV, "win32") + assert "command interpreter" in str(refused.value) + + +def test_a_shim_without_node_falls_back_to_the_checked_interpreter_line(tmp_path): + shim, _script = _npm(tmp_path, node_beside=False) + assert agent_lookup.start_argv([shim, "--version"], ENV, "win32") == [ENV["COMSPEC"], "/c", str(shim), "--version"] + with pytest.raises(OSError): + agent_lookup.start_argv([shim, "a&b"], ENV, "win32") + + +def test_a_program_that_is_not_a_batch_file_is_started_as_it_is(tmp_path): + assert agent_lookup.start_argv(["C:\\tools\\agent.exe", "a&b"], ENV, "win32") == ["C:\\tools\\agent.exe", "a&b"] From 25f2d036667cf4b9d163d6dba1eaab902f455d04 Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sun, 29 Nov 2026 10:04:56 -0500 Subject: [PATCH 09/12] refactor: check the RPC socket peer with the shared loopback check The socket compared its peer against a fixed list that also named the test client. It now uses security.loopback, which the test suite extends in conftest, and a socket without a known peer is closed. --- backend/app/automation.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/app/automation.py b/backend/app/automation.py index f87919f9..f494ccda 100644 --- a/backend/app/automation.py +++ b/backend/app/automation.py @@ -1073,7 +1073,9 @@ async def http_rpc_read(request: Request): @router.websocket("/ws") async def websocket_rpc(socket: WebSocket): - if socket.client and socket.client.host not in ("127.0.0.1", "::1", "testclient"): + from . import security + + if not socket.client or not security.loopback(socket.client.host): await socket.close(code=1008) return await socket.accept() From fa6ea999520634f8b10c8b8d12a9504efb270803 Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sun, 29 Nov 2026 10:59:27 -0500 Subject: [PATCH 10/12] fix: refuse every interpreter-special character on a Windows cmd.exe line When a .cmd or .bat file cannot be followed to the program it wraps and has to start through the command interpreter, any argument (the program path included) holding & | < > ^ ( ) ! % a quote or a control character is now refused, with or without spaces, since the interpreter and the shim's %* act on them even inside quotes. The message points long text to standard input or a file. A followed shim still gets every argument unchanged as an argv list. The recorded hash for agent_lookup 1.0.2 in setup/agents.py is updated to match. --- backend/app/agent_lookup.py | 15 ++++++++------- setup/agents.py | 2 +- tests/test_windows_start.py | 23 ++++++++++++++++++++++- 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/backend/app/agent_lookup.py b/backend/app/agent_lookup.py index 70eb57d9..9cb01312 100644 --- a/backend/app/agent_lookup.py +++ b/backend/app/agent_lookup.py @@ -361,8 +361,7 @@ def _quote(word: str, fish: bool) -> str: _SHIM_TARGET = re.compile(r'"%~?dp0%?\\?([^"%]+)"\s+%\*') -_CMD_NEVER = re.compile(r'[\x00-\x1f\x7f%!"]') -_CMD_UNQUOTED = re.compile(r"[&|<>^()]") +_CMD_NEVER = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]') def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | None: @@ -388,12 +387,14 @@ def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | def cmd_words(words: list[str]) -> list[str]: - """Words for the command interpreter's /c line, refused when the interpreter would read one as more than text: a - control character, %, ! or a quote in any word, or &, |, <, >, ^ or a bracket in a word that is not quoted.""" + """Words for the command interpreter's /c line. A .cmd file reads its arguments again through %*, and the interpreter + acts on & | < > ^ ( ) ! % and quotes even inside quotes, so any word holding one of them, or a control character, is + refused whether or not it has spaces. Long or free text belongs on the program's standard input or in a file.""" for word in words: - quoted = word == "" or " " in word or "\t" in word - if _CMD_NEVER.search(word) or (not quoted and _CMD_UNQUOTED.search(word)): - raise OSError(errno.EINVAL, "an argument holds characters the Windows command interpreter would not pass on as text") + if _CMD_NEVER.search(word): + raise OSError(errno.EINVAL, "an argument holds a character the Windows command interpreter would act on " + "(& | < > ^ ( ) ! % \" or a control character), so it cannot be passed on the command line; " + "pass long text through standard input or a file if the program supports it") return words diff --git a/setup/agents.py b/setup/agents.py index b3f65896..66634a66 100755 --- a/setup/agents.py +++ b/setup/agents.py @@ -73,7 +73,7 @@ def dock_problems(folder: Path = DOCK_DIR) -> list[str]: LOOKUP_HASHES = { "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", - "1.0.2": "59542bdef506af6e2efab9a5f34c7df897bb34fc968612830c3fb6b25dc3454b", + "1.0.2": "c3e2a64f16a4f592b28d091bbe7bdceaf07d027738324e8ac6b44c905c5bea7e", } diff --git a/tests/test_windows_start.py b/tests/test_windows_start.py index 02394897..b1db2de2 100644 --- a/tests/test_windows_start.py +++ b/tests/test_windows_start.py @@ -67,7 +67,7 @@ def _plain(tmp_path): def test_a_batch_file_it_cannot_follow_goes_through_the_interpreter_with_plain_words(tmp_path): batch = _plain(tmp_path) - words = [batch, "--version", "say hello & wave", "(in quotes) ^ <fine>", ""] + words = [batch, "--version", "say hello and wave", "C:\\work\\a file.txt", "--model=x-1", ""] assert agent_lookup.start_argv(words, ENV, "win32") == [ENV["COMSPEC"], "/c", *words] @@ -75,6 +75,11 @@ def test_a_batch_file_it_cannot_follow_goes_through_the_interpreter_with_plain_w "word", [ "a&b", + "say hello & wave", + "(in quotes) ^ <fine>", + "two words | more", + "a (b)", + "wow !", "a|b", "a>b", "a<b", @@ -95,6 +100,22 @@ def test_words_the_interpreter_would_read_as_more_than_text_are_refused(tmp_path with pytest.raises(OSError) as refused: agent_lookup.start_argv([_plain(tmp_path), word], ENV, "win32") assert "command interpreter" in str(refused.value) + assert "standard input or a file" in str(refused.value) + + +@pytest.mark.parametrize("word", ["a&b", "a (b)", "50% of it", 'say "hi"', "line\nbreak"]) +def test_the_program_path_is_held_to_the_same_rule(tmp_path, word): + batch = tmp_path / "agent.bat" + batch.write_text("@echo off\n", encoding="utf-8") + with pytest.raises(OSError): + agent_lookup.cmd_words([str(batch) + word, "--version"]) + + +def test_a_followed_shim_passes_every_character_through_unchanged(tmp_path): + shim, script = _npm(tmp_path) + words = ["a & b", "(x) ^ <y>", "100% !", 'say "hi"', "one\ttwo"] + assert agent_lookup.start_argv([shim, *words], ENV, "win32") == [str(tmp_path / "node.exe"), str(script), *words] + assert ENV["COMSPEC"] not in agent_lookup.start_argv([shim, *words], ENV, "win32") def test_a_shim_without_node_falls_back_to_the_checked_interpreter_line(tmp_path): From 943a5d81440497cc0a2e5c534870d17bc053516a Mon Sep 17 00:00:00 2001 From: gbarnai <greg@nodemode.ai> Date: Sun, 29 Nov 2026 13:43:17 -0500 Subject: [PATCH 11/12] test: run the tests and check scripts with a home folder of their own tests/conftest.py points HOME, USERPROFILE, LOCALAPPDATA, APPDATA and the XDG folders at a temporary folder before any engine module is imported, and puts them back and removes it in pytest_unconfigure. The suite already had its own FORMCUT_DATA_DIR, but the per-user ffmpeg folder and anything else reached through the home folder were the person's own. The suite drops PATH folders that hold an agent program, which can drop Homebrew's bin and with it ffmpeg; the tests then found ffmpeg only because the engine put the person's formcut/ffmpeg folder on PATH. ffmpeg and ffprobe from a dropped folder are now linked beside the agent stand-ins. setup/golden_frames.py and setup/output_checks.py ran the engine in process with no data folder, so a run by hand wrote renders and jobs into ~/Library/Application Support/formcut. Both now call setup/scratch_home.py, which points the home folders and FORMCUT_DATA_DIR inside one temporary folder and removes it when the script ends. The window smoke engine also gets the Windows and XDG folders inside its sandbox home, and the bench and route steps in checks.yml get a data folder under the runner's temporary folder. tests/test_stand_in_home.py checks that the home folder, the per-user ffmpeg folder and the default data folder resolve inside the stand-in, and that the data folder read at import is the suite's own. --- .github/workflows/checks.yml | 3 ++ frontend/tests/window/test_window.py | 6 +++ setup/golden_frames.py | 3 ++ setup/output_checks.py | 3 ++ setup/scratch_home.py | 47 +++++++++++++++++++++++ tests/conftest.py | 56 +++++++++++++++++++++++----- tests/test_stand_in_home.py | 33 ++++++++++++++++ 7 files changed, 142 insertions(+), 9 deletions(-) create mode 100644 setup/scratch_home.py create mode 100644 tests/test_stand_in_home.py diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 259fb8e1..02074a76 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -172,6 +172,7 @@ jobs: shell: bash env: FORMCUT_NO_WARM: "1" + FORMCUT_DATA_DIR: ${{ runner.temp }}/formcut-bench-data run: | cd backend python -c "from app.bench import _demo_project" 2>/dev/null || true @@ -188,6 +189,8 @@ jobs: # cannot read the heredoc. - name: the engine imports and its routes mount once shell: bash + env: + FORMCUT_DATA_DIR: ${{ runner.temp }}/formcut-routes-data run: | python - <<'PY' import sys, collections diff --git a/frontend/tests/window/test_window.py b/frontend/tests/window/test_window.py index 851f47f3..38746032 100644 --- a/frontend/tests/window/test_window.py +++ b/frontend/tests/window/test_window.py @@ -23,6 +23,12 @@ "FORMCUT_FFMPEG_AUTO": "0", "FORMCUT_MODELS_AUTO": "0", "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", } CLEAR_ENV_PREFIX = "FORMCUT_" DIST = REPO / "frontend" / "dist" diff --git a/setup/golden_frames.py b/setup/golden_frames.py index cbc35922..47a08a02 100755 --- a/setup/golden_frames.py +++ b/setup/golden_frames.py @@ -32,6 +32,8 @@ import sys from pathlib import Path +import scratch_home + ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "backend")) @@ -206,6 +208,7 @@ def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--update", action="store_true", help="write the current output as the golden") args = parser.parse_args() + scratch_home.use("formcut-golden-") current = render_all() diff --git a/setup/output_checks.py b/setup/output_checks.py index b23c0d12..9b818dc0 100755 --- a/setup/output_checks.py +++ b/setup/output_checks.py @@ -23,6 +23,8 @@ import time from pathlib import Path +import scratch_home + ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "backend")) @@ -199,6 +201,7 @@ def rpc_checks() -> None: def main() -> int: + scratch_home.use("formcut-output-checks-") export_checks() rpc_checks() print() diff --git a/setup/scratch_home.py b/setup/scratch_home.py new file mode 100644 index 00000000..9a506ff9 --- /dev/null +++ b/setup/scratch_home.py @@ -0,0 +1,47 @@ +"""A home folder and a data folder of their own for a check script that runs the engine in process. + +Call use() before the first engine module is imported: app.paths reads the data folder once, at import. The home +folder, the per-user folders of macOS, Windows and Linux and FORMCUT_DATA_DIR all point inside one temporary folder, +which is removed and the variables put back when the script ends, so a check never adds renders, jobs or downloads to +the person's own formcut folder. +""" + +from __future__ import annotations + +import atexit +import os +import shutil +import tempfile +from pathlib import Path + +HOME_VARIABLES = ("HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", "XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME") + + +def use(prefix: str) -> Path: + """Points the home folders and the data folder inside a new temporary folder and returns it.""" + home = Path(tempfile.mkdtemp(prefix=prefix)).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", + "FORMCUT_DATA_DIR": home / "formcut-data", + } + before = {name: os.environ.get(name) for name in places} + os.environ.update({name: str(place) for name, place in places.items()}) + os.environ.setdefault("FORMCUT_NO_WARM", "1") + atexit.register(_put_back, home, before) + return home + + +def _put_back(home: Path, before: dict) -> None: + for name, value in before.items(): + if value is None: + os.environ.pop(name, None) + else: + os.environ[name] = value + shutil.rmtree(home, ignore_errors=True) diff --git a/tests/conftest.py b/tests/conftest.py index 0857d72d..a227844e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,6 +19,44 @@ ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT / "backend")) +_REAL_HOME = Path.home() +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 + engine module is imported, so the default data folder (read once at import by app.paths), the per-user ffmpeg + folder and anything else reached through the home folder never land in the person's own folders.""" + home = Path(tempfile.mkdtemp(prefix="formcut-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): + import shutil + + 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) + + # The suite's own data folder, removed when the run ends (a full run leaves up to # 150 MB of media, proxies and renders). A folder given in FORMCUT_DATA_DIR is kept. _OWN_DATA_DIR = None if "FORMCUT_DATA_DIR" in os.environ else tempfile.mkdtemp(prefix="formcut-tests-") @@ -28,7 +66,6 @@ AGENT_STAND_INS = ("claude", "codex", "cursor-agent", "agy") _AGENT_SANDBOX = Path(tempfile.mkdtemp(prefix="formcut-agents-")) AGENT_CALLS = _AGENT_SANDBOX / "calls.log" -_REAL_HOME = Path.home() _agent_calls: list[str] = [] if os.name == "posix": (_AGENT_SANDBOX / "bin").mkdir() @@ -42,14 +79,15 @@ ) (_AGENT_SANDBOX / "sh").chmod(0o755) os.environ["SHELL"] = str(_AGENT_SANDBOX / "sh") - os.environ["PATH"] = os.pathsep.join( - [str(_AGENT_SANDBOX / "bin")] - + [ - folder - for folder in os.environ.get("PATH", "").split(os.pathsep) - if folder and not any((Path(folder) / name).exists() for name in (*AGENT_STAND_INS, "agent")) - ] - ) + _folders = [folder for folder in os.environ.get("PATH", "").split(os.pathsep) if folder] + _with_agents = [folder for folder in _folders if any((Path(folder) / name).exists() for name in (*AGENT_STAND_INS, "agent"))] + # A folder left off PATH for holding an agent program can also hold the person's ffmpeg (Homebrew's bin, say); + # the tests run ffmpeg by name, and the per-user ffmpeg folder is now inside the stand-in home, so link it in. + for _tool in ("ffmpeg", "ffprobe"): + _found = next((Path(folder) / _tool for folder in _folders if (Path(folder) / _tool).is_file()), None) + if _found and str(_found.parent) in _with_agents: + (_AGENT_SANDBOX / "bin" / _tool).symlink_to(_found) + os.environ["PATH"] = os.pathsep.join([str(_AGENT_SANDBOX / "bin")] + [folder for folder in _folders if folder not in _with_agents]) for _name in ("NPM_CONFIG_PREFIX", "npm_config_prefix", "PNPM_HOME", "VOLTA_HOME", "BUN_INSTALL", "NVM_SYMLINK"): os.environ.pop(_name, None) for _name in ("CLAUDE", "CODEX", "CURSOR", "ANTIGRAVITY"): diff --git a/tests/test_stand_in_home.py b/tests/test_stand_in_home.py new file mode 100644 index 00000000..4de0b2b8 --- /dev/null +++ b/tests/test_stand_in_home.py @@ -0,0 +1,33 @@ +"""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 + +import pytest +from conftest import _OWN_DATA_DIR, _REAL_HOME, STAND_IN_HOME + + +def _inside(path: Path) -> bool: + resolved = Path(path).resolve() + return resolved == STAND_IN_HOME or STAND_IN_HOME in resolved.parents + + +def test_the_home_folder_and_the_per_user_folders_are_the_stand_in(): + from app import tools + + assert _inside(Path.home()) + assert _inside(tools.user_ffmpeg_dir()) + + +def test_the_default_data_folder_is_inside_the_stand_in(monkeypatch): + from app import paths + + monkeypatch.delenv("FORMCUT_DATA_DIR", raising=False) + assert _inside(paths.data_root()) + + +@pytest.mark.skipif(not _OWN_DATA_DIR, reason="FORMCUT_DATA_DIR was given for this run, and a given folder is used as given") +def test_the_data_folder_read_at_import_is_the_suites_own_and_not_under_the_persons_home(): + from app import paths + + assert Path(_OWN_DATA_DIR).resolve() == paths.DATA_DIR + assert _REAL_HOME.resolve() not in paths.DATA_DIR.parents From f649c03f2ecf3ad716b639e04a9cb8619f1938ec Mon Sep 17 00:00:00 2001 From: nodemode-ai <mackin@nodemode.ai> Date: Sun, 29 Nov 2026 14:32:56 -0500 Subject: [PATCH 12/12] test: check the suite's data folder against the person's data folder on Windows On Windows the system temporary folder is inside the home, so the suite's own data folder from tempfile.mkdtemp was always under the person's home and the stand-in home test failed there. The whole-home check now runs only where the temporary folder is outside the home, and every system checks that the data folder is not the person's own formcut data folder, worked out from the variables as they were before the stand-in home. Checked: tests/test_stand_in_home.py passes on Linux and ruff is clean; the Windows paths from the failed run were checked by hand. Not run on Windows. --- backend/HASHOUT_LOG.md | 6 ++++++ tests/test_stand_in_home.py | 14 ++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index c59a6060..5302bf14 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,12 @@ Reasoning behind engine changes, newest first. +## Unreleased · the suite's data folder on Windows is checked against the person's data folder (`tests/test_stand_in_home.py`) + +- **What was there.** `test_the_data_folder_read_at_import_is_the_suites_own_and_not_under_the_persons_home` asserted that the suite's data folder is not anywhere under the person's home. On Windows the system temporary folder is `%LOCALAPPDATA%\Temp`, inside the home, so the folder `tempfile.mkdtemp` makes there always failed it (CI: `C:\Users\runneradmin\AppData\Local\Temp\formcut-tests-...`). +- **The change.** The whole-home check stays where the temporary folder is outside the home (macOS, Linux). Everywhere the data folder must not be the person's own formcut data folder, worked out as `paths.data_root` would from the variables as they were before the stand-in home (`conftest._HOME_BEFORE`): `~/Library/Application Support/formcut`, `%LOCALAPPDATA%\formcut`, or `$XDG_DATA_HOME/formcut`. +- **Seen.** The file passes on Linux; the Windows paths from the failed run checked by hand: the home check is skipped, the data-folder check passes, and a folder inside `%LOCALAPPDATA%\formcut` would fail it. Not run on Windows. + ## 2.20.2 · the MCP tools give the clip ids that per-clip edits need (`app/agent_mcp.py`) - **What was there.** `formcut_edit` takes a clip id for its per-clip operations (crossfade, trim, move, remove), but no tool gave one: `formcut_add_clip` answered with the clip's name and place, and `formcut_get_project` listed clips by label. An agent could place clips and then not change them. diff --git a/tests/test_stand_in_home.py b/tests/test_stand_in_home.py index 4de0b2b8..575fe916 100644 --- a/tests/test_stand_in_home.py +++ b/tests/test_stand_in_home.py @@ -1,9 +1,11 @@ """The tests run with a home folder of their own (conftest.py), so nothing they write lands in the person's folders.""" +import sys +import tempfile from pathlib import Path import pytest -from conftest import _OWN_DATA_DIR, _REAL_HOME, STAND_IN_HOME +from conftest import _HOME_BEFORE, _OWN_DATA_DIR, _REAL_HOME, STAND_IN_HOME def _inside(path: Path) -> bool: @@ -30,4 +32,12 @@ def test_the_data_folder_read_at_import_is_the_suites_own_and_not_under_the_pers from app import paths assert Path(_OWN_DATA_DIR).resolve() == paths.DATA_DIR - assert _REAL_HOME.resolve() not in paths.DATA_DIR.parents + if _REAL_HOME.resolve() not in Path(tempfile.gettempdir()).resolve().parents: + assert _REAL_HOME.resolve() not in paths.DATA_DIR.parents + if sys.platform == "darwin": + persons = _REAL_HOME / "Library" / "Application Support" / "formcut" + elif sys.platform == "win32": + persons = Path(_HOME_BEFORE.get("LOCALAPPDATA") or _REAL_HOME) / "formcut" + else: + persons = Path(_HOME_BEFORE.get("XDG_DATA_HOME") or _REAL_HOME / ".local" / "share") / "formcut" + assert persons.resolve() != paths.DATA_DIR and persons.resolve() not in paths.DATA_DIR.parents