From 578292b54adae7e25e65bddfdea76c32b3079a52 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:20:04 -0500 Subject: [PATCH 01/11] fix: let the Google sign-in return reach its page The browser opens the Google return address as a cross-site navigation with no Origin header, which the local request check refused, so Google Drive sign-in could never finish. Allow that one read path through; it is still bound to the single-use sign-in state. Escape the message shown on the return page. --- backend/app/main.py | 4 +++- backend/app/routers/cloud.py | 3 ++- backend/tests/test_f1_guard.py | 27 +++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/backend/app/main.py b/backend/app/main.py index 3a8eddd..297224b 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -51,6 +51,8 @@ async def lifespan(app): app = FastAPI(title="FormRef", version=VERSION, lifespan=lifespan) app.add_middleware(CORSMiddleware, allow_origin_regex=r"^(https?://(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?|(chrome|moz)-extension://[a-z0-9-]+)$", allow_credentials=False, allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "X-FormRef-Clip-Token"], expose_headers=["Content-Disposition", "X-FormRef-Scale", "X-FormRef-Width", "X-FormRef-Height"]) +SIGN_IN_RETURNS = {("GET", "/api/cloud/google/callback")} + @app.middleware("http") async def local_access(request: Request, call_next): host = urlparse("http://" + request.headers.get("host", "")).hostname @@ -64,7 +66,7 @@ async def local_access(request: Request, call_next): if not local: return JSONResponse(status_code=403, content={"detail": "FormRef accepts local clients only."}) origin = request.headers.get("origin") - if not origin and request.headers.get("sec-fetch-site", "").strip().lower() == "cross-site": + if not origin and request.headers.get("sec-fetch-site", "").strip().lower() == "cross-site" and (request.method, request.url.path) not in SIGN_IN_RETURNS: return JSONResponse(status_code=403, content={"detail": "Origin is not an allowed local application."}) if origin and not origins.allowed(origin, request.headers.get("host", ""), request.url.path): return JSONResponse(status_code=403, content={"detail": "Origin is not an allowed local application."}) diff --git a/backend/app/routers/cloud.py b/backend/app/routers/cloud.py index 9197def..659a029 100644 --- a/backend/app/routers/cloud.py +++ b/backend/app/routers/cloud.py @@ -1,4 +1,5 @@ import asyncio +import html import re import uuid @@ -44,7 +45,7 @@ def start(name: str, request: Request): @router.get("/google/callback", response_class=HTMLResponse) def google_callback(state: str = "", code: str = "", error: str = ""): status, message = cloud.google_callback(state, code, error) - page = f"FormRef

{message}

" + page = f"FormRef

{html.escape(message)}

" return HTMLResponse(page, status_code=status) diff --git a/backend/tests/test_f1_guard.py b/backend/tests/test_f1_guard.py index f0b1fe2..de842c5 100644 --- a/backend/tests/test_f1_guard.py +++ b/backend/tests/test_f1_guard.py @@ -80,3 +80,30 @@ def test_foreign_websocket_closes_4403(client, headers): with client.websocket_connect(WS_PATH, headers=headers) as ws: ws.receive() assert refused.value.code == 4403 + + +GOOGLE_RETURN = "/api/cloud/google/callback" + + +@pytest.mark.parametrize("value", ["cross-site", "CROSS-SITE"]) +def test_the_google_sign_in_return_reaches_its_page(bare, value): + r = bare.get(GOOGLE_RETURN, params={"state": "unknown", "code": "c"}, headers={"sec-fetch-site": value}) + assert r.status_code == 400 + assert "unknown or expired" in r.text + + +def test_the_google_sign_in_return_only_opens_for_a_read(bare): + assert bare.post(GOOGLE_RETURN, headers={"sec-fetch-site": "cross-site"}).status_code == 403 + + +def test_other_cloud_paths_stay_closed_to_cross_site_requests(bare): + assert bare.get("/api/cloud", headers={"sec-fetch-site": "cross-site"}).status_code == 403 + assert bare.get(GOOGLE_RETURN + "/x", headers={"sec-fetch-site": "cross-site"}).status_code == 403 + + +def test_the_google_sign_in_page_escapes_the_message(bare, monkeypatch): + from app.core import cloud + + monkeypatch.setattr(cloud, "google_callback", lambda state, code, error: (502, "Sign-in failed: x")) + r = bare.get(GOOGLE_RETURN, params={"state": "s", "code": "c"}) + assert "x" not in r.text and "<b>x</b>" in r.text From 5e9b13a9adca6a1628aacef5cc6738b683f37111 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:21:36 -0500 Subject: [PATCH 02/11] fix: start npm .cmd agent programs through node on Windows A Codex or Cursor turn passes the message as one argument holding line breaks and quotes, which the Windows command interpreter cannot carry through a .cmd shim. Read an npm shim and run its node script directly with the node beside it or on PATH. Any other .cmd or .bat still runs under the interpreter, but only with words it reads as plain text; anything else is refused with a clear message. --- backend/app/agent/agent_lookup.py | 40 +++++++++++++++- backend/app/agent/service.py | 2 +- backend/tests/test_windows_start.py | 71 +++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+), 3 deletions(-) create mode 100644 backend/tests/test_windows_start.py diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index ea34eba..084c631 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -359,13 +359,49 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%]+\.(?:js|cjs|mjs))"\s+%\*', re.IGNORECASE) +CMD_ALWAYS = re.compile(r'[\x00-\x1f\x7f%"!]') +CMD_UNQUOTED = re.compile(r"[&|<>^(),;=]") + + +def _shim_target(shim: str, env: dict) -> list[str] | None: + try: + text = Path(shim).read_text(encoding="utf-8", errors="replace") + except OSError: + return None + match = SHIM_TARGET.search(text) + if not match: + return None + folder = Path(shim).parent + script = folder.joinpath(*match.group(1).replace("/", "\\").split("\\")) + if not script.is_file(): + return None + beside = folder / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH")) + return [node, str(script)] if node else None + + +def _cmd_safe(words: list[str]) -> None: + for word in words: + if CMD_ALWAYS.search(word) or (CMD_UNQUOTED.search(word) and not (" " in word or "\t" in word)): + raise ValueError("This text cannot be passed to a .cmd or .bat program on Windows: it holds a line break, a quote, " + "% or ! or a command character. Point FormRef at the program's .exe or node script instead.") + + 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 that only starts a node script is replaced + by node and that script; any other runs under the command interpreter, given only words it reads as plain 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().endswith((".cmd", ".bat")): + return words + target = _shim_target(words[0], env) + if target: + return [*target, *words[1:]] + _cmd_safe(words) + return [env.get("COMSPEC") or "cmd.exe", "/c", *words] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/app/agent/service.py b/backend/app/agent/service.py index 19e5c96..dd69dca 100644 --- a/backend/app/agent/service.py +++ b/backend/app/agent/service.py @@ -314,7 +314,7 @@ async def _cli(self, turn_id, runner, prompt, token, config): self.cli_turns += 1 self.cli_active.append(turn_id) try: - process = await asyncio.create_subprocess_exec(*agent_lookup.start_argv(runners.argv(runner, binary, prompt, token, API_URL, config["model"], mcp_file)), + process = await asyncio.create_subprocess_exec(*agent_lookup.start_argv(runners.argv(runner, binary, prompt, token, API_URL, config["model"], mcp_file), env), cwd=str(ROOT), env=env, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, limit=8 * 1024 * 1024) self.processes[turn_id] = process diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py new file mode 100644 index 0000000..0505a48 --- /dev/null +++ b/backend/tests/test_windows_start.py @@ -0,0 +1,71 @@ +import pytest + +from app.agent import agent_lookup + +NPM_SHIM = ( + '@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n' + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n' + ' SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & ' + '"%_prog%" "%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js" %*\r\n' +) +ENV = {"COMSPEC": "C:\\Windows\\system32\\cmd.exe", "PATH": ""} +PROMPT = 'Rules\n\nmake a "hero" & tidy notes' + + +@pytest.fixture +def shim(tmp_path): + script = tmp_path / "node_modules" / "@openai" / "codex" / "bin" / "codex.js" + script.parent.mkdir(parents=True) + script.write_text("") + path = tmp_path / "codex.cmd" + path.write_text(NPM_SHIM) + return path, script + + +def test_an_npm_shim_runs_its_script_with_the_node_beside_it(shim): + path, script = shim + node = path.parent / "node.exe" + node.write_text("") + argv = agent_lookup.start_argv([str(path), "exec", "--json", PROMPT], ENV, "win32") + assert argv == [str(node), str(script), "exec", "--json", PROMPT] + + +def test_an_npm_shim_runs_its_script_with_the_node_on_the_path(shim, tmp_path): + path, script = shim + bin_dir = tmp_path / "nodejs" + bin_dir.mkdir() + node = bin_dir / "node" + node.write_text("") + node.chmod(0o755) + argv = agent_lookup.start_argv([str(path), "exec", PROMPT], {**ENV, "PATH": str(bin_dir)}, "win32") + assert argv == [str(node), str(script), "exec", PROMPT] + + +@pytest.fixture +def plain_cmd(tmp_path): + path = tmp_path / "tool.cmd" + path.write_text("@echo off\r\nsomething.exe %*\r\n") + return str(path) + + +@pytest.mark.parametrize("word", [PROMPT, "two\nlines", "tab\there\x01", "100%", 'say "hi"', "wow!", "a&b", "a|b", "a>b", "a^b", "(a)"]) +def test_a_plain_cmd_refuses_words_the_interpreter_would_read(plain_cmd, word): + with pytest.raises(ValueError): + agent_lookup.start_argv([plain_cmd, "-p", word], ENV, "win32") + + +@pytest.mark.parametrize("word", ["--version", "status", "a & b", "C:\\Program Files (x86)\\x", ""]) +def test_a_plain_cmd_takes_plain_or_quoted_words(plain_cmd, word): + assert agent_lookup.start_argv([plain_cmd, word], ENV, "win32") == [ENV["COMSPEC"], "/c", plain_cmd, word] + + +def test_a_shim_whose_script_is_missing_falls_back_to_the_checked_interpreter(shim): + path, script = shim + script.unlink() + with pytest.raises(ValueError): + agent_lookup.start_argv([str(path), "exec", PROMPT], ENV, "win32") + + +def test_an_exe_is_started_directly(tmp_path): + exe = str(tmp_path / "codex.exe") + assert agent_lookup.start_argv([exe, "exec", PROMPT], ENV, "win32") == [exe, "exec", PROMPT] From 7142ec87d3d148100a041dc493c8a856ca71873b Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:24:08 -0500 Subject: [PATCH 03/11] fix: hold the data folder lock in every running service Only the desktop engine took engine.lock, so a service started by the MCP server, ./formref serve or ./formref dev let the desktop engine start a second service over the same data folder, and each overwrote the other's boards. The service now takes the lock when it starts, unless its own process already holds it, refuses to start while another holds it, and lets it go when it stops. --- backend/app/core/startup.py | 17 +++++++++++++++++ backend/app/main.py | 21 +++++++++++++++------ backend/tests/test_startup.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 6 deletions(-) diff --git a/backend/app/core/startup.py b/backend/app/core/startup.py index 3e2cac6..4b51eea 100644 --- a/backend/app/core/startup.py +++ b/backend/app/core/startup.py @@ -284,6 +284,23 @@ def claim(data: Path, shell: int) -> tuple[Path, int]: return path, held if state == LEFTOVER else 0 +def hold(data: Path) -> bool: + if number(read_lock(data / LOCK_NAME).get("pid")) == os.getpid(): + return False + data.mkdir(parents=True, exist_ok=True) + claim(data, shell_pid() or os.getppid()) + return True + + +def let_go(data: Path) -> None: + path = data / LOCK_NAME + if number(read_lock(path).get("pid")) == os.getpid(): + try: + path.unlink() + except OSError: + pass + + def shell_pid() -> int: raw = os.environ.get(SHELL_ENV, "").strip() return int(raw) if raw.isascii() and raw.isdigit() else 0 diff --git a/backend/app/main.py b/backend/app/main.py index 297224b..88878c9 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -7,7 +7,7 @@ from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, FileResponse from starlette.middleware.cors import CORSMiddleware -from .core import engine_log, origins +from .core import engine_log, origins, startup from .core.window_key import WindowKeyGuard from .core.config import ROOT, VERSION, settings from .core.engine import broker, EngineError @@ -41,12 +41,21 @@ @asynccontextmanager async def lifespan(app): engine_log.join() + try: + held = startup.hold(settings.data_dir) + except startup.Busy as err: + log.error("%s", err) + raise log.info("FormRef %s using %s", VERSION, settings.data_dir) - terminal.start(asyncio.get_running_loop()) - async with mcp_server.session_manager.run(): - yield - terminal.close_all() - broker.close() + try: + terminal.start(asyncio.get_running_loop()) + async with mcp_server.session_manager.run(): + yield + terminal.close_all() + broker.close() + finally: + if held: + startup.let_go(settings.data_dir) app = FastAPI(title="FormRef", version=VERSION, lifespan=lifespan) app.add_middleware(CORSMiddleware, allow_origin_regex=r"^(https?://(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?|(chrome|moz)-extension://[a-z0-9-]+)$", allow_credentials=False, allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "X-FormRef-Clip-Token"], expose_headers=["Content-Disposition", "X-FormRef-Scale", "X-FormRef-Width", "X-FormRef-Height"]) diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index d80ae5c..c116b5f 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -220,3 +220,34 @@ def test_a_frozen_engine_started_alone_with_no_app_near_it_says_so_and_serves_no assert done.returncode == 4 assert "formref-engine is a part of FormRef and serves nothing on its own. Open FormRef instead." in done.stderr assert not (data / "engine.lock").exists() + + +def test_a_service_started_without_the_app_holds_the_folder_so_the_app_engine_waits(tmp_path): + env = engine_env(tmp_path) + port = env["FORMREF_PORT"] + shell = stand_in() + served = subprocess.Popen([sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", port], cwd=BACKEND, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + assert wait_for(lambda: (tmp_path / "engine.lock").is_file() and json.loads((tmp_path / "engine.lock").read_text()).get("pid") == served.pid) + assert json.loads((tmp_path / "engine.lock").read_text())["shell"] == os.getpid() + second = subprocess.run([sys.executable, "formref_engine.py"], cwd=BACKEND, env=engine_env(tmp_path, FORMREF_SHELL_PID=str(shell.pid)), capture_output=True, text=True, timeout=60) + assert second.returncode == 2 and f"formref is already running on {tmp_path} (engine process {served.pid})." in second.stderr + again = subprocess.run([sys.executable, "-m", "uvicorn", "app.main:app", "--host", "127.0.0.1", "--port", str(free_port())], cwd=BACKEND, env=engine_env(tmp_path), capture_output=True, text=True, timeout=60) + assert again.returncode != 0 and "already running" in again.stderr + assert served.poll() is None + assert wait_for(lambda: _answers(port)) + served.terminate() + assert served.wait(timeout=10) is not None + assert not (tmp_path / "engine.lock").exists() + finally: + stop(shell, served) + + +def _answers(port): + import urllib.request + + try: + with urllib.request.urlopen(f"http://127.0.0.1:{port}/api/health", timeout=1) as r: + return r.status == 200 + except OSError: + return False From 48949cafdc806ec4b23eda68d3ae68cde2edd9a7 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:26:04 -0500 Subject: [PATCH 04/11] fix: give Codex and Cursor panel turns the board tools Codex and Cursor turns from the Agent panel ran in the app folder and relied on the source checkout's MCP files, which the installed app does not have and which name a fixed port. Run them in the agent folder that program tabs already use, whose files point at the running service and send the turn's own token. --- backend/app/agent/service.py | 9 ++++++++- backend/tests/test_agent_programs.py | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/backend/app/agent/service.py b/backend/app/agent/service.py index dd69dca..603faf6 100644 --- a/backend/app/agent/service.py +++ b/backend/app/agent/service.py @@ -63,6 +63,12 @@ def loopback_url(value) -> bool: return False +def _agent_folder() -> Path: + from .programs import workdir + + return workdir() + + class Agents: def __init__(self): self.tokens: set[str] = set() @@ -311,11 +317,12 @@ async def _cli(self, turn_id, runner, prompt, token, config): base = {k: v for k, v in os.environ.items() if k != "FORMREF_WINDOW_KEY_STDOUT"} env = agent_lookup.child_env(binary, base=base, extra={"FORMREF_API_URL": API_URL, "FORMREF_AGENT_TOKEN": token}, shell_timeout=10.0) mcp_file = self.token_file(token, {"mcpServers": {"formref": runners.mcp_server(token, API_URL)}}) if runner == "claude" else "" + folder = ROOT if runner == "claude" else await asyncio.to_thread(_agent_folder) self.cli_turns += 1 self.cli_active.append(turn_id) try: process = await asyncio.create_subprocess_exec(*agent_lookup.start_argv(runners.argv(runner, binary, prompt, token, API_URL, config["model"], mcp_file), env), - cwd=str(ROOT), env=env, stdin=asyncio.subprocess.DEVNULL, + cwd=str(folder), env=env, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, limit=8 * 1024 * 1024) self.processes[turn_id] = process async for raw in process.stdout: diff --git a/backend/tests/test_agent_programs.py b/backend/tests/test_agent_programs.py index e01c32b..1a28e6e 100644 --- a/backend/tests/test_agent_programs.py +++ b/backend/tests/test_agent_programs.py @@ -1,4 +1,5 @@ import json +import re import os import stat from pathlib import Path @@ -234,3 +235,21 @@ def test_a_missing_program_or_an_unknown_kind_is_refused(client, nothing_install def test_starting_a_program_tab_needs_the_window_key(bare, stand_ins): r = bare.post("/api/terminal/agent", json={"kind": "codex"}) assert r.status_code == 403 and r.json() == REFUSED + + +@pytest.mark.parametrize("runner, name", [("codex", "codex"), ("cursor", "cursor-agent")]) +def test_a_codex_or_cursor_panel_turn_runs_in_the_folder_that_gives_it_the_board_tools(client, stand_ins, own_shell, runner, name): + from app.agent import programs + + seen = own_shell / f"{runner}-seen" + (stand_ins / name).write_text(f'#!/bin/sh\nif [ "$1" = "--version" ]; then echo "{name} 0.99.1"; exit 0; fi\npwd -P > "{seen}"\necho "$FORMREF_AGENT_TOKEN" >> "{seen}"\n') + board = client.post("/api/boards", json={"title": f"{runner} turn"}).json()["board"]["id"] + with client.stream("POST", "/api/agent/turns", json={"board_id": board, "message": "tidy", "runner": runner}) as r: + assert r.status_code == 200 + "".join(r.iter_text()) + where, token = seen.read_text().splitlines() + folder = programs.workdir() + assert Path(where) == folder.resolve() + assert re.fullmatch(r"[0-9a-f]{32}", token) + assert programs.TOKEN_VAR in (folder / ".codex" / "config.toml").read_text() + assert programs.TOKEN_VAR in (folder / ".cursor" / "mcp.json").read_text() From adb37f800a0d7c3dbb9145ab37352f1b43abdbdd Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:26:43 -0500 Subject: [PATCH 05/11] fix: keep the outside agents setting in force during Codex and Cursor turns A running Codex or Cursor panel turn let every caller without a token through and attached its changes to that turn. Those turns now carry their own token, so a caller without one is treated by the outside agents setting as at any other time. --- backend/app/agent/service.py | 8 +------- backend/tests/test_agent_guards.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/backend/app/agent/service.py b/backend/app/agent/service.py index 603faf6..13fbc98 100644 --- a/backend/app/agent/service.py +++ b/backend/app/agent/service.py @@ -22,7 +22,6 @@ BULK = 10 CONFIRM_SECONDS = 300 MOVES = {"transform": "Move or resize", "pack": "Pack", "sort": "Sort and lay out", "distribute": "Distribute", "align": "Align", "snap": "Snap", "normalize": "Resize"} -TOKENLESS = ("codex", "cursor") TOKEN_FOLDER = "AgentTokens" ASKED = tuple((method, re.compile(pattern), words) for method, pattern, words in ( ("POST", r"/api/boards", "create a board"), @@ -151,8 +150,6 @@ def save(self, patch: dict) -> dict: def allows(self, client: str) -> bool: if client in self.tokens: return True - if client == "outside" and self.tokenless_turn() is not None: - return True return bool(self.settings()["outside_agents"]) def refuse(self, agent: str | None, method: str, path: str) -> None: @@ -160,9 +157,6 @@ def refuse(self, agent: str | None, method: str, path: str) -> None: self.refusal = {"id": uuid.uuid4().hex, "agent": name, "what": asked(method, path), "answers": list(ANSWERS), "always": "all", "expires": None, "held": False} self.refusals += 1 - def tokenless_turn(self) -> str | None: - return next((t for t in reversed(self.cli_active) if self.turns.get(t, {}).get("runner") in TOKENLESS), None) - async def available(self) -> list[dict]: rows = [] for key, spec in runners.CLI.items(): @@ -240,7 +234,7 @@ def _risky(self, command, items: dict) -> str | None: async def confirm(self, client: str, summary: str) -> bool: """Hold a risky write from a panel turn until the person answers in the Agent panel.""" - turn_id = self.token_turn.get(client) or (self.tokenless_turn() if client == "outside" else None) + turn_id = self.token_turn.get(client) queue = self.queues.get(turn_id or "") if queue is None or turn_id in self.approved or not self.settings()["confirm_changes"]: return True diff --git a/backend/tests/test_agent_guards.py b/backend/tests/test_agent_guards.py index 7fa1621..c0fcbd7 100644 --- a/backend/tests/test_agent_guards.py +++ b/backend/tests/test_agent_guards.py @@ -127,3 +127,13 @@ def test_a_plain_terminal_does_not_inherit_the_key_variable(monkeypatch): env = terminal.base_env() assert "FORMREF_WINDOW_KEY_STDOUT" not in env assert not any(re.search(r"window.?key", k, re.I) for k in env) + + +@pytest.mark.parametrize("runner", ["codex", "cursor"]) +def test_a_running_codex_or_cursor_turn_does_not_let_in_an_outside_caller(bare, reset_agents, runner): + reset_agents.cli_turns = 1 + reset_agents.cli_active.append("t2") + reset_agents.turns["t2"] = {"runner": runner} + assert reset_agents.allows("outside") is False + r = bare.post("/api/boards", json={"title": "x"}, headers={"x-formref-client": "outside"}) + assert r.status_code == 403 and r.json()["code"] == "outside_agents_off" From e2017b1f10b6f2dc1278566e088198ef673be1d3 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:27:44 -0500 Subject: [PATCH 06/11] fix: accept cutout model files larger than the asset limit on import The person cutout and sharp cutout files are about 180 MB, above the 64 MiB limit every upload shared, so importing a model file someone already has could never succeed. Model imports get their own 256 MiB limit and are still checked against the published hash. --- backend/app/core/config.py | 1 + backend/app/main.py | 7 +++++-- backend/app/routers/boards.py | 9 +++++---- backend/tests/test_boards_and_clipper.py | 15 +++++++++++++++ 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 4360058..855d98d 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -12,6 +12,7 @@ class Settings: engine_path: Path max_upload_bytes: int = 64 * 1024 * 1024 max_archive_bytes: int = 256 * 1024 * 1024 + max_model_bytes: int = 256 * 1024 * 1024 max_image_pixels: int = 64_000_000 max_export_pixels: int = 32_000_000 max_export_edge: int = 8192 diff --git a/backend/app/main.py b/backend/app/main.py index 88878c9..2bb996a 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -3,6 +3,7 @@ import ipaddress import logging import mimetypes +import re from urllib.parse import urlparse from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, FileResponse @@ -61,6 +62,7 @@ async def lifespan(app): app.add_middleware(CORSMiddleware, allow_origin_regex=r"^(https?://(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?|(chrome|moz)-extension://[a-z0-9-]+)$", allow_credentials=False, allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "X-FormRef-Clip-Token"], expose_headers=["Content-Disposition", "X-FormRef-Scale", "X-FormRef-Width", "X-FormRef-Height"]) SIGN_IN_RETURNS = {("GET", "/api/cloud/google/callback")} +MODEL_IMPORT = re.compile(r"/api/models/[^/]+/import") @app.middleware("http") async def local_access(request: Request, call_next): @@ -81,9 +83,10 @@ async def local_access(request: Request, call_next): return JSONResponse(status_code=403, content={"detail": "Origin is not an allowed local application."}) length = request.headers.get("content-length") if length: + limit = settings.max_model_bytes if request.method == "POST" and MODEL_IMPORT.fullmatch(request.url.path) else settings.max_upload_bytes try: - if int(length) > settings.max_upload_bytes + 1024 * 1024: - return JSONResponse(status_code=413, content={"detail": "Request exceeds the 64 MiB upload limit."}) + if int(length) > limit + 1024 * 1024: + return JSONResponse(status_code=413, content={"detail": f"Request exceeds the {limit // (1024 * 1024)} MiB upload limit."}) except ValueError: return JSONResponse(status_code=400, content={"detail": "Invalid request content length."}) client = request.headers.get("x-formref-client") diff --git a/backend/app/routers/boards.py b/backend/app/routers/boards.py index ec80f98..a586178 100644 --- a/backend/app/routers/boards.py +++ b/backend/app/routers/boards.py @@ -27,7 +27,8 @@ router = APIRouter(prefix="/api") -async def read_upload(file: UploadFile): +async def read_upload(file: UploadFile, limit: int = 0): + limit = limit or settings.max_upload_bytes chunks = [] size = 0 while True: @@ -35,9 +36,9 @@ async def read_upload(file: UploadFile): if not chunk: break size += len(chunk) - if size > settings.max_upload_bytes: + if size > limit: await file.close() - raise HTTPException(status_code=413, detail="Uploads are limited to 64 MiB.") + raise HTTPException(status_code=413, detail=f"Uploads are limited to {limit // (1024 * 1024)} MiB.") chunks.append(chunk) await file.close() return b"".join(chunks) @@ -227,7 +228,7 @@ def models_download(model: str): @router.post("/models/{model}/import") async def models_import(model: str, file: UploadFile = File(...)): - data = await read_upload(file) + data = await read_upload(file, settings.max_model_bytes) return await asyncio.to_thread(cutout_models.import_file, model, file.filename or "", data) @router.delete("/models/{model}") diff --git a/backend/tests/test_boards_and_clipper.py b/backend/tests/test_boards_and_clipper.py index a486849..4b70787 100644 --- a/backend/tests/test_boards_and_clipper.py +++ b/backend/tests/test_boards_and_clipper.py @@ -146,3 +146,18 @@ def test_resetting_the_token_unpairs_the_old_one(client): assert new != old assert client.get("/api/clip/boards", headers={**EXTENSION, "x-formref-clip-token": old}).status_code == 401 assert client.get("/api/clip/boards", headers={**EXTENSION, "x-formref-clip-token": new}).status_code == 200 + + +def test_a_model_file_larger_than_an_asset_can_be_imported_and_is_still_checked(client): + big = b"\0" * (70 * 1024 * 1024) + r = client.post("/api/models/person-cutout/import", files={"file": ("u2net_human_seg.onnx", big, "application/octet-stream")}) + assert r.status_code == 422 and "SHA-256" in r.json()["detail"] + r = client.post("/api/assets", files={"file": ("big.png", big, "image/png")}) + assert r.status_code == 413 + + +def test_a_model_import_above_its_own_limit_is_refused_before_it_is_read(client): + from app.core.config import settings + + r = client.post("/api/models/person-cutout/import", content=b"x", headers={"content-length": str(settings.max_model_bytes + 2 * 1024 * 1024), "content-type": "application/octet-stream"}) + assert r.status_code == 413 From 0b7db4877c2ef6db69ea9514378525fb499fbfdd Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:32:22 -0500 Subject: [PATCH 07/11] test: give each started engine in the window key tests its own data folder The in-process service now holds the shared test data folder, so a second engine on it is refused as intended. --- backend/tests/test_window_key.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py index 70a6e7c..4ca967f 100644 --- a/backend/tests/test_window_key.py +++ b/backend/tests/test_window_key.py @@ -2,6 +2,7 @@ import os import subprocess import sys +import tempfile import time import urllib.request @@ -55,7 +56,7 @@ def test_an_expired_ticket_is_refused(bare, monkeypatch): def _launch(env_extra): port = free_port() - env = dict(os.environ, FORMREF_PORT=str(port), **env_extra) + env = dict(os.environ, FORMREF_PORT=str(port), FORMREF_DATA_DIR=tempfile.mkdtemp(prefix="key-", dir=os.path.dirname(os.environ["FORMREF_DATA_DIR"])), **env_extra) env.pop("FORMREF_WINDOW_KEY_STDOUT", None) if "FORMREF_WINDOW_KEY_STDOUT" not in env_extra else None proc = subprocess.Popen([sys.executable, "formref_engine.py"], cwd=BACKEND, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) base = f"http://127.0.0.1:{port}" From 9d3decbfb2bfe25187f5458230f43df7a2df419c Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:32:22 -0500 Subject: [PATCH 08/11] chore: record the shared program finder as version 1.1.0 The finder changed how it starts .cmd and .bat programs on Windows, so it carries a new version and its hash is recorded for agents sync. --- backend/app/agent/agent_lookup.py | 2 +- backend/app/agent_manifest.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index 084c631..185a76d 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.1.0" 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", diff --git a/backend/app/agent_manifest.py b/backend/app/agent_manifest.py index 640dd69..104e844 100644 --- a/backend/app/agent_manifest.py +++ b/backend/app/agent_manifest.py @@ -18,6 +18,7 @@ LOOKUP_HASHES = { "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", + "1.1.0": "6e67ab1290619ec9ef6376df8ff9a891e765df8ecc9f2ed5458b6db1b89eb076", } From a1a8b4127eee64d69fe0bd36cc929fb461e90fd9 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:32:22 -0500 Subject: [PATCH 09/11] docs: log the sign-in return, Windows start, data folder lock, panel turn and model import fixes --- backend/HASHOUT_LOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 24b53dc..69edc85 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -8,6 +8,7 @@ ## Contents +- [Unreleased · Google sign-in return, Windows shims, one service per data folder, panel turn tools, model import size](#unreleased--google-sign-in-return-windows-shims-one-service-per-data-folder-panel-turn-tools-model-import-size) - [Unreleased · The window key, and the agent access fixes](#unreleased--the-window-key-and-the-agent-access-fixes) - [Unreleased · agents sync copies the skills to .agents/skills](#unreleased--agents-sync-copies-the-skills-to-agentsskills) - [Unreleased · agents/manifest.json says what the app offers agents](#unreleased--agentsmanifestjson-says-what-the-app-offers-agents) @@ -62,6 +63,22 @@ - [v0.1.0 · Local board service and SDK MCP](#v010--local-board-service-and-sdk-mcp) - [boot_backend.bat](#boot_backendbat) +## Unreleased · Google sign-in return, Windows shims, one service per data folder, panel turn tools, model import size + +- refers-to: `app/main.py` :: SIGN_IN_RETURNS, MODEL_IMPORT, local_access, lifespan; `app/routers/cloud.py` :: google_callback; `app/agent/agent_lookup.py` (the family's file, now 1.1.0) :: start_argv, _shim_target, _cmd_safe; `app/agent_manifest.py` :: LOOKUP_HASHES; `app/core/startup.py` :: hold, let_go; `app/agent/service.py` :: _agent_folder, Agents.allows, confirm, _cli; `app/core/config.py` :: max_model_bytes; `app/routers/boards.py` :: read_upload, models_import + +The Google return. Google sends the browser back to `GET /api/cloud/google/callback` as a cross-site navigation with no Origin, which the no-Origin cross-site refusal blocked. That one read is let through; it does nothing without the single-use sign-in state. The page escapes the message it shows. + +Windows shims. A panel turn passes the message, with line breaks and quotes, as one argument, and the command interpreter cannot carry that through a `.cmd`. The finder reads an npm shim and starts its node script with the node beside it or on PATH, so no interpreter is involved. Any other `.cmd` or `.bat` still goes through `cmd.exe /c`, and every word must be plain to it: no control characters, `%`, `!` or `"`, and `& | < > ^ ( ) , ; =` only in a word with a space or tab, which `list2cmdline` quotes. Anything else is refused with a sentence. The finder moved to 1.1.0 and its hash is recorded; the other family copies need the same version. + +One service per data folder. Only the frozen engine took `engine.lock`, so a service the MCP server, `./formref serve` or `./formref dev` started let the desktop engine run beside it over the same folder. The service now takes the lock in its lifespan, unless its own process already holds it (the frozen engine), with its parent as the shell, refuses to start while another holds it, and removes the lock when it stops. + +Panel turn tools. Codex and Cursor panel turns ran in the app folder and depended on the checkout's MCP files at a fixed port. They now run in the `AgentTabs` folder that program tabs use, whose files point at the running service and send the turn's token from `FORMREF_AGENT_TOKEN`. With a token of their own, the rule that let any tokenless caller act as the running Codex or Cursor turn is gone. + +Model import size. The person cutout and sharp cutout files are near 180 MB. Model imports have their own 256 MiB limit, in the request check and in `read_upload`, and are still checked against the pinned hash. + +Run: the suite with the release board engine; the new tests fail on the previous code. + ## Unreleased · The window key, and the agent access fixes - refers-to: `app/core/window_key.py` (new) :: WindowKeyGuard, OPEN, BRIDGE, claim, ticket, spend; `app/core/seal.py` (new) :: effective, sign; `app/routers/window.py` (new); `app/main.py` :: app.add_middleware; `app/routers/terminal.py` :: _window_only, chat_events, attach; `app/routers/agent.py` :: save_agent_settings; `app/routers/commands.py` :: _window_only; `app/routers/cloud.py` :: from_agent; `app/routers/clip.py` :: get_token, reset_token; `app/agent/service.py` :: loopback_url, Agents.settings, save, allows, tokenless_turn, token_file, revoke, _cli; `app/agent/claude_code.py` :: issue, revoke, argv; `app/agent/chat.py` :: _run; `app/agent/runners.py` :: argv; `app/agent/terminal.py` :: Session.on_close, base_env; `app/cli.py` :: call; `formref_engine.py` :: main; `freeze_engine`; `requirements.txt`, `requirements_macos.txt` From 635c55cd54cc4c91550d09fc4ee94d8e7a72bce3 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:13:40 -0500 Subject: [PATCH 10/11] fix: check every word for a .cmd whose path has a space When the program path itself is quoted, the Windows command interpreter drops the first and last quote of the line, so a word with a space is no longer read as quoted. Such a program now gets only words without command characters. A program name with trailing dots or spaces after .cmd or .bat is treated as one as well. The finder's 1.1.0 hash is updated. --- backend/HASHOUT_LOG.md | 2 +- backend/app/agent/agent_lookup.py | 13 +++++++++++-- backend/app/agent_manifest.py | 2 +- backend/tests/test_windows_start.py | 26 ++++++++++++++++++++++++++ 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 69edc85..ccf5cd0 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -69,7 +69,7 @@ The Google return. Google sends the browser back to `GET /api/cloud/google/callback` as a cross-site navigation with no Origin, which the no-Origin cross-site refusal blocked. That one read is let through; it does nothing without the single-use sign-in state. The page escapes the message it shows. -Windows shims. A panel turn passes the message, with line breaks and quotes, as one argument, and the command interpreter cannot carry that through a `.cmd`. The finder reads an npm shim and starts its node script with the node beside it or on PATH, so no interpreter is involved. Any other `.cmd` or `.bat` still goes through `cmd.exe /c`, and every word must be plain to it: no control characters, `%`, `!` or `"`, and `& | < > ^ ( ) , ; =` only in a word with a space or tab, which `list2cmdline` quotes. Anything else is refused with a sentence. The finder moved to 1.1.0 and its hash is recorded; the other family copies need the same version. +Windows shims. A panel turn passes the message, with line breaks and quotes, as one argument, and the command interpreter cannot carry that through a `.cmd`. The finder reads an npm shim and starts its node script with the node beside it or on PATH, so no interpreter is involved. Any other `.cmd` or `.bat` still goes through `cmd.exe /c`, and every word must be plain to it: no control characters, `%`, `!` or `"`, and `& | < > ^ ( ) , ; =` only in a word with a space or tab, which `list2cmdline` quotes, and nowhere when the program's own path has a space, since the interpreter then drops the first and last quote of the line. A name ending in dots or spaces after `.cmd` or `.bat` counts as one. Anything else is refused with a sentence. The finder moved to 1.1.0 and its hash is recorded; the other family copies need the same version. One service per data folder. Only the frozen engine took `engine.lock`, so a service the MCP server, `./formref serve` or `./formref dev` started let the desktop engine run beside it over the same folder. The service now takes the lock in its lifespan, unless its own process already holds it (the frozen engine), with its parent as the shell, refuses to start while another holds it, and removes the lock when it stops. diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index 185a76d..15554dc 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -381,9 +381,18 @@ def _shim_target(shim: str, env: dict) -> list[str] | None: return [node, str(script)] if node else None +def _spaced(word: str) -> bool: + return " " in word or "\t" in word + + +def _batch(program: str) -> bool: + return program.rstrip(" .").lower().endswith((".cmd", ".bat")) + + def _cmd_safe(words: list[str]) -> None: + shifted = _spaced(words[0]) for word in words: - if CMD_ALWAYS.search(word) or (CMD_UNQUOTED.search(word) and not (" " in word or "\t" in word)): + if CMD_ALWAYS.search(word) or (CMD_UNQUOTED.search(word) and (shifted or not _spaced(word))): raise ValueError("This text cannot be passed to a .cmd or .bat program on Windows: it holds a line break, a quote, " "% or ! or a command character. Point FormRef at the program's .exe or node script instead.") @@ -395,7 +404,7 @@ 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 not words[0].lower().endswith((".cmd", ".bat")): + if not _batch(words[0]): return words target = _shim_target(words[0], env) if target: diff --git a/backend/app/agent_manifest.py b/backend/app/agent_manifest.py index 104e844..822ee29 100644 --- a/backend/app/agent_manifest.py +++ b/backend/app/agent_manifest.py @@ -18,7 +18,7 @@ LOOKUP_HASHES = { "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", - "1.1.0": "6e67ab1290619ec9ef6376df8ff9a891e765df8ecc9f2ed5458b6db1b89eb076", + "1.1.0": "04d32c56f68bce85a93d88d0f216a3ad59b267c761d33c81d0bd43a93c45d3f7", } diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py index 0505a48..9eae569 100644 --- a/backend/tests/test_windows_start.py +++ b/backend/tests/test_windows_start.py @@ -69,3 +69,29 @@ def test_a_shim_whose_script_is_missing_falls_back_to_the_checked_interpreter(sh def test_an_exe_is_started_directly(tmp_path): exe = str(tmp_path / "codex.exe") assert agent_lookup.start_argv([exe, "exec", PROMPT], ENV, "win32") == [exe, "exec", PROMPT] + + +@pytest.fixture +def spaced_cmd(tmp_path): + folder = tmp_path / "Program Files" + folder.mkdir() + path = folder / "tool.cmd" + path.write_text("@echo off\r\nsomething.exe %*\r\n") + return str(path) + + +@pytest.mark.parametrize("word", ["a & b", "x (y)", "p | q"]) +def test_a_cmd_in_a_folder_with_a_space_refuses_command_characters_in_any_word(spaced_cmd, word): + with pytest.raises(ValueError): + agent_lookup.start_argv([spaced_cmd, word], ENV, "win32") + + +def test_a_cmd_in_a_folder_with_a_space_takes_plain_words(spaced_cmd): + assert agent_lookup.start_argv([spaced_cmd, "--version", "two words"], ENV, "win32") == [ENV["COMSPEC"], "/c", spaced_cmd, "--version", "two words"] + + +@pytest.mark.parametrize("suffix", [".cmd.", ".CMD ", ".Bat", ".bat. ."]) +def test_a_batch_name_with_any_case_or_trailing_dots_goes_through_the_check(tmp_path, suffix): + program = str(tmp_path / ("tool" + suffix)) + with pytest.raises(ValueError): + agent_lookup.start_argv([program, "-p", PROMPT], ENV, "win32") From 746fdbbb8dee5c493a9440a9dd7c88ff64036060 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:28:26 -0500 Subject: [PATCH 11/11] fix: refuse every interpreter character for .cmd and .bat programs The Windows command interpreter reads & | < > ^ ( ) ! % and " even inside quotes, and a .cmd shim re-reads its arguments, so a word with a space is no safer than one without. Any program still started through cmd.exe now gets only words that hold none of these characters and no control character, its own path included, and the refusal points at the .exe, the node script, or standard input or a file for long text. An npm-style shim that wraps an .exe now starts that .exe directly with an argv list, as one that wraps a node script already did. The finder's 1.1.0 hash is updated. --- backend/HASHOUT_LOG.md | 2 +- backend/app/agent/agent_lookup.py | 31 +++++++++++---------- backend/app/agent_manifest.py | 2 +- backend/tests/test_windows_start.py | 43 +++++++++++++++++++++++++---- 4 files changed, 55 insertions(+), 23 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index ccf5cd0..f9d02a9 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -69,7 +69,7 @@ The Google return. Google sends the browser back to `GET /api/cloud/google/callback` as a cross-site navigation with no Origin, which the no-Origin cross-site refusal blocked. That one read is let through; it does nothing without the single-use sign-in state. The page escapes the message it shows. -Windows shims. A panel turn passes the message, with line breaks and quotes, as one argument, and the command interpreter cannot carry that through a `.cmd`. The finder reads an npm shim and starts its node script with the node beside it or on PATH, so no interpreter is involved. Any other `.cmd` or `.bat` still goes through `cmd.exe /c`, and every word must be plain to it: no control characters, `%`, `!` or `"`, and `& | < > ^ ( ) , ; =` only in a word with a space or tab, which `list2cmdline` quotes, and nowhere when the program's own path has a space, since the interpreter then drops the first and last quote of the line. A name ending in dots or spaces after `.cmd` or `.bat` counts as one. Anything else is refused with a sentence. The finder moved to 1.1.0 and its hash is recorded; the other family copies need the same version. +Windows shims. A panel turn passes the message, with line breaks and quotes, as one argument, and the command interpreter cannot carry that through a `.cmd`. The finder reads an npm shim and starts what it wraps directly with an argv list: its node script with the node beside it or on PATH, or the `.exe` it names, so no interpreter is involved. Any other `.cmd` or `.bat` still goes through `cmd.exe /c`, which reads `& | < > ^ ( ) ! %` and `"` even inside quotes, so every word, the program's own path included, must hold none of them and no control character, with or without a space. A name ending in dots or spaces after `.cmd` or `.bat` counts as one. Anything else is refused with a sentence that points at the `.exe`, the node script, or standard input or a file for long text. The finder moved to 1.1.0 and its hash is recorded; the other family copies need the same version. One service per data folder. Only the frozen engine took `engine.lock`, so a service the MCP server, `./formref serve` or `./formref dev` started let the desktop engine run beside it over the same folder. The service now takes the lock in its lifespan, unless its own process already holds it (the frozen engine), with its parent as the shell, refuses to start while another holds it, and removes the lock when it stops. diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index 15554dc..3f56dad 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -359,12 +359,12 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" -SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%]+\.(?:js|cjs|mjs))"\s+%\*', re.IGNORECASE) -CMD_ALWAYS = re.compile(r'[\x00-\x1f\x7f%"!]') -CMD_UNQUOTED = re.compile(r"[&|<>^(),;=]") +SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%]+\.(?:js|cjs|mjs|exe))"\s+%\*', re.IGNORECASE) +CMD_REFUSED = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]') def _shim_target(shim: str, env: dict) -> list[str] | None: + """The program an npm-style .cmd shim wraps, as an argv prefix: the .exe itself, or node and the script.""" try: text = Path(shim).read_text(encoding="utf-8", errors="replace") except OSError: @@ -373,16 +373,14 @@ def _shim_target(shim: str, env: dict) -> list[str] | None: if not match: return None folder = Path(shim).parent - script = folder.joinpath(*match.group(1).replace("/", "\\").split("\\")) - if not script.is_file(): + target = folder.joinpath(*match.group(1).replace("/", "\\").split("\\")) + if not target.is_file(): return None + if target.suffix.lower() == ".exe": + return [str(target)] beside = folder / "node.exe" node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH")) - return [node, str(script)] if node else None - - -def _spaced(word: str) -> bool: - return " " in word or "\t" in word + return [node, str(target)] if node else None def _batch(program: str) -> bool: @@ -390,17 +388,20 @@ def _batch(program: str) -> bool: def _cmd_safe(words: list[str]) -> None: - shifted = _spaced(words[0]) + """The command interpreter reads & | < > ^ ( ) ! % and " even inside quotes, and a .cmd re-reads its arguments, so + every word given to it, the program's own path included, must hold none of them and no control character.""" for word in words: - if CMD_ALWAYS.search(word) or (CMD_UNQUOTED.search(word) and (shifted or not _spaced(word))): - raise ValueError("This text cannot be passed to a .cmd or .bat program on Windows: it holds a line break, a quote, " - "% or ! or a command character. Point FormRef at the program's .exe or node script instead.") + if CMD_REFUSED.search(word): + raise ValueError("This text cannot be passed to a .cmd or .bat program on Windows: it holds a line break, a " + "control character or one of & | < > ^ ( ) ! % \". Point FormRef at the program's .exe or node " + "script instead, or pass long text through standard input or a file if the program supports it.") 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. A .cmd or .bat that only starts a node script is replaced - by node and that script; any other runs under the command interpreter, given only words it reads as plain text.""" + by node and that script, and one that only starts an .exe by that .exe, each with the words as an argv list; any other + runs under the command interpreter, and only when no word holds a character the interpreter would read.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): diff --git a/backend/app/agent_manifest.py b/backend/app/agent_manifest.py index 822ee29..414c049 100644 --- a/backend/app/agent_manifest.py +++ b/backend/app/agent_manifest.py @@ -18,7 +18,7 @@ LOOKUP_HASHES = { "1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", - "1.1.0": "04d32c56f68bce85a93d88d0f216a3ad59b267c761d33c81d0bd43a93c45d3f7", + "1.1.0": "a1ac03220d5e73c27f7a38e5e6b6dea53d0c45ab1e3a03869ac2e69fdb9af207", } diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py index 9eae569..2467c9f 100644 --- a/backend/tests/test_windows_start.py +++ b/backend/tests/test_windows_start.py @@ -48,17 +48,48 @@ def plain_cmd(tmp_path): return str(path) -@pytest.mark.parametrize("word", [PROMPT, "two\nlines", "tab\there\x01", "100%", 'say "hi"', "wow!", "a&b", "a|b", "a>b", "a^b", "(a)"]) -def test_a_plain_cmd_refuses_words_the_interpreter_would_read(plain_cmd, word): - with pytest.raises(ValueError): +REFUSED_WORDS = [PROMPT, "two\nlines", "tab\there", "nul\x00", "bell\x07", "del\x7f", "100%", 'say "hi"', "wow!", + "a&b", "a|b", "ab", "a^b", "(a)", "a)", "a & b", "x (y)", "p | q", "C:\\Program Files (x86)\\x"] + + +@pytest.mark.parametrize("word", REFUSED_WORDS) +def test_a_plain_cmd_refuses_every_word_with_a_character_the_interpreter_reads(plain_cmd, word): + with pytest.raises(ValueError, match="standard input or a file"): agent_lookup.start_argv([plain_cmd, "-p", word], ENV, "win32") -@pytest.mark.parametrize("word", ["--version", "status", "a & b", "C:\\Program Files (x86)\\x", ""]) -def test_a_plain_cmd_takes_plain_or_quoted_words(plain_cmd, word): +@pytest.mark.parametrize("word", ["--version", "status", "two words", "--model=gpt,fast;x", "C:\\Program Files\\x", ""]) +def test_a_plain_cmd_takes_plain_words(plain_cmd, word): assert agent_lookup.start_argv([plain_cmd, word], ENV, "win32") == [ENV["COMSPEC"], "/c", plain_cmd, word] +def test_a_plain_cmd_whose_own_path_holds_a_command_character_is_refused(tmp_path): + folder = tmp_path / "tools (x86)" + folder.mkdir() + path = folder / "tool.cmd" + path.write_text("@echo off\r\nsomething.exe %*\r\n") + with pytest.raises(ValueError): + agent_lookup.start_argv([str(path), "--version"], ENV, "win32") + + +def test_an_exe_shim_runs_the_exe_it_wraps_with_an_argv_list(tmp_path): + exe = tmp_path / "node_modules" / "tool" / "bin" / "tool.exe" + exe.parent.mkdir(parents=True) + exe.write_text("") + path = tmp_path / "tool.cmd" + path.write_text('@ECHO off\r\nGOTO start\r\n:start\r\n"%dp0%\\node_modules\\tool\\bin\\tool.exe" %*\r\n') + argv = agent_lookup.start_argv([str(path), "-p", PROMPT], ENV, "win32") + assert argv == [str(exe), "-p", PROMPT] + assert ENV["COMSPEC"] not in argv + + +def test_an_npm_shim_never_goes_through_the_interpreter(shim): + path, script = shim + (path.parent / "node.exe").write_text("") + argv = agent_lookup.start_argv([str(path), "exec", "100% & (done) ^ | !"], ENV, "win32") + assert ENV["COMSPEC"] not in argv and argv[1] == str(script) + + def test_a_shim_whose_script_is_missing_falls_back_to_the_checked_interpreter(shim): path, script = shim script.unlink() @@ -80,7 +111,7 @@ def spaced_cmd(tmp_path): return str(path) -@pytest.mark.parametrize("word", ["a & b", "x (y)", "p | q"]) +@pytest.mark.parametrize("word", ["a & b", "x (y)", "p | q", "plain^"]) def test_a_cmd_in_a_folder_with_a_space_refuses_command_characters_in_any_word(spaced_cmd, word): with pytest.raises(ValueError): agent_lookup.start_argv([spaced_cmd, word], ENV, "win32")