From 5d6b29cb68c008048904b28be00e8cfc6b00e5dc Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 14:59:25 -0500 Subject: [PATCH 1/2] fix(cli): the command line is known by a key the engine writes on each start, not by its name The engine makes a new key on each start and writes it to cli.key in its data folder (mode 0600, created new, removed on stop). ./formvis cli reads it and sends it; only a request with that key skips the Ask question for convert_file and run_command. The X-Formvis-Client header names the caller and skips nothing. tool.call run_command in serve needs yes, as command.run does. The manual says what the command line is and is not asked about. --- backend/HASHOUT_LOG.md | 10 +++ backend/app/core/cli_key.py | 64 +++++++++++++++ backend/app/main.py | 4 +- backend/app/routers/mcp.py | 7 +- backend/tests/test_cli_key.py | 142 ++++++++++++++++++++++++++++++++++ docs/MANUAL.md | 14 +++- setup/cli.py | 51 +++++++++++- 7 files changed, 285 insertions(+), 7 deletions(-) create mode 100644 backend/app/core/cli_key.py create mode 100644 backend/tests/test_cli_key.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index caa5da29..fb6d868f 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,16 @@ Living log for the engine service side, _v0.1.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. +## The command line is known by a key the engine writes, not by its name · after 2.8.3, unreleased (core/cli_key.py new; main.py lifespan; routers/mcp.py _from_cli; setup/cli.py ROOT, KEY_FILE, KEY_HEADER, data_folder, cli_key, headers, call, serve_request; tests/test_cli_key.py new; docs/MANUAL.md) + +- Kind: fix · logged 2026-11-29. +- Why: `_from_cli` took any plain HTTP call with `X-Formvis-Client: formvis-cli` as the command line, and that skips the Ask question for `convert_file` and `run_command`. Any local program can send that header. +- Now: `lifespan` calls `cli_key.issue(data)`, which makes a new `secrets.token_urlsafe(32)` on each start, removes any `cli.key` already in the data folder and creates the file again with `O_CREAT | O_EXCL | O_NOFOLLOW` at mode 0600 (no file is written through, a symbolic link included); when the file cannot be made there is no key and the command line is asked like any agent. Shutdown calls `cli_key.revoke()`, which forgets the key and removes the file while it still holds this run's value. `_from_cli` is `cli_key.valid(header x-formvis-cli-key)` (compared with `hmac.compare_digest`) with no clientInfo and no session id. The `X-Formvis-Client` header still names the caller and skips nothing. +- Command line: `headers()` reads `cli.key` on each call from `data_folder()`, which follows `config.data_dir` for an engine run from the repo (FORMVIS_DATA_DIR, FORMVIS_PORTABLE=1, ~/Formvis when there, the platform folder) without making anything, accepts only a value of the key's shape, and sends it only when FORMVIS_URL is a loopback address. `serve`'s `tool.call` with `run_command` now goes through `command_result`, so a risky command needs `"yes": true` there as in `command.run`. +- Replaced, quoted exactly: `mcp.py` `_from_cli`: ` return request.headers.get("x-formvis-client") == "formvis-cli" and not info and not sid`; `cli.py` `call`: `headers={"Content-Type": "application/json", "X-Formvis-Client": "formvis-cli"}`. +- Not covered: a frozen portable engine (FormvisData beside the installed program) is found by the command line only through FORMVIS_DATA_DIR. On Windows the file mode is not an access list; the key relies on the per-user data folder there. +- Seen: tests/test_cli_key.py here on macOS; two of its tests fail on the earlier `_from_cli`. Not run: Windows. + ## Hardening of the ComfyUI reads, the agent seal, the agent file writes, the library move and the Windows starter · after 2.8.3, unreleased (routers/comfyui.py status, last_graph, upscale_models_route, job, image; core/seal.py SEALED, EARLIER, VERSION, check, sign; services/agents.py _load; routers/mcp.py _convert, _run; routers/projects.py _free_beside, set_folder; services/agent_lookup.py shim_target, cmd_safe, start_argv, VERSION; setup/agents.py LOOKUP_HASHES) - Kind: fix · logged 2026-11-29. diff --git a/backend/app/core/cli_key.py b/backend/app/core/cli_key.py new file mode 100644 index 00000000..45d9c050 --- /dev/null +++ b/backend/app/core/cli_key.py @@ -0,0 +1,64 @@ +"""The command line's key: a random value the engine makes on each start and writes into cli.key in its data folder, +readable by this user only. `./formvis cli` reads the file and sends the value in a header; a request carrying it is +the command line's own, which names its files and confirms risky commands itself. A caller that only names itself +formvis-cli is an outside agent like any other. The file is always made new (a file already there is removed first, +never written through), and it is removed when the engine stops.""" + +import hmac +import logging +import os +import secrets +from pathlib import Path + +FILE_NAME = "cli.key" +HEADER = "x-formvis-cli-key" +_held: dict = {"value": None, "file": None} +log = logging.getLogger("formvis") + + +def path(data: Path) -> Path: + return data / FILE_NAME + + +def _create(target: Path, value: str) -> None: + """Writes value into a file that must not exist yet (O_EXCL, and no symbolic link followed), mode 0600.""" + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) + fd = os.open(target, flags, 0o600) + try: + os.write(fd, value.encode("ascii")) + finally: + os.close(fd) + + +def issue(data: Path) -> str | None: + """A new key for this run, written to the data folder; None (no key, so the command line is asked like any agent) + when the file cannot be made.""" + value = secrets.token_urlsafe(32) + target = path(data) + _held.update(value=None, file=None) + try: + target.unlink(missing_ok=True) + _create(target, value) + except OSError as exc: + log.warning("the command line key could not be written to %s: %s", target, exc) + return None + _held.update(value=value, file=target) + return value + + +def valid(given) -> bool: + held = _held["value"] + return isinstance(given, str) and bool(given) and bool(held) and hmac.compare_digest(given.encode("utf-8"), held.encode("ascii")) + + +def revoke() -> None: + """Forgets this run's key and removes its file, when the file still holds it.""" + value, target = _held["value"], _held["file"] + _held.update(value=None, file=None) + if not value or target is None: + return + try: + if target.read_text(encoding="ascii") == value: + target.unlink() + except (OSError, ValueError): + pass diff --git a/backend/app/main.py b/backend/app/main.py index 6f02ac52..00cafd9d 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -9,7 +9,7 @@ from starlette.datastructures import MutableHeaders from app import ffmpeg_fetch -from app.core import config, runtime +from app.core import cli_key, config, runtime from app.core.local_guard import LocalGuard from app.core import window_key from app.routers import fal as _fal_router @@ -26,9 +26,11 @@ async def lifespan(_: FastAPI): data = config.data_dir() runtime.start_logging(data) + cli_key.issue(data) asyncio.get_running_loop().run_in_executor(None, sessions.prune) _terminal_service.bind(asyncio.get_running_loop()) yield + cli_key.revoke() _claude_service.stop(quiet=True) _terminal_service.close_all() runtime.stop_logging() diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index bde40381..1bb9a372 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -18,7 +18,7 @@ import time import urllib.parse -from app.core import config, window_key +from app.core import cli_key, config, window_key from fastapi import APIRouter, Request, Response from fastapi.responses import StreamingResponse @@ -1286,9 +1286,10 @@ def _client_of(request: Request, params: dict, sid: str | None) -> tuple[str, st def _from_cli(request: Request, params: dict, sid: str | None) -> bool: - """The command line's own HTTP call: named formvis-cli by its header, with no MCP session or clientInfo, through which any agent can claim that name.""" + """The command line's own HTTP call: it carries this run's command line key (core/cli_key.py, read from the data + folder) and no MCP session or clientInfo. A name alone, in a header or in clientInfo, is any agent's claim.""" info = (params.get("_meta") or {}).get("io.modelcontextprotocol/clientInfo") or params.get("clientInfo") - return request.headers.get("x-formvis-client") == "formvis-cli" and not info and not sid + return cli_key.valid(request.headers.get(cli_key.HEADER)) and not info and not sid # Live resources: the same state the read tools give, as documents a client can attach. diff --git a/backend/tests/test_cli_key.py b/backend/tests/test_cli_key.py new file mode 100644 index 00000000..56404c1d --- /dev/null +++ b/backend/tests/test_cli_key.py @@ -0,0 +1,142 @@ +"""The command line's key: the engine writes a new one on each start into a file only this user can read, the +command line sends it, and only a request carrying it skips the Ask question for convert_file and run_command.""" +import os +import stat +import sys +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from app.core import cli_key, config, window_key +from app.main import app +from app.routers import mcp as M +from app.services import agents + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "setup")) +import cli # noqa: E402 + +BASE = "http://127.0.0.1:8190" + + +class Asked: + def __init__(self, headers: dict): + self.headers = {k.lower(): v for k, v in headers.items()} + + +@pytest.fixture(autouse=True) +def no_key_left(): + yield + cli_key.revoke() + + +def test_each_issue_writes_a_new_key_only_this_user_can_read(tmp_path): + first = cli_key.issue(tmp_path) + second = cli_key.issue(tmp_path) + assert first and second and first != second + target = tmp_path / cli_key.FILE_NAME + assert target.read_text() == second + if os.name == "posix": + assert stat.S_IMODE(target.stat().st_mode) == 0o600 + assert cli_key.valid(second) and not cli_key.valid(first) and not cli_key.valid("") and not cli_key.valid(None) + + +def test_a_file_already_there_is_replaced_and_never_written_through(tmp_path): + outside = tmp_path / "outside.txt" + outside.write_text("keep") + target = tmp_path / cli_key.FILE_NAME + target.symlink_to(outside) + value = cli_key.issue(tmp_path) + assert outside.read_text() == "keep" + assert not target.is_symlink() and target.read_text() == value + + +def test_no_key_when_the_file_cannot_be_made(tmp_path): + missing = tmp_path / "not-a-folder" + assert cli_key.issue(missing) is None + assert not cli_key.valid("anything") + + +def test_the_engine_rotates_the_key_on_each_start_and_removes_it_on_stop(tmp_path, monkeypatch): + monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path)) + target = tmp_path / cli_key.FILE_NAME + with TestClient(app, base_url=BASE): + first = target.read_text() + assert cli_key.valid(first) + assert not target.exists() and not cli_key.valid(first) + with TestClient(app, base_url=BASE): + assert target.read_text() != first + + +def test_only_the_key_marks_a_call_as_the_command_lines(tmp_path): + value = cli_key.issue(tmp_path) + named = {"X-Formvis-Client": "formvis-cli"} + assert not M._from_cli(Asked(named), {}, None) + assert not M._from_cli(Asked({**named, cli_key.HEADER: "x" * 43}), {}, None) + assert M._from_cli(Asked({cli_key.HEADER: value}), {}, None) + assert not M._from_cli(Asked({cli_key.HEADER: value}), {"clientInfo": {"name": "formvis-cli"}}, None) + assert not M._from_cli(Asked({cli_key.HEADER: value}), {}, "a-session") + + +def _convert(c, src, dst, extra: dict): + body = {"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "convert_file", "arguments": {"path": str(src), "output_path": str(dst), "overwrite": True}}} + return c.post("/mcp", json=body, headers={"X-Formvis-Client": "formvis-cli", **extra}).json()["result"] + + +def test_a_name_alone_is_asked_and_the_key_is_not(tmp_path, monkeypatch): + from PIL import Image + + data = tmp_path / "data" + monkeypatch.setenv("FORMVIS_DATA_DIR", str(data)) + monkeypatch.setattr(M, "_live", lambda: False) + monkeypatch.setattr(agents, "policy_of", lambda client: "ask") + monkeypatch.setattr(agents, "admit", lambda client: None) + src, dst = tmp_path / "in.png", tmp_path / "out.jpg" + Image.new("RGB", (4, 3), (200, 10, 10)).save(src) + dst.write_bytes(b"old") + with TestClient(app, base_url=BASE, headers={window_key.HEADER: window_key.KEY}) as c: + named = _convert(c, src, dst, {}) + assert named["isError"] and "no formvis window is open" in named["content"][0]["text"] + assert dst.read_bytes() == b"old" + keyed = _convert(c, src, dst, {"X-Formvis-Cli-Key": (data / cli_key.FILE_NAME).read_text()}) + assert not keyed.get("isError"), keyed + assert dst.read_bytes()[:2] == b"\xff\xd8" + + +def test_the_command_line_finds_the_data_folder_the_engine_uses(tmp_path, monkeypatch): + for name in ("FORMVIS_DATA_DIR", "FORMVIS_PORTABLE"): + monkeypatch.delenv(name, raising=False) + home = tmp_path / "home" + home.mkdir() + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.setenv("APPDATA", str(home / "AppData" / "Roaming")) + monkeypatch.setenv("XDG_DATA_HOME", str(home / ".local" / "share")) + assert cli.data_folder() == config.data_dir() + (home / "Formvis").mkdir() + assert cli.data_folder() == config.data_dir() == home / "Formvis" + monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path / "chosen")) + assert cli.data_folder() == config.data_dir() + + +def test_the_command_line_sends_the_key_it_reads(tmp_path, monkeypatch): + monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path)) + value = cli_key.issue(tmp_path) + assert cli.headers()[cli.KEY_HEADER] == value + monkeypatch.setattr(cli, "URL", "http://192.0.2.1:8190") + assert cli.KEY_HEADER not in cli.headers() + monkeypatch.setattr(cli, "URL", BASE) + (tmp_path / cli_key.FILE_NAME).unlink() + (tmp_path / cli_key.FILE_NAME).write_text("not a key\n") + assert cli.KEY_HEADER not in cli.headers() + + +def test_a_risky_command_through_tool_call_still_needs_yes(monkeypatch): + sent = [] + monkeypatch.setattr(cli, "call", lambda method, path, body=None: (200, {"risky": True})) + monkeypatch.setattr(cli, "tool", lambda name, args: sent.append(name) or (True, "", {})) + with pytest.raises(RuntimeError, match="--yes"): + cli.serve_request("tool.call", {"name": "run_command", "arguments": {"id": "file.revert"}}, None) + assert sent == [] + cli.serve_request("tool.call", {"name": "run_command", "arguments": {"id": "file.revert"}, "yes": True}, None) + assert sent == ["run_command"] diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 8246efba..3990b300 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -629,7 +629,8 @@ other modes and depths its menu items are off, with the reason as their tooltip. formvis window can do this"). The saved choice is sealed; if the file is changed outside formvis, the choice reads as Ask again and formvis says so once. A choice saved in the older sealed format is sealed again the first time a newer formvis starts, with Outside agents set to Blocked; set it back in Preferences > Plugins if you had it open. - formvis's own command line (`./formvis cli`, `./formvis headless`) is asked about like any other outside agent. + formvis's own command line (`./formvis cli`, `./formvis headless`) is asked about like any other outside agent, + except for the steps it confirms itself (see The command line below). ## Terminal @@ -689,8 +690,17 @@ other modes and depths its menu items are off, with the reason as their tooltip. commands (`--group Filter` narrows by menu), `./formvis cli describe ` says what one does and what it takes, and `./formvis cli run key=value ...` runs it in the open window as an undoable step. A command whose result undo cannot reverse (a file overwritten, say) runs only with `--yes`. +- What the command line is asked about. Each time the engine starts it makes a new command line key and writes it to + `cli.key` in its data folder, a file only your account can read; it is removed when the engine stops. `./formvis cli` + reads it and sends it with each request. A request with that key is not asked about in the window for `convert` (you + name the files, and a file is replaced only with `--overwrite`) or for running a command (a command that undo cannot + reverse runs only with `--yes`, from `run`, `process` and `serve` alike). Everything else it does is asked about as + for any other program, and Blocked and Deny still refuse it. A program that only calls itself formvis-cli, without + the key, is treated like any other. The key is sent only to an engine on this computer and is found in the data + folder the engine uses (`FORMVIS_DATA_DIR` when you set one); with no key the command line still works and is + asked about like any other program. - The window has to be open (`./formvis boot`); with Outside agents on Ask (Preferences > Plugins) formvis asks you in - the window when a command arrives. Or add `--headless` to + the window when a command arrives that needs it. Or add `--headless` to `list`, `describe`, `run`, `process`, `batch`, `droplet`, `serve` or `convert`: a window with no screen (Playwright's Chromium, as `./formvis bench` uses) is started for that run and is closed when the command ends. It follows the choice you saved in formvis and cannot change it: set Outside agents to Allowed in the window first, because with no screen nobody can diff --git a/setup/cli.py b/setup/cli.py index 7bd8b080..f232a42b 100644 --- a/setup/cli.py +++ b/setup/cli.py @@ -76,6 +76,7 @@ import hmac import json import os +import re import shutil import stat import sys @@ -83,13 +84,58 @@ import urllib.error import urllib.parse import urllib.request +from pathlib import Path URL = os.environ.get("FORMVIS_URL", f"http://127.0.0.1:{os.environ.get('FORMVIS_PORT', '').lstrip('0') or 8190}").rstrip("/") +ROOT = Path(__file__).resolve().parent.parent +KEY_FILE = "cli.key" +KEY_HEADER = "X-Formvis-Cli-Key" +KEY_SHAPE = re.compile(r"[A-Za-z0-9_-]{32,128}") +LOOPBACK = {"127.0.0.1", "localhost", "::1"} + + +def data_folder() -> Path: + """The engine's data folder, found as backend/app/core/config.py data_dir finds it for an engine run from this + folder: FORMVIS_DATA_DIR, the portable folder (FORMVIS_PORTABLE=1), ~/Formvis when it is there, else the + platform's own folder. Nothing is made here.""" + raw = os.environ.get("FORMVIS_DATA_DIR") + if raw: + return Path(raw).expanduser() + if os.environ.get("FORMVIS_PORTABLE") == "1": + return ROOT / "backend" / "FormvisData" + home = Path.home() + if (home / "Formvis").exists(): + return home / "Formvis" + if sys.platform == "darwin": + return home / "Library" / "Application Support" / "formvis" + if sys.platform.startswith("win"): + return Path(os.environ.get("APPDATA") or home / "AppData" / "Roaming") / "formvis" + base = Path(os.environ.get("XDG_DATA_HOME") or ".") + return (base if base.is_absolute() else home / ".local" / "share") / "formvis" + + +def cli_key() -> str | None: + """The key the running engine wrote for the command line (core/cli_key.py), read fresh on each call since the + engine makes a new one each time it starts. Sent only to an engine on this computer, and only a value of the + key's shape is read from the file; None when there is none, and the engine then asks as it does for any agent.""" + if (urllib.parse.urlsplit(URL).hostname or "") not in LOOPBACK: + return None + try: + with open(data_folder() / KEY_FILE, "rb") as f: + value = f.read(129).decode("ascii").strip() + except (OSError, UnicodeDecodeError): + return None + return value if KEY_SHAPE.fullmatch(value) else None + + +def headers() -> dict: + key = cli_key() + return {"Content-Type": "application/json", "X-Formvis-Client": "formvis-cli", **({KEY_HEADER: key} if key else {})} def call(method: str, path: str, body: dict | None = None) -> tuple[int, dict]: data = json.dumps(body).encode() if body is not None else None - req = urllib.request.Request(URL + path, data=data, method=method, headers={"Content-Type": "application/json", "X-Formvis-Client": "formvis-cli"}) + req = urllib.request.Request(URL + path, data=data, method=method, headers=headers()) wait = float(os.environ.get("FORMVIS_CLI_TIMEOUT") or 660) try: with urllib.request.urlopen(req, timeout=wait) as r: @@ -815,6 +861,9 @@ def serve_request(method: str, params: dict, root: str | None): name, args = params.get("name"), params.get("arguments") or {} if not isinstance(name, str) or not isinstance(args, dict): raise RuntimeError("tool.call takes name and arguments.") + if name == "run_command": # the same --yes rule as command.run: the engine does not ask the command line about it + returned = command_result(str(args.get("id", "")), args.get("params") or {}, bool(params.get("yes"))) + return {"message": STEP["said"], "returned": returned} method, params = "", args tool_name = name elif method in TOOL_METHODS: From 8e4739b83684ee7cd010b1c3544b583dd9f197d8 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 15:03:57 -0500 Subject: [PATCH 2/2] fix(cli): the command line finds a data folder set in backend/.env, as the engine does The engine reads FORMVIS_DATA_DIR and FORMVIS_PORTABLE from backend/.env when the environment does not set them; the command line now does the same when it looks for cli.key. The wiki's Agents page says what the key skips. --- .docs/wiki/Agents.md | 2 +- backend/HASHOUT_LOG.md | 3 ++- backend/tests/test_cli_key.py | 16 ++++++++++++++++ docs/MANUAL.md | 4 ++-- setup/cli.py | 22 +++++++++++++++++++--- 5 files changed, 40 insertions(+), 7 deletions(-) diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index aa4d03e5..f0abf781 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -30,5 +30,5 @@ Generated by `./formvis agents sync` and never edited by hand: `formvis-editing/ - Only this computer can connect; `/mcp` checks the Origin header. - Only the formvis window can change what agents may do, answer a question or an approval, or use the terminal dock. The engine makes a window key at each start (`backend/app/core/window_key.py`); every POST, PUT and DELETE except `/mcp`, `/api/window/key` and the two merge routes needs it in `X-Formvis-Window-Key` and is refused with 403 "Only the formvis window can do this" without it, and the terminal, Claude Code and agent sockets must send it as their first message. Run from source, the first page to ask gets the key; the desktop app hands it to its own window. - The saved choice (`agents.json` in the data folder) is sealed. Changed outside formvis, it reads as Ask again, and Agent Connect and Preferences say so once. -- formvis's own command line (`./formvis cli`, `./formvis headless`, `./formvis mcp`) goes in through `/mcp` as an outside agent and is asked about like any other. A script that used to change the agent setting through the engine must now have the person set Outside agents to Allowed in the window (Preferences > Plugins) first. +- formvis's own command line (`./formvis cli`, `./formvis headless`, `./formvis mcp`) goes in through `/mcp` as an outside agent and is asked about like any other, with one exception: `./formvis cli` sends the key the engine writes to `cli.key` in its data folder on each start (`backend/app/core/cli_key.py`, readable by this user only, removed on stop), and a request with that key is not asked about `convert_file` (the command line names the files and `--overwrite`) or `run_command` (a command undo cannot reverse needs `--yes`). The `X-Formvis-Client` header only names the caller and skips nothing. A script that used to change the agent setting through the engine must now have the person set Outside agents to Allowed in the window (Preferences > Plugins) first. - After changing the tools in `mcp.py` or the commands in the window, run `./formvis agents sync` (with `backend/venv/bin` first on the path); the engine tests run `--check`. diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index fb6d868f..f8910a08 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,13 +2,14 @@ Living log for the engine service side, _v0.1.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full. -## The command line is known by a key the engine writes, not by its name · after 2.8.3, unreleased (core/cli_key.py new; main.py lifespan; routers/mcp.py _from_cli; setup/cli.py ROOT, KEY_FILE, KEY_HEADER, data_folder, cli_key, headers, call, serve_request; tests/test_cli_key.py new; docs/MANUAL.md) +## The command line is known by a key the engine writes, not by its name · after 2.8.3, unreleased (core/cli_key.py new; main.py lifespan; routers/mcp.py _from_cli; setup/cli.py ROOT, KEY_FILE, KEY_HEADER, engine_setting, data_folder, cli_key, headers, call, serve_request; tests/test_cli_key.py new; docs/MANUAL.md; .docs/wiki/Agents.md) - Kind: fix · logged 2026-11-29. - Why: `_from_cli` took any plain HTTP call with `X-Formvis-Client: formvis-cli` as the command line, and that skips the Ask question for `convert_file` and `run_command`. Any local program can send that header. - Now: `lifespan` calls `cli_key.issue(data)`, which makes a new `secrets.token_urlsafe(32)` on each start, removes any `cli.key` already in the data folder and creates the file again with `O_CREAT | O_EXCL | O_NOFOLLOW` at mode 0600 (no file is written through, a symbolic link included); when the file cannot be made there is no key and the command line is asked like any agent. Shutdown calls `cli_key.revoke()`, which forgets the key and removes the file while it still holds this run's value. `_from_cli` is `cli_key.valid(header x-formvis-cli-key)` (compared with `hmac.compare_digest`) with no clientInfo and no session id. The `X-Formvis-Client` header still names the caller and skips nothing. - Command line: `headers()` reads `cli.key` on each call from `data_folder()`, which follows `config.data_dir` for an engine run from the repo (FORMVIS_DATA_DIR, FORMVIS_PORTABLE=1, ~/Formvis when there, the platform folder) without making anything, accepts only a value of the key's shape, and sends it only when FORMVIS_URL is a loopback address. `serve`'s `tool.call` with `run_command` now goes through `command_result`, so a risky command needs `"yes": true` there as in `command.run`. - Replaced, quoted exactly: `mcp.py` `_from_cli`: ` return request.headers.get("x-formvis-client") == "formvis-cli" and not info and not sid`; `cli.py` `call`: `headers={"Content-Type": "application/json", "X-Formvis-Client": "formvis-cli"}`. +- Then: `data_folder()` reads FORMVIS_DATA_DIR and FORMVIS_PORTABLE through `engine_setting(name)`, the environment first and else `backend/.env` with the rules of `config._load_env_file`, because the engine takes them from that file too (`backend/.env.example` names FORMVIS_DATA_DIR); before, a data folder set only there left the command line without its key. Replaced, quoted exactly: ` raw = os.environ.get("FORMVIS_DATA_DIR")` and ` if os.environ.get("FORMVIS_PORTABLE") == "1":`. The wiki's Agents page says what the key skips. - Not covered: a frozen portable engine (FormvisData beside the installed program) is found by the command line only through FORMVIS_DATA_DIR. On Windows the file mode is not an access list; the key relies on the per-user data folder there. - Seen: tests/test_cli_key.py here on macOS; two of its tests fail on the earlier `_from_cli`. Not run: Windows. diff --git a/backend/tests/test_cli_key.py b/backend/tests/test_cli_key.py index 56404c1d..44f2b5ab 100644 --- a/backend/tests/test_cli_key.py +++ b/backend/tests/test_cli_key.py @@ -140,3 +140,19 @@ def test_a_risky_command_through_tool_call_still_needs_yes(monkeypatch): assert sent == [] cli.serve_request("tool.call", {"name": "run_command", "arguments": {"id": "file.revert"}, "yes": True}, None) assert sent == ["run_command"] + + +def test_the_command_line_reads_the_data_folder_set_in_the_engine_env_file(tmp_path, monkeypatch): + for name in ("FORMVIS_DATA_DIR", "FORMVIS_PORTABLE"): + monkeypatch.delenv(name, raising=False) + root = tmp_path / "repo" + (root / "backend").mkdir(parents=True) + chosen = tmp_path / "chosen" + (root / "backend" / ".env").write_text(f"# local settings\nFORMVIS_PORTABLE=\nFORMVIS_DATA_DIR = {chosen}\n", encoding="utf-8") + monkeypatch.setattr(cli, "ROOT", root) + assert cli.data_folder() == chosen + monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path / "from-env")) + assert cli.data_folder() == tmp_path / "from-env" + monkeypatch.delenv("FORMVIS_DATA_DIR") + (root / "backend" / ".env").write_text("FORMVIS_PORTABLE=1\n", encoding="utf-8") + assert cli.data_folder() == root / "backend" / "FormvisData" diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 3990b300..059f5fcc 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -697,8 +697,8 @@ other modes and depths its menu items are off, with the reason as their tooltip. reverse runs only with `--yes`, from `run`, `process` and `serve` alike). Everything else it does is asked about as for any other program, and Blocked and Deny still refuse it. A program that only calls itself formvis-cli, without the key, is treated like any other. The key is sent only to an engine on this computer and is found in the data - folder the engine uses (`FORMVIS_DATA_DIR` when you set one); with no key the command line still works and is - asked about like any other program. + folder the engine uses (`FORMVIS_DATA_DIR` when you set one, in the environment or in `backend/.env`); with no key + the command line still works and is asked about like any other program. - The window has to be open (`./formvis boot`); with Outside agents on Ask (Preferences > Plugins) formvis asks you in the window when a command arrives that needs it. Or add `--headless` to `list`, `describe`, `run`, `process`, `batch`, `droplet`, `serve` or `convert`: a window with no screen (Playwright's Chromium, diff --git a/setup/cli.py b/setup/cli.py index f232a42b..50c7a3a4 100644 --- a/setup/cli.py +++ b/setup/cli.py @@ -94,14 +94,30 @@ LOOPBACK = {"127.0.0.1", "localhost", "::1"} +def engine_setting(name: str) -> str | None: + """A setting as the engine sees it: the environment first, else backend/.env, read with the same rules as + backend/app/core/config.py _load_env_file (an empty value is not a setting).""" + if os.environ.get(name): + return os.environ[name] + try: + lines = (ROOT / "backend" / ".env").read_text(encoding="utf-8").splitlines() + except (OSError, UnicodeDecodeError): + return None + for entry in lines: + key, sep, value = entry.strip().partition("=") + if sep and not entry.strip().startswith("#") and key.strip() == name and value.strip(): + return value.strip() + return None + + def data_folder() -> Path: """The engine's data folder, found as backend/app/core/config.py data_dir finds it for an engine run from this folder: FORMVIS_DATA_DIR, the portable folder (FORMVIS_PORTABLE=1), ~/Formvis when it is there, else the - platform's own folder. Nothing is made here.""" - raw = os.environ.get("FORMVIS_DATA_DIR") + platform's own folder; the first two from the environment or backend/.env. Nothing is made here.""" + raw = engine_setting("FORMVIS_DATA_DIR") if raw: return Path(raw).expanduser() - if os.environ.get("FORMVIS_PORTABLE") == "1": + if engine_setting("FORMVIS_PORTABLE") == "1": return ROOT / "backend" / "FormvisData" home = Path.home() if (home / "Formvis").exists():