Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 17 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

## Contents

- [Unreleased · Google sign-in return, Windows shims, one service per data folder, panel turn tools, model import size](#unreleased--google-sign-in-return-windows-shims-one-service-per-data-folder-panel-turn-tools-model-import-size)
- [Unreleased · The window key, and the agent access fixes](#unreleased--the-window-key-and-the-agent-access-fixes)
- [Unreleased · agents sync copies the skills to .agents/skills](#unreleased--agents-sync-copies-the-skills-to-agentsskills)
- [Unreleased · agents/manifest.json says what the app offers agents](#unreleased--agentsmanifestjson-says-what-the-app-offers-agents)
Expand Down Expand Up @@ -62,6 +63,22 @@
- [v0.1.0 · Local board service and SDK MCP](#v010--local-board-service-and-sdk-mcp)
- [boot_backend.bat](#boot_backendbat)

## Unreleased · Google sign-in return, Windows shims, one service per data folder, panel turn tools, model import size

- refers-to: `app/main.py` :: SIGN_IN_RETURNS, MODEL_IMPORT, local_access, lifespan; `app/routers/cloud.py` :: google_callback; `app/agent/agent_lookup.py` (the family's file, now 1.1.0) :: start_argv, _shim_target, _cmd_safe; `app/agent_manifest.py` :: LOOKUP_HASHES; `app/core/startup.py` :: hold, let_go; `app/agent/service.py` :: _agent_folder, Agents.allows, confirm, _cli; `app/core/config.py` :: max_model_bytes; `app/routers/boards.py` :: read_upload, models_import

The Google return. Google sends the browser back to `GET /api/cloud/google/callback` as a cross-site navigation with no Origin, which the no-Origin cross-site refusal blocked. That one read is let through; it does nothing without the single-use sign-in state. The page escapes the message it shows.

Windows shims. A panel turn passes the message, with line breaks and quotes, as one argument, and the command interpreter cannot carry that through a `.cmd`. The finder reads an npm shim and starts what it wraps directly with an argv list: its node script with the node beside it or on PATH, or the `.exe` it names, so no interpreter is involved. Any other `.cmd` or `.bat` still goes through `cmd.exe /c`, which reads `& | < > ^ ( ) ! %` and `"` even inside quotes, so every word, the program's own path included, must hold none of them and no control character, with or without a space. A name ending in dots or spaces after `.cmd` or `.bat` counts as one. Anything else is refused with a sentence that points at the `.exe`, the node script, or standard input or a file for long text. The finder moved to 1.1.0 and its hash is recorded; the other family copies need the same version.

One service per data folder. Only the frozen engine took `engine.lock`, so a service the MCP server, `./formref serve` or `./formref dev` started let the desktop engine run beside it over the same folder. The service now takes the lock in its lifespan, unless its own process already holds it (the frozen engine), with its parent as the shell, refuses to start while another holds it, and removes the lock when it stops.

Panel turn tools. Codex and Cursor panel turns ran in the app folder and depended on the checkout's MCP files at a fixed port. They now run in the `AgentTabs` folder that program tabs use, whose files point at the running service and send the turn's token from `FORMREF_AGENT_TOKEN`. With a token of their own, the rule that let any tokenless caller act as the running Codex or Cursor turn is gone.

Model import size. The person cutout and sharp cutout files are near 180 MB. Model imports have their own 256 MiB limit, in the request check and in `read_upload`, and are still checked against the pinned hash.

Run: the suite with the release board engine; the new tests fail on the previous code.

## Unreleased · The window key, and the agent access fixes

- refers-to: `app/core/window_key.py` (new) :: WindowKeyGuard, OPEN, BRIDGE, claim, ticket, spend; `app/core/seal.py` (new) :: effective, sign; `app/routers/window.py` (new); `app/main.py` :: app.add_middleware; `app/routers/terminal.py` :: _window_only, chat_events, attach; `app/routers/agent.py` :: save_agent_settings; `app/routers/commands.py` :: _window_only; `app/routers/cloud.py` :: from_agent; `app/routers/clip.py` :: get_token, reset_token; `app/agent/service.py` :: loopback_url, Agents.settings, save, allows, tokenless_turn, token_file, revoke, _cli; `app/agent/claude_code.py` :: issue, revoke, argv; `app/agent/chat.py` :: _run; `app/agent/runners.py` :: argv; `app/agent/terminal.py` :: Session.on_close, base_env; `app/cli.py` :: call; `formref_engine.py` :: main; `freeze_engine`; `requirements.txt`, `requirements_macos.txt`
Expand Down
52 changes: 49 additions & 3 deletions backend/app/agent/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.1.0"
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,59 @@ def _quote(word: str, fish: bool) -> str:
return "'" + word.replace("'", "'\"'\"'") + "'"


SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%]+\.(?:js|cjs|mjs|exe))"\s+%\*', re.IGNORECASE)
CMD_REFUSED = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]')


def _shim_target(shim: str, env: dict) -> list[str] | None:
"""The program an npm-style .cmd shim wraps, as an argv prefix: the .exe itself, or node and the script."""
try:
text = Path(shim).read_text(encoding="utf-8", errors="replace")
except OSError:
return None
match = SHIM_TARGET.search(text)
if not match:
return None
folder = Path(shim).parent
target = folder.joinpath(*match.group(1).replace("/", "\\").split("\\"))
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 _batch(program: str) -> bool:
return program.rstrip(" .").lower().endswith((".cmd", ".bat"))


def _cmd_safe(words: list[str]) -> None:
"""The command interpreter reads & | < > ^ ( ) ! % and " even inside quotes, and a .cmd re-reads its arguments, so
every word given to it, the program's own path included, must hold none of them and no control character."""
for word in words:
if CMD_REFUSED.search(word):
raise ValueError("This text cannot be passed to a .cmd or .bat program on Windows: it holds a line break, a "
"control character or one of & | < > ^ ( ) ! % \". Point FormRef at the program's .exe or node "
"script instead, or pass long text through standard input or a file if the program supports it.")


def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]:
"""How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux
(exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat."""
(exec, so the process is the program), directly on Windows. A .cmd or .bat that only starts a node script is replaced
by node and that script, and one that only starts an .exe by that .exe, each with the words as an argv list; any other
runs under the command interpreter, and only when no word holds a character the interpreter would read."""
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 _batch(words[0]):
return words
target = _shim_target(words[0], env)
if target:
return [*target, *words[1:]]
_cmd_safe(words)
return [env.get("COMSPEC") or "cmd.exe", "/c", *words]
shell = login_shell(env, platform)
fish = Path(shell).name == "fish"
return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)]
Expand Down
19 changes: 10 additions & 9 deletions backend/app/agent/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
BULK = 10
CONFIRM_SECONDS = 300
MOVES = {"transform": "Move or resize", "pack": "Pack", "sort": "Sort and lay out", "distribute": "Distribute", "align": "Align", "snap": "Snap", "normalize": "Resize"}
TOKENLESS = ("codex", "cursor")
TOKEN_FOLDER = "AgentTokens"
ASKED = tuple((method, re.compile(pattern), words) for method, pattern, words in (
("POST", r"/api/boards", "create a board"),
Expand Down Expand Up @@ -63,6 +62,12 @@ def loopback_url(value) -> bool:
return False


def _agent_folder() -> Path:
from .programs import workdir

return workdir()


class Agents:
def __init__(self):
self.tokens: set[str] = set()
Expand Down Expand Up @@ -145,18 +150,13 @@ def save(self, patch: dict) -> dict:
def allows(self, client: str) -> bool:
if client in self.tokens:
return True
if client == "outside" and self.tokenless_turn() is not None:
return True
return bool(self.settings()["outside_agents"])

def refuse(self, agent: str | None, method: str, path: str) -> None:
name = "".join(c for c in (agent or "") if c.isprintable())[:64].strip()
self.refusal = {"id": uuid.uuid4().hex, "agent": name, "what": asked(method, path), "answers": list(ANSWERS), "always": "all", "expires": None, "held": False}
self.refusals += 1

def tokenless_turn(self) -> str | None:
return next((t for t in reversed(self.cli_active) if self.turns.get(t, {}).get("runner") in TOKENLESS), None)

async def available(self) -> list[dict]:
rows = []
for key, spec in runners.CLI.items():
Expand Down Expand Up @@ -234,7 +234,7 @@ def _risky(self, command, items: dict) -> str | None:

async def confirm(self, client: str, summary: str) -> bool:
"""Hold a risky write from a panel turn until the person answers in the Agent panel."""
turn_id = self.token_turn.get(client) or (self.tokenless_turn() if client == "outside" else None)
turn_id = self.token_turn.get(client)
queue = self.queues.get(turn_id or "")
if queue is None or turn_id in self.approved or not self.settings()["confirm_changes"]:
return True
Expand Down Expand Up @@ -311,11 +311,12 @@ async def _cli(self, turn_id, runner, prompt, token, config):
base = {k: v for k, v in os.environ.items() if k != "FORMREF_WINDOW_KEY_STDOUT"}
env = agent_lookup.child_env(binary, base=base, extra={"FORMREF_API_URL": API_URL, "FORMREF_AGENT_TOKEN": token}, shell_timeout=10.0)
mcp_file = self.token_file(token, {"mcpServers": {"formref": runners.mcp_server(token, API_URL)}}) if runner == "claude" else ""
folder = ROOT if runner == "claude" else await asyncio.to_thread(_agent_folder)
self.cli_turns += 1
self.cli_active.append(turn_id)
try:
process = await asyncio.create_subprocess_exec(*agent_lookup.start_argv(runners.argv(runner, binary, prompt, token, API_URL, config["model"], mcp_file)),
cwd=str(ROOT), env=env, stdin=asyncio.subprocess.DEVNULL,
process = await asyncio.create_subprocess_exec(*agent_lookup.start_argv(runners.argv(runner, binary, prompt, token, API_URL, config["model"], mcp_file), env),
cwd=str(folder), env=env, stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, limit=8 * 1024 * 1024)
self.processes[turn_id] = process
async for raw in process.stdout:
Expand Down
1 change: 1 addition & 0 deletions backend/app/agent_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
LOOKUP_HASHES = {
"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3",
"1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51",
"1.1.0": "a1ac03220d5e73c27f7a38e5e6b6dea53d0c45ab1e3a03869ac2e69fdb9af207",
}


Expand Down
1 change: 1 addition & 0 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class Settings:
engine_path: Path
max_upload_bytes: int = 64 * 1024 * 1024
max_archive_bytes: int = 256 * 1024 * 1024
max_model_bytes: int = 256 * 1024 * 1024
max_image_pixels: int = 64_000_000
max_export_pixels: int = 32_000_000
max_export_edge: int = 8192
Expand Down
17 changes: 17 additions & 0 deletions backend/app/core/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,23 @@ def claim(data: Path, shell: int) -> tuple[Path, int]:
return path, held if state == LEFTOVER else 0


def hold(data: Path) -> bool:
if number(read_lock(data / LOCK_NAME).get("pid")) == os.getpid():
return False
data.mkdir(parents=True, exist_ok=True)
claim(data, shell_pid() or os.getppid())
return True


def let_go(data: Path) -> None:
path = data / LOCK_NAME
if number(read_lock(path).get("pid")) == os.getpid():
try:
path.unlink()
except OSError:
pass


def shell_pid() -> int:
raw = os.environ.get(SHELL_ENV, "").strip()
return int(raw) if raw.isascii() and raw.isdigit() else 0
Expand Down
32 changes: 23 additions & 9 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import ipaddress
import logging
import mimetypes
import re
from urllib.parse import urlparse
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, FileResponse
from starlette.middleware.cors import CORSMiddleware
from .core import engine_log, origins
from .core import engine_log, origins, startup
from .core.window_key import WindowKeyGuard
from .core.config import ROOT, VERSION, settings
from .core.engine import broker, EngineError
Expand Down Expand Up @@ -41,16 +42,28 @@
@asynccontextmanager
async def lifespan(app):
engine_log.join()
try:
held = startup.hold(settings.data_dir)
except startup.Busy as err:
log.error("%s", err)
raise
log.info("FormRef %s using %s", VERSION, settings.data_dir)
terminal.start(asyncio.get_running_loop())
async with mcp_server.session_manager.run():
yield
terminal.close_all()
broker.close()
try:
terminal.start(asyncio.get_running_loop())
async with mcp_server.session_manager.run():
yield
terminal.close_all()
broker.close()
finally:
if held:
startup.let_go(settings.data_dir)

app = FastAPI(title="FormRef", version=VERSION, lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origin_regex=r"^(https?://(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?|(chrome|moz)-extension://[a-z0-9-]+)$", allow_credentials=False, allow_methods=["GET", "POST", "DELETE", "OPTIONS"], allow_headers=["Content-Type", "X-FormRef-Clip-Token"], expose_headers=["Content-Disposition", "X-FormRef-Scale", "X-FormRef-Width", "X-FormRef-Height"])

SIGN_IN_RETURNS = {("GET", "/api/cloud/google/callback")}
MODEL_IMPORT = re.compile(r"/api/models/[^/]+/import")

@app.middleware("http")
async def local_access(request: Request, call_next):
host = urlparse("http://" + request.headers.get("host", "")).hostname
Expand All @@ -64,15 +77,16 @@ async def local_access(request: Request, call_next):
if not local:
return JSONResponse(status_code=403, content={"detail": "FormRef accepts local clients only."})
origin = request.headers.get("origin")
if not origin and request.headers.get("sec-fetch-site", "").strip().lower() == "cross-site":
if not origin and request.headers.get("sec-fetch-site", "").strip().lower() == "cross-site" and (request.method, request.url.path) not in SIGN_IN_RETURNS:
return JSONResponse(status_code=403, content={"detail": "Origin is not an allowed local application."})
if origin and not origins.allowed(origin, request.headers.get("host", ""), request.url.path):
return JSONResponse(status_code=403, content={"detail": "Origin is not an allowed local application."})
length = request.headers.get("content-length")
if length:
limit = settings.max_model_bytes if request.method == "POST" and MODEL_IMPORT.fullmatch(request.url.path) else settings.max_upload_bytes
try:
if int(length) > settings.max_upload_bytes + 1024 * 1024:
return JSONResponse(status_code=413, content={"detail": "Request exceeds the 64 MiB upload limit."})
if int(length) > limit + 1024 * 1024:
return JSONResponse(status_code=413, content={"detail": f"Request exceeds the {limit // (1024 * 1024)} MiB upload limit."})
except ValueError:
return JSONResponse(status_code=400, content={"detail": "Invalid request content length."})
client = request.headers.get("x-formref-client")
Expand Down
9 changes: 5 additions & 4 deletions backend/app/routers/boards.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,18 @@

router = APIRouter(prefix="/api")

async def read_upload(file: UploadFile):
async def read_upload(file: UploadFile, limit: int = 0):
limit = limit or settings.max_upload_bytes
chunks = []
size = 0
while True:
chunk = await file.read(1024 * 1024)
if not chunk:
break
size += len(chunk)
if size > settings.max_upload_bytes:
if size > limit:
await file.close()
raise HTTPException(status_code=413, detail="Uploads are limited to 64 MiB.")
raise HTTPException(status_code=413, detail=f"Uploads are limited to {limit // (1024 * 1024)} MiB.")
chunks.append(chunk)
await file.close()
return b"".join(chunks)
Expand Down Expand Up @@ -227,7 +228,7 @@ def models_download(model: str):

@router.post("/models/{model}/import")
async def models_import(model: str, file: UploadFile = File(...)):
data = await read_upload(file)
data = await read_upload(file, settings.max_model_bytes)
return await asyncio.to_thread(cutout_models.import_file, model, file.filename or "", data)

@router.delete("/models/{model}")
Expand Down
3 changes: 2 additions & 1 deletion backend/app/routers/cloud.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import html
import re
import uuid

Expand Down Expand Up @@ -44,7 +45,7 @@ def start(name: str, request: Request):
@router.get("/google/callback", response_class=HTMLResponse)
def google_callback(state: str = "", code: str = "", error: str = ""):
status, message = cloud.google_callback(state, code, error)
page = f"<!doctype html><meta charset=utf-8><title>FormRef</title><body style='font:15px system-ui;margin:48px;background:#111113;color:#ececee'><p>{message}</p>"
page = f"<!doctype html><meta charset=utf-8><title>FormRef</title><body style='font:15px system-ui;margin:48px;background:#111113;color:#ececee'><p>{html.escape(message)}</p>"
return HTMLResponse(page, status_code=status)


Expand Down
10 changes: 10 additions & 0 deletions backend/tests/test_agent_guards.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,13 @@ def test_a_plain_terminal_does_not_inherit_the_key_variable(monkeypatch):
env = terminal.base_env()
assert "FORMREF_WINDOW_KEY_STDOUT" not in env
assert not any(re.search(r"window.?key", k, re.I) for k in env)


@pytest.mark.parametrize("runner", ["codex", "cursor"])
def test_a_running_codex_or_cursor_turn_does_not_let_in_an_outside_caller(bare, reset_agents, runner):
reset_agents.cli_turns = 1
reset_agents.cli_active.append("t2")
reset_agents.turns["t2"] = {"runner": runner}
assert reset_agents.allows("outside") is False
r = bare.post("/api/boards", json={"title": "x"}, headers={"x-formref-client": "outside"})
assert r.status_code == 403 and r.json()["code"] == "outside_agents_off"
Loading
Loading