Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
924deeb
fix: pass a plugin's git source to git clone only as a repository
gbarnai Nov 29, 2026
ed3ea16
fix: check the tool deny list first on the Claude Code engine
gbarnai Nov 29, 2026
5b0520d
fix: show the other-devices pairing link only in the FormAT window
gbarnai Nov 29, 2026
2a1dd30
fix: keep sandboxed commands on macOS from starting apps outside the …
gbarnai Nov 29, 2026
eec4bde
fix: keep the built-in browser off FormAT's own engine and window add…
gbarnai Nov 29, 2026
c4b5410
fix: end a bash tool command's whole process tree on stop, timeout an…
gbarnai Nov 29, 2026
01804bc
fix: keep a connector signed in when a token refresh cannot reach the…
gbarnai Nov 29, 2026
f25e332
fix: replace a skill of the same name only after its new copy is comp…
gbarnai Nov 29, 2026
6ff7557
docs: log the engine hardening in the backend HASHOUT log
gbarnai Nov 29, 2026
d9accb4
fix: read the built-in browser's addresses as the browser does and re…
gbarnai Nov 29, 2026
3a11333
fix: start Windows agent shims without the command interpreter where …
gbarnai Nov 29, 2026
5ad00e1
fix: end every process in a stopped bash tool command's group, also o…
gbarnai Nov 29, 2026
fb963ab
fix: never let a git source use a command transport
gbarnai Nov 29, 2026
f1eb6b6
docs: log the second hardening pass in the backend HASHOUT log
gbarnai Nov 29, 2026
5251d31
fix: refuse every command interpreter special character in a Windows …
gbarnai Nov 29, 2026
2c33919
test: run the bash tool process tests with the sandbox off
nodemode-ai Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1326,3 +1326,34 @@ Every read, classified. Public: `/api/health`, `/api/commands`, `/api/commands/{
The walk. `test_every_read_route_is_public_addressed_by_a_random_id_or_refused_without_the_window_key` takes every GET of the OpenAPI document; a new read that is in none of the three lists fails the test, and every private read must answer 403 with the refusal and must not echo the key. Seen failing with `PRIVATE_READS` emptied and with an added unlisted GET route; a new write route is refused by default (seen: 403), and the existing write walk fails if one answers without the key.

Seen with the real engine (format_engine.py, the built window in Chromium, stand-in agent programs on PATH), from source and with FORMAT_WINDOW_KEY_STDOUT=1 and the global given by an initialization script as the shell does: the window with its key wrote (POST /api/uploads 200), ran a command (200) and read the frame (204 with no page open; 200 image/jpeg from the pane itself with the browser open); a local program without the key got 403 on the write, the frame and the socket ticket, 403 with a wrong key, and its command waited for the person's consent; a second claim got 409 (404 in the packaged mode); after a reload the page made no new claim and its writes still answered 200. Before this change the frame answered the local program (204).

### Hardening after 0.32.0 (unreleased) · git sources, the deny list, pairing links, the macOS sandbox, the built-in browser, tool processes, connector refresh, skill replace
- refers-to: app/engine/marketplaces.py :: _git, _clone; app/engine/claude_code.py :: decision_for, run; app/engine/agent_lookup.py :: shim_target, cmd_safe, start_argv; app/core/local_guard.py :: BROWSER_MARK, LocalGuard._permitted; setup/agents.py :: LOOKUP_HASHES; app/engine/agents.py :: outside_result; app/routers/commands.py :: run; app/routers/mcp_http.py :: _call; app/engine/sandbox.py :: wrap; app/engine/browser.py :: own_origin, _url, _worker; app/engine/tools.py :: _bash, _watch, _kill, stop_all; app/routers/__init__.py :: shutdown; app/engine/oauth.py :: OAuthError, _token, access_token; app/engine/skills.py :: _install
- kind: decision
- logged: unreleased

Git sources. A plugin or marketplace git source, ref and sha that start with `-` are refused, and the URL goes after `--`, so git reads it only as a repository (tests/test_marketplace_sources.py).

The deny list on the Claude Code route. `decision_for` checks toolDeny first, then auto mode, toolAllow and Allow for this chat, the same order as tools.decision_for on the API route (tests/test_claude_code_permissions.py). The Claude Code route still gets no sandbox of its own; that is left open.

Pairing links. devices.status, devices.start and devices.forget return the pairing link and its QR code only to the window (a window key or a paired device). Every other caller, the REST route with or without `x-format-agent` and `/mcp`, gets pairUrl and qr as null and a `pairing` sentence; the listener itself still starts for them (tests/test_device_pairing_link.py).

The macOS sandbox. The sandbox-exec profile also denies lsopen, appleevent-send and the LaunchServices lookups, so a sandboxed command cannot hand work to an app that would run outside the sandbox. Seen: `open -g -a Finder` exits 1 inside the profile and 0 without these lines; true, sh, python3 and osascript `return 1` still run (tests/test_sandbox_profile.py).

The built-in browser. `own_origin` matches loopback hosts (localhost, *.localhost, 127/8, ::1, 0.0.0.0) on the engine port, the window ports and the devices port. `_url` refuses them, and a route on the browser context aborts any request to them, redirects and subresources included. Other local ports and public hosts open as before (tests/test_browser_addresses.py). The route was not run here: Playwright is not in the test list.

Tool processes. Every running bash tool command is kept in `_procs`; `stop_all` ends them at engine shutdown. On Windows `_kill` runs `taskkill /T /F`, so the programs cmd.exe started end with it; elsewhere the process group gets SIGTERM, then SIGKILL after 3 seconds (tests/test_tool_processes.py; the Windows branch was not run).

Connector refresh. A refresh that cannot reach the token endpoint (a network error, 429 or 5xx) returns no token and keeps the sign-in; only a refusal signs the connector out (tests/test_oauth_refresh.py).

Skill replace. `_install` copies into `.<name>.incoming-<ns>` first and swaps it in only when the copy is complete; a failed copy leaves the old skill as it was. Saving a skill from its own folder now works, because the copy is made before the old folder moves (tests/test_skill_replace.py). Installing a skill with an existing name still replaces it without asking, as before.

The built-in browser, second pass. `own_origin` reads the host the way the browser does before it compares: tabs and newlines dropped, backslashes as slashes, percent escapes and full-width characters folded, and the IPv4 forms the URL standard accepts (one to four parts, hex, octal, 127.1, 2130706433), IPv4-mapped and IPv4-compatible IPv6, :: and 0.0.0.0. `_url` also resolves a name and refuses it when any address is this computer. The context route now takes every loopback request: it aborts FormAT's own ports and sends the rest with the header `x-format-browser`, and LocalGuard (app/core/local_guard.py :: BROWSER_MARK) refuses any request that carries it, so a request from the built-in browser that reaches the engine by another path is still refused. A name that resolves to this computer only later arrives with its own Host, which LocalGuard already refuses (tests/test_browser_addresses.py).

Git transports. Every git call runs with `protocol.ext.allow=never`, so a source can never name a command transport, whatever the person's own git config says (tests/test_marketplace_sources.py).

Tool processes, second pass. `_kill` waits up to 3 seconds for the whole process group, not only its leader, and then sends SIGKILL to the group if anything in it still runs, so a child that ignores SIGTERM ends too (tests/test_tool_processes.py).

Tool process tests and the sandbox. tests/test_tool_processes.py turns the sandbox off for its tests with an autouse fixture (`sandbox.kind` returns None), as tests/test_sandbox_profile.py already sets `kind` itself. On a machine with bubblewrap, as the CI runner has, `_bash` ran each command in bwrap: its `--tmpfs /tmp` hid the stand-in shell conftest puts in `$SHELL` under the temp folder, so no command started and the SIGTERM test found no pid file. Even with the shell visible, `--unshare-pid` makes `$!` a pid inside the sandbox, which the test cannot check from outside. The tests are about the process group, which they now see unsandboxed; the bubblewrap path is not covered by them. Seen: with bwrap installed, the file failed the same way as CI and now passes, and the suite reads 233 passed, 1 skipped.

The shared finder, version 1.0.2 (app/engine/agent_lookup.py, hash in setup/agents.py `LOOKUP_HASHES`). On Windows `start_argv` no longer puts cmd.exe in front of an npm, pnpm or bun shim: `shim_target` reads the .cmd and runs the .exe it names, or node.exe (beside the shim, then on PATH) and the script it names. A shim of another kind still goes through cmd.exe, now with /d, and only when every word, the program's path included, passes `cmd_safe`: none of & | < > ^ ( ) ! % " and no control character (\x00-\x1f, \x7f), with or without spaces, because the shim reads its arguments again through %* and quoting does not hold there; otherwise the start is refused with an OSError that says to pass long text through stdin or a file. A name ending in .cmd or .bat followed by dots or spaces counts as a shim too. The Claude Code chat run passes its child environment to `start_argv`, so node is looked for on the same PATH the program gets (tests/test_windows_start.py; not run on Windows). The other Form engines still carry 1.0.1.
3 changes: 3 additions & 0 deletions backend/app/core/local_guard.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from urllib.parse import urlsplit

LOOPBACK = {"127.0.0.1", "localhost", "::1"}
BROWSER_MARK = "x-format-browser"


def _host_of(value: str) -> str:
Expand Down Expand Up @@ -30,6 +31,8 @@ def __init__(self, app, origins: list[str]) -> None:

def _permitted(self, headers: dict[str, str], paired: bool = False) -> bool:
host = headers.get("host", "")
if BROWSER_MARK in headers:
return False
if not paired and _host_of(host) not in LOOPBACK:
return False
origin = headers.get("origin")
Expand Down
60 changes: 57 additions & 3 deletions backend/app/engine/agent_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from dataclasses import dataclass, field
from pathlib import Path

VERSION = "1.0.1"
VERSION = "1.0.2"
PROGRAMS: dict = {
"claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin",
"install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex",
Expand Down Expand Up @@ -359,13 +359,67 @@ def _quote(word: str, fish: bool) -> str:
return "'" + word.replace("'", "'\"'\"'") + "'"


def _node(folder: Path, env: dict) -> str | None:
for place in [str(folder), *(env.get("PATH") or env.get("Path") or "").split(";")]:
if place.strip() and Path(place.strip(), "node.exe").is_file():
return str(Path(place.strip(), "node.exe"))
return None


def shim_target(path: str | os.PathLike, env: dict | None = None) -> list[str] | None:
"""The program a Windows .cmd or .bat shim of the npm, pnpm or bun kind starts, as the words to run it with: the .exe
it names, or node and the script it names. None when the shim is of another kind or its target is missing."""
env = os.environ if env is None else env
shim = Path(path)
try:
text = shim.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
hit = re.search(r'"%~?dp0%?[\\/]*([^"%\r\n]+)"\s*%\*', text)
if not hit:
return None
target = shim.parent.joinpath(*[p for p in re.split(r"[\\/]+", hit.group(1)) if p])
if not target.is_file():
return None
if target.suffix.lower() == ".exe":
return [str(target)]
if target.suffix.lower() in (".js", ".cjs", ".mjs"):
node = _node(shim.parent, env)
return [node, str(target)] if node else None
return None


CMD_SPECIAL = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]')
CMD_REFUSED = ("an argument holds a character the Windows command interpreter would read (& | < > ^ ( ) ! % \" or a control "
"character); pass long text through stdin or a file if the program supports it")


def cmd_safe(word: str) -> bool:
"""Whether word can go through the command interpreter: none of & | < > ^ ( ) ! % " and no control character,
quoted or not, because a .cmd shim reads its arguments again through %*."""
return not CMD_SPECIAL.search(word)


def _shim_ending(word: str) -> bool:
return word.rstrip(" .").lower().endswith((".cmd", ".bat"))


def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]:
"""How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux
(exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat."""
(exec, so the process is the program), directly on Windows. A .cmd or .bat shim is replaced by the program it starts;
only a shim of another kind goes through the command interpreter, and then every word, the program's path included,
must pass cmd_safe or the start is refused."""
words = [str(c) for c in cmd]
env = os.environ if env is None else env
if windows(platform):
return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words
if not _shim_ending(words[0]):
return words
direct = shim_target(words[0].rstrip(" ."), env)
if direct:
return [*direct, *words[1:]]
if not all(cmd_safe(w) for w in words):
raise OSError(22, CMD_REFUSED)
return [env.get("COMSPEC") or "cmd.exe", "/d", "/c", *words]
shell = login_shell(env, platform)
fish = Path(shell).name == "fish"
return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)]
Expand Down
6 changes: 6 additions & 0 deletions backend/app/engine/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ def require_outside(client: str, channel: str, cid: str, params: dict | None) ->
raise CommandError("Only the person, in FormAT's window, can change whether outside agents may use FormAT.", 403)


def outside_result(cid: str, result):
if cid.startswith("devices.") and isinstance(result, dict) and result.get("pairUrl"):
return result | {"pairUrl": None, "qr": None, "pairing": "Only FormAT's window shows the pairing link"}
return result


@command("agents.status", "Outside agents", mutates=False,
description="Whether outside agents (coding agents over MCP) may use Format (outsideAgents: ask, allowed or blocked) and which ones have called since the engine started.")
def status() -> dict:
Expand Down
93 changes: 93 additions & 0 deletions backend/app/engine/browser.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import concurrent.futures
import os
import queue
import re
import subprocess
import sys
import threading
Expand Down Expand Up @@ -129,6 +130,7 @@ def _worker() -> None:
return
if fut is not None:
fut.set_exception(CommandError(_state["error"], 503))
ctx.route(loopback, _guard)
page = ctx.pages[0] if ctx.pages else ctx.new_page()
_state.update(open=True, error="")
try:
Expand Down Expand Up @@ -178,6 +180,95 @@ def _do(fn, wait: float = 60):
raise CommandError("The browser did not answer in time", 504) from None


def _ipv4(host: str):
import ipaddress
parts = host.split(".")
if not 1 <= len(parts) <= 4:
return None
nums = []
for p in parts:
if re.fullmatch(r"0[xX][0-9a-fA-F]*", p):
nums.append(int(p[2:] or "0", 16))
elif re.fullmatch(r"0[0-7]+", p):
nums.append(int(p, 8))
elif re.fullmatch(r"[0-9]+", p):
nums.append(int(p))
else:
return None
if any(n > 255 for n in nums[:-1]) or nums[-1] >= 256 ** (5 - len(nums)):
return None
value = nums[-1]
for i, n in enumerate(nums[:-1]):
value += n << (8 * (3 - i))
return ipaddress.IPv4Address(value)


def _address(host: str):
import ipaddress
try:
ip = ipaddress.ip_address(host)
except ValueError:
return _ipv4(host)
if ip.version == 6 and ip.ipv4_mapped is not None:
return ip.ipv4_mapped
if ip.version == 6 and int(ip) >> 32 == 0 and int(ip) > 1:
return ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
return ip


def _host(url: str) -> tuple[str, int | None] | None:
from urllib.parse import unquote, urlsplit
text = re.sub(r"[\t\n\r]", "", url or "").strip().replace("\\", "/")
try:
parts = urlsplit(text)
port = parts.port or {"http": 80, "https": 443, "ws": 80, "wss": 443}.get(parts.scheme.lower())
host = unquote(parts.hostname or "")
except ValueError:
return None
try:
host = host.encode("idna").decode("ascii")
except UnicodeError:
pass
return host.lower().rstrip("."), port


def _local(host: str, resolve: bool = False) -> bool:
if host == "localhost" or host.endswith(".localhost"):
return True
ip = _address(host.split("%", 1)[0])
if ip is not None:
return ip.is_loopback or ip.is_unspecified
if not resolve or not host:
return False
import socket
try:
found = socket.getaddrinfo(host, None)
except (OSError, UnicodeError):
return False
return any(_local(str(row[4][0]).split("%", 1)[0]) for row in found)


def loopback(url: str, resolve: bool = False) -> bool:
got = _host(url)
return got is not None and _local(got[0], resolve)


def own_origin(url: str, resolve: bool = False) -> bool:
got = _host(url)
if got is None or not _local(got[0], resolve):
return False
from app.engine.devices import LAN_PORT
return got[1] in (config.PORT, config.FRONTEND_PORT, config.FRONTEND_PORT + 1, LAN_PORT)


def _guard(route) -> None:
from app.core.local_guard import BROWSER_MARK
if own_origin(route.request.url):
route.abort("blockedbyclient")
return
route.continue_(headers=route.request.all_headers() | {BROWSER_MARK: "1"})


def _url(u: str) -> str:
u = (u or "").strip()
if not u:
Expand All @@ -186,6 +277,8 @@ def _url(u: str) -> str:
u = ("http://" if u.startswith(("localhost", "127.0.0.1")) else "https://") + u
if not u.startswith(("http://", "https://", "about:")):
raise CommandError("The browser opens http and https pages")
if own_origin(u, resolve=True):
raise CommandError("The browser does not open FormAT's own engine or window; open it in FormAT itself")
return u


Expand Down
20 changes: 15 additions & 5 deletions backend/app/engine/claude_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,14 @@ def route(settings: dict) -> str:
return "api"


def decision_for(short: str, settings: dict, conversation_id: str | None = None) -> str:
if short in (settings.get("toolDeny") or []):
return "deny"
if settings.get("permissionMode", "ask") == "auto" or short in (settings.get("toolAllow") or []) or tools.chat_allowed(conversation_id):
return "allow"
return "ask"


@command("claudecode.status", "Claude Code", mutates=False,
description="Whether the Claude Code CLI is installed (its path and version) and which engine answers chats now: api (the Anthropic API key) or claude-code (the person's own Claude Code sign-in). programs says the same for each agent program FormAT looks for: claude, codex, cursor and antigravity (finding is runs, broken or missing; said is the sentence to show).")
def status() -> dict:
Expand Down Expand Up @@ -245,12 +253,13 @@ def can_use(request_id: str, req: dict) -> None:
status_of(tid, "denied")
return respond(request_id, {"behavior": "deny", "message": "Plan mode is on in Format: describe the plan and the person will switch modes to carry it out."})
short = ALLOW_NAMES.get(name, name)
if mode == "auto" or short in (current().get("toolAllow") or []) or tools.chat_allowed(conversation_id):
status_of(tid, "running")
return respond(request_id, {"behavior": "allow", "updatedInput": inp})
if short in (current().get("toolDeny") or []):
decided = decision_for(short, current(), conversation_id)
if decided == "deny":
status_of(tid, "denied")
return respond(request_id, {"behavior": "deny", "message": f"The person does not allow {name} in Format."})
if decided == "allow":
status_of(tid, "running")
return respond(request_id, {"behavior": "allow", "updatedInput": inp})
status_of(tid, "waiting")
update(mid, blocks, meta)
shown, shown_input = view_of(name, inp)
Expand Down Expand Up @@ -382,7 +391,8 @@ def drain() -> None:
try:
if not found["installed"]:
raise providers.ProviderError(found.get("said") or "Claude Code is not installed: install it from https://claude.com/claude-code and sign in once with `claude`")
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)
run_env = child_env(found["path"])
proc = subprocess.Popen(agent_lookup.start_argv(args, run_env), cwd=folder, env=run_env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
threading.Thread(target=drain, daemon=True).start()
threading.Thread(target=watch, daemon=True).start()
send({"type": "control_request", "request_id": "format-init", "request": {"subtype": "initialize", "hooks": None}})
Expand Down
Loading
Loading