From 0bad42ee78d762fd434fec23281d15d6b75969a3 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 21:04:38 -0500 Subject: [PATCH 01/16] fix: never save a movie over another movie whose name differs only by case or cleaning --- backend/HASHOUT_LOG.md | 8 ++++++++ backend/app/routers/library.py | 24 ++++++++++++++++++++---- frontend/HASHOUT_LOG.md | 8 ++++++++ frontend/src/app/app.ts | 8 +++----- frontend/src/io/library-name.ts | 12 ++++++++++++ 5 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 frontend/src/io/library-name.ts diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index f41c40f..f9c158f 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -7,6 +7,14 @@ Last updated: 2026-11-27 · scenes of your own --- +## unreleased · a save never replaces a different movie + +- refers-to: routers/library.py :: _all_movies, _lands_on_other_movie, write_project +- kind: decision +- logged: 2026-11-28 + +- `PUT /api/library/{name}` answers 409 when the name only cleans into another movie's name (a trailing dot or space, a separator) or differs from a movie in the library only by case. On a case-insensitive disk both are one file, so the save would have replaced that movie with no copy in Recently Deleted. A first save under a name that needs cleaning still works, and the window carries on with the cleaned name the engine answers with. + ## v0.37.0 · scenes of your own - refers-to: routers/scenes.py; services/scenes.py; routers/trash.py :: _meta, restore; main.py diff --git a/backend/app/routers/library.py b/backend/app/routers/library.py index 5f08c9b..fca93ac 100644 --- a/backend/app/routers/library.py +++ b/backend/app/routers/library.py @@ -61,6 +61,23 @@ def project_path(name: str) -> Path: return find_movie(stem) or config.library_dir() / f"{stem}{config.PROJECT_EXT}" +def _all_movies() -> list[Path]: + paths = [p for p in config.library_dir().glob(f"*{config.PROJECT_EXT}") if p.is_file()] + for d in _stack_dirs(): + paths += [p for p in d.glob(f"*{config.PROJECT_EXT}") if p.is_file()] + return paths + + +def _lands_on_other_movie(name: str, path: Path) -> bool: + """A save names one movie: a name that only cleans into an existing movie's name, or that differs from one + only by case (one file on a case-insensitive disk), would replace that other movie, so it is refused.""" + raw = name[: -len(config.PROJECT_EXT)] if name.lower().endswith(config.PROJECT_EXT) else name + if raw != path.stem and path.is_file(): + return True + key = path.stem.casefold() + return any(p.stem != path.stem and p.stem.casefold() == key for p in _all_movies()) + + def entry(path: Path) -> dict: st = path.stat() out = {"name": path.stem, "file": path.name, "path": str(path), "size": st.st_size, "modified": st.st_mtime, @@ -84,10 +101,7 @@ def unique_path(stem: str, folder: Path | None = None) -> Path: def list_projects() -> dict: _migrate() folder = config.library_dir() - paths = [p for p in folder.glob(f"*{config.PROJECT_EXT}") if p.is_file()] - for d in _stack_dirs(): - paths += [p for p in d.glob(f"*{config.PROJECT_EXT}") if p.is_file()] - items = [entry(p) for p in paths] + items = [entry(p) for p in _all_movies()] items.sort(key=lambda e: e["modified"], reverse=True) return {"folder": str(folder), "items": items} @@ -429,6 +443,8 @@ def read_preview(name: str, v: str | None = None) -> Response: @router.put("/{name}") async def write_project(name: str, request: Request) -> dict: path = project_path(name) + if _lands_on_other_movie(name, path): + raise HTTPException(409, "Another movie already has that name.") body = await read_limited(request, config.MAX_PROJECT_BYTES, "The project is too large to save.") if body[:4] != b"PK\x03\x04": raise HTTPException(400, "That is not a FormMorpheus project.") diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 0a62365..9a67eb3 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -7,6 +7,14 @@ Last updated: 2026-11-28 · the interface on iPad for 0.32.0 to 0.37.0 --- +## unreleased · free library names compared the way the engine stores them + +- refers-to: io/library-name.ts; app/app.ts :: freeLibraryName +- kind: decision +- logged: 2026-11-28 + +- A new, adopted or duplicated movie takes a name only when no movie has it after the engine's cleaning (separators to `-`, spaces and dots trimmed, the `.fmo` extension dropped) and ignoring case, so it never asks the engine to save over another movie. The engine refuses such a save as well. + ## v0.38.0 · the interface on iPad for 0.32.0 to 0.37.0 - refers-to: styles/ipad-window.css; app/app.ts (the `ai-voice` command, `stage.nav.onContext`); ui/ai-voice-panel.ts; ui/subtitles-panel.ts :: allowListening; app/features/depth.ts diff --git a/frontend/src/app/app.ts b/frontend/src/app/app.ts index d584a28..62b680f 100644 --- a/frontend/src/app/app.ts +++ b/frontend/src/app/app.ts @@ -10,6 +10,7 @@ import type { Asset, Content } from '../engine/types'; import { api, ApiError, capabilities, onServiceChange, serviceReady } from '../io/api'; import { packMovie, unpackMovie } from '../io/fmo'; import { Recovery } from '../io/recovery'; +import { freeName } from '../io/library-name'; import { drawingToFormvis, frameToFormvis, movieToFormvfx } from '../io/round-trip'; import { characterToSvg } from '../io/svg-export'; import { canLinkPaths, sourceApi, trustSource } from '../io/source-api'; @@ -464,11 +465,8 @@ export function startApp(): void { let posterCache: { frame: number; at: number; rev: number; blob: Blob | null } | null = null; let lastCost = 0; let failedOnce = false; - const freeLibraryName = async (base: string): Promise => { - const taken = new Set((await api.library().catch(() => [])).map((i) => i.name)); - if (!taken.has(base)) return base; - for (let n = 2; ; n++) if (!taken.has(`${base} ${n}`)) return `${base} ${n}`; - }; + const freeLibraryName = async (base: string): Promise => + freeName(base, (await api.library().catch(() => [])).map((i) => i.name)); /** Writes the open movie now. `poster` takes a fresh poster from the Playhead frame (leaving); otherwise one up to 5 s old is reused. */ function save(asCopy: boolean, opts: SaveOpts = {}): Promise { diff --git a/frontend/src/io/library-name.ts b/frontend/src/io/library-name.ts new file mode 100644 index 0000000..682fdec --- /dev/null +++ b/frontend/src/io/library-name.ts @@ -0,0 +1,12 @@ +const BAD = /[\\/:*?"<>|\x00-\x1f]/g; + +export function libraryKey(name: string): string { + const stem = name.toLowerCase().endsWith('.fmo') ? name.slice(0, -4) : name; + return stem.replace(BAD, '-').trim().replace(/^\.+|\.+$/g, '').toLowerCase(); +} + +export function freeName(base: string, taken: readonly string[]): string { + const keys = new Set(taken.map(libraryKey)); + if (!keys.has(libraryKey(base))) return base; + for (let n = 2; ; n++) if (!keys.has(libraryKey(`${base} ${n}`))) return `${base} ${n}`; +} From a509db50df505764085e8c7f3eec938ac0ca5a69 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 21:04:38 -0500 Subject: [PATCH 02/16] test: saves under a case or cleaned twin name keep the other movie --- .../tests/library/test_library_projects.py | 30 +++++++++++++++++++ frontend/tests/unit/library-name.test.ts | 26 ++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 frontend/tests/unit/library-name.test.ts diff --git a/backend/tests/library/test_library_projects.py b/backend/tests/library/test_library_projects.py index aea4ac7..e4f87b9 100644 --- a/backend/tests/library/test_library_projects.py +++ b/backend/tests/library/test_library_projects.py @@ -280,3 +280,33 @@ def test_a_poster_over_eight_megabytes_is_refused(client): r = client.put("/api/library/Film/poster", content=PNG + b"\x00" * (8 * 1024 * 1024)) assert r.status_code == 413 assert client.get("/api/library/Film/poster").status_code == 204 + + +def test_a_save_whose_name_differs_only_by_case_keeps_the_other_movie(client): + save(client, "intro", movie_id="first") + r = client.put("/api/library/Intro", content=movie_bytes(movie_id="second")) + assert r.status_code == 409 + assert names(client) == ["intro"] + assert read_json(client.get("/api/library/intro").content)["id"] == "first" + + +@pytest.mark.parametrize("raw", ["Intro.", "Intro ", " Intro", "Intro. .fmo"]) +def test_a_save_whose_name_only_cleans_into_another_movie_keeps_it(client, raw): + save(client, "Intro", movie_id="first") + r = client.put(f"/api/library/{raw}", content=movie_bytes(movie_id="second")) + assert r.status_code == 409 + assert read_json(client.get("/api/library/Intro").content)["id"] == "first" + + +def test_a_new_name_that_needs_cleaning_is_still_saved(client): + r = client.put("/api/library/Intro.", content=movie_bytes()) + assert r.status_code == 200 + assert r.json()["name"] == "Intro" + + +def test_a_case_twin_inside_a_stack_is_refused_too(client): + save(client, "A") + save(client, "Scene") + client.post("/api/library/_stacks", json={"name": "Shorts", "items": ["Scene"]}) + assert client.put("/api/library/scene", content=movie_bytes()).status_code == 409 + assert names(client) == ["A", "Scene"] diff --git a/frontend/tests/unit/library-name.test.ts b/frontend/tests/unit/library-name.test.ts new file mode 100644 index 0000000..4b8803c --- /dev/null +++ b/frontend/tests/unit/library-name.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from 'vitest'; +import { freeName, libraryKey } from '@src/io/library-name'; + +describe('a free name in the library', () => { + it('keeps a name nobody has', () => { + expect(freeName('Intro', ['Outro'])).toBe('Intro'); + }); + + it('numbers a name that is taken', () => { + expect(freeName('Intro', ['Intro', 'Intro 2'])).toBe('Intro 3'); + }); + + it('treats a name that differs only by case as taken', () => { + expect(freeName('Intro', ['intro'])).toBe('Intro 2'); + }); + + it('treats a name that the engine cleans into a taken name as taken', () => { + expect(freeName('Intro.', ['Intro'])).not.toBe('Intro.'); + expect(freeName('Intro ', ['Intro'])).not.toBe('Intro '); + }); + + it('cleans names the way the engine does', () => { + expect(libraryKey(' A/B:c. ')).toBe('a-b-c'); + expect(libraryKey('Film.FMO')).toBe('film'); + }); +}); From 6c0be127a98089207a0868c3ffb106ab74968da5 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:28:45 -0500 Subject: [PATCH 03/16] fix: start npm shims on Windows without the command interpreter and check arguments that still need it An npm .cmd shim is started as the program or node script it names. Another .cmd or .bat keeps the interpreter, with quotes passed as apostrophes and %, control characters and unquoted special characters refused. Shared finder 1.0.2, hash recorded. --- NOTICE.md | 2 +- backend/HASHOUT_LOG.md | 9 ++++ backend/app/services/agent_lookup.py | 63 ++++++++++++++++++++++++++-- setup/agents.py | 3 +- 4 files changed, 72 insertions(+), 5 deletions(-) diff --git a/NOTICE.md b/NOTICE.md index f934d70..9917e8f 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -7,7 +7,7 @@ FormMorpheus is licensed under the Apache License 2.0 (`LICENSE`). It includes o | formvis design system and shell (shell, panel and dialog styles, theme boot, DOM helpers, menus, native menus, caption buttons, Home screen, dialogs, toasts, command registry and palette, number fields, controls), by nodemode-ai | `frontend/src/styles`, `frontend/src/ui`, `frontend/index.html` | Apache-2.0 | | formvis desktop shell (splash and reveal sequence, traffic light placement, text edit routing, packaged engine lookup, window state), by nodemode-ai | `src-tauri/src`, `frontend/public/splash.html`, `setup/` | Apache-2.0 | | formvfx engine patterns (typed event emitter, timeline mapping, ruler ticks, gesture merge for undo), by nodemode-ai | `frontend/src/engine/events.ts`, `frontend/src/ui/timeline.ts`, `frontend/src/engine/history.ts` | Apache-2.0 | -| formvis dock module 2.2.1 (terminal panel, agent tabs, the question an outside agent raises; version in `frontend/src/dock/MANIFEST.json`) and the shared agent program finder 1.0.1, shared Form family code copied unchanged, by nodemode-ai | `frontend/src/dock/`, `backend/app/services/agent_lookup.py` | Apache-2.0 | +| formvis dock module 2.2.1 (terminal panel, agent tabs, the question an outside agent raises; version in `frontend/src/dock/MANIFEST.json`) and the shared agent program finder 1.0.2, shared Form family code copied unchanged, by nodemode-ai | `frontend/src/dock/`, `backend/app/services/agent_lookup.py` | Apache-2.0 | | Remix Icon: the `paintbrush` and `hand` icon paths in `frontend/src/ui/icons.ts`, identical to FormVis's, which credits them to Remix Icon | inline SVG icons | Apache-2.0 (Remix Icon's license through its 4.9 releases; the project changed its license terms in January 2026, and the release these two paths come from was not recorded) | | fflate | `.fmo` movie files (zip), exported frame archives | MIT | | mediabunny 1.61.5 (Vanilagy), used unmodified from npm; source: https://github.com/Vanilagy/mediabunny | reading video and sound files, writing MP4, WebM and MOV exports | MPL-2.0 (file-level copyleft: its files are shipped unedited) | diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index f9c158f..9f6966e 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -15,6 +15,15 @@ Last updated: 2026-11-27 · scenes of your own - `PUT /api/library/{name}` answers 409 when the name only cleans into another movie's name (a trailing dot or space, a separator) or differs from a movie in the library only by case. On a case-insensitive disk both are one file, so the save would have replaced that movie with no copy in Recently Deleted. A first save under a name that needs cleaning still works, and the window carries on with the cleaned name the engine answers with. +## unreleased · agent programs from an npm shim start without the command interpreter + +- refers-to: services/agent_lookup.py :: _shim_target, _cmd_word, start_argv (finder 1.0.2); setup/agents.py :: LOOKUP_HASHES +- kind: decision +- logged: 2026-11-28 + +- On Windows an npm `.cmd` shim is read and started as what it names: the program, or the script with the `node.exe` beside the shim or the `node` on PATH. The program then gets its arguments exactly as given, quotes and `&` included. +- Any other `.cmd` or `.bat` still goes through the command interpreter. It does not read the backslash-escaped quotes of the Windows command line, so a quote in an argument is passed as an apostrophe; it expands `%` inside quotes and ends at a line break, so an argument with `%` or a control character is refused; `& | < > ^ ! ( )` are refused in an argument with no space or tab, the only arguments the command line quotes. + ## v0.37.0 · scenes of your own - refers-to: routers/scenes.py; services/scenes.py; routers/trash.py :: _meta, restore; main.py diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..899568e 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,70 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +_SHIM_TARGET = re.compile(r'"%dp0%\\([^"%]+)"\s*%\*') +_SHIM_PROG = re.compile(r'SET "_prog=((?:%dp0%\\)?[^"%]+)"', re.I) +_CMD_CONTROL = re.compile(r"[\x00-\x1f\x7f]") +_CMD_SPECIAL = re.compile(r"[&|<>^!()]") + + +def _in_shim_folder(base: Path, rel: str) -> Path: + return base.joinpath(*(p for p in re.split(r"[\\/]", rel) if p)) + + +def _shim_target(shim: str, env: dict) -> list[str] | None: + """What an npm .cmd shim runs, so it can be started without the command interpreter: the program it names, or the + script with the node beside the shim or on PATH. None when the file is not a shim of that shape.""" + try: + with open(shim, encoding="utf-8", errors="replace") as f: + text = f.read(16384) + except OSError: + return None + targets = _SHIM_TARGET.findall(text) + if not targets: + return None + base = Path(shim).parent + target = _in_shim_folder(base, targets[-1]) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe" and "%_prog%" not in text: + return [str(target)] + for prog in _SHIM_PROG.findall(text): + if prog.lower().startswith("%dp0%\\"): + here = _in_shim_folder(base, prog[6:]) + found = str(here) if here.is_file() else None + else: + found = shutil.which(prog, path=env.get("PATH")) + if found: + return [found, str(target)] + return None + + +def _cmd_word(word: str) -> str: + """One argument for a .cmd or .bat the command interpreter has to run. It does not read the backslash-escaped quotes + the Windows command line gets, so a quote is passed as an apostrophe. It expands % even inside quotes and ends the + line at a control character, so those are refused, and so are its special characters in a word without a space or + tab, the only words the command line puts in quotes.""" + word = word.replace('"', "'") + if _CMD_CONTROL.search(word) or "%" in word: + raise LookupError("That text cannot be passed to the program: leave out % and line breaks.") + if _CMD_SPECIAL.search(word) and not (" " in word or "\t" in word): + raise LookupError("That text cannot be passed to the program: put a space around & | < > ^ ! ( and ).") + return word + + 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 program or the node + script it names; another .cmd or .bat goes through the command interpreter, with each argument checked.""" 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 words[0].lower().endswith((".cmd", ".bat")): + direct = _shim_target(words[0], env) + if direct: + return [*direct, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/c", *(_cmd_word(w) for w in words)] + return 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 be4cacb..b433032 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -22,7 +22,8 @@ AGENTS_ROUTER = ROOT / "backend" / "app" / "routers" / "agents.py" DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", + "1.0.2": "fb825f40070a3c1d53f6723f919bd84d19383d0ae514be2947a54cd54a50d95b"} PORT = int(os.environ.get("FORMMORPHEUS_PORT") or 9494) PY = "python" if os.name == "nt" else "python3" USAGE = """usage: ./formmorpheus agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from From 8710edbfdb656b80dfe945d28c4621c4092ab525 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:28:45 -0500 Subject: [PATCH 04/16] test: npm shims start directly and interpreter arguments are checked on Windows --- backend/tests/agents/test_agent_lookup.py | 81 +++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/backend/tests/agents/test_agent_lookup.py b/backend/tests/agents/test_agent_lookup.py index 9e464e9..78240c4 100644 --- a/backend/tests/agents/test_agent_lookup.py +++ b/backend/tests/agents/test_agent_lookup.py @@ -292,3 +292,84 @@ def test_sentence_for_a_found_program_gives_the_path_and_how(): assert "/x/codex" in said and agent_lookup.HOW["shell"] in said broken = agent_lookup.sentence(agent_lookup.Found("codex", "Codex", "/x/codex", "path", "broken", error="E42")) assert "E42" in broken + + +NODE_SHIM = """@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\\pkg\\cli.js" %* +""" +EXE_SHIM = '@ECHO off\r\n"%dp0%\\node_modules\\pkg\\bin\\tool.exe" %*\r\n' +PROMPT = 'make the title say "Hi & welcome" (FormMorpheus window: movie "Tom & Jerry")' + + +def shim(folder: Path, text: str, *files: str) -> Path: + for rel in files: + target = folder.joinpath(*rel.split("\\")) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("") + path = folder / "claude.cmd" + path.write_text(text) + return path + + +def test_start_argv_on_windows_runs_an_npm_shim_with_the_node_beside_it(tmp_path): + path = shim(tmp_path, NODE_SHIM, "node.exe", "node_modules\\pkg\\cli.js") + argv = agent_lookup.start_argv([str(path), "--flag", PROMPT], {"COMSPEC": "C:\\cmd.exe"}, "win32") + assert argv == [str(tmp_path / "node.exe"), str(tmp_path / "node_modules" / "pkg" / "cli.js"), "--flag", PROMPT] + + +def test_start_argv_on_windows_runs_an_npm_shim_with_node_from_path(tmp_path): + path = shim(tmp_path / "npm", NODE_SHIM, "node_modules\\pkg\\cli.js") + node = exe(tmp_path / "bin" / "node") + argv = agent_lookup.start_argv([str(path), PROMPT], {"PATH": str(node.parent)}, "win32") + assert argv == [str(node), str(tmp_path / "npm" / "node_modules" / "pkg" / "cli.js"), PROMPT] + + +def test_start_argv_on_windows_runs_the_program_an_npm_shim_names(tmp_path): + path = shim(tmp_path, EXE_SHIM, "node_modules\\pkg\\bin\\tool.exe") + argv = agent_lookup.start_argv([str(path), PROMPT], {}, "win32") + assert argv == [str(tmp_path / "node_modules" / "pkg" / "bin" / "tool.exe"), PROMPT] + + +def test_start_argv_on_windows_keeps_the_interpreter_when_the_shim_target_is_missing(tmp_path): + path = shim(tmp_path, NODE_SHIM) + argv = agent_lookup.start_argv([str(path), "-v"], {"COMSPEC": "C:\\cmd.exe"}, "win32") + assert argv == ["C:\\cmd.exe", "/c", str(path), "-v"] + + +def test_start_argv_on_windows_passes_quotes_to_a_cmd_as_apostrophes(): + argv = agent_lookup.start_argv(["C:\\x\\claude.cmd", "--flag", PROMPT], {"COMSPEC": "C:\\cmd.exe"}, "win32") + assert argv[:4] == ["C:\\cmd.exe", "/c", "C:\\x\\claude.cmd", "--flag"] + assert argv[4] == "make the title say 'Hi & welcome' (FormMorpheus window: movie 'Tom & Jerry')" + line = subprocess.list2cmdline(argv[1:]) + assert '\\"' not in line + assert line.endswith('"' + argv[4] + '"') + + +@pytest.mark.parametrize("word", ["a&b", "x|y", "(z)", "a^b", "say\nhi", "tab\there\x00", "50% off", "%PATH%", "a\x7fb"]) +def test_start_argv_on_windows_refuses_text_the_interpreter_would_read_for_a_cmd(word): + with pytest.raises(LookupError): + agent_lookup.start_argv(["C:\\x\\claude.cmd", word], {}, "win32") + + +def test_start_argv_on_windows_refuses_a_shim_path_the_interpreter_would_read(): + with pytest.raises(LookupError): + agent_lookup.start_argv(["C:\\a&b\\claude.cmd", "-v"], {}, "win32") + + +def test_start_argv_on_windows_leaves_an_exe_argument_as_it_is(): + assert agent_lookup.start_argv(["C:\\x\\claude.exe", 'say "hi" & 50%'], {}, "win32") == ["C:\\x\\claude.exe", 'say "hi" & 50%'] From bc02592323111fb6f190dde80e22969a12afab1b Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:30:36 -0500 Subject: [PATCH 05/16] fix: import conversions read only the local file they are given Pass -protocol_whitelist file to every ffmpeg read of an import, refuse an import that starts as a text list of files, and store list endings as in.bin. --- backend/HASHOUT_LOG.md | 8 ++++++++ backend/app/routers/transcode.py | 27 +++++++++++++++++++++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 9f6966e..a50735c 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -24,6 +24,14 @@ Last updated: 2026-11-27 · scenes of your own - On Windows an npm `.cmd` shim is read and started as what it names: the program, or the script with the `node.exe` beside the shim or the `node` on PATH. The program then gets its arguments exactly as given, quotes and `&` included. - Any other `.cmd` or `.bat` still goes through the command interpreter. It does not read the backslash-escaped quotes of the Windows command line, so a quote in an argument is passed as an apostrophe; it expands `%` inside quotes and ends at a line break, so an argument with `%` or a control character is refused; `& | < > ^ ! ( )` are refused in an argument with no space or tab, the only arguments the command line quotes. +## unreleased · import conversions read only the file they are given + +- refers-to: routers/transcode.py :: LOCAL_ONLY, LIST_ENDINGS, LIST_HEADS, _input_name, _starts_as_a_list, _duration, _command, _heif_with_ffmpeg, start +- kind: decision +- logged: 2026-11-28 + +- Every ffmpeg read of an imported file passes `-protocol_whitelist file`, as the proxy and the audio encodes do. An import that starts as a text list of other files (a playlist, a concat list, an SDP description) answers 400, and a playlist or list ending is stored as `in.bin`, so ffmpeg goes by the content. + ## v0.37.0 · scenes of your own - refers-to: routers/scenes.py; services/scenes.py; routers/trash.py :: _meta, restore; main.py diff --git a/backend/app/routers/transcode.py b/backend/app/routers/transcode.py index 872a113..f5cf708 100644 --- a/backend/app/routers/transcode.py +++ b/backend/app/routers/transcode.py @@ -50,6 +50,23 @@ class Transcode: MAX_CONCURRENT = 2 PROBE_TIMEOUT = 30 _slots: asyncio.Semaphore | None = None +# ffmpeg reads only the one local file it is given: playlist and list formats name other files to open +LOCAL_ONLY = ("-protocol_whitelist", "file") +LIST_ENDINGS = frozenset({".m3u", ".m3u8", ".ffconcat", ".concat", ".txt", ".sdp", ".pls", ".xspf", ".cue"}) +LIST_HEADS = (b"#extm3u", b"ffconcat", b"<", b"#ext", b"file ", b"[playlist]", b"v=0") + + +def _input_name(name: str) -> str: + suffix = Path(name).suffix[:12] + if not re.fullmatch(r"\.[A-Za-z0-9]+", suffix) or suffix.lower() in LIST_ENDINGS: + return "in.bin" + return "in" + suffix + + +def _starts_as_a_list(src: Path) -> bool: + with open(src, "rb") as f: + head = f.read(64).lstrip(b"\xef\xbb\xbf \t\r\n").lower() + return head.startswith(LIST_HEADS) def _get(job_id: str) -> Transcode: @@ -118,7 +135,7 @@ def capabilities() -> dict: async def _duration(path: str, src: Path) -> tuple[float, bool]: """Seconds and whether the first video stream carries alpha, from `ffmpeg -i`.""" proc = await asyncio.create_subprocess_exec( - path, "-hide_banner", "-nostdin", "-i", str(src), stdin=asyncio.subprocess.DEVNULL, + path, "-hide_banner", "-nostdin", *LOCAL_ONLY, "-i", str(src), stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE, ) _, err = await _communicate(proc) @@ -132,7 +149,7 @@ async def _duration(path: str, src: Path) -> tuple[float, bool]: def _command(info: ff.FfmpegInfo, src: Path, out: Path, kind: str, alpha: bool, encoder: str) -> list[str]: - cmd = [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-progress", "pipe:1", "-nostats", "-i", str(src)] + cmd = [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-progress", "pipe:1", "-nostats", *LOCAL_ONLY, "-i", str(src)] if kind == "audio": return cmd + ["-vn", "-map", "0:a:0", "-c:a", "pcm_s16le", "-ar", "48000", str(out)] # sizes must be even for 4:2:0 @@ -231,7 +248,7 @@ def _heif_with_ffmpeg(info: ff.FfmpegInfo, src: Path, out: Path) -> None: import subprocess done = subprocess.run( - [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-i", str(src), "-frames:v", "1", "-an", "-pix_fmt", "rgba", str(out)], + [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", *LOCAL_ONLY, "-i", str(src), "-frames:v", "1", "-an", "-pix_fmt", "rgba", str(out)], capture_output=True, text=True, timeout=120, check=False, stdin=subprocess.DEVNULL, ) if done.returncode != 0 or not out.is_file() or out.stat().st_size == 0: @@ -276,9 +293,11 @@ async def start(request: Request, kind: str, name: str = "import") -> dict: job_id = uuid.uuid4().hex[:16] folder = config.jobs_dir() / f"import-{job_id}" folder.mkdir(parents=True, exist_ok=True) - src = folder / ("in" + (Path(name).suffix[:12] if re.fullmatch(r"\.[A-Za-z0-9]+", Path(name).suffix[:12]) else ".bin")) + src = folder / _input_name(name) try: await _stream_to(request, src, MAX_IMPORT_BYTES) + if _starts_as_a_list(src): + raise HTTPException(400, "That file is not a picture, a video or a sound.") except BaseException: shutil.rmtree(folder, ignore_errors=True) raise From 538001fe4bae0ab86a06bff6011728005f90ab2c Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:30:36 -0500 Subject: [PATCH 06/16] test: import conversions keep ffmpeg to the one local file --- backend/tests/media/test_transcode_inputs.py | 83 ++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 backend/tests/media/test_transcode_inputs.py diff --git a/backend/tests/media/test_transcode_inputs.py b/backend/tests/media/test_transcode_inputs.py new file mode 100644 index 0000000..5a14ba0 --- /dev/null +++ b/backend/tests/media/test_transcode_inputs.py @@ -0,0 +1,83 @@ +import asyncio +from pathlib import Path + +import pytest + +from app.routers import transcode +from app.services.ffmpeg import FfmpegInfo + + +@pytest.fixture +def ffmpeg(monkeypatch): + calls: list = [] + info = FfmpegInfo(path="/fake/ffmpeg", version="7", encoders=["libx264"]) + monkeypatch.setattr(transcode.ff, "probe", lambda *a, **k: info) + + def no_task(coro): + coro.close() + + monkeypatch.setattr(transcode.asyncio, "create_task", no_task) + return calls + + +def leftovers(data_dir: Path) -> list: + return [p for p in data_dir.rglob("*") if p.parent.name.startswith("import-")] + + +@pytest.mark.parametrize("head", [b"#EXTM3U\n#EXTINF:1,\nhttps://example.invalid/a.ts\n", b"\xef\xbb\xbf ffconcat version 1.0\n", b"file 'a.wav'\n", b"[playlist]\n"]) +def test_an_import_that_starts_as_a_list_of_files_is_refused(client, ffmpeg, data_dir, head): + reply = client.post("/api/transcode?kind=audio&name=clip.aif", content=head) + assert reply.status_code == 400 + assert leftovers(data_dir) == [] + + +def test_an_import_of_a_binary_sound_is_taken(client, ffmpeg): + reply = client.post("/api/transcode?kind=audio&name=clip.aif", content=b"FORM\x00\x00\x00\x10AIFFCOMM" + b"\x00" * 40) + assert reply.status_code == 200 + + +@pytest.mark.parametrize("name,kept", [("clip.aif", "in.aif"), ("clip.M3U8", "in.bin"), ("list.ffconcat", "in.bin"), ("a.txt", "in.bin"), + ("noext", "in.bin"), ("bad.a-b", "in.bin")]) +def test_the_input_keeps_only_a_media_ending(name, kept): + assert transcode._input_name(name) == kept + + +def test_every_ffmpeg_read_of_an_import_is_limited_to_the_local_file(tmp_path): + info = FfmpegInfo(path="/fake/ffmpeg", version="7") + for kind in ("audio", "video"): + cmd = transcode._command(info, tmp_path / "in.aif", tmp_path / "out.wav", kind, False, "libx264") + at = cmd.index("-i") + assert cmd[at - 2:at] == ["-protocol_whitelist", "file"] + + +def test_the_duration_probe_is_limited_to_the_local_file(monkeypatch, tmp_path): + seen: list = [] + + class Proc: + async def communicate(self): + return b"", b"Duration: 00:00:02.00" + + async def spawn(*argv, **kwargs): + seen.append(list(argv)) + return Proc() + + monkeypatch.setattr(transcode.asyncio, "create_subprocess_exec", spawn) + assert asyncio.run(transcode._duration("/fake/ffmpeg", tmp_path / "in.aif"))[0] == 2.0 + at = seen[0].index("-i") + assert seen[0][at - 2:at] == ["-protocol_whitelist", "file"] + + +def test_the_heic_fallback_is_limited_to_the_local_file(monkeypatch, tmp_path): + import subprocess + + seen: list = [] + + def fake_run(argv, **kwargs): + seen.append(argv) + Path(argv[-1]).write_bytes(b"png") + return subprocess.CompletedProcess(argv, 0, "", "") + + monkeypatch.setattr(subprocess, "run", fake_run) + transcode._heif_with_ffmpeg(FfmpegInfo(path="/fake/ffmpeg", version="7"), tmp_path / "in.heic", tmp_path / "out.png") + at = seen[0].index("-i") + assert seen[0][at - 2:at] == ["-protocol_whitelist", "file"] From 558bea4c49b7495a2734b1c67492b63f7a70f4ab Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:32:51 -0500 Subject: [PATCH 07/16] fix: settings writers read, change and write under one lock so none undoes another Choosing a library folder now records the choice after the copy against the settings as they are then. Each write uses its own part file. --- backend/HASHOUT_LOG.md | 8 ++++++++ backend/app/core/config.py | 23 ++++++++++++++++++++--- backend/app/routers/system.py | 9 +++++---- backend/app/services/agent_access.py | 13 +++++++------ backend/app/services/voice_remote.py | 12 +++++++----- 5 files changed, 47 insertions(+), 18 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index a50735c..6f1dd86 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -32,6 +32,14 @@ Last updated: 2026-11-27 · scenes of your own - Every ffmpeg read of an imported file passes `-protocol_whitelist file`, as the proxy and the audio encodes do. An import that starts as a text list of other files (a playlist, a concat list, an SDP description) answers 400, and a playlist or list ending is stored as `in.bin`, so ffmpeg goes by the content. +## unreleased · settings writers never undo each other + +- refers-to: core/config.py :: write_settings, update_settings; routers/system.py :: set_library; services/agent_access.py :: set_choice; services/voice_remote.py :: save_local +- kind: decision +- logged: 2026-11-28 + +- `update_settings(change)` reads, changes and writes settings.json under one lock, and each write uses its own part file, removed if the swap fails. Choosing a library folder reads the settings again after the copy, so an outside-agents choice or a voice setting made while a large library was copied is kept. + ## v0.37.0 · scenes of your own - refers-to: routers/scenes.py; services/scenes.py; routers/trash.py :: _meta, restore; main.py diff --git a/backend/app/core/config.py b/backend/app/core/config.py index e435150..429034a 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -1,10 +1,15 @@ import json import os import sys +import threading +import uuid +from collections.abc import Callable from pathlib import Path from app import __version__ +_settings_lock = threading.RLock() + APP_NAME = "formmorpheus" VERSION = __version__ FRONTEND_PORT = 5194 @@ -75,9 +80,21 @@ def read_settings() -> dict: def write_settings(data: dict) -> None: path = settings_path() - tmp = path.with_name(f".{path.name}.{os.getpid()}.part") - tmp.write_text(json.dumps(data), "utf-8") - os.replace(tmp, path) + tmp = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part") + with _settings_lock: + try: + tmp.write_text(json.dumps(data), "utf-8") + os.replace(tmp, path) + finally: + tmp.unlink(missing_ok=True) + + +def update_settings(change: Callable[[dict], dict]) -> dict: + """Reads, changes and writes settings.json as one step, so two writers never undo each other's change.""" + with _settings_lock: + data = change(read_settings()) + write_settings(data) + return data def library_source() -> str: diff --git a/backend/app/routers/system.py b/backend/app/routers/system.py index d2dfbce..e80d85d 100644 --- a/backend/app/routers/system.py +++ b/backend/app/routers/system.py @@ -71,14 +71,13 @@ def set_library(body: LibraryBody) -> dict: if config.library_source() == "override": raise HTTPException(409, "The library folder is set by FORMMORPHEUS_LIBRARY_DIR, so it cannot be changed here.") old = config.library_dir() - settings = config.read_settings() if body.dir is None or not body.dir.strip(): - settings.pop("libraryDir", None) + chosen = None target = config.default_library_dir() target.mkdir(parents=True, exist_ok=True) else: target = _safe_folder(body.dir) - settings["libraryDir"] = str(target) + chosen = str(target) copied = 0 if body.copyMovies and target.resolve() != old.resolve(): # Top-level movies and order file, the legacy stacks file, then each stack folder (movies + hidden order file). @@ -100,7 +99,9 @@ def _copy(src: Path, dst: Path) -> int: sub.mkdir(exist_ok=True) for src in list(d.glob(f"*{config.PROJECT_EXT}")) + [d / ".order.json"]: copied += _copy(src, sub / src.name) - config.write_settings(settings) + # read again after the copy: a choice made in Preferences while it ran is kept + rest = lambda s: {k: v for k, v in s.items() if k != "libraryDir"} + config.update_settings(lambda s: rest(s) if chosen is None else {**rest(s), "libraryDir": chosen}) return {"dir": str(config.library_dir()), "copied": copied, "source": config.library_source()} diff --git a/backend/app/services/agent_access.py b/backend/app/services/agent_access.py index 925f6b7..39715b5 100644 --- a/backend/app/services/agent_access.py +++ b/backend/app/services/agent_access.py @@ -18,10 +18,11 @@ def choice() -> str: def set_choice(value: str) -> dict: if value not in CHOICES: raise ValueError(f"The choice is one of {', '.join(CHOICES)}.") - stored = {k: v for k, v in config.read_settings().items() if k not in ("agentsAllowed", "agentsBlocked", seal.FIELD)} - if value == "allowed": - stored["agentsAllowed"] = True - elif value == "blocked": - stored["agentsBlocked"] = True - config.write_settings(seal.sign(stored)) + mark = {"allowed": {"agentsAllowed": True}, "blocked": {"agentsBlocked": True}}.get(value, {}) + + def change(settings: dict) -> dict: + stored = {k: v for k, v in settings.items() if k not in ("agentsAllowed", "agentsBlocked", seal.FIELD)} + return seal.sign({**stored, **mark}) + + config.update_settings(change) return state() diff --git a/backend/app/services/voice_remote.py b/backend/app/services/voice_remote.py index 836f7d6..89daf98 100644 --- a/backend/app/services/voice_remote.py +++ b/backend/app/services/voice_remote.py @@ -125,11 +125,13 @@ def save_local(base: str, model: str, voice: str, key: str | None) -> dict: _set_secret(LOCAL_ACCOUNT, key.strip()) elif key == "": _delete_secret(LOCAL_ACCOUNT) - settings = config.read_settings() - section = settings.get("voice") if isinstance(settings.get("voice"), dict) else {} - section["local"] = {"base": clean, "model": (model or "").strip(), "voice": (voice or "").strip()} - settings["voice"] = section - config.write_settings(settings) + local = {"base": clean, "model": (model or "").strip(), "voice": (voice or "").strip()} + + def change(settings: dict) -> dict: + section = settings.get("voice") if isinstance(settings.get("voice"), dict) else {} + return {**settings, "voice": {**section, "local": local}} + + config.update_settings(change) return local_settings() From a64f9923543c9199d9d46e3926278bb525a6779d Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:32:51 -0500 Subject: [PATCH 08/16] test: setting changes made during a library copy or at the same time are kept --- backend/tests/core/test_settings_writers.py | 59 +++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 backend/tests/core/test_settings_writers.py diff --git a/backend/tests/core/test_settings_writers.py b/backend/tests/core/test_settings_writers.py new file mode 100644 index 0000000..843eeff --- /dev/null +++ b/backend/tests/core/test_settings_writers.py @@ -0,0 +1,59 @@ +import shutil +import threading + +from app.core import config, seal +from app.routers import system +from app.services import agent_access + + +def test_concurrent_setting_changes_all_land(data_dir): + def bump(i: int) -> None: + for _ in range(20): + config.update_settings(lambda s: {**s, f"k{i}": s.get(f"k{i}", 0) + 1}) + + threads = [threading.Thread(target=bump, args=(i,)) for i in range(6)] + for t in threads: + t.start() + for t in threads: + t.join() + assert config.read_settings() == {f"k{i}": 20 for i in range(6)} + assert [p.name for p in data_dir.iterdir()] == ["settings.json"] + + +def test_a_failed_settings_write_leaves_no_part_file(data_dir, monkeypatch): + def refuse(src, dst): + raise OSError("disk full") + + monkeypatch.setattr(config.os, "replace", refuse) + try: + config.write_settings({"a": 1}) + except OSError: + pass + assert list(data_dir.iterdir()) == [] + + +def test_an_agent_choice_made_while_the_library_is_copied_is_kept(client, data_dir, tmp_path, monkeypatch): + monkeypatch.setattr(seal, "sign", lambda merged: dict(merged)) + old = config.library_dir() + (old / "Film.fmo").write_bytes(b"PK\x03\x04") + real_copy = shutil.copy2 + + def copy_then_choose(src, dst, *a, **k): + agent_access.set_choice("blocked") + return real_copy(src, dst, *a, **k) + + monkeypatch.setattr(system.shutil, "copy2", copy_then_choose) + target = tmp_path / "NewLibrary" + reply = client.post("/api/system/library", json={"dir": str(target), "copyMovies": True}) + assert reply.status_code == 200 + assert reply.json()["copied"] == 1 + stored = config.read_settings() + assert stored["agentsBlocked"] is True + assert stored["libraryDir"] in (str(target), str(target.resolve())) + + +def test_going_back_to_the_default_library_keeps_other_settings(client, data_dir, tmp_path): + config.write_settings({"libraryDir": str(tmp_path / "Lib"), "voice": {"local": {"base": "x"}}}) + reply = client.post("/api/system/library", json={"dir": None}) + assert reply.status_code == 200 + assert config.read_settings() == {"voice": {"local": {"base": "x"}}} From 91b96b1a0d2af5fc072b43a815be25c892793259 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:41:24 -0500 Subject: [PATCH 09/16] fix: keep arguments to a Windows .cmd intact when its path has a space When the program path is quoted, & | < > and ^ are refused in every argument. A name ending in dots or spaces counts as a .cmd or .bat, a shim whose node is itself a .cmd or .bat keeps the interpreter, and a refused version check reports the program as broken. Finder 1.0.2 hash updated. --- backend/app/services/agent_lookup.py | 25 ++++++++++++++++--- backend/tests/agents/test_agent_lookup.py | 29 +++++++++++++++++++++++ setup/agents.py | 2 +- 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index 899568e..c98ea7e 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -363,6 +363,12 @@ def _quote(word: str, fish: bool) -> str: _SHIM_PROG = re.compile(r'SET "_prog=((?:%dp0%\\)?[^"%]+)"', re.I) _CMD_CONTROL = re.compile(r"[\x00-\x1f\x7f]") _CMD_SPECIAL = re.compile(r"[&|<>^!()]") +_CMD_JOIN = re.compile(r"[&|<>^]") + + +def _batch(path: str) -> bool: + # Windows drops trailing dots and spaces from a file name, so "x.cmd." still runs as a .cmd + return path.rstrip(". ").lower().endswith((".cmd", ".bat")) def _in_shim_folder(base: Path, rel: str) -> Path: @@ -392,7 +398,8 @@ def _shim_target(shim: str, env: dict) -> list[str] | None: found = str(here) if here.is_file() else None else: found = shutil.which(prog, path=env.get("PATH")) - if found: + # a node that is itself a .cmd or .bat would bring the command interpreter back + if found and not _batch(found): return [found, str(target)] return None @@ -410,6 +417,16 @@ def _cmd_word(word: str) -> str: return word +def _cmd_words(words: list[str]) -> list[str]: + """Every word checked by _cmd_word. When the program's path has a space or tab it is put in quotes, and the command + interpreter then drops the first and the last quote of the line, which moves the quoting of every word after it, so + & | < > and ^ are refused in every word.""" + out = [_cmd_word(w) for w in words] + if (" " in out[0] or "\t" in out[0]) and any(_CMD_JOIN.search(w) for w in out): + raise LookupError("That text cannot be passed to the program: leave out & | < > and ^, or install the program in a folder without spaces.") + return out + + 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. An npm .cmd shim is started as the program or the node @@ -417,11 +434,11 @@ def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - if words[0].lower().endswith((".cmd", ".bat")): + if _batch(words[0]): direct = _shim_target(words[0], env) if direct: return [*direct, *words[1:]] - return [env.get("COMSPEC") or "cmd.exe", "/c", *(_cmd_word(w) for w in words)] + return [env.get("COMSPEC") or "cmd.exe", "/c", *_cmd_words(words)] return words shell = login_shell(env, platform) fish = Path(shell).name == "fish" @@ -473,6 +490,8 @@ def check(found: Found, env: dict | None = None, timeout: float = 15.0, fresh: b kept = ("broken", None, f"it gave no answer to --version in {timeout:g} seconds", time.monotonic()) except OSError as exc: kept = ("broken", None, exc.strerror or str(exc), time.monotonic()) + except LookupError as exc: + kept = ("broken", None, str(exc), time.monotonic()) with _lock: _checked[key] = kept found.state, found.version, found.error = kept[0], kept[1], kept[2] diff --git a/backend/tests/agents/test_agent_lookup.py b/backend/tests/agents/test_agent_lookup.py index 78240c4..8578ec0 100644 --- a/backend/tests/agents/test_agent_lookup.py +++ b/backend/tests/agents/test_agent_lookup.py @@ -371,5 +371,34 @@ def test_start_argv_on_windows_refuses_a_shim_path_the_interpreter_would_read(): agent_lookup.start_argv(["C:\\a&b\\claude.cmd", "-v"], {}, "win32") +def test_start_argv_on_windows_refuses_joining_characters_when_the_cmd_path_has_a_space(): + with pytest.raises(LookupError): + agent_lookup.start_argv(["C:\\Program Files\\x\\claude.cmd", "Tom & Jerry"], {}, "win32") + + +def test_start_argv_on_windows_keeps_spaced_text_for_a_cmd_path_with_a_space(): + argv = agent_lookup.start_argv(["C:\\Program Files (x86)\\x\\tool.cmd", "say hi"], {"COMSPEC": "C:\\cmd.exe"}, "win32") + assert argv == ["C:\\cmd.exe", "/c", "C:\\Program Files (x86)\\x\\tool.cmd", "say hi"] + + +@pytest.mark.parametrize("name", ["C:\\x\\claude.cmd.", "C:\\x\\claude.BAT ", "C:\\x\\claude.cmd. ."]) +def test_start_argv_on_windows_treats_a_trailing_dot_or_space_as_a_cmd(name): + with pytest.raises(LookupError): + agent_lookup.start_argv([name, "a&b"], {}, "win32") + + +def test_start_argv_on_windows_never_starts_a_shim_through_a_node_that_is_a_cmd(tmp_path): + text = NODE_SHIM.replace("node.exe", "node.cmd").replace('SET "_prog=node"', 'SET "_prog=%dp0%\\node.bat"') + path = shim(tmp_path, text, "node.cmd", "node.bat", "node_modules\\pkg\\cli.js") + argv = agent_lookup.start_argv([str(path), "-v"], {"COMSPEC": "C:\\cmd.exe"}, "win32") + assert argv == ["C:\\cmd.exe", "/c", str(path), "-v"] + + +def test_check_reports_text_the_interpreter_cannot_take_as_broken(): + found = agent_lookup.Found("claude", "Claude Code", "C:\\a&b\\claude.cmd", "path", "found") + checked = agent_lookup.check(found, {}, platform="win32", fresh=True) + assert checked.state == "broken" and "cannot be passed" in checked.error + + def test_start_argv_on_windows_leaves_an_exe_argument_as_it_is(): assert agent_lookup.start_argv(["C:\\x\\claude.exe", 'say "hi" & 50%'], {}, "win32") == ["C:\\x\\claude.exe", 'say "hi" & 50%'] diff --git a/setup/agents.py b/setup/agents.py index b433032..ff17fc4 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -23,7 +23,7 @@ DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", - "1.0.2": "fb825f40070a3c1d53f6723f919bd84d19383d0ae514be2947a54cd54a50d95b"} + "1.0.2": "08e173783595396d887315c49a5c4f52cf4af8c04f8ef62a7e738bff5c11f622"} PORT = int(os.environ.get("FORMMORPHEUS_PORT") or 9494) PY = "python" if os.name == "nt" else "python3" USAGE = """usage: ./formmorpheus agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from From 48b08e5759f95c19063cb619a6f5fa4ba03c05da Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:41:24 -0500 Subject: [PATCH 10/16] fix: treat movie names that differ only by Unicode form as the same name --- backend/app/routers/library.py | 12 +++++++++--- backend/tests/library/test_library_projects.py | 7 +++++++ frontend/src/io/library-name.ts | 2 +- frontend/tests/unit/library-name.test.ts | 5 +++++ 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/backend/app/routers/library.py b/backend/app/routers/library.py index fca93ac..d33c14c 100644 --- a/backend/app/routers/library.py +++ b/backend/app/routers/library.py @@ -7,6 +7,7 @@ import shutil import threading import time +import unicodedata import zipfile from pathlib import Path @@ -70,12 +71,17 @@ def _all_movies() -> list[Path]: def _lands_on_other_movie(name: str, path: Path) -> bool: """A save names one movie: a name that only cleans into an existing movie's name, or that differs from one - only by case (one file on a case-insensitive disk), would replace that other movie, so it is refused.""" + only by case or by Unicode form (one file on a case-insensitive or form-insensitive disk), would replace that other + movie, so it is refused.""" raw = name[: -len(config.PROJECT_EXT)] if name.lower().endswith(config.PROJECT_EXT) else name if raw != path.stem and path.is_file(): return True - key = path.stem.casefold() - return any(p.stem != path.stem and p.stem.casefold() == key for p in _all_movies()) + key = _name_key(path.stem) + return any(p.stem != path.stem and _name_key(p.stem) == key for p in _all_movies()) + + +def _name_key(stem: str) -> str: + return unicodedata.normalize("NFC", stem).casefold() def entry(path: Path) -> dict: diff --git a/backend/tests/library/test_library_projects.py b/backend/tests/library/test_library_projects.py index e4f87b9..e17a81d 100644 --- a/backend/tests/library/test_library_projects.py +++ b/backend/tests/library/test_library_projects.py @@ -298,6 +298,13 @@ def test_a_save_whose_name_only_cleans_into_another_movie_keeps_it(client, raw): assert read_json(client.get("/api/library/Intro").content)["id"] == "first" +def test_a_save_whose_name_differs_only_by_unicode_form_keeps_the_other_movie(client): + save(client, "Café", movie_id="first") + r = client.put("/api/library/Café", content=movie_bytes(movie_id="second")) + assert r.status_code == 409 + assert read_json(client.get("/api/library/Café").content)["id"] == "first" + + def test_a_new_name_that_needs_cleaning_is_still_saved(client): r = client.put("/api/library/Intro.", content=movie_bytes()) assert r.status_code == 200 diff --git a/frontend/src/io/library-name.ts b/frontend/src/io/library-name.ts index 682fdec..ea8abd0 100644 --- a/frontend/src/io/library-name.ts +++ b/frontend/src/io/library-name.ts @@ -2,7 +2,7 @@ const BAD = /[\\/:*?"<>|\x00-\x1f]/g; export function libraryKey(name: string): string { const stem = name.toLowerCase().endsWith('.fmo') ? name.slice(0, -4) : name; - return stem.replace(BAD, '-').trim().replace(/^\.+|\.+$/g, '').toLowerCase(); + return stem.replace(BAD, '-').trim().replace(/^\.+|\.+$/g, '').normalize('NFC').toUpperCase().toLowerCase(); } export function freeName(base: string, taken: readonly string[]): string { diff --git a/frontend/tests/unit/library-name.test.ts b/frontend/tests/unit/library-name.test.ts index 4b8803c..a666e8e 100644 --- a/frontend/tests/unit/library-name.test.ts +++ b/frontend/tests/unit/library-name.test.ts @@ -19,6 +19,11 @@ describe('a free name in the library', () => { expect(freeName('Intro ', ['Intro'])).not.toBe('Intro '); }); + it('treats a name in another Unicode form or a wider case as taken', () => { + expect(freeName('Café', ['Café'])).toBe('Café 2'); + expect(freeName('STRASSE', ['Straße'])).toBe('STRASSE 2'); + }); + it('cleans names the way the engine does', () => { expect(libraryKey(' A/B:c. ')).toBe('a-b-c'); expect(libraryKey('Film.FMO')).toBe('film'); From ee56e9dbd5d632db956cf28fd3244fa0ce4d3264 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:41:24 -0500 Subject: [PATCH 11/16] docs: record the command interpreter and Unicode name decisions --- backend/HASHOUT_LOG.md | 4 ++-- frontend/HASHOUT_LOG.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 6f1dd86..c1179dd 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -13,7 +13,7 @@ Last updated: 2026-11-27 · scenes of your own - kind: decision - logged: 2026-11-28 -- `PUT /api/library/{name}` answers 409 when the name only cleans into another movie's name (a trailing dot or space, a separator) or differs from a movie in the library only by case. On a case-insensitive disk both are one file, so the save would have replaced that movie with no copy in Recently Deleted. A first save under a name that needs cleaning still works, and the window carries on with the cleaned name the engine answers with. +- `PUT /api/library/{name}` answers 409 when the name only cleans into another movie's name (a trailing dot or space, a separator) or differs from a movie in the library only by case or Unicode form (NFC against NFD). On a case-insensitive or form-insensitive disk both are one file, so the save would have replaced that movie with no copy in Recently Deleted. A first save under a name that needs cleaning still works, and the window carries on with the cleaned name the engine answers with. ## unreleased · agent programs from an npm shim start without the command interpreter @@ -22,7 +22,7 @@ Last updated: 2026-11-27 · scenes of your own - logged: 2026-11-28 - On Windows an npm `.cmd` shim is read and started as what it names: the program, or the script with the `node.exe` beside the shim or the `node` on PATH. The program then gets its arguments exactly as given, quotes and `&` included. -- Any other `.cmd` or `.bat` still goes through the command interpreter. It does not read the backslash-escaped quotes of the Windows command line, so a quote in an argument is passed as an apostrophe; it expands `%` inside quotes and ends at a line break, so an argument with `%` or a control character is refused; `& | < > ^ ! ( )` are refused in an argument with no space or tab, the only arguments the command line quotes. +- Any other `.cmd` or `.bat` still goes through the command interpreter. It does not read the backslash-escaped quotes of the Windows command line, so a quote in an argument is passed as an apostrophe; it expands `%` inside quotes and ends at a line break, so an argument with `%` or a control character is refused; `& | < > ^ ! ( )` are refused in an argument with no space or tab, the only arguments the command line quotes. When the program's own path has a space or tab, the interpreter drops the first and last quote of the line, so `& | < > ^` are refused in every argument. A name ending in dots or spaces counts as a `.cmd` or `.bat`, a shim whose node is itself a `.cmd` or `.bat` keeps the interpreter, and a `--version` check that is refused reports the program as broken. ## unreleased · import conversions read only the file they are given diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 9a67eb3..624f210 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -13,7 +13,7 @@ Last updated: 2026-11-28 · the interface on iPad for 0.32.0 to 0.37.0 - kind: decision - logged: 2026-11-28 -- A new, adopted or duplicated movie takes a name only when no movie has it after the engine's cleaning (separators to `-`, spaces and dots trimmed, the `.fmo` extension dropped) and ignoring case, so it never asks the engine to save over another movie. The engine refuses such a save as well. +- A new, adopted or duplicated movie takes a name only when no movie has it after the engine's cleaning (separators to `-`, spaces and dots trimmed, the `.fmo` extension dropped) and ignoring case and Unicode form, so it never asks the engine to save over another movie. The engine refuses such a save as well. ## v0.38.0 · the interface on iPad for 0.32.0 to 0.37.0 From a5ab7c38a0016aac27f76d2fdf2d87e487ccc71c Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:08:40 -0500 Subject: [PATCH 12/16] fix: refuse every interpreter character in words passed to a Windows .cmd A .cmd or .bat that is not an npm shim still runs through the command interpreter, now with /d. Any word, the program path included, with & | < > ^ ( ) ! % " or a control character is refused whether or not it has spaces, and the message points to standard input or a file for long text. Words are passed unchanged. Finder 1.0.2 hash updated. --- backend/app/services/agent_lookup.py | 43 +++++++++++++--------------- setup/agents.py | 2 +- 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index c98ea7e..f3aad6d 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -361,9 +361,9 @@ def _quote(word: str, fish: bool) -> str: _SHIM_TARGET = re.compile(r'"%dp0%\\([^"%]+)"\s*%\*') _SHIM_PROG = re.compile(r'SET "_prog=((?:%dp0%\\)?[^"%]+)"', re.I) -_CMD_CONTROL = re.compile(r"[\x00-\x1f\x7f]") -_CMD_SPECIAL = re.compile(r"[&|<>^!()]") -_CMD_JOIN = re.compile(r"[&|<>^]") +# the command interpreter and the .cmd it runs (which re-reads %*) act on these even inside quotes +_CMD_REFUSED = re.compile(r'[&|<>^()!%"\x00-\x1f\x7f]') +_CMD_LONG_TEXT = "pass long text through standard input or a file if the program supports it" def _batch(path: str) -> bool: @@ -404,33 +404,29 @@ def _shim_target(shim: str, env: dict) -> list[str] | None: return None -def _cmd_word(word: str) -> str: - """One argument for a .cmd or .bat the command interpreter has to run. It does not read the backslash-escaped quotes - the Windows command line gets, so a quote is passed as an apostrophe. It expands % even inside quotes and ends the - line at a control character, so those are refused, and so are its special characters in a word without a space or - tab, the only words the command line puts in quotes.""" - word = word.replace('"', "'") - if _CMD_CONTROL.search(word) or "%" in word: - raise LookupError("That text cannot be passed to the program: leave out % and line breaks.") - if _CMD_SPECIAL.search(word) and not (" " in word or "\t" in word): - raise LookupError("That text cannot be passed to the program: put a space around & | < > ^ ! ( and ).") - return word +def _quoted(word: str) -> bool: + return word == "" or " " in word or "\t" in word def _cmd_words(words: list[str]) -> list[str]: - """Every word checked by _cmd_word. When the program's path has a space or tab it is put in quotes, and the command - interpreter then drops the first and the last quote of the line, which moves the quoting of every word after it, so - & | < > and ^ are refused in every word.""" - out = [_cmd_word(w) for w in words] - if (" " in out[0] or "\t" in out[0]) and any(_CMD_JOIN.search(w) for w in out): - raise LookupError("That text cannot be passed to the program: leave out & | < > and ^, or install the program in a folder without spaces.") - return out + """The words of a .cmd or .bat the command interpreter has to run, unchanged. Quoting does not protect a word there, + so any word, the program's path included, with & | < > ^ ( ) ! % " or a control character is refused, spaces or + not. A quoted path keeps its quotes only when no other word is quoted, so then no word may have a space either.""" + for i, word in enumerate(words): + if _CMD_REFUSED.search(word): + where = "the program's path" if i == 0 else "the text" + raise LookupError(f"That text cannot be passed to the program: {where} has one of & | < > ^ ( ) ! % \" or a " + f"line break, which the command interpreter would read; {_CMD_LONG_TEXT}.") + if _quoted(words[0]) and any(_quoted(w) for w in words[1:]): + raise LookupError("That text cannot be passed to the program: its path has a space, so the text cannot; " + f"{_CMD_LONG_TEXT}, or install the program in a folder without spaces.") + return list(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. An npm .cmd shim is started as the program or the node - script it names; another .cmd or .bat goes through the command interpreter, with each argument checked.""" + script it names, with no command interpreter; another .cmd or .bat goes through it, with every word checked.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): @@ -438,7 +434,8 @@ def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) direct = _shim_target(words[0], env) if direct: return [*direct, *words[1:]] - return [env.get("COMSPEC") or "cmd.exe", "/c", *_cmd_words(words)] + # /d skips the interpreter's AutoRun commands + return [env.get("COMSPEC") or "cmd.exe", "/d", "/c", *_cmd_words(words)] return words shell = login_shell(env, platform) fish = Path(shell).name == "fish" diff --git a/setup/agents.py b/setup/agents.py index ff17fc4..395ca92 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -23,7 +23,7 @@ DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", - "1.0.2": "08e173783595396d887315c49a5c4f52cf4af8c04f8ef62a7e738bff5c11f622"} + "1.0.2": "f8eda36da1f8efdf1a3438b890082c1feb961a7951583a4541cc39e321c7a656"} PORT = int(os.environ.get("FORMMORPHEUS_PORT") or 9494) PY = "python" if os.name == "nt" else "python3" USAGE = """usage: ./formmorpheus agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from From 6c3ea94b2314224d2bc11fb595e4e740c247065f Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:08:40 -0500 Subject: [PATCH 13/16] test: words for a Windows .cmd are refused on any interpreter character and npm shims still start directly --- backend/tests/agents/test_agent_lookup.py | 46 +++++++++++++---------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/backend/tests/agents/test_agent_lookup.py b/backend/tests/agents/test_agent_lookup.py index 8578ec0..4f2ff4f 100644 --- a/backend/tests/agents/test_agent_lookup.py +++ b/backend/tests/agents/test_agent_lookup.py @@ -175,7 +175,7 @@ def test_start_argv_quotes_for_fish_with_backslashes(): def test_start_argv_on_windows_puts_the_interpreter_before_a_cmd_only(): - assert agent_lookup.start_argv(["C:\\x\\codex.CMD", "-v"], {"COMSPEC": "C:\\cmd.exe"}, "win32") == ["C:\\cmd.exe", "/c", "C:\\x\\codex.CMD", "-v"] + assert agent_lookup.start_argv(["C:\\x\\codex.CMD", "-v"], {"COMSPEC": "C:\\cmd.exe"}, "win32") == ["C:\\cmd.exe", "/d", "/c", "C:\\x\\codex.CMD", "-v"] assert agent_lookup.start_argv(["C:\\x\\codex.exe"], {}, "win32") == ["C:\\x\\codex.exe"] @@ -348,37 +348,43 @@ def test_start_argv_on_windows_runs_the_program_an_npm_shim_names(tmp_path): def test_start_argv_on_windows_keeps_the_interpreter_when_the_shim_target_is_missing(tmp_path): path = shim(tmp_path, NODE_SHIM) argv = agent_lookup.start_argv([str(path), "-v"], {"COMSPEC": "C:\\cmd.exe"}, "win32") - assert argv == ["C:\\cmd.exe", "/c", str(path), "-v"] + assert argv == ["C:\\cmd.exe", "/d", "/c", str(path), "-v"] -def test_start_argv_on_windows_passes_quotes_to_a_cmd_as_apostrophes(): - argv = agent_lookup.start_argv(["C:\\x\\claude.cmd", "--flag", PROMPT], {"COMSPEC": "C:\\cmd.exe"}, "win32") - assert argv[:4] == ["C:\\cmd.exe", "/c", "C:\\x\\claude.cmd", "--flag"] - assert argv[4] == "make the title say 'Hi & welcome' (FormMorpheus window: movie 'Tom & Jerry')" - line = subprocess.list2cmdline(argv[1:]) - assert '\\"' not in line - assert line.endswith('"' + argv[4] + '"') +def test_start_argv_on_windows_passes_plain_words_to_a_cmd_unchanged(): + argv = agent_lookup.start_argv(["C:\\x\\claude.cmd", "--flag", "say hi to the movie, 'Tom'"], {"COMSPEC": "C:\\cmd.exe"}, "win32") + assert argv == ["C:\\cmd.exe", "/d", "/c", "C:\\x\\claude.cmd", "--flag", "say hi to the movie, 'Tom'"] -@pytest.mark.parametrize("word", ["a&b", "x|y", "(z)", "a^b", "say\nhi", "tab\there\x00", "50% off", "%PATH%", "a\x7fb"]) -def test_start_argv_on_windows_refuses_text_the_interpreter_would_read_for_a_cmd(word): +def test_start_argv_on_windows_refuses_a_long_prompt_for_a_cmd_and_names_stdin(): + with pytest.raises(LookupError, match="standard input or a file"): + agent_lookup.start_argv(["C:\\x\\claude.cmd", "--flag", PROMPT], {}, "win32") + + +@pytest.mark.parametrize("word", ["a&b", "x|y", "(z)", "a^b", "ab", "wow!", '"q"', "say\nhi", "tab\there\x00", + "50% off", "%PATH%", "a\x7fb", "a\x1bb", "Tom & Jerry", "say (hi)", 'say "hi"', "50 %"]) +def test_start_argv_on_windows_refuses_interpreter_characters_for_a_cmd_with_or_without_spaces(word): with pytest.raises(LookupError): agent_lookup.start_argv(["C:\\x\\claude.cmd", word], {}, "win32") -def test_start_argv_on_windows_refuses_a_shim_path_the_interpreter_would_read(): - with pytest.raises(LookupError): - agent_lookup.start_argv(["C:\\a&b\\claude.cmd", "-v"], {}, "win32") +@pytest.mark.parametrize("path", ["C:\\a&b\\claude.cmd", "C:\\Program Files (x86)\\x\\tool.cmd", "C:\\50%\\x.cmd", 'C:\\a"b\\x.bat']) +def test_start_argv_on_windows_refuses_a_cmd_path_the_interpreter_would_read(path): + with pytest.raises(LookupError, match="program's path"): + agent_lookup.start_argv([path, "-v"], {}, "win32") -def test_start_argv_on_windows_refuses_joining_characters_when_the_cmd_path_has_a_space(): +def test_start_argv_on_windows_refuses_spaced_text_when_the_cmd_path_has_a_space(): + with pytest.raises(LookupError): + agent_lookup.start_argv(["C:\\Program Files\\x\\claude.cmd", "say hi"], {}, "win32") with pytest.raises(LookupError): - agent_lookup.start_argv(["C:\\Program Files\\x\\claude.cmd", "Tom & Jerry"], {}, "win32") + agent_lookup.start_argv(["C:\\Program Files\\x\\claude.cmd", ""], {}, "win32") -def test_start_argv_on_windows_keeps_spaced_text_for_a_cmd_path_with_a_space(): - argv = agent_lookup.start_argv(["C:\\Program Files (x86)\\x\\tool.cmd", "say hi"], {"COMSPEC": "C:\\cmd.exe"}, "win32") - assert argv == ["C:\\cmd.exe", "/c", "C:\\Program Files (x86)\\x\\tool.cmd", "say hi"] +def test_start_argv_on_windows_keeps_a_cmd_path_with_a_space_when_no_other_word_is_quoted(): + argv = agent_lookup.start_argv(["C:\\Program Files\\x\\tool.cmd", "-v"], {"COMSPEC": "C:\\cmd.exe"}, "win32") + assert argv == ["C:\\cmd.exe", "/d", "/c", "C:\\Program Files\\x\\tool.cmd", "-v"] + assert subprocess.list2cmdline(argv[1:]).count('"') == 2 @pytest.mark.parametrize("name", ["C:\\x\\claude.cmd.", "C:\\x\\claude.BAT ", "C:\\x\\claude.cmd. ."]) @@ -391,7 +397,7 @@ def test_start_argv_on_windows_never_starts_a_shim_through_a_node_that_is_a_cmd( text = NODE_SHIM.replace("node.exe", "node.cmd").replace('SET "_prog=node"', 'SET "_prog=%dp0%\\node.bat"') path = shim(tmp_path, text, "node.cmd", "node.bat", "node_modules\\pkg\\cli.js") argv = agent_lookup.start_argv([str(path), "-v"], {"COMSPEC": "C:\\cmd.exe"}, "win32") - assert argv == ["C:\\cmd.exe", "/c", str(path), "-v"] + assert argv == ["C:\\cmd.exe", "/d", "/c", str(path), "-v"] def test_check_reports_text_the_interpreter_cannot_take_as_broken(): From 93346df1eb0f132085511b36d0b98a22a3c54a54 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:08:40 -0500 Subject: [PATCH 14/16] fix: import conversions read only real media containers The probe is held to an allowlist of containers with -format_whitelist, a list or manifest container is refused, and the conversion is pinned with -f to the container the probe found and given -protocol_whitelist file,pipe. --- backend/app/routers/transcode.py | 47 +++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/backend/app/routers/transcode.py b/backend/app/routers/transcode.py index f5cf708..638cf0d 100644 --- a/backend/app/routers/transcode.py +++ b/backend/app/routers/transcode.py @@ -52,6 +52,15 @@ class Transcode: _slots: asyncio.Semaphore | None = None # ffmpeg reads only the one local file it is given: playlist and list formats name other files to open LOCAL_ONLY = ("-protocol_whitelist", "file") +CONVERT_LOCAL_ONLY = ("-protocol_whitelist", "file,pipe") +# Real containers only. Every read is held to these, and the conversion is pinned to the one the probe found, so a +# list or manifest demuxer (hls, dash, concat, imf, sdp, image sequences and the like) never opens the input. +MEDIA_DEMUXERS = ("mov", "matroska", "avi", "mpegts", "mpeg", "mxf", "flv", "asf", "ogg", "wav", "w64", "aiff", "caf", + "mp3", "flac", "aac", "ac3", "eac3", "dts", "truehd", "amr", "au", "wv") +LIST_DEMUXERS = frozenset({"hls", "applehttp", "dash", "concat", "imf", "sdp", "rtp", "rtsp", "ffmetadata", "webm_dash_manifest", + "image2", "tee", "data"}) +MEDIA_ONLY = ("-format_whitelist", ",".join(MEDIA_DEMUXERS)) +NOT_MEDIA = "That file is not a picture, a video or a sound." LIST_ENDINGS = frozenset({".m3u", ".m3u8", ".ffconcat", ".concat", ".txt", ".sdp", ".pls", ".xspf", ".cue"}) LIST_HEADS = (b"#extm3u", b"ffconcat", b"<", b"#ext", b"file ", b"[playlist]", b"v=0") @@ -132,24 +141,41 @@ def capabilities() -> dict: return {"ffmpeg": info is not None, "heif": heif_available() or ffmpeg_reads_heif(info)} -async def _duration(path: str, src: Path) -> tuple[float, bool]: - """Seconds and whether the first video stream carries alpha, from `ffmpeg -i`.""" +def demuxer_of(probe_text: str) -> str: + """The container `ffmpeg -i` read, by its first name, when it is one of MEDIA_DEMUXERS; else the file is refused.""" + m = re.search(r"^Input #0, ([^\s,]+)[^\n]*, from ", probe_text, re.M) + name = m.group(1).lower() if m else "" + if name in LIST_DEMUXERS or name not in MEDIA_DEMUXERS: + raise RuntimeError(NOT_MEDIA) + return name + + +async def _duration(path: str, src: Path) -> tuple[float, bool, str]: + """Seconds, whether the first video stream carries alpha and the container, from `ffmpeg -i` held to the local file + and to MEDIA_DEMUXERS.""" proc = await asyncio.create_subprocess_exec( - path, "-hide_banner", "-nostdin", *LOCAL_ONLY, "-i", str(src), stdin=asyncio.subprocess.DEVNULL, + path, "-hide_banner", "-nostdin", *LOCAL_ONLY, *MEDIA_ONLY, "-i", str(src), stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE, ) _, err = await _communicate(proc) text = err.decode("utf-8", "replace") + demuxer = demuxer_of(text) seconds = 0.0 m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", text) if m: seconds = int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3)) alpha = bool(re.search(r"Video:.*\b(yuva\w*|argb|rgba|bgra|abgr|gbrap\w*|ya8|ya16\w*)\b", text)) - return seconds, alpha + return seconds, alpha, demuxer + + +def _pinned_input(src: Path, demuxer: str) -> list[str]: + if demuxer not in MEDIA_DEMUXERS: + raise RuntimeError(NOT_MEDIA) + return [*CONVERT_LOCAL_ONLY, *MEDIA_ONLY, "-f", demuxer, "-i", str(src)] -def _command(info: ff.FfmpegInfo, src: Path, out: Path, kind: str, alpha: bool, encoder: str) -> list[str]: - cmd = [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-progress", "pipe:1", "-nostats", *LOCAL_ONLY, "-i", str(src)] +def _command(info: ff.FfmpegInfo, src: Path, out: Path, kind: str, alpha: bool, encoder: str, demuxer: str) -> list[str]: + cmd = [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-progress", "pipe:1", "-nostats", *_pinned_input(src, demuxer)] if kind == "audio": return cmd + ["-vn", "-map", "0:a:0", "-c:a", "pcm_s16le", "-ar", "48000", str(out)] # sizes must be even for 4:2:0 @@ -181,7 +207,7 @@ async def _convert(job: Transcode, src: Path) -> None: try: if info is None: raise RuntimeError("ffmpeg was not found. Install it, or set FORMMORPHEUS_FFMPEG to its path.") - seconds, alpha = await _duration(info.path, src) + seconds, alpha, demuxer = await _duration(info.path, src) job.alpha = alpha and job.kind == "video" if job.kind == "audio": out, encoder, job.mime = job.folder / "out.wav", "pcm_s16le", "audio/wav" @@ -199,7 +225,7 @@ async def _convert(job: Transcode, src: Path) -> None: err_path = job.folder / "ffmpeg.err" with open(err_path, "wb") as err: proc = await asyncio.create_subprocess_exec( - *_command(info, src, out, job.kind, job.alpha, encoder), stdin=asyncio.subprocess.DEVNULL, + *_command(info, src, out, job.kind, job.alpha, encoder, demuxer), stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=err, ) job.proc = proc @@ -248,7 +274,8 @@ def _heif_with_ffmpeg(info: ff.FfmpegInfo, src: Path, out: Path) -> None: import subprocess done = subprocess.run( - [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", *LOCAL_ONLY, "-i", str(src), "-frames:v", "1", "-an", "-pix_fmt", "rgba", str(out)], + # HEIF is read by the mov demuxer + [info.path, "-hide_banner", "-nostdin", "-y", "-loglevel", "error", *_pinned_input(src, "mov"), "-frames:v", "1", "-an", "-pix_fmt", "rgba", str(out)], capture_output=True, text=True, timeout=120, check=False, stdin=subprocess.DEVNULL, ) if done.returncode != 0 or not out.is_file() or out.stat().st_size == 0: @@ -297,7 +324,7 @@ async def start(request: Request, kind: str, name: str = "import") -> dict: try: await _stream_to(request, src, MAX_IMPORT_BYTES) if _starts_as_a_list(src): - raise HTTPException(400, "That file is not a picture, a video or a sound.") + raise HTTPException(400, NOT_MEDIA) except BaseException: shutil.rmtree(folder, ignore_errors=True) raise From 9961a543ca6a862d7e162bab69d3ba3c10972ebc Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:08:40 -0500 Subject: [PATCH 15/16] test: import conversions are pinned to the probed container and refuse list containers --- backend/tests/media/test_transcode_inputs.py | 65 ++++++++++++++++---- 1 file changed, 54 insertions(+), 11 deletions(-) diff --git a/backend/tests/media/test_transcode_inputs.py b/backend/tests/media/test_transcode_inputs.py index 5a14ba0..241f87e 100644 --- a/backend/tests/media/test_transcode_inputs.py +++ b/backend/tests/media/test_transcode_inputs.py @@ -42,29 +42,57 @@ def test_the_input_keeps_only_a_media_ending(name, kept): assert transcode._input_name(name) == kept -def test_every_ffmpeg_read_of_an_import_is_limited_to_the_local_file(tmp_path): +def pinned(cmd: list, demuxer: str) -> None: + at = cmd.index("-i") + assert cmd[at - 6:at] == ["-protocol_whitelist", "file,pipe", "-format_whitelist", ",".join(transcode.MEDIA_DEMUXERS), "-f", demuxer] + + +def test_every_ffmpeg_conversion_of_an_import_is_pinned_to_the_local_file_and_its_container(tmp_path): info = FfmpegInfo(path="/fake/ffmpeg", version="7") - for kind in ("audio", "video"): - cmd = transcode._command(info, tmp_path / "in.aif", tmp_path / "out.wav", kind, False, "libx264") - at = cmd.index("-i") - assert cmd[at - 2:at] == ["-protocol_whitelist", "file"] + for kind, demuxer in (("audio", "aiff"), ("video", "mov")): + pinned(transcode._command(info, tmp_path / "in.aif", tmp_path / "out.wav", kind, False, "libx264", demuxer), demuxer) + + +@pytest.mark.parametrize("demuxer", ["hls", "concat", "dash", "imf", "sdp", "image2", ""]) +def test_a_conversion_never_starts_with_a_list_or_unknown_container(tmp_path, demuxer): + with pytest.raises(RuntimeError): + transcode._command(FfmpegInfo(path="/fake/ffmpeg", version="7"), tmp_path / "in.bin", tmp_path / "out.wav", "audio", False, "", demuxer) -def test_the_duration_probe_is_limited_to_the_local_file(monkeypatch, tmp_path): +def test_the_allowed_containers_hold_no_list_or_manifest_demuxer(): + assert not set(transcode.MEDIA_DEMUXERS) & transcode.LIST_DEMUXERS + assert {"hls", "dash", "concat", "imf", "sdp"} <= transcode.LIST_DEMUXERS + + +def probe_with(monkeypatch, text: bytes) -> list: seen: list = [] class Proc: async def communicate(self): - return b"", b"Duration: 00:00:02.00" + return b"", text async def spawn(*argv, **kwargs): seen.append(list(argv)) return Proc() monkeypatch.setattr(transcode.asyncio, "create_subprocess_exec", spawn) - assert asyncio.run(transcode._duration("/fake/ffmpeg", tmp_path / "in.aif"))[0] == 2.0 + return seen + + +def test_the_duration_probe_is_limited_to_the_local_file_and_real_containers(monkeypatch, tmp_path): + seen = probe_with(monkeypatch, b"Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'in.mov':\n Duration: 00:00:02.00, start: 0\n") + assert asyncio.run(transcode._duration("/fake/ffmpeg", tmp_path / "in.mov")) == (2.0, False, "mov") at = seen[0].index("-i") - assert seen[0][at - 2:at] == ["-protocol_whitelist", "file"] + assert seen[0][at - 4:at] == ["-protocol_whitelist", "file", "-format_whitelist", ",".join(transcode.MEDIA_DEMUXERS)] + + +@pytest.mark.parametrize("text", [b"Input #0, hls, from 'in.bin':\n Duration: 00:00:02.00\n", b"Input #0, concat, from 'in.bin':\n", + b"Input #0, dash, from 'in.bin':\n", b"Input #0, image2, from 'in.bin':\n", + b"[in#0] Format not on whitelist\nin.bin: Invalid argument\n", b""]) +def test_the_duration_probe_refuses_a_list_or_unknown_container(monkeypatch, tmp_path, text): + probe_with(monkeypatch, text) + with pytest.raises(RuntimeError, match="not a picture"): + asyncio.run(transcode._duration("/fake/ffmpeg", tmp_path / "in.bin")) def test_the_heic_fallback_is_limited_to_the_local_file(monkeypatch, tmp_path): @@ -79,5 +107,20 @@ def fake_run(argv, **kwargs): monkeypatch.setattr(subprocess, "run", fake_run) transcode._heif_with_ffmpeg(FfmpegInfo(path="/fake/ffmpeg", version="7"), tmp_path / "in.heic", tmp_path / "out.png") - at = seen[0].index("-i") - assert seen[0][at - 2:at] == ["-protocol_whitelist", "file"] + pinned(seen[0], "mov") + + +def test_a_real_ffmpeg_reads_a_sound_and_refuses_a_list_of_files(tmp_path): + import shutil + import subprocess + + path = shutil.which("ffmpeg") + if path is None: + pytest.skip("no ffmpeg on PATH") + sound = tmp_path / "a.wav" + subprocess.run([path, "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "sine=d=1", str(sound)], check=True, stdin=subprocess.DEVNULL) + assert asyncio.run(transcode._duration(path, sound))[2] == "wav" + listed = tmp_path / "in.bin" + listed.write_text(f"ffconcat version 1.0\nfile '{sound}'\n") + with pytest.raises(RuntimeError, match="not a picture"): + asyncio.run(transcode._duration(path, listed)) From c452a343ef97fae75f6bb2b5d6eadcbac343397a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:08:40 -0500 Subject: [PATCH 16/16] docs: record the interpreter word rule and the pinned import container --- backend/HASHOUT_LOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index c1179dd..bf665a8 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -17,20 +17,21 @@ Last updated: 2026-11-27 · scenes of your own ## unreleased · agent programs from an npm shim start without the command interpreter -- refers-to: services/agent_lookup.py :: _shim_target, _cmd_word, start_argv (finder 1.0.2); setup/agents.py :: LOOKUP_HASHES +- refers-to: services/agent_lookup.py :: _shim_target, _CMD_REFUSED, _cmd_words, start_argv (finder 1.0.2); setup/agents.py :: LOOKUP_HASHES - kind: decision - logged: 2026-11-28 - On Windows an npm `.cmd` shim is read and started as what it names: the program, or the script with the `node.exe` beside the shim or the `node` on PATH. The program then gets its arguments exactly as given, quotes and `&` included. -- Any other `.cmd` or `.bat` still goes through the command interpreter. It does not read the backslash-escaped quotes of the Windows command line, so a quote in an argument is passed as an apostrophe; it expands `%` inside quotes and ends at a line break, so an argument with `%` or a control character is refused; `& | < > ^ ! ( )` are refused in an argument with no space or tab, the only arguments the command line quotes. When the program's own path has a space or tab, the interpreter drops the first and last quote of the line, so `& | < > ^` are refused in every argument. A name ending in dots or spaces counts as a `.cmd` or `.bat`, a shim whose node is itself a `.cmd` or `.bat` keeps the interpreter, and a `--version` check that is refused reports the program as broken. +- Any other `.cmd` or `.bat` still goes through the command interpreter (`/d /c`, so no AutoRun command runs first). Quoting does not protect a word there: the interpreter and the `.cmd`, which reads its `%*` again, act on `& | < > ^ ( ) ! %` and `"` even inside quotes. So every word, the program's path included, with any of those or a control character (`\x00`-`\x1f`, `\x7f`) is refused, spaces or not, and the message says to pass long text through standard input or a file when the program supports it. Words are passed unchanged; the earlier apostrophe swap for quotes and the space-based exceptions are gone. A quoted path keeps its quotes only when it is the one quoted word on the line, so when the path has a space no other word may have one. A name ending in dots or spaces counts as a `.cmd` or `.bat`, a shim whose node is itself a `.cmd` or `.bat` keeps the interpreter, and a `--version` check that is refused reports the program as broken. ## unreleased · import conversions read only the file they are given -- refers-to: routers/transcode.py :: LOCAL_ONLY, LIST_ENDINGS, LIST_HEADS, _input_name, _starts_as_a_list, _duration, _command, _heif_with_ffmpeg, start +- refers-to: routers/transcode.py :: LOCAL_ONLY, CONVERT_LOCAL_ONLY, MEDIA_DEMUXERS, LIST_DEMUXERS, LIST_ENDINGS, LIST_HEADS, _input_name, _starts_as_a_list, demuxer_of, _duration, _pinned_input, _command, _heif_with_ffmpeg, start - kind: decision - logged: 2026-11-28 - Every ffmpeg read of an imported file passes `-protocol_whitelist file`, as the proxy and the audio encodes do. An import that starts as a text list of other files (a playlist, a concat list, an SDP description) answers 400, and a playlist or list ending is stored as `in.bin`, so ffmpeg goes by the content. +- The first-bytes check is a quick early answer, not the guard. The guard is the container: the probe runs with `-format_whitelist` set to MEDIA_DEMUXERS (real containers only), and the container it names is checked again against that list and LIST_DEMUXERS (hls, dash, concat, imf, sdp, image sequences and the like), so a list or manifest is refused whatever its first bytes. The conversion is then pinned with `-f` to that container, held to the same list, and given `-protocol_whitelist file,pipe`. A HEIC picture read by ffmpeg is pinned to the mov demuxer. No ffprobe is needed: the probe is the person's ffmpeg itself, so an install without ffprobe still converts. ## unreleased · settings writers never undo each other