From 4e127a04c5b872017fe365159db7668f3b1306d2 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:49:42 -0500 Subject: [PATCH 1/8] fix(agents): agent controls and settings writes need the window key Approving a pending agent call, reading the bridge queue, posting window tool results, changing agent policies, rotating the token, stopping agent work and writing settings now require the window key, as the terminal routes already do. The window sends the key on every engine call, so its behaviour is unchanged; the bridge goodbye beacon stays open because a beacon cannot carry a header. Checked with python -m pytest (501 passed). --- backend/app/routers/agents.py | 22 ++++---- backend/app/routers/settings.py | 5 +- .../cb03/test_routers_agents_window_key.py | 52 +++++++++++++++++++ 3 files changed, 67 insertions(+), 12 deletions(-) create mode 100644 backend/tests/cb03/test_routers_agents_window_key.py diff --git a/backend/app/routers/agents.py b/backend/app/routers/agents.py index 12d58e1..ea7e8db 100644 --- a/backend/app/routers/agents.py +++ b/backend/app/routers/agents.py @@ -1,10 +1,12 @@ -from fastapi import APIRouter, Body, Query, Request, Response +from fastapi import APIRouter, Body, Depends, Query, Request, Response from pydantic import BaseModel, StrictBool +from app.core import window_key from app.core.errors import ApiError from app.services import agents, mcp_tools router = APIRouter() +WINDOW = [Depends(window_key.require)] class Decision(BaseModel): @@ -12,12 +14,12 @@ class Decision(BaseModel): remember: StrictBool = False -@router.post("/agents/catalogue") +@router.post("/agents/catalogue", dependencies=WINDOW) def post_catalogue(body: dict = Body(...)): return agents.catalogue.set(body, mcp_tools.names()) -@router.get("/agents/bridge/next") +@router.get("/agents/bridge/next", dependencies=WINDOW) async def bridge_next(request: Request, wait: float = Query(25, ge=0, le=30)): item = await agents.bridge.next_item(wait, request.is_disconnected) if item is None: @@ -34,40 +36,40 @@ def bridge_bye(): return Response(status_code=204) -@router.post("/agents/bridge/{item_id}/result") +@router.post("/agents/bridge/{item_id}/result", dependencies=WINDOW) def bridge_result(item_id: str, body: dict = Body(...)): if not agents.bridge.result(item_id, body): raise ApiError(404, "call_not_found", "No pending call with that id.") return {"ok": True} -@router.post("/agents/approvals/{item_id}") +@router.post("/agents/approvals/{item_id}", dependencies=WINDOW) def approval(item_id: str, body: Decision): if not agents.bridge.decide(item_id, body.allow, body.remember): raise ApiError(404, "approval_not_found", "No pending approval with that id.") return {"ok": True} -@router.get("/agents/state") +@router.get("/agents/state", dependencies=WINDOW) def read_state(): return agents.public_state() -@router.put("/agents/state") +@router.put("/agents/state", dependencies=WINDOW) def write_state(body: dict = Body(...)): return agents.put_state(body) -@router.post("/agents/token/rotate") +@router.post("/agents/token/rotate", dependencies=WINDOW) def rotate_token(): return {"tokenPath": str(agents.rotate_token())} -@router.get("/agents/activity") +@router.get("/agents/activity", dependencies=WINDOW) def read_activity(): return {"calls": agents.activity.list(), "max": agents.ACTIVITY_MAX} -@router.post("/agents/stop") +@router.post("/agents/stop", dependencies=WINDOW) def stop(): return {"stopped": agents.bridge.stop()} diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index 3d41694..15dd62c 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -1,5 +1,6 @@ -from fastapi import APIRouter, Body +from fastapi import APIRouter, Body, Depends +from app.core import window_key from app.services import settings router = APIRouter() @@ -10,6 +11,6 @@ def read_settings(): return settings.get() -@router.put("/settings") +@router.put("/settings", dependencies=[Depends(window_key.require)]) def write_settings(body: dict = Body(...)): return settings.update(body) diff --git a/backend/tests/cb03/test_routers_agents_window_key.py b/backend/tests/cb03/test_routers_agents_window_key.py new file mode 100644 index 0000000..6f07256 --- /dev/null +++ b/backend/tests/cb03/test_routers_agents_window_key.py @@ -0,0 +1,52 @@ +import pytest + +from app.services import agents + +WINDOW_ONLY = [ + ("post", "/api/agents/catalogue", {"tools": [], "commands": []}), + ("get", "/api/agents/bridge/next?wait=0", None), + ("post", "/api/agents/bridge/none/result", {"ok": True, "result": {"text": "x"}}), + ("post", "/api/agents/approvals/none", {"allow": True, "remember": True}), + ("get", "/api/agents/state", None), + ("put", "/api/agents/state", {"allowed": True, "policies": {"someone": "allow"}}), + ("post", "/api/agents/token/rotate", None), + ("get", "/api/agents/activity", None), + ("post", "/api/agents/stop", None), + ("put", "/api/settings", {"agentsAllowed": True}), +] + + +def _send(client, method: str, path: str, body): + return getattr(client, method)(path, json=body) if body is not None else getattr(client, method)(path) + + +@pytest.mark.parametrize(("method", "path", "body"), WINDOW_ONLY) +def test_agent_controls_refuse_a_caller_without_the_window_key(anon_client, method, path, body): + response = _send(anon_client, method, path, body) + assert response.status_code == 403 + assert response.json()["error"]["code"] == "window_key_required" + + +@pytest.mark.parametrize(("method", "path", "body"), WINDOW_ONLY) +def test_agent_controls_answer_the_window(client, method, path, body): + response = _send(client, method, path, body) + assert response.status_code != 403 + + +def test_a_caller_without_the_window_key_cannot_turn_agents_on(anon_client, client): + client.put("/api/agents/state", json={"allowed": False}) + anon_client.put("/api/agents/state", json={"allowed": True, "policies": {"someone": "allow"}}) + anon_client.put("/api/settings", json={"agentsAllowed": True}) + state = client.get("/api/agents/state").json() + assert state["allowed"] is False + assert "someone" not in state["policies"] + + +def test_a_caller_without_the_window_key_cannot_take_queued_approvals(anon_client, monkeypatch): + monkeypatch.setattr(agents.bridge, "queue", agents.deque([{"kind": "approval", "id": "kept"}])) + assert anon_client.get("/api/agents/bridge/next?wait=0").status_code == 403 + assert [item["id"] for item in agents.bridge.queue] == ["kept"] + + +def test_the_window_can_still_say_goodbye_without_headers(anon_client): + assert anon_client.post("/api/agents/bridge/bye").status_code == 204 From 17d5cf4e019e429f721fbde8373206dbc1fd826e Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:51:32 -0500 Subject: [PATCH 2/8] fix(agents): ask before agent tools delete folders, tags or characters or replace a project folders_delete, tags_delete and characters_delete cannot be undone, and projects_update with a doc replaces the whole document with no earlier version kept. They now ask the owner whatever the client policy, as projects_delete and library_delete already do. Renames and cover changes still follow the policy. Tool descriptions, the skill references and agents/manifest.json (./formcraft agents sync) say so. Checked with python -m pytest (518 passed) and check_skills.py. --- .../references/tools-by-task.md | 2 +- .../formcraft-harness/references/tool-map.md | 8 ++--- .../references/tools-by-task.md | 2 +- .../formcraft-harness/references/tool-map.md | 8 ++--- agents/manifest.json | 4 +++ backend/app/services/mcp_tools.py | 8 ++--- .../cb02/test_services_mcp_tools_approval.py | 35 +++++++++++++++++++ 7 files changed, 53 insertions(+), 14 deletions(-) create mode 100644 backend/tests/cb02/test_services_mcp_tools_approval.py diff --git a/.agents/skills/formcraft-driving/references/tools-by-task.md b/.agents/skills/formcraft-driving/references/tools-by-task.md index 5b0ccf9..e81b86f 100644 --- a/.agents/skills/formcraft-driving/references/tools-by-task.md +++ b/.agents/skills/formcraft-driving/references/tools-by-task.md @@ -66,7 +66,7 @@ Needs the window. `scene_state` to read, `scene_add` to place objects, `scene_up ## Projects -`projects_list` and `projects_get` read; `projects_create` and `projects_update` write; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. A project open in the window reloads when changed under it. +`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. ## Catalogue of commands diff --git a/.agents/skills/formcraft-harness/references/tool-map.md b/.agents/skills/formcraft-harness/references/tool-map.md index 8b4b74c..2bed3cb 100644 --- a/.agents/skills/formcraft-harness/references/tool-map.md +++ b/.agents/skills/formcraft-harness/references/tool-map.md @@ -44,18 +44,18 @@ These run in the engine and work with the window closed. Code: `backend/app/serv | `folders_list` | R | `GET /api/folders` | | | `folders_create` | W | `POST /api/folders` | | | `folders_update` | W | `PATCH /api/folders/{id}` | | -| `folders_delete` | D | `DELETE /api/folders/{id}` | | +| `folders_delete` | D | `DELETE /api/folders/{id}` | asks | | `folders_add_items` | W | `POST /api/folders/{id}/items` | | | `tags_list` | R | `GET /api/tags` | | | `tags_apply` | W | `POST /api/tags/apply` | | | `tags_rename` | W | `PATCH /api/tags/{name}` | | -| `tags_delete` | D | `DELETE /api/tags/{name}` | | +| `tags_delete` | D | `DELETE /api/tags/{name}` | asks | | `characters_list`, `characters_get` | R | `GET /api/characters`, `/{id}` | | | `characters_create`, `characters_update` | W | `POST`, `PATCH /api/characters` | | -| `characters_delete` | D | `DELETE /api/characters/{id}` | | +| `characters_delete` | D | `DELETE /api/characters/{id}` | asks | | `prompt_history` | R | `GET /api/prompts` | | | `projects_list`, `projects_get` | R | `GET /api/projects`, `/{id}` | kinds storyboard, scene, canvas, board, edit | -| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path | +| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path; replacing the document asks | | `projects_export` | W | `POST /api/projects/{id}/export` | overwriting a file asks | | `projects_import` | W | `POST /api/projects/import` | | | `projects_delete` | D | `DELETE /api/projects/{id}` | asks | diff --git a/.claude/skills/formcraft-driving/references/tools-by-task.md b/.claude/skills/formcraft-driving/references/tools-by-task.md index 5b0ccf9..e81b86f 100644 --- a/.claude/skills/formcraft-driving/references/tools-by-task.md +++ b/.claude/skills/formcraft-driving/references/tools-by-task.md @@ -66,7 +66,7 @@ Needs the window. `scene_state` to read, `scene_add` to place objects, `scene_up ## Projects -`projects_list` and `projects_get` read; `projects_create` and `projects_update` write; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. A project open in the window reloads when changed under it. +`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. ## Catalogue of commands diff --git a/.claude/skills/formcraft-harness/references/tool-map.md b/.claude/skills/formcraft-harness/references/tool-map.md index 8b4b74c..2bed3cb 100644 --- a/.claude/skills/formcraft-harness/references/tool-map.md +++ b/.claude/skills/formcraft-harness/references/tool-map.md @@ -44,18 +44,18 @@ These run in the engine and work with the window closed. Code: `backend/app/serv | `folders_list` | R | `GET /api/folders` | | | `folders_create` | W | `POST /api/folders` | | | `folders_update` | W | `PATCH /api/folders/{id}` | | -| `folders_delete` | D | `DELETE /api/folders/{id}` | | +| `folders_delete` | D | `DELETE /api/folders/{id}` | asks | | `folders_add_items` | W | `POST /api/folders/{id}/items` | | | `tags_list` | R | `GET /api/tags` | | | `tags_apply` | W | `POST /api/tags/apply` | | | `tags_rename` | W | `PATCH /api/tags/{name}` | | -| `tags_delete` | D | `DELETE /api/tags/{name}` | | +| `tags_delete` | D | `DELETE /api/tags/{name}` | asks | | `characters_list`, `characters_get` | R | `GET /api/characters`, `/{id}` | | | `characters_create`, `characters_update` | W | `POST`, `PATCH /api/characters` | | -| `characters_delete` | D | `DELETE /api/characters/{id}` | | +| `characters_delete` | D | `DELETE /api/characters/{id}` | asks | | `prompt_history` | R | `GET /api/prompts` | | | `projects_list`, `projects_get` | R | `GET /api/projects`, `/{id}` | kinds storyboard, scene, canvas, board, edit | -| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path | +| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path; replacing the document asks | | `projects_export` | W | `POST /api/projects/{id}/export` | overwriting a file asks | | `projects_import` | W | `POST /api/projects/import` | | | `projects_delete` | D | `DELETE /api/projects/{id}` | asks | diff --git a/agents/manifest.json b/agents/manifest.json index 78aa29a..e4b8879 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -76,6 +76,10 @@ "library_import", "library_save_copy", "library_delete", + "folders_delete", + "tags_delete", + "characters_delete", + "projects_update", "projects_export", "projects_delete", "starter_pack_install", diff --git a/backend/app/services/mcp_tools.py b/backend/app/services/mcp_tools.py index eeca524..31af333 100644 --- a/backend/app/services/mcp_tools.py +++ b/backend/app/services/mcp_tools.py @@ -562,7 +562,7 @@ async def folders_update(a, ctx): return await _t(svc.library.update_folder, a["id"], fields) -@tool("folders_delete", "Delete a folder", "Delete a folder; its items stay in the library.", {"id": _s("Folder id.")}, ("id",), hint="D") +@tool("folders_delete", "Delete a folder", "Delete a folder; its items stay in the library. The owner is asked to approve.", {"id": _s("Folder id.")}, ("id",), hint="D", risky=True) async def folders_delete(a, ctx): await _t(svc.library.delete_folder, a["id"]) return {"deleted": True} @@ -588,7 +588,7 @@ async def tags_rename(a, ctx): return await _t(svc.library.rename_tag, a["name"], a["newName"]) -@tool("tags_delete", "Delete a tag", "Remove a tag from every item.", {"name": _s("Tag name.")}, ("name",), hint="D") +@tool("tags_delete", "Delete a tag", "Remove a tag from every item. The owner is asked to approve.", {"name": _s("Tag name.")}, ("name",), hint="D", risky=True) async def tags_delete(a, ctx): await _t(svc.library.delete_tag, a["name"]) return {"deleted": True} @@ -617,7 +617,7 @@ async def characters_update(a, ctx): return await _t(svc.characters.update, a["id"], fields) -@tool("characters_delete", "Delete a character", "Delete a character.", {"id": _s("Character id.")}, ("id",), hint="D") +@tool("characters_delete", "Delete a character", "Delete a character. The owner is asked to approve.", {"id": _s("Character id.")}, ("id",), hint="D", risky=True) async def characters_delete(a, ctx): await _t(svc.characters.delete, a["id"]) return {"deleted": True} @@ -645,7 +645,7 @@ async def projects_create(a, ctx): return await _t(svc.projects.create, a["kind"], a["name"], a["doc"]) -@tool("projects_update", "Update a project", "Replace a project's document, rename it or set its cover image. A project open in the window reloads.", {"id": _s("Project id."), "name": _s("New name."), "doc": _o("A new document."), "coverId": _null("string", "Cover library id.")}, ("id",), hint="U") +@tool("projects_update", "Update a project", "Replace a project's document, rename it or set its cover image. A project open in the window reloads. Replacing the document asks the owner to approve.", {"id": _s("Project id."), "name": _s("New name."), "doc": _o("A new document."), "coverId": _null("string", "Cover library id.")}, ("id",), hint="U", risky=lambda a: "doc" in a) async def projects_update(a, ctx): if "doc" in a: name = a.get("name") or (await _t(svc.projects.get_summary, a["id"]))["name"] diff --git a/backend/tests/cb02/test_services_mcp_tools_approval.py b/backend/tests/cb02/test_services_mcp_tools_approval.py new file mode 100644 index 0000000..486ebc3 --- /dev/null +++ b/backend/tests/cb02/test_services_mcp_tools_approval.py @@ -0,0 +1,35 @@ +import pytest + +from app.services import mcp_tools + +ALWAYS_ASK = [ + ("projects_delete", {"id": "p"}), + ("library_delete", {"ids": ["m"]}), + ("characters_delete", {"id": "c"}), + ("folders_delete", {"id": "f"}), + ("tags_delete", {"name": "t"}), + ("projects_update", {"id": "p", "doc": {}}), +] + +NO_ASK = [ + ("projects_update", {"id": "p", "name": "New"}), + ("projects_update", {"id": "p", "coverId": None}), + ("characters_update", {"id": "c", "name": "New"}), + ("folders_update", {"id": "f", "name": "New"}), + ("tags_rename", {"name": "t", "newName": "u"}), +] + + +@pytest.mark.parametrize(("name", "args"), ALWAYS_ASK) +def test_calls_that_cannot_be_undone_ask_the_owner_whatever_the_policy(name, args): + assert mcp_tools.is_risky(name, args) + + +@pytest.mark.parametrize(("name", "args"), NO_ASK) +def test_renames_and_covers_follow_the_client_policy(name, args): + assert not mcp_tools.is_risky(name, args) + + +@pytest.mark.parametrize("name", sorted({n for n, _ in ALWAYS_ASK})) +def test_tools_that_ask_say_so_in_their_description(name): + assert "approve" in mcp_tools.get(name)["description"] From 72c1dd62dc3bf7aa17698cbc20992dbd68a57559 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:53:08 -0500 Subject: [PATCH 3/8] fix(agents): type the first prompt into a Claude Code tab started through cmd.exe On Windows a Claude Code installed as a .cmd or .bat script is started through the command interpreter, which reads its own command line and treats quotes, &, |, < > and % in it specially. The prompt from the ask box is no longer put on that command line; it is typed into the new tab once it starts, as a prompt for a tab already running is. A real program (.exe) and macOS and Linux still take the prompt as an argument. The shared agent finder is unchanged. Checked with python -m pytest (524 passed). --- backend/app/services/claude_code.py | 12 +++-- .../cb03/test_services_claude_code_prompt.py | 50 +++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 backend/tests/cb03/test_services_claude_code_prompt.py diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 2e36846..0e03332 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -126,13 +126,17 @@ def workdir() -> Path: return folder -def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None) -> list[str]: +def through_interpreter(path: str, platform: str | None = None) -> bool: + return agent_lookup.windows(platform) and str(path).lower().endswith((".cmd", ".bat")) + + +def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None, platform: str | None = None) -> list[str]: cmd = [path, "--mcp-config", mcp_file, "--allowedTools", f"mcp__{TAB_ENTRY}", "--append-system-prompt", NOTE] if resume: cmd += ["--resume", resume] - if prompt: + if prompt and not through_interpreter(path, platform): cmd.append(prompt) - return agent_lookup.start_argv(cmd) + return agent_lookup.start_argv(cmd, platform=platform) def status() -> dict: @@ -162,6 +166,8 @@ def open_tab(prompt: str | None = None, cols: int = 100, rows: int = 30, fresh: revoke(token) raise session.on_close.append(lambda: revoke(token)) + if prompt and through_interpreter(found.path): + terminal.write(session.id, prompt + "\r") return session.describe() diff --git a/backend/tests/cb03/test_services_claude_code_prompt.py b/backend/tests/cb03/test_services_claude_code_prompt.py new file mode 100644 index 0000000..bff5cf1 --- /dev/null +++ b/backend/tests/cb03/test_services_claude_code_prompt.py @@ -0,0 +1,50 @@ +from types import SimpleNamespace + +import pytest + +from app.services import agent_lookup, claude_code, terminal + +PROMPT = 'make a "red & blue" poster at 100% | then stop' + + +def test_a_windows_command_script_never_carries_the_prompt_on_its_command_line(): + argv = claude_code.tab_argv(r"C:\npm\claude.cmd", "mcp.json", PROMPT, platform="win32") + assert argv[1] == "/c" + assert PROMPT not in argv + assert not any("red & blue" in word for word in argv) + + +def test_a_windows_batch_file_never_carries_the_prompt_either(): + argv = claude_code.tab_argv(r"C:\tools\CLAUDE.BAT", "mcp.json", PROMPT, platform="win32") + assert PROMPT not in argv + + +def test_a_windows_program_still_takes_the_prompt_as_its_last_word(): + argv = claude_code.tab_argv(r"C:\bin\claude.exe", "mcp.json", PROMPT, platform="win32") + assert argv[0] == r"C:\bin\claude.exe" + assert argv[-1] == PROMPT + + +def test_macos_and_linux_still_pass_the_prompt_to_the_program(monkeypatch): + monkeypatch.setattr(agent_lookup, "login_shell", lambda env=None, platform=None: "/bin/sh") + argv = claude_code.tab_argv("/usr/local/bin/claude", "mcp.json", PROMPT, platform="darwin") + assert "'make a \"red & blue\" poster at 100% | then stop'" in argv[-1] + + +@pytest.mark.parametrize(("path", "typed"), [(r"C:\npm\claude.cmd", True), (r"C:\bin\claude.exe", False)]) +def test_a_prompt_left_off_the_command_line_is_typed_into_the_new_tab(monkeypatch, path, typed): + session = SimpleNamespace(id="s1", on_close=[], describe=lambda: {"id": "s1"}) + started = [] + written = [] + monkeypatch.setattr(terminal, "SESSIONS", {}) + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(agent_lookup, "login_shell", lambda env=None, platform=None: "/bin/sh") + monkeypatch.setattr(claude_code, "usable", lambda kind: SimpleNamespace(state="runs", path=path)) + monkeypatch.setattr(claude_code, "issue", lambda: ("token", "mcp.json")) + monkeypatch.setattr(claude_code, "child_env", lambda p=None, extra=None: {}) + monkeypatch.setattr(claude_code, "workdir", lambda: "here") + monkeypatch.setattr(terminal, "open_session", lambda cwd, cols, rows, title, argv, env, kind: started.append(argv) or session) + monkeypatch.setattr(terminal, "write", lambda sid, data: written.append((sid, data))) + claude_code.open_tab(PROMPT) + assert written == ([("s1", PROMPT + "\r")] if typed else []) + assert (PROMPT in started[0]) is not typed From 7065d7720e8de1552c8b15484589835ba9264ec7 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:54:37 -0500 Subject: [PATCH 4/8] fix(engine): trust the Vite dev and preview origins only in dev mode config.window_origins() lists localhost and 127.0.0.1 on the Vite dev and preview ports only when FORMCRAFT_DEV is 1. A release engine admits its own origin and the desktop window origins, so another local server that happens to use those ports is refused. LocalGuard accepts the origin list as a function and reads it per request, so the switch is honoured however the engine was started. The two dock tests that model the Vite page now run in dev mode, as that page does. Checked with python -m pytest (529 passed). --- backend/app/core/config.py | 5 +++- backend/app/core/local_guard.py | 9 +++++-- backend/app/main.py | 2 +- backend/tests/cb01/test_core_local_guard.py | 24 +++++++++++++++++++ .../cb03/test_routers_terminal_window_key.py | 6 +++-- 5 files changed, 40 insertions(+), 6 deletions(-) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 4f69433..eca11f1 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -76,4 +76,7 @@ def cors_origins() -> list[str]: def window_origins() -> list[str]: preview = FRONTEND_PORT + 1 - return [*cors_origins(), f"http://localhost:{preview}", f"http://127.0.0.1:{preview}", "tauri://localhost", "http://tauri.localhost"] + desktop = ["tauri://localhost", "http://tauri.localhost"] + if not is_dev(): + return desktop + return [*cors_origins(), f"http://localhost:{preview}", f"http://127.0.0.1:{preview}", *desktop] diff --git a/backend/app/core/local_guard.py b/backend/app/core/local_guard.py index 4ef42cd..43925a8 100644 --- a/backend/app/core/local_guard.py +++ b/backend/app/core/local_guard.py @@ -38,9 +38,14 @@ def _loopback_client(client) -> bool: class LocalGuard: - def __init__(self, app, origins: list[str]) -> None: + def __init__(self, app, origins) -> None: self.app = app - self.allowed = {key for key in (_origin_key(o) for o in origins) if key is not None} + self.origins = origins + + @property + def allowed(self) -> set: + origins = self.origins() if callable(self.origins) else self.origins + return {key for key in (_origin_key(o) for o in origins) if key is not None} def _permitted(self, scope, headers: dict[str, str]) -> bool: if not _loopback_client(scope.get("client")): diff --git a/backend/app/main.py b/backend/app/main.py index 201cde0..f558c7f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -71,7 +71,7 @@ async def lifespan(_: FastAPI): errors.install(app) if config.is_dev(): app.add_middleware(CORSMiddleware, allow_origins=config.cors_origins(), allow_methods=["*"], allow_headers=["*"]) -app.add_middleware(LocalGuard, origins=config.window_origins()) +app.add_middleware(LocalGuard, origins=config.window_origins) for _router in (system.router, settings_router.router, keys.router, jobs_router.router, events_router.router, media_router.router, costs.router, models_router.router, plan.router, generate.router, folders.router, tags.router, characters_router.router, prompts.router, projects.router, scene.router, pack_router.router, edit_router.router): app.include_router(_router, prefix="/api") diff --git a/backend/tests/cb01/test_core_local_guard.py b/backend/tests/cb01/test_core_local_guard.py index 55276b9..ea359ea 100644 --- a/backend/tests/cb01/test_core_local_guard.py +++ b/backend/tests/cb01/test_core_local_guard.py @@ -147,3 +147,27 @@ def test_a_rebound_host_header_is_refused_even_for_the_window(client): def test_a_cross_site_fetch_without_origin_is_refused(anon_client): assert anon_client.get("/api/health", headers={"sec-fetch-site": "cross-site"}).status_code == 403 assert anon_client.get("/api/health", headers={"sec-fetch-site": "same-origin"}).status_code == 200 + + +DEV_SERVER_ORIGINS = [f"http://{host}:{port}" for host in ("localhost", "127.0.0.1") for port in (config.FRONTEND_PORT, config.FRONTEND_PORT + 1)] + + +@pytest.mark.parametrize("origin", DEV_SERVER_ORIGINS) +def test_a_release_engine_refuses_the_dev_server_origins(monkeypatch, origin): + monkeypatch.delenv("FORMCRAFT_DEV", raising=False) + assert origin not in config.window_origins() + assert not LocalGuard(None, config.window_origins)._permitted(scope(), {"host": HOST, "origin": origin}) + + +@pytest.mark.parametrize("origin", DEV_SERVER_ORIGINS) +def test_a_dev_engine_admits_the_dev_server_origins(monkeypatch, origin): + monkeypatch.setenv("FORMCRAFT_DEV", "1") + assert origin in config.window_origins() + assert LocalGuard(None, config.window_origins)._permitted(scope(), {"host": HOST, "origin": origin}) + + +def test_the_desktop_window_origins_are_admitted_in_both_modes(monkeypatch): + for dev in ("1", "0"): + monkeypatch.setenv("FORMCRAFT_DEV", dev) + for origin in ("tauri://localhost", "http://tauri.localhost"): + assert LocalGuard(None, config.window_origins)._permitted(scope(), {"host": HOST, "origin": origin}) diff --git a/backend/tests/cb03/test_routers_terminal_window_key.py b/backend/tests/cb03/test_routers_terminal_window_key.py index 46cfb73..55a1ea6 100644 --- a/backend/tests/cb03/test_routers_terminal_window_key.py +++ b/backend/tests/cb03/test_routers_terminal_window_key.py @@ -18,7 +18,8 @@ def test_the_adapter_header_is_the_one_the_engine_reads(): @pytest.mark.parametrize("origin", [engine_origin(), vite_origin()]) -def test_a_dock_list_built_like_the_adapter_is_accepted(fresh, origin): +def test_a_dock_list_built_like_the_adapter_is_accepted(fresh, monkeypatch, origin): + monkeypatch.setenv("FORMCRAFT_DEV", "1") client = page(origin) key = claim(client) response = client.get("/api/terminal", headers=adapter_headers(key)) @@ -27,7 +28,8 @@ def test_a_dock_list_built_like_the_adapter_is_accepted(fresh, origin): @pytest.mark.parametrize("origin", [engine_origin(), vite_origin()]) -def test_a_dock_list_without_the_key_is_refused(fresh, origin): +def test_a_dock_list_without_the_key_is_refused(fresh, monkeypatch, origin): + monkeypatch.setenv("FORMCRAFT_DEV", "1") client = page(origin) claim(client) response = client.get("/api/terminal", headers={"Accept": "application/json"}) From 2905ed9457aa46e5db0b2db0643a700cefeee7d5 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:55:00 -0500 Subject: [PATCH 5/8] docs(engine): record the agent control, approval, prompt and origin changes in the engine log --- backend/HASHOUT_LOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 70b4453..bf92312 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2246,3 +2246,13 @@ From VERIFY_v0.8.0_E2E.md. A closed page's long poll could take a queued call: t - **Tool list check (`setup/agents.py`).** `WINDOW_TOOL_NAMES` is read from `services/agents.py` with `ast`, as `mcp_tools.py` already was, so the engine is never imported. - **CI.** The `install` job runs `./formcraft install` and the self-check. `install-desktop`, the freeze and the desktop build still run in no job. - Removed code: none. + +## 2026-11-28 · agent controls, approvals, the Windows prompt and dev origins {#agents-hardening} + +- refers-to: app/routers/agents.py :: WINDOW; app/routers/settings.py :: write_settings; app/services/mcp_tools.py :: folders_delete, tags_delete, characters_delete, projects_update; app/services/claude_code.py :: through_interpreter, tab_argv, open_tab; app/core/config.py :: window_origins; app/core/local_guard.py :: LocalGuard.allowed; app/main.py; tests/cb01/test_core_local_guard.py, tests/cb02/test_services_mcp_tools_approval.py, tests/cb03/test_routers_agents_window_key.py, tests/cb03/test_services_claude_code_prompt.py +- **Window key on agent routes.** Every `/api/agents/*` route except `POST /api/agents/bridge/bye` now depends on `window_key.require`, and so does `PUT /api/settings` (it carries `agentsAllowed`). These are the window's controls: the bridge queue, results, approvals, policies, the token, activity and stop. The window's patched `fetch` adds the key to every `/api/` call, so it is unaffected. `bye` stays open because the window sends it with `sendBeacon`, which cannot set a header; it only shortens the connected grace period. `GET /api/settings` stays open. +- **Approvals for changes that cannot be undone.** `folders_delete`, `tags_delete` and `characters_delete` are `risky=True`, and `projects_update` is risky when `doc` is given (the document is replaced and no earlier version is kept). They ask whatever the client policy, like `projects_delete` and `library_delete`. Renames and cover changes still follow the policy. `projects_update` remembers as `projects_update:` (the callable-risky key), so a remembered yes covers later document replacements for that client. +- **Windows prompt.** A Claude Code found as a `.cmd` or `.bat` starts as `cmd.exe /c ...`, and cmd.exe reads its command line itself: inner quotes, `& | < > ^` and `%VAR%` are not protected by the MSVC quoting pywinpty applies. `tab_argv` leaves the prompt off that command line and `open_tab` types it into the new tab with a carriage return, as it already did for a running tab. `.exe` and macOS and Linux are unchanged. The check lives in `claude_code.py`, because `agent_lookup.py` is the family's shared finder, held to a recorded hash by `setup/agents.py`. +- **Dev origins.** `config.window_origins()` lists `localhost` and `127.0.0.1` on 5290 and 5291 only when `FORMCRAFT_DEV=1`; otherwise only `tauri://localhost` and `http://tauri.localhost` (the engine's own origin is always admitted by the guard). `LocalGuard` takes the list or a function returning it and evaluates it per request; `main.py` passes the function. Tests that model the Vite page set `FORMCRAFT_DEV=1`. +- **Open.** Client names are still what the client reports (`clientInfo.name` or `X-Formcraft-Client`) and every client shares one bearer token, so remembered approvals and policies are per name, not per credential. New names get `ask`. Binding them to a client would need a token per client. +- Removed code: none. From cfcfbd691d644ea9630f99c4e162d8f6d60056b7 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:35:55 -0500 Subject: [PATCH 6/8] fix(agents): ask every time before an agent replaces a project document approval_key gave every projects_update the same key, so a remembered yes for a rename or a cover change also covered a later call that replaces the whole document. A projects_update with a doc now has its own key, projects_update:doc, and that answer is never stored or honoured, like an unpriced generate. The approval item says rememberable false, and the window hides the remember box for it. Checked with python -m pytest (556 passed), npm run typecheck and npm test (1186 passed). --- .../references/tools-by-task.md | 2 +- .../references/tools-by-task.md | 2 +- backend/app/services/agents.py | 17 ++++-- .../cb02/test_services_agents_replace_doc.py | 60 +++++++++++++++++++ frontend/HASHOUT_LOG.md | 6 ++ frontend/src/automation/approvals.ts | 2 +- frontend/src/io/api-agents.ts | 1 + 7 files changed, 83 insertions(+), 7 deletions(-) create mode 100644 backend/tests/cb02/test_services_agents_replace_doc.py diff --git a/.agents/skills/formcraft-driving/references/tools-by-task.md b/.agents/skills/formcraft-driving/references/tools-by-task.md index e81b86f..0d93e99 100644 --- a/.agents/skills/formcraft-driving/references/tools-by-task.md +++ b/.agents/skills/formcraft-driving/references/tools-by-task.md @@ -66,7 +66,7 @@ Needs the window. `scene_state` to read, `scene_add` to place objects, `scene_up ## Projects -`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. +`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks every time (that answer is never remembered); `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. ## Catalogue of commands diff --git a/.claude/skills/formcraft-driving/references/tools-by-task.md b/.claude/skills/formcraft-driving/references/tools-by-task.md index e81b86f..0d93e99 100644 --- a/.claude/skills/formcraft-driving/references/tools-by-task.md +++ b/.claude/skills/formcraft-driving/references/tools-by-task.md @@ -66,7 +66,7 @@ Needs the window. `scene_state` to read, `scene_add` to place objects, `scene_up ## Projects -`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. +`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks every time (that answer is never remembered); `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. ## Catalogue of commands diff --git a/backend/app/services/agents.py b/backend/app/services/agents.py index d3066ee..aaafd4f 100644 --- a/backend/app/services/agents.py +++ b/backend/app/services/agents.py @@ -26,6 +26,8 @@ POLICIES = ("allow", "ask", "deny") DEFAULT_POLICY = "ask" PRICED_KEY = "generate<=" +REPLACE_DOC_KEY = "projects_update:doc" +NEVER_REMEMBERED = ("generate", REPLACE_DOC_KEY) ACTIVITY_MAX = 200 NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,128}$") BLOCKED_PREFIXES = ("keys_", "key_", "settings_", "encode_", "cover_", "agents_", "agent_") @@ -138,7 +140,11 @@ def remembered(client: str, tool: str) -> bool: bound = _bound(tool) if bound is not None: return any(b is not None and bound <= b + 1e-9 for b in map(_bound, items)) - return tool != "generate" and tool in items + return rememberable(tool) and tool in items + + +def rememberable(key: str) -> bool: + return key not in NEVER_REMEMBERED def approval_key(tool: str, args: dict) -> str: @@ -146,13 +152,15 @@ def approval_key(tool: str, args: dict) -> str: if tool == "command_run": return f"{tool}:{args.get('id')}" + if tool == "projects_update": + return REPLACE_DOC_KEY if "doc" in args else tool if callable(mcp_tools.TOOLS.get(tool, {}).get("risky")): return f"{tool}:{args.get('path') or args.get('dir') or ''}" return tool def remember(client: str, tool: str) -> None: - if tool == "generate": + if not rememberable(tool): return with _lock: state = _load() @@ -347,8 +355,9 @@ async def ask(self, client: str, tool: str, args: dict, cost, ctx=None) -> None: raise ToolError("window_required", f"{tool} needs your approval in the FormCraft window and the window is not open. Open FormCraft, then call again.") item_id = uuid.uuid4().hex future = asyncio.get_running_loop().create_future() - self.approvals[item_id] = (future, client, priced_key(approval_key(tool, args), cost)) - item = {"kind": "approval", "id": item_id, "tool": tool, "args": args, "client": client} + key = priced_key(approval_key(tool, args), cost) + self.approvals[item_id] = (future, client, key) + item = {"kind": "approval", "id": item_id, "tool": tool, "args": args, "client": client, "rememberable": rememberable(key)} if cost is not None: item["costUsd"] = cost self._put(item) diff --git a/backend/tests/cb02/test_services_agents_replace_doc.py b/backend/tests/cb02/test_services_agents_replace_doc.py new file mode 100644 index 0000000..63ff686 --- /dev/null +++ b/backend/tests/cb02/test_services_agents_replace_doc.py @@ -0,0 +1,60 @@ +import asyncio +import time + +from app.services import agents + +RENAME = {"id": "p", "name": "New"} +REPLACE = {"id": "p", "doc": {}} + + +def test_replacing_a_document_has_its_own_approval_key(): + assert agents.approval_key("projects_update", RENAME) != agents.approval_key("projects_update", REPLACE) + assert agents.approval_key("projects_update", {"id": "p", "coverId": None}) == agents.approval_key("projects_update", RENAME) + + +def test_a_remembered_rename_does_not_cover_replacing_the_document(data_dir): + agents.remember("client", agents.approval_key("projects_update", RENAME)) + assert agents.remembered("client", agents.approval_key("projects_update", RENAME)) + assert not agents.remembered("client", agents.approval_key("projects_update", REPLACE)) + + +def test_approval_to_replace_a_document_is_never_remembered(data_dir): + key = agents.approval_key("projects_update", REPLACE) + agents.remember("client", key) + assert not agents.remembered("client", key) + assert all(key not in c["remembered"] for c in agents.public_state()["clients"]) + + +def test_a_stored_replace_entry_is_not_honoured(data_dir): + key = agents.approval_key("projects_update", REPLACE) + state = agents._load() + agents._save({**state, "remembered": {"client": [key]}}) + assert not agents.remembered("client", key) + + +def _asked(args: dict) -> tuple[dict, bool]: + async def run(): + bridge = agents.Bridge() + bridge.until = time.monotonic() + 60 + task = asyncio.create_task(bridge.ask("client", "projects_update", args, None)) + while not bridge.queue: + await asyncio.sleep(0) + item = bridge.queue.popleft() + bridge.decide(item["id"], True, True) + await task + return item + + item = asyncio.run(run()) + return item, agents.remembered("client", agents.approval_key("projects_update", args)) + + +def test_the_window_is_told_a_document_replacement_cannot_be_remembered(data_dir): + item, kept = _asked(REPLACE) + assert item["rememberable"] is False + assert not kept + + +def test_an_ordinary_update_can_still_be_remembered(data_dir): + item, kept = _asked(RENAME) + assert item["rememberable"] is True + assert kept diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 8c50a0b..bcf9b42 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -7151,3 +7151,9 @@ Checked in a real Chrome against the engine: a reload keeps the dock working (th - **OBJ and STL (shipped in v0.9.4).** A conversion to GLB in the window, made the way `fbx-convert.ts` converts FBX, with `ui/viewers/library-glb.ts` keeping the converted file in the library for reuse. The owner approved changing the two assertions in `tests/unit/ui/viewers/kinds.test.ts` that said OBJ is unknown and cannot be previewed. `ui/tools/mesh-tools.ts` goes through the viewer's own conversion. `ui/canvas/model3d/render.ts` reads only glTF and has no FBX path either, so a model as a canvas layer needs a conversion before `renderModel` for FBX, OBJ and STL alike. `ui/library/library-modal.ts` now asks `modelFormat` like the grid tile. The library keeps no file beside an OBJ, so its material file is never found and a converted model is neutral grey. - **Remember box.** The approval dialog is built once and reused, so with no estimate the label stays in place with `visibility: hidden` and a disabled checkbox, and `finish` ignores a disabled box. Removing the label would shift the dialog. - **Source maps (`vite.config.ts`).** Production builds emit none; `npm run dev` still serves them. `setup/freeze_backend` rebuilds a `dist` that still has `.map` files and stops if any remain. + +## 2026-11-28 · approvals that are never remembered {#approvals-never-remembered} + +- refers-to: src/automation/approvals.ts :: ApprovalDialog; src/io/api-agents.ts :: BridgeApproval +- **Remember box.** An approval item may carry `rememberable: false` (the engine sends it for replacing a project's document). The dialog then hides and disables the remember box the same way it does for an unpriced generate, so the layout does not move. An item without the field behaves as before. +- Removed code: none. diff --git a/frontend/src/automation/approvals.ts b/frontend/src/automation/approvals.ts index a22d31e..a6ac9c3 100644 --- a/frontend/src/automation/approvals.ts +++ b/frontend/src/automation/approvals.ts @@ -102,7 +102,7 @@ class ApprovalDialog extends Dialog { const price = priced ? `$${(item.costUsd as number).toFixed(2)}` : ''; if (priced) setText(q(this.costRow, '.fc-ag-val'), price); this.remember.checked = false; - const offered = priced || item.tool !== 'generate'; + const offered = item.rememberable !== false && (priced || item.tool !== 'generate'); this.keep.style.visibility = offered ? '' : 'hidden'; setDisabled(this.remember, !offered); setText(this.rememberText, t(priced ? 'Remember this choice for {client} up to {cost}' : 'Remember this choice for {client}').replace('{client}', item.client).replace('{cost}', price)); diff --git a/frontend/src/io/api-agents.ts b/frontend/src/io/api-agents.ts index 07d3c72..fbe0d32 100644 --- a/frontend/src/io/api-agents.ts +++ b/frontend/src/io/api-agents.ts @@ -50,6 +50,7 @@ export interface BridgeApproval { args: Record; client: string; costUsd?: number; + rememberable?: boolean; } export interface BridgeWithdraw { From 4861220448b4dee8dbbd5ec439348f5fd4aa23b5 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:35:55 -0500 Subject: [PATCH 7/8] fix(agents): refuse command script launches whose words cmd.exe would read itself When an agent program is a .cmd or .bat file it starts through cmd.exe /c, which reads its own command line. Every word on that line must now be text with no control characters and no % " & | < > ^ or !, and parentheses pass only inside a word that gets quoted. Otherwise the tab is not started and the window shows why. The Claude Code tab, the other agent tabs and the sign-in check all go through this. A real program and macOS and Linux are unchanged. The engine log records both changes. Checked with python -m pytest (556 passed). --- backend/HASHOUT_LOG.md | 5 ++- backend/app/services/agent_programs.py | 4 +- backend/app/services/claude_code.py | 24 +++++++++++- .../cb03/test_services_claude_code_prompt.py | 37 +++++++++++++++++++ 4 files changed, 66 insertions(+), 4 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index bf92312..b750a90 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2249,9 +2249,10 @@ From VERIFY_v0.8.0_E2E.md. A closed page's long poll could take a queued call: t ## 2026-11-28 · agent controls, approvals, the Windows prompt and dev origins {#agents-hardening} -- refers-to: app/routers/agents.py :: WINDOW; app/routers/settings.py :: write_settings; app/services/mcp_tools.py :: folders_delete, tags_delete, characters_delete, projects_update; app/services/claude_code.py :: through_interpreter, tab_argv, open_tab; app/core/config.py :: window_origins; app/core/local_guard.py :: LocalGuard.allowed; app/main.py; tests/cb01/test_core_local_guard.py, tests/cb02/test_services_mcp_tools_approval.py, tests/cb03/test_routers_agents_window_key.py, tests/cb03/test_services_claude_code_prompt.py +- refers-to: app/routers/agents.py :: WINDOW; app/routers/settings.py :: write_settings; app/services/mcp_tools.py :: folders_delete, tags_delete, characters_delete, projects_update; app/services/claude_code.py :: through_interpreter, interpreter_safe, interpreter_argv, tab_argv, open_tab; app/services/agent_programs.py :: open_tab, claude_signed_in; app/services/agents.py :: NEVER_REMEMBERED, rememberable, approval_key, remember, remembered, Bridge.ask; frontend src/automation/approvals.ts; app/core/config.py :: window_origins; app/core/local_guard.py :: LocalGuard.allowed; app/main.py; tests/cb01/test_core_local_guard.py, tests/cb02/test_services_mcp_tools_approval.py, tests/cb03/test_routers_agents_window_key.py, tests/cb03/test_services_claude_code_prompt.py, tests/cb02/test_services_agents_replace_doc.py - **Window key on agent routes.** Every `/api/agents/*` route except `POST /api/agents/bridge/bye` now depends on `window_key.require`, and so does `PUT /api/settings` (it carries `agentsAllowed`). These are the window's controls: the bridge queue, results, approvals, policies, the token, activity and stop. The window's patched `fetch` adds the key to every `/api/` call, so it is unaffected. `bye` stays open because the window sends it with `sendBeacon`, which cannot set a header; it only shortens the connected grace period. `GET /api/settings` stays open. -- **Approvals for changes that cannot be undone.** `folders_delete`, `tags_delete` and `characters_delete` are `risky=True`, and `projects_update` is risky when `doc` is given (the document is replaced and no earlier version is kept). They ask whatever the client policy, like `projects_delete` and `library_delete`. Renames and cover changes still follow the policy. `projects_update` remembers as `projects_update:` (the callable-risky key), so a remembered yes covers later document replacements for that client. +- **Approvals for changes that cannot be undone.** `folders_delete`, `tags_delete` and `characters_delete` are `risky=True`, and `projects_update` is risky when `doc` is given (the document is replaced and no earlier version is kept). They ask whatever the client policy, like `projects_delete` and `library_delete`. Renames and cover changes still follow the policy. `agents.approval_key` keys a `projects_update` with `doc` as `projects_update:doc` and every other `projects_update` as `projects_update`, so a remembered rename or cover change never covers a document replacement. `projects_update:doc` is in `agents.NEVER_REMEMBERED` with the bare `generate`: `remember` never stores it, `remembered` never honours a stored copy, and the approval item carries `rememberable: false` so the window hides the remember box. +- **Command scripts on Windows.** `claude_code.interpreter_argv` wraps `agent_lookup.start_argv` for the Claude Code tab and the other agent tabs. When the program is a `.cmd` or `.bat`, every word must be text with no control character (`\x00` to `\x1f`, `\x7f`), and no `%`, `"`, `&`, `|`, `<`, `>`, `^` or `!`, quoted or not, because cmd.exe can drop the outer quotes of a `/c` line; `(` and `)` pass only in a word that holds a space or tab, which `list2cmdline` quotes. Otherwise the tab is refused with a `LookupError` (the router's 409 path) and `claude_signed_in` reports unknown without running the program. Open: resolving the npm shim to its `node` target and starting that without cmd.exe would remove the interpreter entirely; it needs a Windows machine to check the shim formats. - **Windows prompt.** A Claude Code found as a `.cmd` or `.bat` starts as `cmd.exe /c ...`, and cmd.exe reads its command line itself: inner quotes, `& | < > ^` and `%VAR%` are not protected by the MSVC quoting pywinpty applies. `tab_argv` leaves the prompt off that command line and `open_tab` types it into the new tab with a carriage return, as it already did for a running tab. `.exe` and macOS and Linux are unchanged. The check lives in `claude_code.py`, because `agent_lookup.py` is the family's shared finder, held to a recorded hash by `setup/agents.py`. - **Dev origins.** `config.window_origins()` lists `localhost` and `127.0.0.1` on 5290 and 5291 only when `FORMCRAFT_DEV=1`; otherwise only `tauri://localhost` and `http://tauri.localhost` (the engine's own origin is always admitted by the guard). `LocalGuard` takes the list or a function returning it and evaluates it per request; `main.py` passes the function. Tests that model the Vite page set `FORMCRAFT_DEV=1`. - **Open.** Client names are still what the client reports (`clientInfo.name` or `X-Formcraft-Client`) and every client shares one bearer token, so remembered approvals and policies are per name, not per credential. New names get `ask`. Binding them to a client would need a token per client. diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 4d40c22..e311e87 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -25,6 +25,8 @@ def find(kind: str) -> str | None: def claude_signed_in(path: str) -> bool | None: if os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("CLAUDE_CODE_OAUTH_TOKEN"): return True + if claude_code.through_interpreter(path) and not claude_code.interpreter_safe([path]): + return None try: out = agent_lookup.run([path, "auth", "status"], claude_code.child_env(path), claude_code.CHECK_WAIT) data = json.loads(out.stdout) @@ -143,7 +145,7 @@ def open_tab(kind: str, cols: int = 100, rows: int = 30) -> dict: if own: write_tab_entry(own, token) wrote = True if own else write_config(kind, folder) - session = terminal.open_session(str(folder), cols, rows, program["title"], agent_lookup.start_argv([found.path]), claude_code.child_env(found.path, {TOKEN_VAR: token}), kind) + session = terminal.open_session(str(folder), cols, rows, program["title"], claude_code.interpreter_argv([found.path]), claude_code.child_env(found.path, {TOKEN_VAR: token}), kind) except BaseException: claude_code.revoke(token) if own: diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 0e03332..54c5b12 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -1,6 +1,7 @@ import hmac import json import os +import re import secrets import time from pathlib import Path @@ -18,6 +19,9 @@ INAPP_HEADER = "x-formcraft-tab" INAPP_NAME = "Claude Code in formcraft" TAB_ENTRY = "formcraft_tab" +CMD_NEVER = re.compile(r'[\x00-\x1f\x7f%"&|<>^!]') +CMD_UNQUOTED = re.compile(r"[()]") +CMD_REFUSED = "This program is a Windows command script and its command line holds characters the command interpreter reads itself, so it was not started." NOTE = ("You are Claude Code running inside formcraft, the scene and generation studio open on this computer. " "Work through the formcraft_tab MCP server's tools: start with app_status, use plan_generation or estimate_cost before generate, " "which spends the owner's money and asks them first, and follow jobs with job_wait. " @@ -130,13 +134,31 @@ def through_interpreter(path: str, platform: str | None = None) -> bool: return agent_lookup.windows(platform) and str(path).lower().endswith((".cmd", ".bat")) +def interpreter_safe(words: list) -> bool: + for word in words: + if not isinstance(word, (str, Path)): + return False + text = str(word) + if CMD_NEVER.search(text): + return False + if CMD_UNQUOTED.search(text) and not (" " in text or "\t" in text): + return False + return True + + +def interpreter_argv(cmd: list, platform: str | None = None) -> list[str]: + if cmd and through_interpreter(cmd[0], platform) and not interpreter_safe(cmd): + raise LookupError(CMD_REFUSED) + return agent_lookup.start_argv(cmd, platform=platform) + + def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None, platform: str | None = None) -> list[str]: cmd = [path, "--mcp-config", mcp_file, "--allowedTools", f"mcp__{TAB_ENTRY}", "--append-system-prompt", NOTE] if resume: cmd += ["--resume", resume] if prompt and not through_interpreter(path, platform): cmd.append(prompt) - return agent_lookup.start_argv(cmd, platform=platform) + return interpreter_argv(cmd, platform) def status() -> dict: diff --git a/backend/tests/cb03/test_services_claude_code_prompt.py b/backend/tests/cb03/test_services_claude_code_prompt.py index bff5cf1..c60ba37 100644 --- a/backend/tests/cb03/test_services_claude_code_prompt.py +++ b/backend/tests/cb03/test_services_claude_code_prompt.py @@ -48,3 +48,40 @@ def test_a_prompt_left_off_the_command_line_is_typed_into_the_new_tab(monkeypatc claude_code.open_tab(PROMPT) assert written == ([("s1", PROMPT + "\r")] if typed else []) assert (PROMPT in started[0]) is not typed + + +@pytest.mark.parametrize("word", ["a\nb", "a\rb", "a\x00b", "a\x1bb", "a\x7fb", "%PATH%", "a b %c", 'say "hi"', "a&b", "a b & c", "a|b", "ab", "a^b", "a!b", "(a)"]) +def test_a_command_script_refuses_words_the_interpreter_would_read(word): + with pytest.raises(LookupError): + claude_code.tab_argv(r"C:\npm\claude.cmd", "mcp.json", None, word, platform="win32") + + +def test_a_command_script_refuses_a_word_that_is_not_text(): + assert not claude_code.interpreter_safe([r"C:\npm\claude.cmd", 3]) + assert not claude_code.interpreter_safe([r"C:\npm\claude.cmd", None]) + + +@pytest.mark.parametrize("path", [r"C:\Program Files (x86)\npm\claude.cmd", r"C:\Users\me\AppData\Roaming\npm\claude.cmd"]) +def test_a_command_script_still_starts_with_ordinary_words(path): + argv = claude_code.tab_argv(path, r"C:\Users\me\data\mcp-1.json", None, "abc-123", platform="win32") + assert argv[1] == "/c" + assert argv[2] == path + + +def test_a_windows_program_keeps_any_characters_in_its_words(): + argv = claude_code.tab_argv(r"C:\bin\claude.exe", "mcp.json", None, "a&b%c", platform="win32") + assert "a&b%c" in argv + + +def test_another_agent_started_as_a_command_script_is_refused_too(monkeypatch): + from app.services import agent_programs + + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False) + ran = [] + monkeypatch.setattr(agent_lookup, "run", lambda *a, **k: ran.append(a)) + with pytest.raises(LookupError): + claude_code.interpreter_argv([r"C:\npm\a&b\codex.cmd"]) + assert agent_programs.claude_signed_in(r"C:\npm\a&b\claude.cmd") is None + assert ran == [] From 62ed5f57307d9204fadc5baa11e8c1b003cce91a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:02:18 -0500 Subject: [PATCH 8/8] fix(agents): start npm command shims directly and refuse every interpreter character otherwise An agent program found as an npm-style .cmd shim is now resolved to the node script or program it wraps and started from an argv list without cmd.exe, for the Claude Code tab, the other agent tabs, the version check and the sign-in check. The resolved tab takes the prompt on its command line again. When a shim does not resolve and cmd.exe is still used, any word, including the program path, holding & | < > ^ ( ) ! % " or a control character is refused whether or not it holds a space, because quoting does not protect it there. The earlier exception for parentheses in a quoted word is removed. The refusal says to pass long text through standard input or a file. The version check of such a script no longer goes through the shared finder's cmd.exe start. Checked with python -m pytest (579 passed), npm run typecheck, npm run build, npm test (1186 passed), the engine self-check, setup/versions.py and check_skills.py. --- backend/HASHOUT_LOG.md | 6 +- backend/app/services/agent_programs.py | 9 +- backend/app/services/claude_code.py | 78 ++++++---- backend/app/services/command_script.py | 66 +++++++++ .../cb03/test_services_claude_code_prompt.py | 13 +- .../cb03/test_services_command_script.py | 136 ++++++++++++++++++ 6 files changed, 274 insertions(+), 34 deletions(-) create mode 100644 backend/app/services/command_script.py create mode 100644 backend/tests/cb03/test_services_command_script.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index b750a90..59d4b20 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2249,11 +2249,11 @@ From VERIFY_v0.8.0_E2E.md. A closed page's long poll could take a queued call: t ## 2026-11-28 · agent controls, approvals, the Windows prompt and dev origins {#agents-hardening} -- refers-to: app/routers/agents.py :: WINDOW; app/routers/settings.py :: write_settings; app/services/mcp_tools.py :: folders_delete, tags_delete, characters_delete, projects_update; app/services/claude_code.py :: through_interpreter, interpreter_safe, interpreter_argv, tab_argv, open_tab; app/services/agent_programs.py :: open_tab, claude_signed_in; app/services/agents.py :: NEVER_REMEMBERED, rememberable, approval_key, remember, remembered, Bridge.ask; frontend src/automation/approvals.ts; app/core/config.py :: window_origins; app/core/local_guard.py :: LocalGuard.allowed; app/main.py; tests/cb01/test_core_local_guard.py, tests/cb02/test_services_mcp_tools_approval.py, tests/cb03/test_routers_agents_window_key.py, tests/cb03/test_services_claude_code_prompt.py, tests/cb02/test_services_agents_replace_doc.py +- refers-to: app/routers/agents.py :: WINDOW; app/routers/settings.py :: write_settings; app/services/mcp_tools.py :: folders_delete, tags_delete, characters_delete, projects_update; app/services/claude_code.py :: located, checked_script, through_interpreter, interpreter_safe, direct, launch_words, interpreter_argv, run, tab_argv, open_tab; app/services/command_script.py :: safe, resolve; app/services/agent_programs.py :: open_tab, claude_signed_in; app/services/agents.py :: NEVER_REMEMBERED, rememberable, approval_key, remember, remembered, Bridge.ask; frontend src/automation/approvals.ts; app/core/config.py :: window_origins; app/core/local_guard.py :: LocalGuard.allowed; app/main.py; tests/cb01/test_core_local_guard.py, tests/cb02/test_services_mcp_tools_approval.py, tests/cb03/test_routers_agents_window_key.py, tests/cb03/test_services_claude_code_prompt.py, tests/cb03/test_services_command_script.py, tests/cb02/test_services_agents_replace_doc.py - **Window key on agent routes.** Every `/api/agents/*` route except `POST /api/agents/bridge/bye` now depends on `window_key.require`, and so does `PUT /api/settings` (it carries `agentsAllowed`). These are the window's controls: the bridge queue, results, approvals, policies, the token, activity and stop. The window's patched `fetch` adds the key to every `/api/` call, so it is unaffected. `bye` stays open because the window sends it with `sendBeacon`, which cannot set a header; it only shortens the connected grace period. `GET /api/settings` stays open. - **Approvals for changes that cannot be undone.** `folders_delete`, `tags_delete` and `characters_delete` are `risky=True`, and `projects_update` is risky when `doc` is given (the document is replaced and no earlier version is kept). They ask whatever the client policy, like `projects_delete` and `library_delete`. Renames and cover changes still follow the policy. `agents.approval_key` keys a `projects_update` with `doc` as `projects_update:doc` and every other `projects_update` as `projects_update`, so a remembered rename or cover change never covers a document replacement. `projects_update:doc` is in `agents.NEVER_REMEMBERED` with the bare `generate`: `remember` never stores it, `remembered` never honours a stored copy, and the approval item carries `rememberable: false` so the window hides the remember box. -- **Command scripts on Windows.** `claude_code.interpreter_argv` wraps `agent_lookup.start_argv` for the Claude Code tab and the other agent tabs. When the program is a `.cmd` or `.bat`, every word must be text with no control character (`\x00` to `\x1f`, `\x7f`), and no `%`, `"`, `&`, `|`, `<`, `>`, `^` or `!`, quoted or not, because cmd.exe can drop the outer quotes of a `/c` line; `(` and `)` pass only in a word that holds a space or tab, which `list2cmdline` quotes. Otherwise the tab is refused with a `LookupError` (the router's 409 path) and `claude_signed_in` reports unknown without running the program. Open: resolving the npm shim to its `node` target and starting that without cmd.exe would remove the interpreter entirely; it needs a Windows machine to check the shim formats. -- **Windows prompt.** A Claude Code found as a `.cmd` or `.bat` starts as `cmd.exe /c ...`, and cmd.exe reads its command line itself: inner quotes, `& | < > ^` and `%VAR%` are not protected by the MSVC quoting pywinpty applies. `tab_argv` leaves the prompt off that command line and `open_tab` types it into the new tab with a carriage return, as it already did for a running tab. `.exe` and macOS and Linux are unchanged. The check lives in `claude_code.py`, because `agent_lookup.py` is the family's shared finder, held to a recorded hash by `setup/agents.py`. +- **Command scripts on Windows.** `claude_code.launch_words` is the one place a Windows `.cmd` or `.bat` start is decided, used by `interpreter_argv` (the Claude Code tab and the other agent tabs), `claude_code.run` (the sign-in check) and `checked_script` (the `--version` check `located` uses for a script instead of `agent_lookup.check`, which would start it through cmd.exe). First `command_script.resolve` reads an npm-style shim (at most 64 KiB): the last line holding `%*`, its last quoted word that starts with `%dp0%` or `%~dp0` and is not `node.exe`, with no other `%` left. The target must be an existing file inside the shim's folder (its parent for a `.bin` folder). A `.js`, `.cjs` or `.mjs` target runs as `[node.exe, script, ...]`, with `node.exe` from the shim's folder or else the child PATH; an `.exe` target runs as itself. Then no cmd.exe is involved, the words are an argv list and the prompt goes on the command line again. When the shim does not resolve, cmd.exe is still used and every word, the program path included, must be text with none of `& | < > ^ ( ) ! % "` and no control character (`\x00` to `\x1f`, `\x7f`), with or without spaces: the `/c` line is read by cmd.exe and again by the shim's `%*`, so quoting protects nothing. Otherwise a `LookupError` with `command_script.REFUSED` (the router's 409 path), which says to pass long text through standard input or a file; the checks report broken or unknown without running anything. The earlier exception for `(` and `)` inside a quoted word is gone. Open: the shim formats are checked against hand-written samples in `tests/cb03/test_services_command_script.py`, not yet on a Windows machine. +- **Windows prompt.** A Claude Code found as a `.cmd` or `.bat` starts as `cmd.exe /c ...`, and cmd.exe reads its command line itself: inner quotes, `& | < > ^` and `%VAR%` are not protected by the MSVC quoting pywinpty applies. `tab_argv` leaves the prompt off that command line (only while the shim does not resolve, see above) and `open_tab` types it into the new tab with a carriage return, as it already did for a running tab. `.exe` and macOS and Linux are unchanged. The check lives in `claude_code.py`, because `agent_lookup.py` is the family's shared finder, held to a recorded hash by `setup/agents.py`. - **Dev origins.** `config.window_origins()` lists `localhost` and `127.0.0.1` on 5290 and 5291 only when `FORMCRAFT_DEV=1`; otherwise only `tauri://localhost` and `http://tauri.localhost` (the engine's own origin is always admitted by the guard). `LocalGuard` takes the list or a function returning it and evaluates it per request; `main.py` passes the function. Tests that model the Vite page set `FORMCRAFT_DEV=1`. - **Open.** Client names are still what the client reports (`clientInfo.name` or `X-Formcraft-Client`) and every client shares one bearer token, so remembered approvals and policies are per name, not per credential. New names get `ask`. Binding them to a client would need a token per client. - Removed code: none. diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index e311e87..de9f124 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -25,12 +25,10 @@ def find(kind: str) -> str | None: def claude_signed_in(path: str) -> bool | None: if os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("CLAUDE_CODE_OAUTH_TOKEN"): return True - if claude_code.through_interpreter(path) and not claude_code.interpreter_safe([path]): - return None try: - out = agent_lookup.run([path, "auth", "status"], claude_code.child_env(path), claude_code.CHECK_WAIT) + out = claude_code.run([path, "auth", "status"], claude_code.child_env(path), claude_code.CHECK_WAIT) data = json.loads(out.stdout) - except (OSError, subprocess.SubprocessError, ValueError): + except (OSError, subprocess.SubprocessError, ValueError, LookupError): return None return bool(data.get("loggedIn")) if isinstance(data, dict) and "loggedIn" in data else None @@ -145,7 +143,8 @@ def open_tab(kind: str, cols: int = 100, rows: int = 30) -> dict: if own: write_tab_entry(own, token) wrote = True if own else write_config(kind, folder) - session = terminal.open_session(str(folder), cols, rows, program["title"], claude_code.interpreter_argv([found.path]), claude_code.child_env(found.path, {TOKEN_VAR: token}), kind) + env = claude_code.child_env(found.path, {TOKEN_VAR: token}) + session = terminal.open_session(str(folder), cols, rows, program["title"], claude_code.interpreter_argv([found.path], env=env), env, kind) except BaseException: claude_code.revoke(token) if own: diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 54c5b12..1fa5e0f 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -1,13 +1,13 @@ import hmac import json import os -import re import secrets +import subprocess import time from pathlib import Path from app.core import config -from app.services import agent_lookup, agents, terminal +from app.services import agent_lookup, agents, command_script, terminal KEEP_ENV = agent_lookup.KEEP_ENV OVERRIDES = {"claude": ("FORMCRAFT_CLAUDE_BIN",), "codex": ("FORMCRAFT_CODEX_BIN",), "cursor": ("FORMCRAFT_CURSOR_BIN",), "antigravity": ("FORMCRAFT_ANTIGRAVITY_BIN",)} @@ -19,9 +19,6 @@ INAPP_HEADER = "x-formcraft-tab" INAPP_NAME = "Claude Code in formcraft" TAB_ENTRY = "formcraft_tab" -CMD_NEVER = re.compile(r'[\x00-\x1f\x7f%"&|<>^!]') -CMD_UNQUOTED = re.compile(r"[()]") -CMD_REFUSED = "This program is a Windows command script and its command line holds characters the command interpreter reads itself, so it was not started." NOTE = ("You are Claude Code running inside formcraft, the scene and generation studio open on this computer. " "Work through the formcraft_tab MCP server's tools: start with app_status, use plan_generation or estimate_cost before generate, " "which spends the owner's money and asks them first, and follow jobs with job_wait. " @@ -45,7 +42,30 @@ def child_env(path: str | None = None, extra: dict | None = None) -> dict: def located(kind: str, fresh: bool = False) -> agent_lookup.Found: found = agent_lookup.find(kind, setting=setting(kind), override_vars=OVERRIDES.get(kind, ()), shell_timeout=SHELL_WAIT, fresh=fresh) - return agent_lookup.check(found, child_env(found.path), CHECK_WAIT, fresh) + env = child_env(found.path) + if found.path and through_interpreter(found.path): + return checked_script(found, env) + return agent_lookup.check(found, env, CHECK_WAIT, fresh) + + +def checked_script(found: agent_lookup.Found, env: dict, platform: str | None = None) -> agent_lookup.Found: + try: + out = run([found.path, "--version"], env, CHECK_WAIT, platform) + except LookupError as exc: + found.state, found.version, found.error = "broken", None, str(exc) + return found + except subprocess.TimeoutExpired: + found.state, found.version, found.error = "broken", None, f"it gave no answer to --version in {CHECK_WAIT:g} seconds" + return found + except OSError as exc: + found.state, found.version, found.error = "broken", None, exc.strerror or str(exc) + return found + if out.returncode == 0: + found.state, found.version, found.error = "runs", agent_lookup._version(out.stdout), "" + else: + found.state, found.version = "broken", None + found.error = agent_lookup._last_line(out.stderr) or agent_lookup._last_line(out.stdout) or f"it ended with code {out.returncode}" + return found def usable(kind: str) -> agent_lookup.Found: @@ -131,34 +151,41 @@ def workdir() -> Path: def through_interpreter(path: str, platform: str | None = None) -> bool: - return agent_lookup.windows(platform) and str(path).lower().endswith((".cmd", ".bat")) + return agent_lookup.windows(platform) and str(path).lower().endswith(command_script.SUFFIXES) def interpreter_safe(words: list) -> bool: - for word in words: - if not isinstance(word, (str, Path)): - return False - text = str(word) - if CMD_NEVER.search(text): - return False - if CMD_UNQUOTED.search(text) and not (" " in text or "\t" in text): - return False - return True + return command_script.safe(words) + + +def direct(path: str, env: dict | None = None, platform: str | None = None) -> list[str]: + if not through_interpreter(path, platform): + return [str(path)] + return command_script.resolve(path, env) or [str(path)] + + +def launch_words(cmd: list, env: dict | None = None, platform: str | None = None) -> list: + words = direct(cmd[0], env, platform) + list(cmd[1:]) if cmd else [] + if words and through_interpreter(words[0], platform) and not interpreter_safe(words): + raise LookupError(command_script.REFUSED) + return words + + +def interpreter_argv(cmd: list, platform: str | None = None, env: dict | None = None) -> list[str]: + return agent_lookup.start_argv(launch_words(cmd, env, platform), platform=platform) -def interpreter_argv(cmd: list, platform: str | None = None) -> list[str]: - if cmd and through_interpreter(cmd[0], platform) and not interpreter_safe(cmd): - raise LookupError(CMD_REFUSED) - return agent_lookup.start_argv(cmd, platform=platform) +def run(cmd: list, env: dict, timeout: float = CHECK_WAIT, platform: str | None = None): + return agent_lookup.run(launch_words(cmd, env, platform), env, timeout, platform) -def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None, platform: str | None = None) -> list[str]: +def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None, platform: str | None = None, env: dict | None = None) -> list[str]: cmd = [path, "--mcp-config", mcp_file, "--allowedTools", f"mcp__{TAB_ENTRY}", "--append-system-prompt", NOTE] if resume: cmd += ["--resume", resume] - if prompt and not through_interpreter(path, platform): + if prompt and not through_interpreter(direct(path, env, platform)[0], platform): cmd.append(prompt) - return interpreter_argv(cmd, platform) + return interpreter_argv(cmd, platform, env) def status() -> dict: @@ -182,13 +209,14 @@ def open_tab(prompt: str | None = None, cols: int = 100, rows: int = 30, fresh: raise LookupError(said(found)) title = "Claude Code (resumed)" if resume else "Claude Code" token, mcp_file = issue() + env = child_env(found.path) try: - session = terminal.open_session(str(workdir()), cols, rows, title, tab_argv(found.path, mcp_file, prompt or None, resume), child_env(found.path), "claude") + session = terminal.open_session(str(workdir()), cols, rows, title, tab_argv(found.path, mcp_file, prompt or None, resume, env=env), env, "claude") except BaseException: revoke(token) raise session.on_close.append(lambda: revoke(token)) - if prompt and through_interpreter(found.path): + if prompt and through_interpreter(direct(found.path, env)[0]): terminal.write(session.id, prompt + "\r") return session.describe() diff --git a/backend/app/services/command_script.py b/backend/app/services/command_script.py new file mode 100644 index 0000000..c8a1770 --- /dev/null +++ b/backend/app/services/command_script.py @@ -0,0 +1,66 @@ +import os +import re +from pathlib import Path + +NEVER = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]') +REFUSED = ("This program is a Windows command script, which starts through the command interpreter, and one of its words holds " + "a character that interpreter reads itself (& | < > ^ ( ) ! % \" or a control character), so it was not started. " + "Pass long or free text through standard input or a file if the program supports it.") +SUFFIXES = (".cmd", ".bat") +SCRIPTS = (".js", ".cjs", ".mjs") +HERE = re.compile(r"^%~?dp0%?[\\/]?", re.IGNORECASE) +QUOTED = re.compile(r'"([^"]*)"') +MAX_BYTES = 64 * 1024 + + +def safe(words: list) -> bool: + return all(isinstance(word, (str, Path)) and not NEVER.search(str(word)) for word in words) + + +def _text(shim: Path) -> str | None: + try: + if not shim.is_file() or shim.stat().st_size > MAX_BYTES: + return None + return shim.read_bytes().decode("utf-8", errors="replace") + except OSError: + return None + + +def _target(text: str) -> str | None: + line = next((ln for ln in reversed(text.splitlines()) if "%*" in ln), None) + if line is None: + return None + named = [HERE.sub("", word) for word in QUOTED.findall(line) if HERE.match(word)] + named = [word for word in named if word.lower() != "node.exe"] + return named[-1] if named and "%" not in named[-1] else None + + +def _inside(target: Path, shim: Path) -> bool: + folder = shim.parent.resolve() + root = folder.parent if folder.name.lower() == ".bin" else folder + return target.is_relative_to(root) + + +def _node(shim: Path, env: dict) -> str | None: + folders = [str(shim.parent)] + [p for p in (env.get("PATH") or "").split(";") if p] + return next((str(Path(f) / "node.exe") for f in folders if (Path(f) / "node.exe").is_file()), None) + + +def resolve(path: str | os.PathLike, env: dict | None = None) -> list[str] | None: + """The program an npm-style command script starts, as words to run without the command interpreter: [node, script] + for a JavaScript target, [program] for an .exe target. None when the script is not of that form or its target is + missing or outside the script's folder.""" + shim = Path(path) + text = _text(shim) if shim.suffix.lower() in SUFFIXES else None + rel = _target(text) if text else None + if not rel: + return None + target = Path(shim.parent, *[part for part in re.split(r"[\\/]+", rel) if part]).resolve() + if not target.is_file() or not _inside(target, shim): + return None + if target.suffix.lower() == ".exe": + return [str(target)] + if target.suffix.lower() in SCRIPTS: + node = _node(shim, os.environ if env is None else env) + return [node, str(target)] if node else None + return None diff --git a/backend/tests/cb03/test_services_claude_code_prompt.py b/backend/tests/cb03/test_services_claude_code_prompt.py index c60ba37..ff4def4 100644 --- a/backend/tests/cb03/test_services_claude_code_prompt.py +++ b/backend/tests/cb03/test_services_claude_code_prompt.py @@ -61,7 +61,18 @@ def test_a_command_script_refuses_a_word_that_is_not_text(): assert not claude_code.interpreter_safe([r"C:\npm\claude.cmd", None]) -@pytest.mark.parametrize("path", [r"C:\Program Files (x86)\npm\claude.cmd", r"C:\Users\me\AppData\Roaming\npm\claude.cmd"]) +@pytest.mark.parametrize("word", ["a (b)", "(a b)", "a b)", "say \"a b\"", "a b !c", "a\tb^c"]) +def test_a_command_script_refuses_those_words_even_when_they_hold_a_space(word): + with pytest.raises(LookupError, match="standard input or a file"): + claude_code.tab_argv(r"C:\npm\claude.cmd", "mcp.json", None, word, platform="win32") + + +def test_a_command_script_whose_own_path_holds_parentheses_is_refused(): + with pytest.raises(LookupError): + claude_code.tab_argv(r"C:\Program Files (x86)\npm\claude.cmd", "mcp.json", None, platform="win32") + + +@pytest.mark.parametrize("path", [r"C:\Program Files\npm\claude.cmd", r"C:\Users\me\AppData\Roaming\npm\claude.cmd"]) def test_a_command_script_still_starts_with_ordinary_words(path): argv = claude_code.tab_argv(path, r"C:\Users\me\data\mcp-1.json", None, "abc-123", platform="win32") assert argv[1] == "/c" diff --git a/backend/tests/cb03/test_services_command_script.py b/backend/tests/cb03/test_services_command_script.py new file mode 100644 index 0000000..64e0a7a --- /dev/null +++ b/backend/tests/cb03/test_services_command_script.py @@ -0,0 +1,136 @@ +from types import SimpleNamespace + +import pytest + +from app.services import agent_lookup, agent_programs, claude_code, command_script, terminal + +JS_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)\r\n\r\n' + 'endLocal & "%_prog%" "%dp0%\\node_modules\\tool\\cli.js" %*\r\n' +) +EXE_SHIM = '@ECHO off\r\nSETLOCAL\r\nSET dp0=%~dp0\r\nendLocal & "%dp0%\\node_modules\\tool\\bin\\tool.exe" %*\r\n' +OLD_SHIM = '@IF EXIST "%~dp0\\node.exe" (\r\n "%~dp0\\node.exe" "%~dp0\\node_modules\\tool\\cli.js" %*\r\n) ELSE (\r\n node "%~dp0\\node_modules\\tool\\cli.js" %*\r\n)\r\n' +PROMPT = 'make a "red & blue" poster at 100% | then (stop) !' + + +def make(folder, text, name="claude.cmd", target=("node_modules", "tool", "cli.js"), node=True): + folder.mkdir(parents=True, exist_ok=True) + shim = folder / name + shim.write_text(text, encoding="utf-8") + if target: + file = folder.joinpath(*target) + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text("", encoding="utf-8") + if node: + (folder / "node.exe").write_text("", encoding="utf-8") + return shim + + +def test_a_script_shim_resolves_to_node_and_its_script(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM) + words = command_script.resolve(shim, {"PATH": ""}) + assert words == [str((tmp_path / "npm" / "node.exe")), str((tmp_path / "npm" / "node_modules" / "tool" / "cli.js").resolve())] + + +def test_an_older_script_shim_resolves_the_same_way(tmp_path): + shim = make(tmp_path / "npm", OLD_SHIM) + assert command_script.resolve(shim, {"PATH": ""})[1].endswith("cli.js") + + +def test_node_is_taken_from_the_path_when_the_shim_folder_has_none(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM, node=False) + (tmp_path / "nodejs").mkdir() + (tmp_path / "nodejs" / "node.exe").write_text("", encoding="utf-8") + words = command_script.resolve(shim, {"PATH": str(tmp_path / "nodejs")}) + assert words[0] == str(tmp_path / "nodejs" / "node.exe") + + +def test_a_shim_without_any_node_is_not_resolved(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM, node=False) + assert command_script.resolve(shim, {"PATH": ""}) is None + + +def test_a_program_shim_resolves_to_the_program(tmp_path): + shim = make(tmp_path / "npm", EXE_SHIM, target=("node_modules", "tool", "bin", "tool.exe"), node=False) + assert command_script.resolve(shim, {"PATH": ""}) == [str((tmp_path / "npm" / "node_modules" / "tool" / "bin" / "tool.exe").resolve())] + + +@pytest.mark.parametrize("text", [ + "@echo off\r\necho hello\r\n", + '@echo off\r\n"%dp0%\\node_modules\\tool\\cli.js"\r\n', + '@echo off\r\n"%dp0%\\..\\elsewhere\\cli.js" %*\r\n', + '@echo off\r\n"%dp0%\\%OTHER%\\cli.js" %*\r\n', + '@echo off\r\n"%dp0%\\node_modules\\tool\\run.bat" %*\r\n', +]) +def test_other_command_scripts_are_not_resolved(tmp_path, text): + (tmp_path / "elsewhere").mkdir() + (tmp_path / "elsewhere" / "cli.js").write_text("", encoding="utf-8") + shim = make(tmp_path / "npm", text, target=("node_modules", "tool", "run.bat")) + assert command_script.resolve(shim, {"PATH": ""}) is None + + +def test_a_missing_target_is_not_resolved(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM, target=None) + assert command_script.resolve(shim, {"PATH": ""}) is None + + +def test_a_resolved_shim_starts_without_the_interpreter_and_keeps_every_word(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM) + argv = claude_code.tab_argv(str(shim), "mcp.json", PROMPT, platform="win32", env={"PATH": ""}) + assert argv[0] == str(tmp_path / "npm" / "node.exe") + assert "/c" not in argv + assert argv[-1] == PROMPT + + +def test_an_unresolved_shim_still_refuses_words_the_interpreter_would_read(tmp_path): + shim = make(tmp_path / "npm", "@echo off\r\necho hello\r\n", target=None) + with pytest.raises(LookupError): + claude_code.interpreter_argv([str(shim), "a&b"], platform="win32", env={"PATH": ""}) + + +def test_a_resolved_tab_gets_its_prompt_on_the_command_line_not_typed(monkeypatch, tmp_path): + shim = make(tmp_path / "npm", JS_SHIM) + session = SimpleNamespace(id="s1", on_close=[], describe=lambda: {"id": "s1"}) + started, written = [], [] + monkeypatch.setattr(terminal, "SESSIONS", {}) + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(claude_code, "usable", lambda kind: SimpleNamespace(state="runs", path=str(shim))) + monkeypatch.setattr(claude_code, "issue", lambda: ("token", "mcp.json")) + monkeypatch.setattr(claude_code, "child_env", lambda p=None, extra=None: {"PATH": ""}) + monkeypatch.setattr(claude_code, "workdir", lambda: "here") + monkeypatch.setattr(terminal, "open_session", lambda cwd, cols, rows, title, argv, env, kind: started.append(argv) or session) + monkeypatch.setattr(terminal, "write", lambda sid, data: written.append((sid, data))) + claude_code.open_tab(PROMPT) + assert written == [] + assert started[0][-1] == PROMPT + + +def test_the_version_check_of_an_unresolved_unsafe_script_runs_nothing(monkeypatch): + ran = [] + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(agent_lookup, "run", lambda *a, **k: ran.append(a)) + found = claude_code.checked_script(agent_lookup.Found("claude", "Claude Code", path=r"C:\a&b\claude.cmd"), {"PATH": ""}) + assert found.state == "broken" + assert "standard input or a file" in found.error + assert ran == [] + + +def test_the_version_check_and_sign_in_check_run_the_resolved_program(monkeypatch, tmp_path): + shim = make(tmp_path / "a&b" / "npm", JS_SHIM) + ran = [] + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(claude_code, "child_env", lambda p=None, extra=None: {"PATH": ""}) + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False) + + def fake_run(cmd, env, timeout=15.0, platform=None): + ran.append(cmd) + return SimpleNamespace(returncode=0, stdout='{"loggedIn": true}' if "auth" in cmd else "2.0.1 (tool)", stderr="") + + monkeypatch.setattr(agent_lookup, "run", fake_run) + found = claude_code.checked_script(agent_lookup.Found("claude", "Claude Code", path=str(shim)), {"PATH": ""}) + assert (found.state, found.version) == ("runs", "2.0.1") + assert agent_programs.claude_signed_in(str(shim)) is True + assert [cmd[0] for cmd in ran] == [str(tmp_path / "a&b" / "npm" / "node.exe")] * 2 + assert ran[0][2:] == ["--version"] and ran[1][2:] == ["auth", "status"]