diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 3434bf1..348ab81 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -21,6 +21,8 @@ Decisions, reasons and anything left out, newest first. Code carries no comments ## Unreleased (2026-11-19): four agent programs, found by the family's finder, and tests that start none of them - `app/services/agent_lookup.py` (new) is the family's finder, version 1.0.1, copied unchanged from FormVis and never edited here; `setup/agents.py` holds the hash for each version. It looks, in order, at the development override variable, the engine's PATH, the known install folders and the person's shell PATH, and answers three ways: runs, found but does not start, not found. The reason: an app started from the Dock, the Start menu or a desktop launcher gets the system's short PATH, and a bare PATH search called installed programs missing. +- `app/services/consent.py` :: `details`, `declared`, `unknown`, `unknown_refusal`, `check` · The lines in a request to allow an outside agent's call are built only from the arguments the tool's schema declares; a call that names any other argument is refused before anyone is asked, with a message that names the extra arguments. Path, folder and target arguments come first, then the rest in schema order. Text values are quoted and kept printable; a long path shows its end and any other long value its start, each marked with its full length; a list shows five items and how many more; past eight lines the last says how many arguments are not shown. The first line says the arguments are as sent by the named agent and not checked by formtools. The reason: the person decides from these lines, so they show only what the tool will act on and say where it came from. +- `agent_lookup.py` 1.0.2 · On Windows a `.cmd` or `.bat` program is started as the program its npm-style shim names (`node` with the script, or the `.exe`), so the words reach it unchanged. A batch file it cannot read that way still goes through the command interpreter, and `start_argv` raises `StartRefused` (an `OSError`) for any word with a control character (0x00 to 0x1f, 0x7f) or one of `& | < > ^ ( ) ! %` and the double quote, whether or not the word has spaces; the message says to pass long text through standard input or a file. The reason: the interpreter and the shim's `%*` read the whole line again, quotes do not protect a word there, and backslash escaping does not hold. When the program's own path needs quotes, `cmd /c` keeps the line only with no other word that needs quotes, so that is refused too. A `node` found on PATH that is itself a `.cmd` or `.bat` is not used for a direct start. - `app/services/claude_code.py` :: `child_env`, `located`, `usable`, `said`, `cli`, `_signed_in`, `info`, `start`, `program`, `terminal_argv`, `open_terminal`. Every look for Claude Code and every start goes through the finder. `_from_login_shell`, `CANDIDATES` and `SYSTEM_PATHS` are gone; the finder holds that list. `child_env` takes the program's path so its own folder is first on PATH (a node script finds the node beside it). formtools has no path setting, so `setting()` answers `None`. Override variables: `FORMTOOLS_CLAUDE_BIN`, `FORMTOOLS_CODEX_BIN`, `FORMTOOLS_CURSOR_BIN`, `FORMTOOLS_ANTIGRAVITY_BIN`. - `app/services/agent_programs.py` :: `PROGRAMS`, `find`, `status`, `_describe`, `open_terminal`. Antigravity (`agy`) is the fourth program. `status` and `programs` keep their names and add the finder's fields per program: `finding` (`runs`, `broken`, `missing`), `how`, `looked`, `error`, `said`. `installed` is true only when `--version` ran with exit code 0. Antigravity's `signedIn` stays `None`: it has no status command. `_version` is gone; the finder reads the version. - The Antigravity tab: `tab_folder`, `write_tab_entry`, `remove_tab_entry`. Antigravity reads its MCP servers from a file in its workspace, so its tab runs in a folder of formtools's own, `/AgentTabs/antigravity`, and gets the entry `formtools_tab` (the address and the tab's token) in `.agents/mcp_config.json` there, mode 0600, written whole, every other entry and key kept. The entry is taken out when the tab closes, only while it still carries that tab's token. Decision: not the shared `/Agent` folder the other tabs use, because `FORMTOOLS_AGENT_DIR` can point that at a folder of the person's, and a token does not belong there. Two Antigravity tabs share the one entry; the newer tab's token wins. The Codex and Cursor tabs are unchanged (token in the environment, the per-tab file named by `FORMTOOLS_MCP_CONFIG`). diff --git a/backend/app/core/filetypes.py b/backend/app/core/filetypes.py index c331161..73c980b 100644 --- a/backend/app/core/filetypes.py +++ b/backend/app/core/filetypes.py @@ -1,5 +1,7 @@ import mimetypes +INERT_HEADERS = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": "sandbox"} + FAMILY = frozenset("fvd fmv formvis fc fmw fsc fequeue fldb".split()) RAW = frozenset( diff --git a/backend/app/routers/fs.py b/backend/app/routers/fs.py index 783070a..e358d5a 100644 --- a/backend/app/routers/fs.py +++ b/backend/app/routers/fs.py @@ -8,7 +8,7 @@ from fastapi.responses import FileResponse from app.core.errors import ApiError -from app.core.filetypes import classify, content_type, ext_of +from app.core.filetypes import INERT_HEADERS, classify, content_type, ext_of router = APIRouter(prefix="/api") @@ -212,4 +212,4 @@ def file_raw(path: str) -> FileResponse: pass except OSError: raise ApiError(400, "formtools is not allowed to read that file") - return FileResponse(target, media_type=content_type(target.name), content_disposition_type="inline") + return FileResponse(target, media_type=content_type(target.name), content_disposition_type="inline", headers=INERT_HEADERS) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..9f665e3 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.0.2" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -359,13 +359,75 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class StartRefused(OSError): + pass + + +SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%*?<>|\r\n]+)"\s*%\*') +SHIM_BYTES = 65536 +CMD_SPECIAL = frozenset('&|<>^()!%"') +CMD_REFUSED = ("this program is started through the Windows command interpreter, which reads {what} as commands even inside quotes, " + "so the start was refused; remove them, or pass long text through standard input or a file if the program supports it") + + +def shim_target(path: str, env: dict) -> list[str] | None: + """The program an npm-style .cmd shim starts, so it can be started directly: [node, script] for a script, [program] for + an .exe beside the shim. None when the shim is not one this recognises or its target is missing.""" + try: + with open(path, "rb") as f: + text = f.read(SHIM_BYTES).decode("utf-8", "replace") + except OSError: + return None + found = SHIM_TARGET.search(text) + if not found: + return None + folder = Path(path).parent + target = folder.joinpath(*found.group(1).split("\\")) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe": + return [str(target)] + if target.suffix.lower() not in (".js", ".cjs", ".mjs"): + return None + beside = folder / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH") or None) + return [node, str(target)] if node and not node.lower().endswith((".cmd", ".bat")) else None + + +def _quoted(word: str) -> bool: + return " " in word or "\t" in word or not word + + +def cmd_safe(words: list[str]) -> None: + """Refuses any word the command interpreter could read as more than text, quoted or not: a control character or one of + & | < > ^ ( ) ! % and the double quote. When the program itself is quoted, cmd /c keeps the line only when no other + word needs quotes, so that is refused too.""" + for word in words: + if any(ord(ch) < 32 or ord(ch) == 127 for ch in word): + raise StartRefused(CMD_REFUSED.format(what="line breaks and control characters")) + if CMD_SPECIAL.intersection(word): + raise StartRefused(CMD_REFUSED.format(what='the characters & | < > ^ ( ) ! % "')) + if _quoted(words[0]) and any(_quoted(word) for word in words[1:]): + raise StartRefused("this program is in a folder with spaces and is started through the Windows command interpreter, which " + "drops the quotes when another word has spaces, so the start was refused; remove the spaces from the other " + "words, move the program to a folder without spaces, 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 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 is started as the program its shim names when + it can be read, otherwise through the command interpreter with every word checked by cmd_safe.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not words[0].lower().endswith((".cmd", ".bat")): + return words + direct = shim_target(words[0], env) + if direct: + return [*direct, *words[1:]] + cmd_safe(words) + return [env.get("COMSPEC") or "cmd.exe", "/c", *words] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/app/services/consent.py b/backend/app/services/consent.py index f2d3ee8..0fb2b2d 100644 --- a/backend/app/services/consent.py +++ b/backend/app/services/consent.py @@ -17,7 +17,12 @@ WHERE = "formtools, Settings, Integration, Outside agents" BLOCKED = f"Outside agents are blocked in {WHERE}, so this call was refused. Tell the person where to change it and stop; do not retry." BLOCKED_INSIDE = f"Agents are blocked in {WHERE}, and that includes this tab, so this call was refused. Tell the person where to change it and stop; do not retry." -PUBLIC = ("id", "tool", "title", "effect", "at", "agent", "agentNamed", "what", "answers", "alwaysScope", "expires") +PUBLIC = ("id", "tool", "title", "effect", "at", "agent", "agentNamed", "what", "details", "answers", "alwaysScope", "expires") +DETAIL_LINES = 8 +VALUE_CHARS = 160 +ITEM_CHARS = 60 +LIST_SHOWN = 5 +PATH_WORDS = ("path", "folder", "dir", "dest", "target", "out", "input") DENIED = "The person did not allow this in the formtools window, so it was refused. Do not retry unless they ask you to." NO_WINDOW = f"formtools asks the person before an outside agent changes anything, and no formtools window is open to ask. Ask them to open formtools, or to choose Allowed in {WHERE}." TIMED_OUT = "Nobody answered in the formtools window in time, so this call was refused. Ask the person to look at the formtools window, then retry." @@ -88,6 +93,91 @@ def what(tool, arguments) -> str: return f"run {tool.name}" +def _plain(text: str) -> str: + return "".join(ch if ch.isprintable() else f"\\u{ord(ch):04x}" for ch in text) + + +def _resolved(value: str) -> str: + parts = value.replace(os.altsep or os.sep, os.sep).split(os.sep) + if ".." not in parts or not os.path.isabs(value): + return value + head, name = os.path.split(value.rstrip(os.sep)) + return os.path.realpath(value) if name == ".." else os.path.join(os.path.realpath(head), name) + + +def _text(value) -> tuple[str, bool]: + if isinstance(value, str): + return _resolved(value), True + try: + return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str), False + except ValueError: + return str(value), False + + +def _quote(text: str) -> str: + return '"' + text.replace('"', '\\"') + '"' + + +def _value(value, pathy: bool, limit: int) -> str: + text, string = _text(value) + text = _plain(text) + if len(text) <= limit: + return _quote(text) if string else text + cut = "..." + text[-limit:] if pathy else text[:limit] + "..." + shown = _quote(cut) if string else cut + return f"{shown} (shortened from {len(text)} characters)" + + +def _shown(value, pathy: bool) -> str: + if not isinstance(value, list): + return _value(value, pathy, VALUE_CHARS) + items = [_value(v, pathy, ITEM_CHARS) for v in value[:LIST_SHOWN]] + more = len(value) - LIST_SHOWN + return ", ".join(items) + (f", and {more} more" if more > 0 else "") if items else "[]" + + +def _pathy(name: str) -> bool: + low = name.lower() + return any(word in low for word in PATH_WORDS) + + +def declared(tool) -> list[str]: + schema = tool.schema.get("properties") if isinstance(tool.schema, dict) else None + return list(schema) if isinstance(schema, dict) else [] + + +def unknown(tool, arguments) -> list[str]: + if not isinstance(arguments, dict): + return [] + known = set(declared(tool)) + return [str(name) for name in arguments if name not in known] + + +def _names(tool, arguments: dict) -> list[str]: + skip = {"id"} if tool.name == "run_command" else set() + known = [name for name in declared(tool) if name in arguments and name not in skip] + return [*(n for n in known if _pathy(n)), *(n for n in known if not _pathy(n))] + + +def details(tool, arguments, agent: str = "") -> list[str]: + if not isinstance(arguments, dict): + return [] + lines = [f"{_plain(name)}: {_shown(arguments[name], _pathy(name))}" for name in _names(tool, arguments)] + if not lines: + return [] + if len(lines) > DETAIL_LINES: + lines = [*lines[:DETAIL_LINES - 1], f"and {len(lines) - DETAIL_LINES + 1} more arguments not shown"] + who = _plain(agent or agents.UNNAMED)[:80] + return [f"Arguments as sent by {who}, not checked by formtools:", *lines] + + +def unknown_refusal(tool, names: list[str]) -> str: + listed = ", ".join(_quote(_plain(n)[:40]) for n in names[:LIST_SHOWN]) + more = f" and {len(names) - LIST_SHOWN} more" if len(names) > LIST_SHOWN else "" + return (f"This call gave {tool.name} arguments it does not take ({listed}{more}), so it was refused before asking the person. " + "Send only the arguments the tool lists, then retry.") + + def _tell(kind: str, **fields) -> None: try: from_thread.run(bridge.notify, {"t": kind, **fields}) @@ -121,11 +211,14 @@ def check(tool, inapp: bool, agent: str = "", arguments: dict | None = None) -> return BLOCKED_INSIDE if inapp else BLOCKED if inapp or mode == "allowed": return None + extra = unknown(tool, arguments) + if extra: + return unknown_refusal(tool, extra) if not bridge.connected(): return NO_WINDOW now = time.time() item = {"id": secrets.token_urlsafe(12), "tool": tool.name, "title": tool.description, "effect": tool.effect, "at": now, "answer": None, "done": threading.Event(), - "agent": agent or agents.UNNAMED, "agentNamed": bool(agent) and agent != agents.UNNAMED, "what": what(tool, arguments), + "agent": agent or agents.UNNAMED, "agentNamed": bool(agent) and agent != agents.UNNAMED, "what": what(tool, arguments), "details": details(tool, arguments, agent), "answers": ["deny", "once", "always"] if seal.available() else ["deny", "once"], "alwaysScope": "all", "expires": now + WAIT} with _lock: _pending[item["id"]] = item diff --git a/backend/app/tools/desktop/__init__.py b/backend/app/tools/desktop/__init__.py index 3636a70..64e30a6 100644 --- a/backend/app/tools/desktop/__init__.py +++ b/backend/app/tools/desktop/__init__.py @@ -15,7 +15,7 @@ def hosts_read_tool(_: dict) -> dict: def env_read_tool(args: dict) -> dict: scope = args.get("scope") - return envvars.scopes(str(scope) if scope else None) + return envvars.for_agents(envvars.scopes(str(scope) if scope else None)) registry.register( @@ -33,7 +33,7 @@ def env_read_tool(args: dict) -> dict: ), McpTool( "env_read", - "Read environment variables by scope: process (this engine), user and system where the system has them. Each scope says whether the window can edit it and where it is stored. Read only; edits are made in the formtools window.", + "Read environment variables by scope: process (this engine), user and system where the system has them. Each scope says whether the window can edit it and where it is stored. Read only; edits are made in the formtools window. A variable whose name or value looks like a key, token, password or signed-in address comes back with an empty value and hidden true; the window shows it.", ENV_SCHEMA, env_read_tool, effect=READS, diff --git a/backend/app/tools/desktop/envvars.py b/backend/app/tools/desktop/envvars.py index b0f7faa..08b9bda 100644 --- a/backend/app/tools/desktop/envvars.py +++ b/backend/app/tools/desktop/envvars.py @@ -11,6 +11,12 @@ POSIX_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") PLAIN_VALUE = re.compile(r"^[A-Za-z0-9_@%+=:,./~-]+$") LINE_NAME = re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=") +SECRET_NAME = re.compile(r"KEY|TOKEN|SECRET|PASS|CREDENTIAL|CREDS|AUTH|COOKIE|SESSION|PRIVATE|SIGNATURE|DSN|CERT|_PWD$|(^|_)PAT($|_)", re.I) +SECRET_VALUE = re.compile( + r"://[^/\s@]+@|[?&][^=&]*(token|key|secret|sig|password|auth)[^=&]*=|-----BEGIN|^(sk|pk|rk)[-_]" + r"|^(gh[pousr]_|github_pat_|glpat-|xox[abpsr]-|hf_|npm_[A-Za-z0-9]{20})|^(AKIA|ASIA)[A-Z0-9]{12}|^AIza|^ya29\.|^eyJ[A-Za-z0-9_-]{8,}\.", + re.I, +) MANAGED_FILE = "60-formtools.conf" MANAGED_HEADER = "# Variables set from formtools. Other environment.d files are left alone.\n" USER_KEY = "Environment" @@ -44,6 +50,20 @@ def sorted_vars(items: dict[str, str]) -> list[dict]: return [{"name": name, "value": items[name]} for name in sorted(items, key=lambda key: (key.casefold(), key))] +def secret_like(name: str, value: str) -> bool: + return bool(SECRET_NAME.search(name) or SECRET_VALUE.search(value)) + + +def for_agents(found: dict) -> dict: + return { + **found, + "scopes": [ + {**scope, "vars": [{**row, "value": "", "hidden": True} if secret_like(row["name"], row["value"]) else row for row in scope["vars"]]} + for scope in found["scopes"] + ], + } + + def process_scope() -> dict: return { "id": "process", diff --git a/backend/app/tools/model/router.py b/backend/app/tools/model/router.py index 515bca4..fa41ba5 100644 --- a/backend/app/tools/model/router.py +++ b/backend/app/tools/model/router.py @@ -4,13 +4,14 @@ from fastapi.responses import FileResponse from pydantic import BaseModel +from app.core.filetypes import INERT_HEADERS from app.routers.fs import absolute from app.tools.model import assets, service router = APIRouter(prefix="/api/model") CACHE_HEADER = {"Cache-Control": "private, max-age=300"} -ASSET_HEADERS = {"Cache-Control": "private, max-age=300", "X-Content-Type-Options": "nosniff"} +ASSET_HEADERS = {"Cache-Control": "private, max-age=300", **INERT_HEADERS} class ConvertRequest(BaseModel): diff --git a/backend/tests/agents/test_windows_start.py b/backend/tests/agents/test_windows_start.py new file mode 100644 index 0000000..cdfa236 --- /dev/null +++ b/backend/tests/agents/test_windows_start.py @@ -0,0 +1,155 @@ +import stat + +import pytest + +NPM_SHIM = """@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\\node.exe" ( + SET "_prog=%dp0%\\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %* +""" +PROMPT = 'Rename the files in "Q1 & Q2" to dates, 100% done' +ENV = {"COMSPEC": "C:\\Windows\\system32\\cmd.exe", "PATH": ""} + + +def start(cmd, env=ENV): + from app.services import agent_lookup + + return agent_lookup.start_argv(cmd, env, "win32") + + +@pytest.fixture +def npm_folder(tmp_path): + folder = tmp_path / "npm" + script = folder / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("console.log('stand-in')\n", encoding="utf-8") + (folder / "claude.cmd").write_text(NPM_SHIM, encoding="utf-8") + return folder, script + + +def test_an_npm_shim_with_node_beside_it_starts_node_directly_with_the_prompt_untouched(npm_folder): + folder, script = npm_folder + (folder / "node.exe").write_bytes(b"") + argv = start([str(folder / "claude.cmd"), "--", PROMPT]) + assert argv == [str(folder / "node.exe"), str(script), "--", PROMPT] + + +def test_an_npm_shim_without_node_beside_it_starts_the_node_on_the_path(npm_folder, tmp_path): + folder, script = npm_folder + tools = tmp_path / "tools" + tools.mkdir() + node = tools / "node" + node.write_text("#!/bin/sh\n", encoding="utf-8") + node.chmod(node.stat().st_mode | stat.S_IXUSR) + argv = start([str(folder / "claude.cmd"), "--", PROMPT], {**ENV, "PATH": str(tools)}) + assert argv == [str(node), str(script), "--", PROMPT] + + +def test_a_shim_that_names_an_exe_beside_it_starts_that_program(tmp_path): + (tmp_path / "bin").mkdir() + (tmp_path / "bin" / "agent.exe").write_bytes(b"") + (tmp_path / "agent.cmd").write_text('@"%~dp0\\bin\\agent.exe" %*\r\n', encoding="utf-8") + assert start([str(tmp_path / "agent.cmd"), "-p", "a&b"]) == [str(tmp_path / "bin" / "agent.exe"), "-p", "a&b"] + + +@pytest.fixture +def plain_bat(tmp_path): + bat = tmp_path / "claude.bat" + bat.write_text("@echo off\r\nrem nothing to read here\r\n", encoding="utf-8") + return str(bat) + + +def test_an_unknown_batch_file_goes_through_the_interpreter_when_every_word_is_plain_text(plain_bat): + words = [plain_bat, "--allowedTools", "a,b", "--", "Rename the files to dates"] + assert start(words) == [ENV["COMSPEC"], "/c", *words] + + +SPECIALS = ["&", "|", "<", ">", "^", "(", ")", "!", "%", '"'] +CONTROLS = ["\x00", "\n", "\r", "\t", "\x1b", "\x1f", "\x7f"] + + +@pytest.mark.parametrize("word", [f"a{ch}b" for ch in SPECIALS] + [f"Q1 {ch} Q2" for ch in SPECIALS] + ["%USERPROFILE%", PROMPT]) +def test_an_unknown_batch_file_refuses_interpreter_characters_with_or_without_spaces(plain_bat, word): + from app.services import agent_lookup + + with pytest.raises(agent_lookup.StartRefused) as refused: + start([plain_bat, "--", word]) + assert "& | < > ^ ( ) ! %" in str(refused.value) + assert "standard input or a file" in str(refused.value) + assert isinstance(refused.value, OSError) + + +@pytest.mark.parametrize("ch", CONTROLS) +def test_an_unknown_batch_file_refuses_control_characters(plain_bat, ch): + from app.services import agent_lookup + + with pytest.raises(agent_lookup.StartRefused) as refused: + start([plain_bat, "--", f"one{ch}two"]) + assert "control characters" in str(refused.value) + + +@pytest.mark.parametrize("ch", SPECIALS) +def test_an_unknown_batch_file_refuses_interpreter_characters_in_an_option_value(plain_bat, ch): + from app.services import agent_lookup + + with pytest.raises(agent_lookup.StartRefused): + start([plain_bat, f"--allowedTools=a{ch}b"]) + + +def test_an_npm_shim_passes_interpreter_characters_unchanged_because_no_interpreter_runs(npm_folder): + folder, script = npm_folder + (folder / "node.exe").write_bytes(b"") + words = [f"x{ch}y" for ch in SPECIALS] + ["line one\nline two"] + argv = start([str(folder / "claude.cmd"), "--", *words]) + assert argv == [str(folder / "node.exe"), str(script), "--", *words] + assert ENV["COMSPEC"] not in argv + + +def test_a_program_that_is_not_a_batch_file_is_started_as_given_on_windows(): + assert start(["C:\\Tools\\claude.exe", "--", PROMPT]) == ["C:\\Tools\\claude.exe", "--", PROMPT] + + +@pytest.fixture +def spaced_bat(tmp_path): + folder = tmp_path / "Program Files" + folder.mkdir() + bat = folder / "claude.bat" + bat.write_text("@echo off\r\n", encoding="utf-8") + return str(bat) + + +def test_a_batch_file_in_a_folder_with_spaces_runs_when_the_other_words_are_plain(spaced_bat): + words = [spaced_bat, "--allowedTools", "a,b"] + assert start(words) == [ENV["COMSPEC"], "/c", *words] + + +@pytest.mark.parametrize("word", ["Q1 & Q2", "a&b", "x (draft)", "two words"]) +def test_a_batch_file_in_a_folder_with_spaces_refuses_operators_and_other_words_with_spaces(spaced_bat, word): + from app.services import agent_lookup + + with pytest.raises(agent_lookup.StartRefused): + start([spaced_bat, "--", word]) + + +def test_an_npm_shim_whose_node_on_the_path_is_a_batch_file_goes_through_the_checked_interpreter(npm_folder, tmp_path, monkeypatch): + from app.services import agent_lookup + + folder, _ = npm_folder + node = tmp_path / "node.cmd" + node.write_text("@echo off\r\n", encoding="utf-8") + monkeypatch.setattr(agent_lookup.shutil, "which", lambda name, path=None: str(node)) + shim = str(folder / "claude.cmd") + assert start([shim, "--version"]) == [ENV["COMSPEC"], "/c", shim, "--version"] diff --git a/backend/tests/core/test_fs_routes.py b/backend/tests/core/test_fs_routes.py index 7f10974..3a0b59d 100644 --- a/backend/tests/core/test_fs_routes.py +++ b/backend/tests/core/test_fs_routes.py @@ -184,3 +184,12 @@ def test_home_route_names_the_home_folder_first_and_lists_known_folders_that_exi listed = {root["name"] for root in reply["roots"][1:]} for name in ("Desktop", "Documents", "Downloads", "Movies", "Videos", "Music"): assert (name in listed) == (home / name).is_dir() + + +@pytest.mark.parametrize("name,body", [("page.html", b""), ("drawing.svg", b""), ("blob.bin", b"\x00")]) +def test_raw_file_route_serves_files_as_inert_documents_that_cannot_run_script(client, tmp_path, name, body): + (tmp_path / name).write_bytes(body) + reply = client.get("/api/file/raw", params={"path": str(tmp_path / name)}) + assert reply.content == body + assert reply.headers["x-content-type-options"] == "nosniff" + assert reply.headers["content-security-policy"] == "sandbox" diff --git a/backend/tests/media/test_model_assets_convert.py b/backend/tests/media/test_model_assets_convert.py index ad592c0..cd40c57 100644 --- a/backend/tests/media/test_model_assets_convert.py +++ b/backend/tests/media/test_model_assets_convert.py @@ -273,3 +273,11 @@ def test_an_asset_request_for_a_model_that_is_gone_is_a_404(client, folder): def test_a_folder_named_as_the_asset_is_not_served(client, folder): (folder / "textures").mkdir() assert asset(client, folder / "tri.gltf", "textures").status_code == 404 + + +def test_an_asset_beside_a_model_is_served_as_an_inert_document_that_cannot_run_script(client, folder): + (folder / "page.html").write_bytes(b"") + answer = asset(client, folder / "tri.gltf", "page.html") + assert answer.content == b"" + assert answer.headers["x-content-type-options"] == "nosniff" + assert answer.headers["content-security-policy"] == "sandbox" diff --git a/backend/tests/test_consent.py b/backend/tests/test_consent.py index e6da17f..77aee80 100644 --- a/backend/tests/test_consent.py +++ b/backend/tests/test_consent.py @@ -332,3 +332,99 @@ def test_no_mcp_tool_can_reach_the_choice(app): from app.routers import mcp assert not [t.name for t in mcp.all_tools() if "access" in t.name or "consent" in t.name] + + +HEADER = "Arguments as sent by an outside agent, not checked by formtools:" + + +def fake_tool(*names, name="probe_tool"): + return types.SimpleNamespace(name=name, schema={"type": "object", "properties": {n: {} for n in names}}) + + +def test_a_request_shows_the_paths_and_flags_the_call_will_act_on_as_sent_by_the_agent(keychain, window): + thread, seen = answer_when_asked("deny") + paths = [f"/shoot/photo-{n}.jpg" for n in range(8)] + call = {**CALL, "params": {"name": "trash_files", "arguments": {"paths": paths}}} + assert result(dispatch(call))[0] is True + thread.join() + details = seen[0]["details"] + assert details[0] == HEADER + assert details[1] == "paths: " + ", ".join(f'"{p}"' for p in paths[:5]) + ", and 3 more" + + +def test_a_call_with_arguments_the_tool_does_not_declare_is_refused_before_asking(keychain, window): + from app.services import consent + + call = {**CALL, "params": {"name": "trash_files", "arguments": {"paths": ["/shoot/a.jpg"], "note": "fine"}}} + error, text = result(dispatch(call)) + assert error and '"note"' in text and "does not take" in text + assert consent.pending() == [] + + +def test_details_are_built_only_from_declared_arguments_with_path_keys_first(): + from app.services import consent + + tool = fake_tool("mode", "overwrite", "path", "folder", "target") + lines = consent.details(tool, {"overwrite": True, "mode": "copy", "target": "/b", "folder": "/a", "path": "/c", "extra": "x"}) + assert lines == [HEADER, 'path: "/c"', 'folder: "/a"', 'target: "/b"', 'mode: "copy"', "overwrite: true"] + assert consent.unknown(tool, {"path": "/c", "extra": "x"}) == ["extra"] + + +def test_details_say_how_many_arguments_were_left_out(): + from app.services import consent + + names = [f"opt{n}" for n in range(12)] + lines = consent.details(fake_tool(*names), {n: 1 for n in names}, "probe-agent") + assert lines[0] == "Arguments as sent by probe-agent, not checked by formtools:" + assert len(lines) == 1 + consent.DETAIL_LINES + assert lines[-1] == "and 5 more arguments not shown" + + +def test_a_long_path_shows_its_end_and_is_marked_as_shortened(): + from app.services import consent + + long_path = "/shoot/" + "a" * 300 + "/keep-me.jpg" + [_, line] = consent.details(fake_tool("path"), {"path": long_path}) + assert line.endswith(f'/keep-me.jpg" (shortened from {len(long_path)} characters)') + assert line.startswith('path: "...') + + +def test_a_long_value_that_is_not_a_path_shows_its_start_and_is_marked_as_shortened(): + from app.services import consent + + [_, line] = consent.details(fake_tool("pattern"), {"pattern": "x" * 500}) + assert line == 'pattern: "' + "x" * consent.VALUE_CHARS + '..." (shortened from 500 characters)' + + +def test_values_are_quoted_and_kept_printable(): + from app.services import consent + + [_, line] = consent.details(fake_tool("name"), {"name": 'a"b\nc'}) + assert line == 'name: "a\\"b\\u000ac"' + assert all(ch.isprintable() for ch in line) + + +def test_a_command_request_shows_its_parameters_and_keeps_lines_printable(keychain, window): + thread, seen = answer_when_asked("deny") + named = {"name": "run_command", "arguments": {"id": "rename-apply", "params": {"folder": "/tmp/a\nb", "pattern": "x" * 500}}} + assert result(dispatch({**CALL, "params": named}))[0] is True + thread.join() + asked = seen[0] + assert asked["what"] == "run the command rename-apply" + header, line = asked["details"] + assert header == HEADER + assert line.startswith('params: {"folder": "/tmp/a\\nb", "pattern": "xxx') + assert all(ch.isprintable() for ch in line) and "(shortened from" in line + + +def test_a_request_shows_where_a_path_with_parent_steps_really_points(keychain, window, tmp_path): + thread, seen = answer_when_asked("deny") + real = tmp_path.resolve() + long_path = str(real / "shoot" / ("a" * 300) / ".." / ".." / "Documents") + named = {"name": "trash_files", "arguments": {"paths": [long_path, "/shoot/\u202emoc.jpg"]}} + assert result(dispatch({**CALL, "params": named}))[0] is True + thread.join() + target = str(real / "Documents") + shown = target if len(target) <= 60 else "..." + target[-60:] + tail = "" if len(target) <= 60 else f" (shortened from {len(target)} characters)" + assert seen[0]["details"] == [HEADER, f'paths: "{shown}"{tail}, "/shoot/\\u202emoc.jpg"'] diff --git a/backend/tests/utilities/test_utilities_desktop.py b/backend/tests/utilities/test_utilities_desktop.py index 45a47c1..6aea288 100644 --- a/backend/tests/utilities/test_utilities_desktop.py +++ b/backend/tests/utilities/test_utilities_desktop.py @@ -290,3 +290,28 @@ def test_a_value_with_a_dollar_sign_reads_back_literally_in_the_environment_d_fo client.post("/api/env", json={"scope": "user", "name": "PRICE", "value": "cost$HOME"}) line = [row for row in profile.read_text(encoding="utf-8").splitlines() if row.startswith("PRICE=")][0] assert environment_d_value(line) == "cost$HOME" + + +def test_an_agent_reading_the_environment_gets_secret_values_hidden_while_the_window_sees_them(client, monkeypatch): + secrets = {"FORM_TEST_API_KEY": "sk-test-1", "FORM_TEST_TOKEN": "t-2", "FORM_TEST_PASSWORD": "p-3", "FORM_TEST_DB": "postgres://me:pw@db.example/app"} + for name, value in {**secrets, "FORM_TEST_PLAIN": "kept"}.items(): + monkeypatch.setenv(name, value) + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "env_read", "arguments": {"scope": "process"}}}) + rows = {row["name"]: row for row in json.loads(reply.json()["result"]["content"][0]["text"])["scopes"][0]["vars"]} + for name in secrets: + assert rows[name]["value"] == "" and rows[name]["hidden"] is True + assert rows["FORM_TEST_PLAIN"] == {"name": "FORM_TEST_PLAIN", "value": "kept"} + text = reply.json()["result"]["content"][0]["text"] + assert not [value for value in secrets.values() if value in text] + window = {row["name"]: row["value"] for row in client.get("/api/env").json()["scopes"][0]["vars"]} + assert all(window[name] == value for name, value in secrets.items()) + + +def test_an_agent_reading_the_environment_gets_well_known_token_values_hidden_whatever_the_name(client, monkeypatch): + secrets = {"FORM_TEST_GH": "ghp_" + "a" * 36, "FORM_TEST_SMTP_PASS": "p-1", "FORM_TEST_MYSQL_PWD": "p-2", "FORM_TEST_HOOK": "https://hooks.example/x?access_token=t-3", "FORM_TEST_REMOTE": "https://t-4@git.example/repo"} + for name, value in {**secrets, "FORM_TEST_SITE": "https://example.com/a?page=2"}.items(): + monkeypatch.setenv(name, value) + reply = client.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "env_read", "arguments": {"scope": "process"}}}) + rows = {row["name"]: row for row in json.loads(reply.json()["result"]["content"][0]["text"])["scopes"][0]["vars"]} + assert [name for name in secrets if rows[name]["value"] != "" or rows[name].get("hidden") is not True] == [] + assert rows["FORM_TEST_SITE"]["value"] == "https://example.com/a?page=2" diff --git a/frontend/src/dock-adapter.ts b/frontend/src/dock-adapter.ts index 041edb9..4f52f01 100644 --- a/frontend/src/dock-adapter.ts +++ b/frontend/src/dock-adapter.ts @@ -26,7 +26,7 @@ function asRequest(r: AgentRequest): ConsentRequest { const offers = (r.answers ?? ['deny', 'once', 'always']).filter((x): x is ConsentChoice => x === 'deny' || x === 'once' || x === 'always'); return { id: r.id, agent: r.agentNamed ? r.agent ?? '' : '', what: r.what ?? `run ${r.tool}`, offers, always: r.alwaysScope === 'agent' ? 'agent' : 'all', escape: 'deny', - notes: [EFFECTS[r.effect] ?? '', 'If nobody answers within two minutes the request is refused.'].filter((x) => x !== ''), + notes: [...(Array.isArray(r.details) ? r.details.filter((x): x is string => typeof x === 'string') : []), EFFECTS[r.effect] ?? '', 'If nobody answers within two minutes the request is refused.'].filter((x) => x !== ''), ...(typeof r.expires === 'number' ? { expires: r.expires * 1000 } : {}), }; } diff --git a/frontend/src/io/api.ts b/frontend/src/io/api.ts index 24bde48..38c0828 100644 --- a/frontend/src/io/api.ts +++ b/frontend/src/io/api.ts @@ -182,7 +182,7 @@ const qs = (params: Record): string => Object.entries(params).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join('&'); export type AgentAccess = 'ask' | 'allowed' | 'blocked'; -export interface AgentRequest { id: string; tool: string; title: string; effect: 'reads' | 'adds' | 'alters'; at: number; agent?: string; agentNamed?: boolean; what?: string; answers?: string[]; alwaysScope?: string; expires?: number } +export interface AgentRequest { id: string; tool: string; title: string; effect: 'reads' | 'adds' | 'alters'; at: number; agent?: string; agentNamed?: boolean; what?: string; details?: string[]; answers?: string[]; alwaysScope?: string; expires?: number } export interface AgentState { access: AgentAccess; seal: 'ok' | 'unsealed' | 'unavailable' | 'broken'; sealBroken: boolean; notice: string; requests: AgentRequest[] } export const api = { diff --git a/frontend/tests/unit/io/outside-agents.test.ts b/frontend/tests/unit/io/outside-agents.test.ts new file mode 100644 index 0000000..0400886 --- /dev/null +++ b/frontend/tests/unit/io/outside-agents.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from 'vitest'; +import type { ConsentRequest } from '../../../src/dock/adapter'; +import { outsideAgents } from '../../../src/dock-adapter'; + +describe('an outside agent request', () => { + it('lists the paths and flags the call names before what the call can do', () => { + const seen: ConsentRequest[] = []; + outsideAgents.subscribe((r) => seen.push(r), () => undefined); + outsideAgents.arrive({ id: 'd1', tool: 'trash_files', title: 'Trash', effect: 'alters', at: 1, what: 'run trash_files', details: ['paths: /shoot/a.jpg, /shoot/b.jpg', 'overwrite: true'] }); + expect(seen[0].notes).toEqual(['paths: /shoot/a.jpg, /shoot/b.jpg', 'overwrite: true', 'It can delete, move or overwrite files.', 'If nobody answers within two minutes the request is refused.']); + }); +}); diff --git a/setup/HASHOUT_LOG.md b/setup/HASHOUT_LOG.md index 3107fe5..f680bce 100644 --- a/setup/HASHOUT_LOG.md +++ b/setup/HASHOUT_LOG.md @@ -14,7 +14,7 @@ ## 2026-11-19 · Unreleased · the shared dock is module 2.2.0, the shared finder is held to its hash, and Antigravity is a fourth client - `agents.py` :: `DOCK_VERSION`, `DOCK` · `2.2.0`, and the manifest's tab list gains `antigravity`. `agents sync` rewrote `agents/manifest.json` (the dock's tab list only). -- `agents.py` :: `LOOKUP`, `LOOKUP_HASHES`, `lookup_problems`, `lookup` (new) · `backend/app/services/agent_lookup.py` is the family's finder for the agent programs, copied unchanged. The record holds the SHA-256 of the file at each version (`1.0.0` and `1.0.1`); `lookup_problems` reads `VERSION` from the file, hashes its bytes and names a file that is missing or does not match. `check` and `sync --check` report it, and plain `sync` now ends with code 1 when it finds one. The hash is of the bytes, so the file must be checked out with LF endings (`.gitattributes` already says so). +- `agents.py` :: `LOOKUP`, `LOOKUP_HASHES`, `lookup_problems`, `lookup` (new) · `backend/app/services/agent_lookup.py` is the family's finder for the agent programs, copied unchanged. The record holds the SHA-256 of the file at each version (`1.0.0`, `1.0.1` and `1.0.2`); `lookup_problems` reads `VERSION` from the file, hashes its bytes and names a file that is missing or does not match. `check` and `sync --check` report it, and plain `sync` now ends with code 1 when it finds one. The hash is of the bytes, so the file must be checked out with LF endings (`.gitattributes` already says so). - `agents.py` :: `install_claude` · Claude Code is found by the finder, loaded from its file by path, in place of a bare PATH search, and `claude mcp` runs in the finder's child environment. When it is not found the line says where the finder looked. - `agents.py` :: `install_antigravity` (new), `CLIENTS` · `./formtools agents install antigravity` writes the `formtools` server into `~/.gemini/config/mcp_config.json`, the file Google documents for the Antigravity IDE and CLI. Every other server and key is kept, the file is replaced whole after a dated backup, and nothing is written when the entry is already there. An entry named `formtools` that formtools did not write is left alone and said. If only the older `~/.gemini/antigravity-cli/mcp_config.json` exists, the documented file is still the one written and the older one is said to be left alone. Antigravity gets the MCP server only; the driving skill goes to the three programs that read skills. - Run on Linux under a made-up home with stand-ins: a dry run changed nothing; the real run added `formtools` beside a seeded server and a seeded key and left a backup; a second run said "already in"; `install claude --dry-run` found the stand-in and named the command; an unknown client ended with code 2 and the four names. Not run: the entry that is not ours, the older file case, plain `sync` over a finder that does not match, Windows, a real `agy` or `claude`. diff --git a/setup/agents.py b/setup/agents.py index 1628b38..94b672a 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -27,7 +27,7 @@ DOCK_VERSION = "2.2.1" LOOKUP = os.path.join(ROOT, "backend", "app", "services", "agent_lookup.py") LOOKUP_REL = "backend/app/services/agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "9035a947a4b9c0e2ced96b27fec7f95f971467d27d344c41cef1543423f72194"} ENGINE_FACTS = """ import json from app.main import app