diff --git a/.agents/skills/formext-harness/references/tools.md b/.agents/skills/formext-harness/references/tools.md index 7a51ad4..584c8ae 100644 --- a/.agents/skills/formext-harness/references/tools.md +++ b/.agents/skills/formext-harness/references/tools.md @@ -258,7 +258,7 @@ Check, then build the deterministic .formpkg (sorted entries, fixed timestamps), | --- | --- | --- | --- | | `id` | string | yes | The project id (projects lists them). | | `reproduce` | boolean | no | Also run the reproducibility check. | -| `out` | string | no | Save the .formpkg to this file or folder. | +| `out` | string | no | Save the .formpkg to this folder, or to this file name ending in .formpkg. | | `anyway` | boolean | no | Package despite code errors (never despite contract errors). Say so to the person. | ## builds @@ -349,6 +349,6 @@ Write the project into a folder in form.ext-registry's layout (extensions/[id]/ | Argument | Type | Required | Meaning | | --- | --- | --- | --- | | `id` | string | yes | The project id (projects lists them). | -| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use instead of form.ext's copy (saved as the setting registry.checkout). | +| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use for this submit instead of form.ext's copy (to keep one for every submit, set registry.checkout in the form.ext window's Settings). | | `pull_request` | boolean | no | Also fork, push and open the pull request. Ask the person first: it posts publicly under their GitHub account. | | `ready` | boolean | no | Only report whether git and gh are installed and signed in. | diff --git a/.claude/skills/formext-harness/references/tools.md b/.claude/skills/formext-harness/references/tools.md index 7a51ad4..584c8ae 100644 --- a/.claude/skills/formext-harness/references/tools.md +++ b/.claude/skills/formext-harness/references/tools.md @@ -258,7 +258,7 @@ Check, then build the deterministic .formpkg (sorted entries, fixed timestamps), | --- | --- | --- | --- | | `id` | string | yes | The project id (projects lists them). | | `reproduce` | boolean | no | Also run the reproducibility check. | -| `out` | string | no | Save the .formpkg to this file or folder. | +| `out` | string | no | Save the .formpkg to this folder, or to this file name ending in .formpkg. | | `anyway` | boolean | no | Package despite code errors (never despite contract errors). Say so to the person. | ## builds @@ -349,6 +349,6 @@ Write the project into a folder in form.ext-registry's layout (extensions/[id]/ | Argument | Type | Required | Meaning | | --- | --- | --- | --- | | `id` | string | yes | The project id (projects lists them). | -| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use instead of form.ext's copy (saved as the setting registry.checkout). | +| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use for this submit instead of form.ext's copy (to keep one for every submit, set registry.checkout in the form.ext window's Settings). | | `pull_request` | boolean | no | Also fork, push and open the pull request. Ask the person first: it posts publicly under their GitHub account. | | `ready` | boolean | no | Only report whether git and gh are installed and signed in. | diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 223a7f5..3be5f3f 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,16 @@ The living log of the form.ext engine. Read it before editing `backend/`. Core files belong to the engine module; module routers and services (`routers/.py`, `services/.py`) keep their own notes in their own HASHOUT logs. +## Unreleased: loopback requests, window-only checkout, plain launcher words {#loopback} + +- refers-to: app/services/local_host.py; app/services/agent_start.py; app/services/settings.py; app/services/consent.py; app/cli.py; ../setup/agents.py +- `LoopbackHostGuard` (outermost middleware) refuses any HTTP request or WebSocket whose Host is not localhost, 127.0.0.1, ::1 or tauri.localhost; in-process calls pass. `/api/live` checks Origin and Host with the same `origin_ok` the terminal routes use. Test clients use `http://127.0.0.1:8640`, and WebSocket tests give the full `ws://127.0.0.1:8640/...` address because the test client ignores its base address for sockets. +- `registry.checkout` changes only with the window key, like `agent_access`. The `submit` tool's `checkout` goes in the body of `POST /api/publish/{pid}/registry` (and `/registry/pull-request`) and is used for that submit only. +- The consent request's `what` names the local path argument (`LOCAL_PATHS`), made absolute before the check. At most `MAX_WAITING` (8) requests wait at once. `run_op` asks `forwards()` once. `package` writes only to a folder or a `.formpkg` name, through a temporary file. +- `agent_lookup.py` stays the shared 1.0.1 copy. `agent_start.start_argv` wraps it: on Windows an npm `.cmd` launcher is followed to its script (with the `node.exe` beside it or `node` on PATH) or its `.exe`; any other `.cmd` or `.bat` goes through `cmd.exe /c` only when every word is plain. On Windows the MCP launcher is `formext.bat`. +- The consent `what` shows the resolved path, keeps a trailing separator, and writes control, format and line separator characters as `\uXXXX`. `package` writes its temporary file with `tempfile.mkstemp`. `POST /api/window/key` checks Origin and Host with `origin_ok`. Words given to `cmd.exe /c` may not hold any of `& | < > ^ ( ) !` even inside spaces, since `cmd /c` can strip the outer quotes. The refusal (`agent_start.RefusedWord`) says to pass long or special text through stdin or a file when the program accepts one. +- Not run: anything on Windows. + ## v0.11.0: one runner for the tests, by layer {#test-runner} - refers-to: ../setup/test; ../formext; ../formext.bat; ../tests/stand_ins.py; ../docs/TESTING.md; ../.github/workflows/ci.yml diff --git a/backend/app/cli.py b/backend/app/cli.py index 1426233..936b135 100644 --- a/backend/app/cli.py +++ b/backend/app/cli.py @@ -5,6 +5,7 @@ import re import shutil import sys +import tempfile import threading import time import urllib.error @@ -677,8 +678,17 @@ def op_package(eng: Engine, id: str, reproduce: bool = False, out: str | None = if target.is_dir() or out.endswith(("/", os.sep)): target.mkdir(parents=True, exist_ok=True) target = target / (build.get("file") or f"{build['id']}-{build['version']}.formpkg") + if target.suffix.lower() != ".formpkg": + raise OpError(f"out must be a folder or a file name ending in .formpkg, not {target}") target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(data) + handle, part = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".part", dir=target.parent) + try: + with os.fdopen(handle, "wb") as fh: + fh.write(data) + os.replace(part, target) + except BaseException: + Path(part).unlink(missing_ok=True) + raise result["saved"] = str(target.resolve()) return result @@ -804,20 +814,21 @@ def op_submit(eng: Engine, id: str, checkout: str | None = None, pull_request: b _need(eng, "publish", "Submit to Registry", route) if ready: return eng.get(f"/api/publish/{q(id)}/registry/pull-request") + body = {} if checkout: folder = Path(checkout).expanduser().resolve() if not (folder / "tools" / "check.py").is_file(): raise OpError(f"{folder} is not a form.ext-registry checkout (it has no tools/check.py)") - eng.call("PUT", "/api/settings", {"registry": {"checkout": str(folder)}}) + body = {"checkout": str(folder)} if pull_request: try: - return eng.call("POST", f"/api/publish/{q(id)}/registry/pull-request", {}) + return eng.call("POST", f"/api/publish/{q(id)}/registry/pull-request", body) except EngineError as err: needs = err.data.get("needs") if isinstance(err.data, dict) else None if needs: raise OpError(err.message, {"needs": needs}) from err raise - return eng.call(route[0], route[1], {}) + return eng.call(route[0], route[1], body) def _sources(eng: Engine) -> None: @@ -1096,7 +1107,7 @@ def op_agents_sync(eng: Engine) -> dict: Op("package", "Package", "Check, then build the deterministic .formpkg (sorted entries, fixed timestamps), with SHA-256 and size. Refused on contract errors (every host would refuse the package) and, unless anyway, on code errors. reproduce also rebuilds it with the kit's own formpkg command and compares the SHA-256; out saves a copy.", op_package, [ P_ID, Param("reproduce", "boolean", "Also run the reproducibility check."), - Param("out", help="Save the .formpkg to this file or folder."), + Param("out", help="Save the .formpkg to this folder, or to this file name ending in .formpkg."), Param("anyway", "boolean", "Package despite code errors (never despite contract errors). Say so to the person."), ], read_only=False, say=_say_package), Op("builds", "Builds", "Every build of a project, newest first, with SHA-256, size and signatures.", op_builds, [P_ID], say=lambda d: "\n".join(f"{b['sha256'][:16]} {b.get('version')} {b.get('bytes')} bytes {len(b.get('signatures') or [])} signatures" for b in d["builds"]) or "no builds yet"), @@ -1127,7 +1138,7 @@ def op_agents_sync(eng: Engine) -> dict: ], read_only=False, asks=True, say=_say_publish), Op("submit", "Submit to Registry", "Write the project into a folder in form.ext-registry's layout (extensions/[id]/ with package/, the source, package.json when there is one, README.md, LICENSE, CHANGELOG.md and a screenshot slot), and run the registry's own tools/check.py on it from the copy of the registry form.ext keeps (it fetches it; when that fails form.ext's own Check runs, and it says which ran). With pull_request it then forks nodemode-dev/form.ext-registry into the person's GitHub account, pushes the folder on a branch and opens the pull request, through GitHub's gh command line; it refuses while the checks fail or a placeholder text is left. ready reports what the one-step pull request still needs on this computer. Without pull_request it pushes nothing and gives the commands to do it by hand.", op_submit, [ P_ID, - Param("checkout", help="Your own clone of nodemode-dev/form.ext-registry to use instead of form.ext's copy (saved as the setting registry.checkout)."), + Param("checkout", help="Your own clone of nodemode-dev/form.ext-registry to use for this submit instead of form.ext's copy (to keep one for every submit, set registry.checkout in the form.ext window's Settings)."), Param("pull_request", "boolean", "Also fork, push and open the pull request. Ask the person first: it posts publicly under their GitHub account.", flag="--pull-request"), Param("ready", "boolean", "Only report whether git and gh are installed and signed in."), ], read_only=False, asks=True, say=_say_submit), @@ -1156,16 +1167,21 @@ def run_op(eng: Engine, name: str, args: dict) -> Any: for p in op.params: if p.enum and p.name in clean and clean[p.name] not in p.enum: raise OpError(f"{p.name} is one of {', '.join(p.enum)}") - if op.mcp and not op.read_only and not eng.forwards(): + local = LOCAL_PATHS.get(name) + named = None + if local and isinstance(clean.get(local), str) and clean[local]: + given = clean[local] + folder = os.sep if given.endswith(("/", os.sep)) else "" + clean[local] = str(Path(given).expanduser().absolute()) + folder + named = {local: str(Path(clean[local]).resolve()) + folder} + forwards = op.mcp and eng.forwards() + if op.mcp and not op.read_only and not forwards: from app.services import consent - refused = consent.check(name, op.title, clean) + refused = consent.check(name, op.title, clean, named) if refused: raise OpError(refused, {"agentAccess": consent.access()}) - if op.mcp and eng.forwards(): - local = LOCAL_PATHS.get(name) - if local and isinstance(clean.get(local), str) and clean[local]: - clean[local] = str(Path(clean[local]).expanduser().absolute()) + if forwards: return eng.tool(name, clean) return op.run(eng, **clean) diff --git a/backend/app/main.py b/backend/app/main.py index 4d355e5..08f0db4 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -13,6 +13,7 @@ from app import __version__, routers from app.services import consent, paths from app.services.bus import bus +from app.services.local_host import LoopbackHostGuard from app.services.window_key import WindowKeyGuard from app.services.workspace import WorkspaceError, watcher @@ -51,6 +52,7 @@ async def lifespan(app: FastAPI): allow_methods=["*"], allow_headers=["*"], ) +app.add_middleware(LoopbackHostGuard) @app.exception_handler(WorkspaceError) diff --git a/backend/app/routers/agents.py b/backend/app/routers/agents.py index baffe47..f527752 100644 --- a/backend/app/routers/agents.py +++ b/backend/app/routers/agents.py @@ -15,13 +15,13 @@ def _window(request: Request) -> None: @router.get("/requests") -def list_requests(request: Request) -> dict: +async def list_requests(request: Request) -> dict: _window(request) return {"access": consent.access(), "requests": consent.pending(), "sealReset": bool(settings.get().get("agentAccessReset"))} @router.post("/requests/{request_id}") -def answer_request(request: Request, request_id: str, body: dict = Body(...)) -> dict: +async def answer_request(request: Request, request_id: str, body: dict = Body(...)) -> dict: _window(request) if not consent.answer(request_id, str(body.get("answer") or "")): raise HTTPException(404, "That request was already answered or has expired") diff --git a/backend/app/routers/health.py b/backend/app/routers/health.py index 0563597..b2100a4 100644 --- a/backend/app/routers/health.py +++ b/backend/app/routers/health.py @@ -13,7 +13,7 @@ @router.get("/api/health") -def health(request: Request): +async def health(request: Request): state = request.app.state return { "ok": True, diff --git a/backend/app/routers/live.py b/backend/app/routers/live.py index 121fa92..402191b 100644 --- a/backend/app/routers/live.py +++ b/backend/app/routers/live.py @@ -5,6 +5,7 @@ from fastapi import APIRouter, WebSocket, WebSocketDisconnect from app import __version__ +from app.services.local_host import origin_ok from app.services import consent, window_key from app.services.bus import bus @@ -13,6 +14,9 @@ @router.websocket("/api/live") async def live(ws: WebSocket): + if not origin_ok(ws.headers.get("origin"), ws.headers.get("host")): + await ws.close(code=4403) + return await ws.accept() bus.attach(asyncio.get_running_loop()) queue = bus.subscribe() diff --git a/backend/app/routers/publish.py b/backend/app/routers/publish.py index 6a611a2..7c3a263 100644 --- a/backend/app/routers/publish.py +++ b/backend/app/routers/publish.py @@ -22,9 +22,16 @@ def send(pid: str): return publish.send(pid) +def _checkout(body: dict | None) -> str | None: + chosen = (body or {}).get("checkout") + if chosen is not None and not isinstance(chosen, str): + raise ValueError("checkout is the path of a form.ext-registry checkout") + return chosen or None + + @router.post("/{pid}/registry") -def submit(pid: str): - return publish.submit(pid) +def submit(pid: str, body: dict | None = Body(None)): + return publish.submit(pid, _checkout(body)) @router.get("/{pid}/registry/pull-request") @@ -33,9 +40,9 @@ def pull_request_ready(pid: str): @router.post("/{pid}/registry/pull-request") -def pull_request(pid: str): +def pull_request(pid: str, body: dict | None = Body(None)): try: - return registry_pr.open_pull_request(pid) + return registry_pr.open_pull_request(pid, _checkout(body)) except registry_pr.Needs as exc: return JSONResponse({"detail": exc.message, "needs": exc.needs}, status_code=exc.status) diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index e32804d..bac7e44 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -7,30 +7,16 @@ import json import os from typing import Literal -from urllib.parse import urlparse from fastapi import APIRouter, Depends, HTTPException, Request, WebSocket, WebSocketDisconnect from pydantic import BaseModel, Field from app.services import agent_programs, claude_code, terminal, window_key +from app.services.local_host import origin_ok -LOOPBACK = {"localhost", "127.0.0.1", "::1", "tauri.localhost"} MAX_SOCKETS = 24 -def _loopback(netloc: str | None) -> bool: - return bool(netloc) and (urlparse(f"//{netloc}").hostname or "") in LOOPBACK - - -def origin_ok(origin: str | None, host: str | None) -> bool: - if not _loopback(host): - return False - if not origin: - return True - parsed = urlparse(origin) - return parsed.scheme in ("http", "https", "tauri") and (parsed.hostname or "") in LOOPBACK - - def require_local(request: Request) -> None: if not origin_ok(request.headers.get("origin"), request.headers.get("host")): raise HTTPException(status_code=403, detail="Only the form.ext window on this computer may use the terminals.") diff --git a/backend/app/routers/window.py b/backend/app/routers/window.py index 1baea0f..7f5eda6 100644 --- a/backend/app/routers/window.py +++ b/backend/app/routers/window.py @@ -1,14 +1,17 @@ -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, HTTPException, Request from app.services import window_key +from app.services.local_host import origin_ok router = APIRouter(prefix="/api/window", tags=["window"]) @router.post("/key") -def claim_window_key() -> dict: +def claim_window_key(request: Request) -> dict: if window_key.stdout_mode(): raise HTTPException(404, "Not Found") + if not origin_ok(request.headers.get("origin"), request.headers.get("host")): + raise HTTPException(403, "Only the form.ext window on this computer may claim the window key") key = window_key.claim() if key is None: raise HTTPException(409, "Another window already holds this engine's window key; use that window, or restart form.ext") diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 4f8a70b..bcbc57d 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -11,7 +11,7 @@ import time from pathlib import Path -from app.services import agent_lookup, claude_code, consent, paths, terminal +from app.services import agent_lookup, agent_start, claude_code, consent, paths, terminal TOKEN_VAR = "FORMEXT_INAPP_TOKEN" PROGRAMS = { @@ -99,7 +99,7 @@ def open_terminal(kind: str, port: int, cols: int = 100, rows: int = 30, project path = found.path own = tab_folder(kind) if kind == "antigravity" else None folder = str(own) if own else claude_code.project_folder(project) - argv = agent_lookup.start_argv([path]) + argv = agent_start.start_argv([path]) token = secrets.token_urlsafe(32) env = claude_code.terminal_env(port, path, {TOKEN_VAR: token, "FORMEXT_MCP_URL": terminal.engine_url(port) + "/mcp"}) consent.open_tab(token, "") diff --git a/backend/app/services/agent_start.py b/backend/app/services/agent_start.py new file mode 100644 index 0000000..2bd847e --- /dev/null +++ b/backend/app/services/agent_start.py @@ -0,0 +1,62 @@ +"""How form.ext starts an agent program. On Windows a .cmd or .bat launcher would go through the command interpreter, which reads +its own special characters in the words, so an npm launcher is followed to the node script or program it runs and that is started +directly; any other launcher is started through the interpreter only when every word is plain.""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +from pathlib import Path + +from app.services import agent_lookup + +SHIM_TARGET = re.compile(r'"%dp0%\\([^"%]+)"\s+%\*') +CONTROL = re.compile(r"[\x00-\x1f\x7f]") +SPECIAL = set('&|<>^()!') + + +class RefusedWord(OSError): + pass + + +def _shim(path: str, env: dict) -> list[str] | None: + try: + text = Path(path).read_text(encoding="utf-8", errors="replace") + except OSError: + return None + found = SHIM_TARGET.findall(text) + if not found: + return None + folder = Path(path).parent + target = folder / found[-1].replace("\\", os.sep) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe": + return [str(target)] + beside = folder / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH")) + return [node, str(target)] if node else None + + +def plain(word: str) -> bool: + return not (CONTROL.search(word) or "%" in word or '"' in word or SPECIAL & set(word)) + + +def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: + words = [str(c) for c in cmd] + env = os.environ if env is None else env + if not (agent_lookup.windows(platform) and words and words[0].lower().endswith((".cmd", ".bat"))): + return agent_lookup.start_argv(words, env, platform) + direct = _shim(words[0], env) + if direct: + return [*direct, *words[1:]] + bad = next((w for w in words if not plain(w)), None) + if bad is not None: + raise RefusedWord(f"{Path(words[0]).name} is a command script, and one of its words cannot be passed to it safely (a control character, %, a double quote, or one of & | < > ^ ( ) !). Pass long or special text through stdin or a file if the program accepts one.") + return agent_lookup.start_argv(words, env, platform) + + +def run(cmd: list, env: dict, timeout: float = 15.0, platform: str | None = None) -> subprocess.CompletedProcess: + return subprocess.run(start_argv(cmd, env, platform), capture_output=True, text=True, errors="replace", timeout=timeout, env=env, stdin=subprocess.DEVNULL) diff --git a/backend/app/services/agents.py b/backend/app/services/agents.py index 8791db7..271e9d0 100644 --- a/backend/app/services/agents.py +++ b/backend/app/services/agents.py @@ -23,10 +23,14 @@ ) +def launcher_name(platform: str | None = None) -> str: + return "formext.bat" if (platform or sys.platform).startswith("win") else "formext" + + def formext_command() -> list[str]: if paths.frozen(): return [sys.executable, "mcp"] - return [str(paths.repo_root() / "formext"), "mcp"] + return [str(paths.repo_root() / launcher_name()), "mcp"] def formmcp_command() -> list[str] | None: diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 033e6fa..48d7ebc 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -14,7 +14,7 @@ import time from app.cli import allowed_tools -from app.services import agent_lookup, agents, consent, paths, sources, terminal +from app.services import agent_lookup, agent_start, agents, consent, paths, sources, terminal from app.services.workspace import WorkspaceError, workspace log = logging.getLogger("formext.claude_code") @@ -96,7 +96,7 @@ def _signed_in(path: str) -> bool | None: if os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("CLAUDE_CODE_OAUTH_TOKEN"): return True try: - out = agent_lookup.run([path, "auth", "status"], child_env(path), CHECK_WAIT) + out = agent_start.run([path, "auth", "status"], child_env(path), CHECK_WAIT) except (OSError, subprocess.SubprocessError): return None try: @@ -374,7 +374,8 @@ def start(mode: str = "ask", fresh: bool = False, port: int | None = None, proje AGENT.names.clear() set_state("starting") try: - proc = subprocess.Popen(agent_lookup.start_argv(args), cwd=folder, env=child_env(found["path"]), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) + env = child_env(found["path"]) + proc = subprocess.Popen(agent_start.start_argv(args, env), cwd=folder, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) except OSError as exc: consent.close_tab(AGENT.token) AGENT.token = None @@ -438,7 +439,7 @@ def terminal_argv(path: str, mcp_file: str, folder: str, project: str | None, pr cmd += ["--resume", resume] if prompt: cmd.append(prompt) - return agent_lookup.start_argv(cmd) + return agent_start.start_argv(cmd) def open_terminal(port: int, prompt: str | None = None, resume: str | None = None, cols: int = 100, rows: int = 30, diff --git a/backend/app/services/consent.py b/backend/app/services/consent.py index ba1ec3b..6e5741b 100644 --- a/backend/app/services/consent.py +++ b/backend/app/services/consent.py @@ -4,6 +4,7 @@ import secrets import threading import time +import unicodedata from app.services.bus import bus @@ -14,6 +15,8 @@ NO_WINDOW = "form.ext asks the person before an outside agent changes anything, and no form.ext window is open to ask. Ask them to open form.ext, or to choose Allowed in Settings, Developer, Outside agents." TIMED_OUT = "Nobody answered in the form.ext window in time, so this call was refused. Ask the person to look at the form.ext window, then retry." BLOCKED_TAB = "Agents are blocked in form.ext's Settings, Developer, Outside agents, and that stops this tab's changes too, so this call was refused. Tell the person where to change it and stop; do not retry." +BUSY = "Too many requests are already waiting for the person in the form.ext window, so this call was refused. Wait for them to answer, then retry one at a time." +MAX_WAITING = 8 ANSWERS = ("deny", "once", "always") ALWAYS_COVERS = "all" SHOWN = ("id", "tool", "title", "project", "at", "agent", "what", "answers", "always", "expires") @@ -128,7 +131,17 @@ def answer(request_id: str, choice: str) -> bool: return True -def check(tool: str, title: str, args: dict) -> str | None: +def shown(text: str) -> str: + return "".join(f"\\u{ord(c):04x}" if unicodedata.category(c) in ("Cc", "Cf", "Zl", "Zp") else c for c in text) + + +def _what(tool: str, title: str, project: str, local: dict | None) -> str: + said = f"run {title} ({tool})" + (f" in the project {shown(project)}" if project else "") + named = [f"{key} {shown(value)}" for key, value in (local or {}).items() if isinstance(value, str) and value] + return said + (", with the local path " + ", ".join(named) if named else "") + + +def check(tool: str, title: str, args: dict, local: dict | None = None) -> str | None: mode = access() if mode == "blocked": return BLOCKED_TAB if _inapp.get() else BLOCKED @@ -138,9 +151,11 @@ def check(tool: str, title: str, args: dict) -> str | None: return NO_WINDOW now, project = time.time(), str(args.get("id") or "") item = {"id": secrets.token_urlsafe(12), "tool": tool, "title": title, "project": project, "at": now, "agent": _agent.get(), - "what": f"run {title} ({tool})" + (f" in the project {project}" if project else ""), "answers": list(ANSWERS), "always": ALWAYS_COVERS, + "what": _what(tool, title, project, local), "answers": list(ANSWERS), "always": ALWAYS_COVERS, "expires": now + WAIT, "answer": None, "done": threading.Event()} with _lock: + if sum(1 for r in _pending.values() if r["answer"] is None) >= MAX_WAITING: + return BUSY _pending[item["id"]] = item bus.emit("agents.ask", {"id": item["id"], "expires": item["expires"]}) try: diff --git a/backend/app/services/local_host.py b/backend/app/services/local_host.py new file mode 100644 index 0000000..c69e94f --- /dev/null +++ b/backend/app/services/local_host.py @@ -0,0 +1,48 @@ +import json +from urllib.parse import urlparse + +from app.services.window_key import INPROCESS + +LOOPBACK = {"localhost", "127.0.0.1", "::1", "tauri.localhost"} +REFUSED = "form.ext answers only requests addressed to this computer (localhost or 127.0.0.1)" + + +def loopback(netloc: str | None) -> bool: + if not netloc: + return False + try: + return (urlparse(f"//{netloc}").hostname or "") in LOOPBACK + except ValueError: + return False + + +def origin_ok(origin: str | None, host: str | None) -> bool: + if not loopback(host): + return False + if not origin: + return True + try: + parsed = urlparse(origin) + return parsed.scheme in ("http", "https", "tauri") and (parsed.hostname or "") in LOOPBACK + except ValueError: + return False + + +def _host(scope) -> str | None: + return next((v.decode("latin-1") for k, v in scope.get("headers", []) if k.decode("latin-1").lower() == "host"), None) + + +class LoopbackHostGuard: + def __init__(self, app) -> None: + self.app = app + + async def __call__(self, scope, receive, send) -> None: + if scope["type"] not in ("http", "websocket") or scope.get(INPROCESS) is True or loopback(_host(scope)): + await self.app(scope, receive, send) + return + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 4403}) + return + body = json.dumps({"detail": REFUSED}).encode("utf-8") + await send({"type": "http.response.start", "status": 403, "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]}) + await send({"type": "http.response.body", "body": body}) diff --git a/backend/app/services/publish.py b/backend/app/services/publish.py index ff1134e..22af408 100644 --- a/backend/app/services/publish.py +++ b/backend/app/services/publish.py @@ -303,21 +303,25 @@ def registry_root() -> Path: return submissions_dir() / "registry" -def registry_checkout() -> Path | None: - configured = settings.value("registry.checkout") - if not isinstance(configured, str) or not configured.strip(): +def _configured(chosen: str | None = None) -> str: + configured = chosen if isinstance(chosen, str) and chosen.strip() else settings.value("registry.checkout") + return configured.strip() if isinstance(configured, str) else "" + + +def registry_checkout(chosen: str | None = None) -> Path | None: + configured = _configured(chosen) + if not configured: return sources.host_dir("registry") - return Path(configured.strip()).expanduser() + return Path(configured).expanduser() -def registry_checkout_managed() -> bool: - configured = settings.value("registry.checkout") - return not (isinstance(configured, str) and configured.strip()) +def registry_checkout_managed(chosen: str | None = None) -> bool: + return not _configured(chosen) -def _ensure_registry() -> str | None: +def _ensure_registry(chosen: str | None = None) -> str | None: """Bring form.ext's own copy of the registry up to date before a submit, so its tools/check.py is the one CI runs; a note when it cannot.""" - if not registry_checkout_managed(): + if not registry_checkout_managed(chosen): return None try: sources.pull("registry", update=sources.present("registry")) @@ -412,8 +416,8 @@ def _own_checks(folder: Path, manifest: dict) -> dict: return {"by": "formext", "tool": "form.ext Check", "ok": not errors, "problems": problems, "report": "\n".join(lines), "note": "The registry's tools/check.py was not run: set registry.checkout to a local clone of nodemode-dev/form.ext-registry to run the same checks CI runs. form.ext ran its own Check, the kit's package rules and the metadata files instead."} -def _registry_checks(root: Path, folder: Path, manifest: dict) -> dict: - checkout = registry_checkout() +def _registry_checks(root: Path, folder: Path, manifest: dict, chosen: str | None = None) -> dict: + checkout = registry_checkout(chosen) script = checkout / "tools" / "check.py" if checkout else None if not script or not script.is_file(): out = _own_checks(folder, manifest) @@ -461,7 +465,7 @@ def _run_registry_check(checkout: Path, script: Path, root: Path, folder: Path, return {"by": "registry", "tool": str(script), "ok": not result.errors, "problems": problems, "report": "\n".join(lines), "note": f"The registry's own tools/check.py from {checkout} ran on the folder (imported, nothing vendored), as CI runs it on a pull request."} -def submit(pid: str) -> dict: +def submit(pid: str, checkout: str | None = None) -> dict: manifest = workspace.manifest(pid) eid = manifest.get("id") version = manifest.get("version") @@ -490,8 +494,8 @@ def submit(pid: str) -> dict: shutil.rmtree(staging, ignore_errors=True) raise screenshot = next((n for n in SCREENSHOT_NAMES if (folder / n).is_file()), None) - fetch_note = _ensure_registry() - checks = _registry_checks(root, folder, manifest) + fetch_note = _ensure_registry(checkout) + checks = _registry_checks(root, folder, manifest, checkout) if fetch_note and checks["by"] == "formext": checks["note"] = f"{fetch_note}, so form.ext ran its own Check, the kit's package rules and the metadata files instead of the registry's tools/check.py." try: diff --git a/backend/app/services/registry_pr.py b/backend/app/services/registry_pr.py index 5950340..42ebb7e 100644 --- a/backend/app/services/registry_pr.py +++ b/backend/app/services/registry_pr.py @@ -259,11 +259,11 @@ def _push(program: str, user: dict, folder: Path, eid: str, branch: str, message return commit -def open_pull_request(pid: str) -> dict: +def open_pull_request(pid: str, checkout: str | None = None) -> dict: ready = readiness(fresh=True) if not ready["ready"]: raise Needs("the pull request needs a little setup first: " + " ".join(n["say"] for n in ready["needs"]), ready["needs"]) - record = publish.submit(pid) + record = publish.submit(pid, checkout) folder = Path(record["folder"]) if not record["checks"]["ok"]: raise Needs("the checks found problems, so no pull request was opened; fix them and submit again", [{"what": "checks", "say": p["message"], "how": p.get("where", "")} for p in record["checks"]["problems"]]) diff --git a/backend/app/services/settings.py b/backend/app/services/settings.py index 9dde545..d013695 100644 --- a/backend/app/services/settings.py +++ b/backend/app/services/settings.py @@ -68,10 +68,20 @@ def value(key: str, default: Any = None) -> Any: return current +def _outside(patch: dict) -> dict: + out = {k: v for k, v in patch.items() if k != "agent_access"} + registry = out.get("registry") + if isinstance(registry, dict) and "checkout" in registry: + out["registry"] = {k: v for k, v in registry.items() if k != "checkout"} + return out + + def update(patch: dict, window: bool = False) -> dict: if not isinstance(patch, dict): raise ValueError("settings must be an object") - patch = {k: v for k, v in patch.items() if k not in (seal.FIELD, "sealBroken", "agentAccessReset") and (window or k != "agent_access")} + patch = {k: v for k, v in patch.items() if k not in (seal.FIELD, "sealBroken", "agentAccessReset")} + if not window: + patch = _outside(patch) if patch.get("agent_access") not in (None, "", "ask", "allowed", "blocked"): raise ValueError("agent_access is ask, allowed or blocked") with _lock: diff --git a/backend/formext_engine.py b/backend/formext_engine.py index e3c40ed..19fd506 100644 --- a/backend/formext_engine.py +++ b/backend/formext_engine.py @@ -234,7 +234,7 @@ def push(*_args) -> None: stubs = { "readiness": lambda fresh=False: {"ready": True, "needs": []}, - "publish": SimpleNamespace(submit=lambda pid: {"folder": str(root / "ext"), "checks": {"ok": True, "problems": []}}, PLAIN={}), + "publish": SimpleNamespace(submit=lambda pid, checkout=None: {"folder": str(root / "ext"), "checks": {"ok": True, "problems": []}}, PLAIN={}), "workspace": SimpleNamespace(manifest=lambda pid: {"id": "selfcheck-ext", "version": "1.0.0", "product": "formext"}), "gh": lambda: "gh", "_user": lambda program: {"login": "selfcheck"}, diff --git a/setup/agents.py b/setup/agents.py index 8387625..bb3744b 100755 --- a/setup/agents.py +++ b/setup/agents.py @@ -30,7 +30,8 @@ SKILLS = ROOT / ".claude" / "skills" MIRRORS = ROOT / ".agents" / "skills" -LAUNCH = str(ROOT / "formext") if (ROOT / "formext").is_file() else os.environ.get("FORMEXT_LAUNCHER") or os.environ.get("APPIMAGE") or str(ROOT / "formext") +SCRIPT = ROOT / hub.launcher_name() +LAUNCH = str(SCRIPT) if SCRIPT.is_file() else os.environ.get("FORMEXT_LAUNCHER") or os.environ.get("APPIMAGE") or str(SCRIPT) HOSTS = ROOT / ".claude" / "skills" / "HOSTS.md" EMOJI = re.compile("[" + "-".join(chr(c) for c in (0x1F000, 0x1FAFF)) + chr(0x2600) + "-" + chr(0x27BF) + chr(0x2B00) + "-" + chr(0x2BFF) + chr(0xFE0F) + chr(0x200D) + "]") CLIENTS = ("claude", "codex", "cursor", "antigravity") @@ -287,7 +288,7 @@ def install_codex(home: Path, dry: bool, said: list) -> None: text = cfg.read_text(encoding="utf-8") if cfg.exists() else "" new = text for name, (cmd, args) in servers().items(): - block = f'[mcp_servers.{name}]\ncommand = "{cmd}"\nargs = [{", ".join(json.dumps(a) for a in args)}]\nstartup_timeout_sec = 90\ntool_timeout_sec = 600\n' + block = f'[mcp_servers.{name}]\ncommand = {json.dumps(cmd)}\nargs = [{", ".join(json.dumps(a) for a in args)}]\nstartup_timeout_sec = 90\ntool_timeout_sec = 600\n' found = re.search(r"(?ms)^\[mcp_servers\." + re.escape(name) + r"\]\n.*?(?=^\[|\Z)", new) if found and found.group(0).strip() == block.strip(): said.append(f" MCP server {name} already in {cfg}") diff --git a/tests/cli/test_local_paths.py b/tests/cli/test_local_paths.py new file mode 100644 index 0000000..77b67d5 --- /dev/null +++ b/tests/cli/test_local_paths.py @@ -0,0 +1,58 @@ +import json + +import pytest + +from .conftest import cli, cli_json, make_home + +CHECK = "from pathlib import Path\nPath(__file__).with_name('ran.txt').write_text('ran', encoding='utf-8')\nraise SystemExit(0)\n" + + +@pytest.fixture(scope="module") +def studio(tmp_path_factory): + home = make_home(tmp_path_factory.mktemp("paths"), "allowed") + made = cli(home, "new", "Path Board", "--app", "formwav", "--starter", "panel") + assert made.returncode == 0, made.stderr + return home + + +def saved_settings(home): + try: + return json.loads((home / "settings.json").read_text(encoding="utf-8")) + except OSError: + return {} + + +def test_a_checkout_given_to_submit_is_used_for_that_submit_and_not_saved(studio, tmp_path): + clone = tmp_path / "my-registry" + (clone / "tools").mkdir(parents=True) + (clone / "tools" / "check.py").write_text(CHECK, encoding="utf-8") + cli(studio, "submit", "path-board", "--checkout", str(clone)) + assert (clone / "tools" / "ran.txt").read_text(encoding="utf-8") == "ran" + assert (saved_settings(studio).get("registry") or {}).get("checkout", "") == "" + + +def test_package_refuses_to_write_over_a_file_that_is_not_a_formpkg(studio, tmp_path): + keep = tmp_path / "notes.txt" + keep.write_text("my notes\n", encoding="utf-8") + code, answer = cli_json(studio, "package", "path-board", "--out", str(keep)) + assert code != 0 + assert ".formpkg" in answer["error"] + assert keep.read_text(encoding="utf-8") == "my notes\n" + + +def test_package_saves_to_a_file_name_ending_in_formpkg(studio, tmp_path): + target = tmp_path / "board.formpkg" + code, answer = cli_json(studio, "package", "path-board", "--out", str(target)) + assert code == 0 + assert answer["saved"] == str(target.resolve()) + assert target.read_bytes()[:2] == b"PK" + assert [p.name for p in tmp_path.iterdir()] == ["board.formpkg"] + + +def test_package_saves_into_a_new_folder_named_with_a_trailing_slash(studio, tmp_path): + folder = tmp_path / "builds" + code, answer = cli_json(studio, "package", "path-board", "--out", str(folder) + "/") + assert code == 0 + saved = [p.name for p in folder.iterdir()] + assert len(saved) == 1 and saved[0].endswith(".formpkg") + assert answer["saved"] == str((folder / saved[0]).resolve()) diff --git a/tests/publish/conftest.py b/tests/publish/conftest.py index 185cc2a..cfd7b35 100644 --- a/tests/publish/conftest.py +++ b/tests/publish/conftest.py @@ -52,7 +52,7 @@ def calls(self) -> list[str]: @pytest.fixture(scope="session") def client(): - with TestClient(app, headers={window_key.HEADER: window_key.KEY}) as c: + with TestClient(app, base_url="http://127.0.0.1:8640", headers={window_key.HEADER: window_key.KEY}) as c: yield c diff --git a/tests/security/conftest.py b/tests/security/conftest.py index 77096db..cbc320a 100644 --- a/tests/security/conftest.py +++ b/tests/security/conftest.py @@ -35,9 +35,9 @@ def home(tmp_path, monkeypatch): @pytest.fixture def client(home): - return TestClient(app, headers={window_key.HEADER: window_key.KEY}, raise_server_exceptions=False) + return TestClient(app, base_url="http://127.0.0.1:8640", headers={window_key.HEADER: window_key.KEY}, raise_server_exceptions=False) @pytest.fixture def outsider(home): - return TestClient(app, raise_server_exceptions=False) + return TestClient(app, base_url="http://127.0.0.1:8640", raise_server_exceptions=False) diff --git a/tests/security/test_security_feeds.py b/tests/security/test_security_feeds.py index 6384451..6f2b7a9 100644 --- a/tests/security/test_security_feeds.py +++ b/tests/security/test_security_feeds.py @@ -8,6 +8,8 @@ from app.services import agent_feed, window_key from app.services.bus import Bus +LIVE = "ws://127.0.0.1:8640/api/live" + def _run(coro): return asyncio.run(coro) @@ -91,7 +93,7 @@ async def scenario(): def test_creating_a_key_is_announced_on_the_live_socket(client, outsider): - with outsider.websocket_connect("/api/live") as ws: + with outsider.websocket_connect(LIVE) as ws: assert ws.receive_json()["name"] == "hello" assert client.post("/api/keys", json={"id": "acme", "name": "Acme"}).status_code == 200 for _ in range(20): @@ -104,13 +106,13 @@ def test_creating_a_key_is_announced_on_the_live_socket(client, outsider): def test_the_live_hello_reports_the_running_version(outsider): version = outsider.get("/api/health").json()["version"] - with outsider.websocket_connect("/api/live") as ws: + with outsider.websocket_connect(LIVE) as ws: hello = ws.receive_json() assert hello["data"] == {"app": "formext", "version": version} def test_the_live_socket_answers_a_ping_with_a_pong(outsider): - with outsider.websocket_connect("/api/live") as ws: + with outsider.websocket_connect(LIVE) as ws: ws.receive_json() ws.send_text("ping") for _ in range(20): diff --git a/tests/security/test_security_loopback.py b/tests/security/test_security_loopback.py new file mode 100644 index 0000000..bfab595 --- /dev/null +++ b/tests/security/test_security_loopback.py @@ -0,0 +1,56 @@ +import pytest +from fastapi.testclient import TestClient +from starlette.websockets import WebSocketDisconnect + +from app.main import app +from app.services import window_key + +LIVE = "ws://127.0.0.1:8640/api/live" + + +@pytest.fixture +def stranger(home): + return TestClient(app, base_url="http://rebound.example:8640", raise_server_exceptions=False) + + +def test_reads_addressed_to_another_host_name_are_refused(stranger, client): + seen = client.get("/api/projects") + assert seen.status_code == 200 + for path in ("/api/projects", "/api/settings", "/api/health"): + res = stranger.get(path) + assert res.status_code == 403 + assert "this computer" in res.json()["detail"] + + +def test_the_window_key_cannot_be_claimed_through_another_host_name(stranger): + res = stranger.post("/api/window/key") + assert res.status_code == 403 + assert window_key.KEY not in res.text + + +def test_a_page_from_another_site_cannot_take_the_window_key_first(outsider, monkeypatch): + monkeypatch.setattr(window_key, "STATE", {"claimed": False, "secondClaim": False}) + res = outsider.post("/api/window/key", headers={"origin": "https://elsewhere.example"}) + assert res.status_code == 403 + assert window_key.KEY not in res.text + assert window_key.STATE["claimed"] is False + assert outsider.post("/api/window/key", headers={"origin": "http://localhost:5640"}).json()["key"] == window_key.KEY + + +def test_the_live_socket_refuses_a_page_from_another_site(outsider): + with pytest.raises(WebSocketDisconnect) as refused: + with outsider.websocket_connect(LIVE, headers={"origin": "https://elsewhere.example"}) as ws: + ws.receive_json() + assert refused.value.code == 4403 + + +def test_the_live_socket_refuses_another_host_name(outsider): + with pytest.raises(WebSocketDisconnect) as refused: + with outsider.websocket_connect("ws://rebound.example:8640/api/live") as ws: + ws.receive_json() + assert refused.value.code == 4403 + + +def test_the_live_socket_says_hello_to_the_window_origin(outsider): + with outsider.websocket_connect(LIVE, headers={"origin": "http://localhost:5640"}) as ws: + assert ws.receive_json()["name"] == "hello" diff --git a/tests/security/test_security_window_key.py b/tests/security/test_security_window_key.py index eea13b0..6c1c1a7 100644 --- a/tests/security/test_security_window_key.py +++ b/tests/security/test_security_window_key.py @@ -9,6 +9,7 @@ REFUSED = "Only the form.ext window can do this" NEVER_CALLED = ("/send", "/registry/pull-request") READS = {"GET", "HEAD", "OPTIONS"} +LIVE = "ws://127.0.0.1:8640/api/live" def _walk(routes, prefix=""): @@ -160,7 +161,7 @@ def _until(ws, wanted): def test_the_live_socket_admits_a_window_that_says_hello_with_the_key(outsider, monkeypatch): from app.services.bus import bus monkeypatch.setattr(bus, "_loop", bus._loop) - with outsider.websocket_connect("/api/live") as ws: + with outsider.websocket_connect(LIVE) as ws: assert ws.receive_json()["name"] == "hello" ws.send_json({"type": "window", "key": window_key.KEY}) assert _until(ws, ("window.admitted", "window.refused")) == "window.admitted" @@ -169,7 +170,7 @@ def test_the_live_socket_admits_a_window_that_says_hello_with_the_key(outsider, def test_the_live_socket_refuses_a_window_hello_with_a_wrong_key(outsider, monkeypatch): from app.services.bus import bus monkeypatch.setattr(bus, "_loop", bus._loop) - with outsider.websocket_connect("/api/live") as ws: + with outsider.websocket_connect(LIVE) as ws: assert ws.receive_json()["name"] == "hello" ws.send_json({"type": "window", "key": "not-the-key"}) assert _until(ws, ("window.admitted", "window.refused")) == "window.refused" @@ -178,7 +179,7 @@ def test_the_live_socket_refuses_a_window_hello_with_a_wrong_key(outsider, monke def test_the_live_socket_delivers_bus_events_in_the_order_they_were_sent(outsider, monkeypatch): from app.services.bus import bus monkeypatch.setattr(bus, "_loop", bus._loop) - with outsider.websocket_connect("/api/live") as ws: + with outsider.websocket_connect(LIVE) as ws: assert ws.receive_json()["name"] == "hello" for i in range(25): bus.emit("security.order", {"n": i}) diff --git a/tests/test_agent_consent_limits.py b/tests/test_agent_consent_limits.py new file mode 100644 index 0000000..984674d --- /dev/null +++ b/tests/test_agent_consent_limits.py @@ -0,0 +1,136 @@ +import os +import sys +import threading +import time +import unittest +from pathlib import Path + +import stand_ins + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "backend")) + +from app import cli +from app.services import consent + + +class Recorder: + def __init__(self): + self.events = [] + + def emit(self, name, data=None): + self.events.append((name, data)) + + +def wait_for(test, timeout=5.0): + end = time.time() + timeout + while time.time() < end: + if test(): + return True + time.sleep(0.01) + return False + + +class Flaky(cli.Engine): + def __init__(self, answers): + super().__init__(None, "local") + self.answers = list(answers) + self.tools = [] + self.sent = [] + + def forwards(self): + return self.answers.pop(0) if self.answers else False + + def tool(self, name, args): + self.tools.append((name, args)) + return {"forwarded": name} + + def send(self, method, path, body=None, query=None, timeout=300): + self.sent.append((method, path)) + return 500, {}, b'{"detail": "not reached in this test"}' + + +class ConsentLimits(unittest.TestCase): + def setUp(self): + self.saved = (consent.access, consent.bus, consent.WAIT) + consent.bus = Recorder() + consent.access = lambda: "ask" + consent.window_opened() + + def tearDown(self): + for item in consent.pending(): + consent.answer(item["id"], "deny") + consent.access, consent.bus, consent.WAIT = self.saved + consent.window_closed() + + def test_the_request_names_the_local_file_a_tool_will_write(self): + box = {} + target = (Path(os.environ["HOME"]) / "notes.txt").resolve() + thread = threading.Thread(target=lambda: box.update(answer=self._run("package", {"id": "beat-board", "out": "~/notes.txt"}))) + thread.start() + self.assertTrue(wait_for(lambda: consent.pending())) + item = consent.pending()[0] + self.assertIn(str(target), item["what"]) + self.assertTrue(item["what"].startswith("run Package (package) in the project beat-board")) + consent.answer(item["id"], "deny") + thread.join(5) + self.assertEqual(box["answer"], consent.DENIED) + + def test_the_request_shows_invisible_characters_in_a_path_as_escapes(self): + box = {} + given = str(Path(os.environ["HOME"]) / "a‮gkpmrof.txt\nin the project other") + thread = threading.Thread(target=lambda: box.update(answer=self._run("package", {"id": "beat-board", "out": given}))) + thread.start() + self.assertTrue(wait_for(lambda: consent.pending())) + what = consent.pending()[0]["what"] + self.assertIn("a\\u202egkpmrof.txt\\u000ain the project other", what) + self.assertNotIn("‮", what) + self.assertNotIn("\n", what) + consent.answer(consent.pending()[0]["id"], "deny") + thread.join(5) + self.assertEqual(box["answer"], consent.DENIED) + + def test_the_request_names_the_folder_a_path_resolves_to(self): + box = {} + home = Path(os.environ["HOME"]) + thread = threading.Thread(target=lambda: box.update(answer=self._run("write", {"id": "beat-board", "path": "k.txt", "source": str(home / "projects" / ".." / "secret.txt")}))) + thread.start() + self.assertTrue(wait_for(lambda: consent.pending())) + what = consent.pending()[0]["what"] + self.assertIn("source " + str((home / "secret.txt").resolve()), what) + self.assertNotIn("..", what) + consent.answer(consent.pending()[0]["id"], "deny") + thread.join(5) + self.assertEqual(box["answer"], consent.DENIED) + + def test_a_call_is_refused_at_once_when_too_many_are_already_waiting(self): + threads = [threading.Thread(target=consent.check, args=("new", "New extension", {})) for _ in range(consent.MAX_WAITING)] + for t in threads: + t.start() + self.assertTrue(wait_for(lambda: len(consent.pending()) == consent.MAX_WAITING)) + started = time.time() + self.assertEqual(consent.check("new", "New extension", {}), consent.BUSY) + self.assertLess(time.time() - started, 1.0) + for item in consent.pending(): + consent.answer(item["id"], "deny") + for t in threads: + t.join(5) + self.assertEqual(consent.pending(), []) + + def test_a_write_decided_as_forwarded_is_never_run_in_this_process(self): + eng = Flaky([True, False]) + answer = cli.run_op(eng, "write", {"id": "beat-board", "path": "notes.txt", "text": "hello"}) + self.assertEqual(answer, {"forwarded": "write"}) + self.assertEqual(eng.sent, []) + self.assertEqual([name for name, _ in eng.tools], ["write"]) + + def _run(self, name, args): + try: + cli.run_op(Flaky([False]), name, args) + except cli.OpError as err: + return err.message + return None + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_agent_start.py b/tests/test_agent_start.py new file mode 100644 index 0000000..241d25e --- /dev/null +++ b/tests/test_agent_start.py @@ -0,0 +1,115 @@ +import importlib.util +import os +import subprocess +import sys +import tempfile +import tomllib +import unittest +from pathlib import Path + +import stand_ins + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "backend")) + +from app.services import agent_start, agents + +NPM_SHIM = '@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\nIF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@scope\\tool\\cli.js" %*\r\n' +EXE_SHIM = '@ECHO off\r\n"%dp0%\\tool.exe" %*\r\n' +ENV = {"COMSPEC": "cmd.exe", "PATH": ""} + + +class AgentStart(unittest.TestCase): + def setUp(self): + self.box = Path(tempfile.mkdtemp(prefix="agent-start-")) + + def shim(self, text, *targets): + for rel in targets: + path = self.box.joinpath(*rel.split("/")) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("", encoding="utf-8") + launcher = self.box / "tool.cmd" + launcher.write_text(text, encoding="utf-8") + return str(launcher) + + def test_an_npm_launcher_runs_its_script_with_the_node_beside_it_and_no_interpreter(self): + launcher = self.shim(NPM_SHIM, "node.exe", "node_modules/@scope/tool/cli.js") + argv = agent_start.start_argv([launcher, "-p", "line one\nline two & more"], ENV, "win32") + self.assertEqual(argv, [str(self.box / "node.exe"), str(self.box / "node_modules" / "@scope" / "tool" / "cli.js"), "-p", "line one\nline two & more"]) + + def test_a_launcher_that_names_a_program_runs_that_program(self): + launcher = self.shim(EXE_SHIM, "tool.exe") + self.assertEqual(agent_start.start_argv([launcher, "--version"], ENV, "win32"), [str(self.box / "tool.exe"), "--version"]) + + def test_an_unknown_command_script_gets_plain_words_through_the_interpreter(self): + launcher = self.shim("@echo off\r\nrem nothing to follow\r\n") + self.assertEqual(agent_start.start_argv([launcher, "--version", "a b c"], ENV, "win32"), ["cmd.exe", "/c", launcher, "--version", "a b c"]) + + def test_an_unknown_command_script_refuses_words_the_interpreter_would_read(self): + launcher = self.shim("@echo off\r\n") + for word in ("two\nlines", "50%", "%PATH%", 'say "hi"', "a&b", "x|y", "(z)", "up^", "bang!", "tab\there\x07", "a b & c", "in (quotes)"): + with self.subTest(word=word): + with self.assertRaises(OSError): + agent_start.start_argv([launcher, word], ENV, "win32") + + def test_a_refused_word_names_the_script_and_points_to_stdin_or_a_file(self): + launcher = self.shim("@echo off\r\n") + with self.assertRaises(agent_start.RefusedWord) as caught: + agent_start.start_argv([launcher, "-p", "a long prompt (with notes)"], ENV, "win32") + self.assertIn("tool.cmd", str(caught.exception)) + self.assertIn("stdin or a file", str(caught.exception)) + + def test_a_batch_file_in_capitals_is_held_to_the_same_plain_words(self): + launcher = self.box / "TOOL.BAT" + launcher.write_text("@echo off\r\n", encoding="utf-8") + env = {"COMSPEC": "C:\\Windows\\System32\\cmd.exe", "PATH": ""} + self.assertEqual(agent_start.start_argv([str(launcher), "run"], env, "win32"), ["C:\\Windows\\System32\\cmd.exe", "/c", str(launcher), "run"]) + with self.assertRaises(agent_start.RefusedWord): + agent_start.start_argv([str(launcher), "a>b"], env, "win32") + + def test_an_npm_launcher_with_no_node_to_run_it_falls_back_to_plain_words_only(self): + launcher = self.shim(NPM_SHIM, "node_modules/@scope/tool/cli.js") + self.assertEqual(agent_start.start_argv([launcher, "--version"], ENV, "win32"), ["cmd.exe", "/c", launcher, "--version"]) + with self.assertRaises(agent_start.RefusedWord): + agent_start.start_argv([launcher, "-p", "one & two"], ENV, "win32") + + def test_on_this_system_a_program_starts_and_gets_its_words_unchanged(self): + if os.name == "nt": + self.skipTest("the login shell path is for macOS and Linux") + words = ["printf", "%s|", "two\nlines", "50%", "a&b"] + out = subprocess.run(agent_start.start_argv(words), capture_output=True, text=True, timeout=30) + self.assertEqual(out.stdout, "two\nlines|50%|a&b|") + + +class CodexConfig(unittest.TestCase): + def load(self): + spec = importlib.util.spec_from_file_location("formext_setup_agents_toml", ROOT / "setup" / "agents.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + def test_a_windows_launcher_path_is_written_to_codex_as_valid_toml(self): + setup = self.load() + launcher = "C:\\Users\\Ann\\form.ext\\formext.bat" + setup.servers = lambda: {"formext": [launcher, ["mcp"]]} + home = Path(tempfile.mkdtemp(prefix="codex-home-")) + os.environ["CODEX_HOME"] = str(home / ".codex") + try: + setup.install_codex(home, False, []) + data = tomllib.loads((home / ".codex" / "config.toml").read_text(encoding="utf-8")) + self.assertEqual(data["mcp_servers"]["formext"]["command"], launcher) + self.assertEqual(data["mcp_servers"]["formext"]["args"], ["mcp"]) + said = [] + setup.install_codex(home, False, said) + self.assertIn("already in", said[1]) + finally: + os.environ.pop("CODEX_HOME", None) + + def test_the_windows_launcher_is_the_batch_twin(self): + self.assertEqual(agents.launcher_name("win32"), "formext.bat") + self.assertEqual(agents.launcher_name("darwin"), "formext") + self.assertTrue((ROOT / agents.launcher_name("win32")).is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/validate/conftest.py b/tests/validate/conftest.py index 11baec1..871f7d7 100644 --- a/tests/validate/conftest.py +++ b/tests/validate/conftest.py @@ -25,7 +25,7 @@ def client(): from app.main import app from app.services import window_key - return TestClient(app, headers={window_key.HEADER: window_key.KEY}) + return TestClient(app, base_url="http://127.0.0.1:8640", headers={window_key.HEADER: window_key.KEY}) @pytest.fixture diff --git a/tests/workspace/conftest.py b/tests/workspace/conftest.py index caa51da..26c439c 100644 --- a/tests/workspace/conftest.py +++ b/tests/workspace/conftest.py @@ -26,12 +26,12 @@ def home(tmp_path, monkeypatch): @pytest.fixture def client(home): - return TestClient(app, headers={window_key.HEADER: window_key.KEY}, raise_server_exceptions=False) + return TestClient(app, base_url="http://127.0.0.1:8640", headers={window_key.HEADER: window_key.KEY}, raise_server_exceptions=False) @pytest.fixture def outsider(home): - return TestClient(app, raise_server_exceptions=False) + return TestClient(app, base_url="http://127.0.0.1:8640", raise_server_exceptions=False) @pytest.fixture