diff --git a/backend/app/authoring_tools.py b/backend/app/authoring_tools.py index 195ca47b..996cbb0e 100644 --- a/backend/app/authoring_tools.py +++ b/backend/app/authoring_tools.py @@ -5,14 +5,10 @@ Annotations follow the MCP meaning: readOnlyHint false for anything that changes the site; destructiveHint only where a call deletes or overwrites what a person may have made (removals, a preset applied over existing values); idempotentHint where repeating the same call leaves the same result.""" -import asyncio import base64 import binascii import json -import urllib.error -import urllib.request -from .config import AUTH_TOKEN, PORT from .engine import EngineError from .mcp_catalog import REVISION, tool from .mcp_domains import compact @@ -122,25 +118,6 @@ def matches(item): return result -def _send(locale): - url = f'http://127.0.0.1:{PORT}/api/handoff/formpublisher' + (f'?locale={urllib.request.quote(locale)}' if locale else '') - headers = {'X-FormWeb-Channel': 'agent', 'Content-Type': 'application/json'} - if AUTH_TOKEN: - headers['Authorization'] = 'Bearer ' + AUTH_TOKEN - request = urllib.request.Request(url, data=b'{}', headers=headers, method='POST') - try: - with urllib.request.urlopen(request, timeout=60) as response: - return json.loads(response.read()) - except urllib.error.HTTPError as error: - try: - detail = json.loads(error.read()).get('detail', error.reason) - except ValueError: - detail = error.reason - raise EngineError(str(detail), error.code) - except (urllib.error.URLError, OSError) as error: - raise EngineError(f'Could not reach the FormWeb hand-off route: {error}', 502) - - async def dispatch(name, arguments): from . import library, library_routes from .code_components import build_component @@ -213,8 +190,9 @@ async def dispatch(name, arguments): hosts = [child for page in result.get('pages') or [] for child in site['nodes'].get(roots.get(page, ''), {}).get('children', [])] return {**made, **(await _bring_in(hosts))} if name == 'send_to_formpublisher': + from .handoff import send_to_formpublisher studio.access.authorize('read') - return await asyncio.to_thread(_send, arguments.get('locale')) + return await send_to_formpublisher(arguments.get('locale')) if name == 'copy_element': from .fragment_routes import fragment_of if arguments.get('clip') is True and arguments.get('embed_assets') is not True: diff --git a/backend/app/claude_code.py b/backend/app/claude_code.py index ea8a47be..3f6cdfe5 100644 --- a/backend/app/claude_code.py +++ b/backend/app/claude_code.py @@ -8,9 +8,11 @@ import json import os import secrets +import shutil +from dataclasses import replace from pathlib import Path -from . import agent_lookup +from . import agent_lookup, windows_start from .config import DATA_DIR, PORT from .engine import EngineError @@ -76,6 +78,8 @@ def workdir(): def located(kind, fresh=False): found = agent_lookup.find(kind, setting=None, override_vars=OVERRIDES.get(kind, ()), shell_timeout=10.0, fresh=fresh) + if found.path and not windows_start.startable(found.path): + return replace(found, state='broken', error=windows_start.REFUSED) return agent_lookup.check(found, child_env(path=found.path), 15.0, fresh) @@ -132,7 +136,7 @@ def _base(binary, prompt, resume, headless, config): def _wrap(argv): - return agent_lookup.start_argv(argv) + return windows_start.start_words(argv, node=lambda: shutil.which('node', path=child_env(path=argv[0]).get('PATH'))) def argv(prompt, resume, config): diff --git a/backend/app/clients.py b/backend/app/clients.py index b9fa27b6..1abd2aad 100644 --- a/backend/app/clients.py +++ b/backend/app/clients.py @@ -5,14 +5,15 @@ reads one file for the whole account, ~/.gemini/config/mcp_config.json: its card adds the one entry named formweb there when the person asks, keeps every other entry and key, and leaves alone an entry of that name it did not write. The Claude Code card's Open button does not depend on its file: it starts Claude through POST /api/terminal/open with -FormWeb's own MCP config. +FormWeb's own MCP config. On Windows the Codex file names formweb.bat in this folder. The installed app ships no +launcher, so there it writes none of these files. """ import json import os from pathlib import Path from . import claude_code -from .config import ROOT +from .config import FROZEN, ROOT from .engine import EngineError CLIENTS = { @@ -40,6 +41,15 @@ } +INSTALLED = 'The installed app does not include the formweb launcher these files start, so nothing was written. Open in Agent Connect starts each program with FormWeb\'s tools.' + + +def content(client_id, system=None): + if client_id == 'codex' and (system or os.name) == 'nt': + return f'[mcp_servers.formweb]\ncommand = {json.dumps(str(ROOT / "formweb.bat"), ensure_ascii=False)}\nargs = ["mcp"]\nstartup_timeout_sec = 30\ntool_timeout_sec = 120\n' + return CLIENTS[client_id]['content'] + + ANTIGRAVITY = {'name': 'Antigravity', 'path': '~/.gemini/config/mcp_config.json', 'cli': 'agy', 'start': 'agy'} ANTIGRAVITY_ENTRY = 'formweb' OLDER_FILE = '~/.gemini/antigravity-cli/mcp_config.json' @@ -94,7 +104,7 @@ def card(client_id): spec = CLIENTS[client_id] path = ROOT / spec['path'] current = path.read_text(encoding='utf-8') if path.is_file() else None - status = 'missing' if current is None else 'ready' if current == spec['content'] else 'changed' + status = 'missing' if current is None else 'ready' if current == content(client_id) else 'changed' found = claude_code.located('claude' if client_id == 'claude-code' else client_id).path is not None return {'id': client_id, 'name': spec['name'], 'file': spec['path'], 'status': status, 'cliFound': found, 'cli': spec['cli'], 'start': spec['start'], 'launch': '/api/terminal/open' if client_id == 'claude-code' else None} @@ -104,6 +114,8 @@ def cards(): def write(client_id): + if FROZEN: + raise EngineError(INSTALLED, 409) if client_id == 'antigravity': return antigravity_write() if client_id not in CLIENTS: @@ -113,5 +125,5 @@ def write(client_id): if not path.is_relative_to(ROOT.resolve()): raise EngineError('Client file must stay inside the FormWeb folder.', 400) path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(spec['content'], encoding='utf-8') + path.write_text(content(client_id), encoding='utf-8') return card(client_id) diff --git a/backend/app/config.py b/backend/app/config.py index 6176cece..5e8d2c7f 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -18,7 +18,15 @@ DATA_DIR = Path(os.getenv('FORMWEB_DATA_DIR', str(ROOT / 'Data' if FROZEN else ROOT / 'backend/data'))).resolve() FRONTEND_DIST = Path(os.getenv('FORMWEB_FRONTEND_DIST', str(BUNDLE / 'frontend_dist' if FROZEN else ROOT / 'frontend/dist'))).resolve() AUTH_TOKEN = os.getenv('FORMWEB_AUTH_TOKEN', '') -ORIGINS = tuple(x.strip() for x in os.getenv('FORMWEB_ORIGINS', f'http://localhost:5240,http://127.0.0.1:5240,http://localhost:5241,http://127.0.0.1:5241,http://localhost:{PORT},http://127.0.0.1:{PORT}').split(',') if x.strip()) +DEV_PORTS = (5240, 5241) + + +def default_origins(frozen: bool, port: int) -> tuple[str, ...]: + ports = (port,) if frozen else (*DEV_PORTS, port) + return tuple(f'http://{host}:{item}' for item in ports for host in ('localhost', '127.0.0.1')) + + +ORIGINS = tuple(x.strip() for x in os.getenv('FORMWEB_ORIGINS', ','.join(default_origins(FROZEN, PORT))).split(',') if x.strip()) PUBLIC_BASE = f'http://127.0.0.1:{PORT}' CLIP_SECONDS_DEFAULT = 15 * 60 diff --git a/backend/app/mcp_domains.py b/backend/app/mcp_domains.py index 2f6714bd..7664b5f8 100644 --- a/backend/app/mcp_domains.py +++ b/backend/app/mcp_domains.py @@ -113,12 +113,16 @@ } +def removing(command) -> bool: + return str(command).endswith(('.remove', '.delete')) or command == 'site.replace' + + def domain_tools(): tools = [] for name, title, intro, commands in DOMAINS: lines = '\n'.join(f'- {command} {COMMAND_DOCS[command]}' for command in commands) description = f'{intro} One command per call, applied as one undo step.\n{lines}' - removes = any(command.endswith('.remove') or command == 'site.replace' for command in commands) + removes = any(removing(command) for command in commands) tools.append({ 'name': name, 'title': title, diff --git a/backend/app/mcp_server.py b/backend/app/mcp_server.py index 8296dddb..8f7e4ced 100644 --- a/backend/app/mcp_server.py +++ b/backend/app/mcp_server.py @@ -14,7 +14,7 @@ from .config import ORIGINS, PORT, VERSION from .engine import EngineError from .mcp_catalog import TOOLS as BASE_TOOLS -from .mcp_domains import COMMAND_DOCS, DOMAIN_BY_NAME, DOMAIN_TOOLS, INSTRUCTIONS, PROMPTS, compact, tokens, tree +from .mcp_domains import COMMAND_DOCS, DOMAIN_BY_NAME, DOMAIN_TOOLS, INSTRUCTIONS, PROMPTS, compact, removing, tokens, tree from .providers.catalog import PROVIDER_BY_NAME, PROVIDER_TOOLS from .providers.service import dispatch_tool as provider_dispatch from .service import studio @@ -75,9 +75,9 @@ async def call_tool(context, params): errors = list(Draft202012Validator(BY_NAME[params.name]['inputSchema']).iter_errors(arguments)) if errors: raise EngineError(errors[0].message[:400], 422) - removes = params.name == 'apply_commands' and any(str(item.get('command', '')).endswith(('.remove', '.delete')) for item in arguments.get('commands', []) if isinstance(item, dict)) + removes = params.name == 'apply_commands' and any(removing(item.get('command', '')) for item in arguments.get('commands', []) if isinstance(item, dict)) if params.name in DOMAIN_BY_NAME: # domain tools: judge the one command, not the tool's worst case - removes = arguments['command'].endswith('.remove') or arguments['command'] == 'site.replace' + removes = removing(arguments['command']) if params.name == 'motion_track': # judged per call like the domain tools: only a null track deletes removes = arguments['track'] is None if params.name == 'library_import_site': # only an import that replaces matching routes swaps content away diff --git a/backend/app/windows_start.py b/backend/app/windows_start.py new file mode 100644 index 00000000..2e49c540 --- /dev/null +++ b/backend/app/windows_start.py @@ -0,0 +1,103 @@ +"""How FormWeb starts an agent program on Windows. A program installed by npm is a .cmd file that only starts node with +its script, so FormWeb starts node with that script itself and no command interpreter reads the words. Any other .cmd or +.bat is run by cmd.exe, which reads the whole line again and treats some characters as its own syntax even inside quotes. +Such a start is refused when any word holds a control character or one of & | < > ^ ( ) ! % ", and when a program path +that needs quotes is followed by a word that needs quotes, so every word reaches the program as it was given.""" +import re +import shutil +from pathlib import Path + +from . import agent_lookup +from .engine import EngineError + +BATCH = ('.cmd', '.bat') +CONTROL = re.compile(r'[\x00-\x1f\x7f]') +RESERVED = frozenset('&|<>^()!%"') +SHIM = re.compile(r'("%_prog%"\s+)?"%dp0%\\([^"%\r\n]+)"\s+%\*') +PROG = re.compile(r'SET\s+"_prog=%dp0%\\([^"%\r\n]+)"', re.IGNORECASE) +NATIVE = ('.exe', '.com') +STREAM = re.compile(r'(::\$data)?[ .]*$', re.IGNORECASE) +REFUSED = ('This program is started through cmd.exe on Windows, which reads some characters as its own syntax even inside quotes, ' + 'so it was not started. A word given to it may not hold line breaks or other control characters, or any of ' + '& | < > ^ ( ) ! % ", and a program path with spaces or @ may not be followed by a word with spaces. Pass long text ' + 'through standard input or a file if the program supports it, or give the path to a program that is not a .cmd or .bat file.') + + +def _node(folder: Path, node) -> str | None: + beside = folder / 'node.exe' + if beside.is_file(): + return str(beside) + found = node() if node else shutil.which('node') + return found if found and _suffix(found) in NATIVE else None + + +def _suffix(path) -> str: + return Path(STREAM.sub('', str(path))).suffix.lower() + + +def shim_target(path, node=None) -> list[str] | None: + """What an npm .cmd shim starts, when its target is inside the shim's folder: [node, script] for a node script, + [program] for a native program, else None. Node is used only as node.exe, never through another batch file.""" + shim = Path(path) + if _suffix(shim) != '.cmd': + return None + try: + text = shim.read_text(encoding='utf-8', errors='replace')[:16384] + except OSError: + return None + hit = SHIM.search(text) + parts = [part for part in re.split(r'[\\/]', hit.group(2)) if part] if hit else [] + if not parts or any(part in ('.', '..') or ':' in part for part in parts): + return None + script = shim.parent.joinpath(*parts) + if not script.is_file(): + return None + if not hit.group(1): + return [str(script)] if _suffix(script) in NATIVE else None + prog = PROG.search(text) + if not prog or prog.group(1).lower() != 'node.exe': + return None + program = _node(shim.parent, node) + return [program, str(script)] if program else None + + +def _plain(word: str) -> bool: + return not CONTROL.search(word) and not RESERVED.intersection(word) + + +def _needs_quotes(word: str) -> bool: + return word == '' or ' ' in word + + +def cmd_safe(words) -> bool: + """Whether cmd.exe /c would pass every word to the batch file unchanged. No word may hold a control character or a + reserved character, quoted or not. A quoted program path keeps its quotes only when it is the line's one quoted + word and holds no @, so a path that needs quotes may not be followed by another word that needs them.""" + words = [str(word) for word in words] + if not words or not all(_plain(word) for word in words): + return False + program, rest = words[0], words[1:] + if _needs_quotes(program): + return '@' not in program and not any(_needs_quotes(word) for word in rest) + return True + + +def _batch(words, platform) -> bool: + return agent_lookup.windows(platform) and _suffix(words[0]) in BATCH + + +def start_words(cmd, platform=None, node=None) -> list[str]: + words = [str(word) for word in cmd] + if not _batch(words, platform): + return agent_lookup.start_argv(words, platform=platform) + direct = shim_target(words[0], node) + if direct: + return [*direct, *words[1:]] + if not cmd_safe(words): + raise EngineError(REFUSED, 400) + return agent_lookup.start_argv(words, platform=platform) + + +def startable(path, platform=None) -> bool: + """Whether the finder's own check (path --version) can run this program safely.""" + return not _batch([path], platform) or cmd_safe([path, '--version']) diff --git a/backend/tests/test_agent_asks.py b/backend/tests/test_agent_asks.py new file mode 100644 index 00000000..ffa27e19 --- /dev/null +++ b/backend/tests/test_agent_asks.py @@ -0,0 +1,60 @@ +import pytest + +from test_f2_f3_mcp import agents_on, call, payload # noqa: F401 + + +@pytest.fixture() +def agents_asking(client): + assert client.post("/api/agents", json={"enabled": True}).status_code == 200 + previous = client.post("/api/approvals/settings", json={}).json()["agentDestructive"] + client.post("/api/approvals/settings", json={"agentDestructive": True}) + yield + client.post("/api/approvals/settings", json={"agentDestructive": previous}) + client.post("/api/agents", json={"enabled": False}) + + +@pytest.fixture() +def asked(monkeypatch): + from app.engine import EngineError + from app.service import studio + + seen = [] + + async def refuse(kind, subject, *args, **kwargs): + seen.append(subject["tool"]) + raise EngineError("Declined.", 403) + + monkeypatch.setattr(studio.approvals, "wait", refuse) + return seen + + +def test_replacing_the_whole_site_through_apply_commands_asks_first_like_edit_site(client, agents_asking, asked): + state = client.get("/api/state").json() + before = state["site"] + replacement = {**before, "name": "Replaced by a batch"} + result = call(client, "apply_commands", {"commands": [{"command": "site.replace", "params": {"site": replacement}}]}) + assert result.get("isError") and asked == ["apply_commands"] + assert client.get("/api/state").json()["site"]["name"] == before["name"] + result = call(client, "edit_site", {"command": "site.replace", "params": {"site": replacement}}) + assert result.get("isError") and asked == ["apply_commands", "edit_site"] + + +def test_an_ordinary_batch_does_not_ask(client, agents_asking, asked): + result = call(client, "apply_commands", {"commands": [{"command": "token.set", "params": {"name": "asks-none", "value": "#123456"}}]}) + assert not result.get("isError") and asked == [] + + +def test_the_formpublisher_tool_delivers_without_the_window_key(client, agents_on, monkeypatch): + from app import handoff + + sent = [] + + def receive(url, data, headers): + sent.append(headers["Content-Type"]) + return {"site": "site-1", "revision": "rev-1"} + + monkeypatch.setattr(handoff, "_post", receive) + result = call(client, "send_to_formpublisher", {}) + assert not result.get("isError"), result + assert payload(result)["delivered"] == "live" and payload(result)["site"] == "site-1" + assert sent == ["application/zip"] diff --git a/backend/tests/test_agent_client_files.py b/backend/tests/test_agent_client_files.py new file mode 100644 index 00000000..804ed289 --- /dev/null +++ b/backend/tests/test_agent_client_files.py @@ -0,0 +1,40 @@ +import pytest + + +@pytest.mark.parametrize("client_id", ["claude-code", "codex", "cursor", "antigravity"]) +def test_the_installed_app_writes_no_client_file_that_starts_a_launcher_it_does_not_ship(client, monkeypatch, tmp_path, client_id): + from app import clients + + monkeypatch.setattr(clients, "FROZEN", True) + monkeypatch.setattr(clients, "ROOT", tmp_path) + answer = client.post(f"/api/agents/clients/{client_id}", json={}) + assert answer.status_code == 409 and "installed app" in answer.json()["detail"] + assert list(tmp_path.iterdir()) == [] and not clients.antigravity_file().exists() + + +def test_the_codex_file_on_windows_starts_the_windows_launcher_without_a_unix_shell(monkeypatch, tmp_path): + import tomllib + + from app import clients + + monkeypatch.setattr(clients, "ROOT", tmp_path / "Form Web") + entry = tomllib.loads(clients.content("codex", "nt"))["mcp_servers"]["formweb"] + assert entry["command"] == str(tmp_path / "Form Web" / "formweb.bat") and entry["args"] == ["mcp"] + assert clients.content("codex", "posix") == clients.CLIENTS["codex"]["content"] + + +def test_the_installed_app_accepts_only_its_own_window_origin_by_default(): + from app import config + + assert config.default_origins(True, 8241) == ("http://localhost:8241", "http://127.0.0.1:8241") + assert "http://localhost:5240" in config.default_origins(False, 8240) and "http://127.0.0.1:8240" in config.default_origins(False, 8240) + + +def test_the_codex_file_on_windows_keeps_any_folder_name_readable(monkeypatch, tmp_path): + import tomllib + + from app import clients + + folder = tmp_path / "Sites \U0001f3a8 \"draft\" \\ café" + monkeypatch.setattr(clients, "ROOT", folder) + assert tomllib.loads(clients.content("codex", "nt"))["mcp_servers"]["formweb"]["command"] == str(folder / "formweb.bat") diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py new file mode 100644 index 00000000..f130fa28 --- /dev/null +++ b/backend/tests/test_windows_start.py @@ -0,0 +1,165 @@ +import pytest + +SHIM = ( + '@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n' + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\n' + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@scope\\tool\\cli.js" %*\r\n' +) + + +@pytest.fixture() +def npm_folder(tmp_path): + folder = tmp_path / "npm" + (folder / "node_modules" / "@scope" / "tool").mkdir(parents=True) + (folder / "node_modules" / "@scope" / "tool" / "cli.js").write_text("") + (folder / "tool.cmd").write_text(SHIM) + return folder + + +def test_an_npm_shim_is_started_through_node_without_the_command_interpreter(npm_folder): + from app import windows_start + + (npm_folder / "node.exe").write_text("") + words = windows_start.start_words([str(npm_folder / "tool.cmd"), "--", "a prompt with 50% & \"quotes\"\nand a second line"], platform="win32") + assert words == [str(npm_folder / "node.exe"), str(npm_folder / "node_modules" / "@scope" / "tool" / "cli.js"), "--", "a prompt with 50% & \"quotes\"\nand a second line"] + + +def test_a_shim_without_node_beside_it_uses_node_from_the_path(npm_folder, tmp_path): + from app import windows_start + + elsewhere = tmp_path / "node-home" + elsewhere.mkdir() + words = windows_start.start_words([str(npm_folder / "tool.cmd"), "--version"], platform="win32", node=lambda: str(elsewhere / "node.exe")) + assert words[0] == str(elsewhere / "node.exe") and words[2:] == ["--version"] + + +def test_a_shim_naming_a_script_outside_its_folder_is_not_followed(npm_folder): + from app import windows_start + + (npm_folder / "tool.cmd").write_text(SHIM.replace("node_modules\\@scope\\tool\\cli.js", "..\\other\\cli.js")) + assert windows_start.shim_target(npm_folder / "tool.cmd", lambda: "node.exe") is None + + +RESERVED_WORDS = [ + "line\nbreak", "tab\there", "bell\x07", "nul\x00", "esc\x1b", "del\x7f", "50%", "%PATH%", "a&b", "a|b", "a>b", "a