Skip to content
12 changes: 12 additions & 0 deletions backend/app/core/seal.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ def effective(stored: dict) -> dict:
return {**out, "seal": "broken", "sealBroken": True}


def vouch(text: str) -> str | None:
key = _load(True)
return hmac.new(key, text.encode("utf-8"), hashlib.sha256).hexdigest() if key is not None else None


def vouched(text: str, mark) -> bool:
key = _load(False)
if not _CACHE["available"]:
return True
return key is not None and isinstance(mark, str) and hmac.compare_digest(mark, hmac.new(key, text.encode("utf-8"), hashlib.sha256).hexdigest())


def sign(merged: dict) -> dict:
key = _load(True)
if key is None:
Expand Down
4 changes: 3 additions & 1 deletion backend/app/routers/agentdock.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from app.core import window_key
from app.routers.live import local_origin
from app.services import agent_programs, chat, claude_code, events, terminal
from app.services import agent_lookup, agent_programs, chat, claude_code, events, terminal
from app.services.claude_code import AgentError

router = APIRouter(tags=["agent-dock"])
Expand Down Expand Up @@ -68,6 +68,8 @@ def _agent(fn, *args, **kw):
return fn(*args, **kw)
except AgentError as e:
raise HTTPException(e.status, str(e)) from None
except agent_lookup.Refused as e:
raise HTTPException(400, str(e)) from None


@router.get("/api/terminals")
Expand Down
59 changes: 56 additions & 3 deletions backend/app/services/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 All @@ -45,6 +45,10 @@
MARK = "__FORM_AGENT_LOOKUP__"
HOW = {"setting": "your setting", "override": "the development override", "path": "the engine's PATH", "folder": "a known install folder", "shell": "your shell's PATH"}
RETRY_SECONDS = 60.0
CONTROL = re.compile(r"[\x00-\x1f\x7f]")
CMD_SPECIAL = frozenset('&|<>^()!%"')
SHIM = re.compile(r'"%(?:~dp0|dp0%)\\([^"%\r\n]+)"\s+%\*')
SCRIPTS = (".js", ".mjs", ".cjs")

_lock = threading.RLock()
_shell: dict = {}
Expand Down Expand Up @@ -359,13 +363,62 @@ def _quote(word: str, fish: bool) -> str:
return "'" + word.replace("'", "'\"'\"'") + "'"


class Refused(OSError):
pass


def shim_target(path: str | os.PathLike, env: dict | None = None) -> list[str] | None:
"""The program an npm .cmd shim starts (node and the script beside the shim, or an .exe), so it can run without the
command interpreter; None when the file is not such a shim or what it names is not inside its folder."""
env = os.environ if env is None else env
shim = Path(path)
try:
text = shim.read_text(encoding="utf-8", errors="replace")[:20000]
base = shim.parent.resolve()
except OSError:
return None
hits = SHIM.findall(text)
if not hits:
return None
try:
target = base.joinpath(*[part for part in re.split(r"[\\/]", hits[-1]) if part]).resolve()
except (OSError, ValueError):
return None
if base not in target.parents or not target.is_file():
return None
if target.suffix.lower() == ".exe":
return [str(target)]
if target.suffix.lower() not in SCRIPTS:
return None
node = base / "node.exe"
found = str(node) if node.is_file() else shutil.which("node", path=env.get("PATH") or None)
return [found, str(target)] if found else None


def cmd_words(words: list[str]) -> list[str]:
"""The words for cmd.exe /c, refused when any holds a character the command interpreter or a batch file's %* can read
as more than text (& | < > ^ ( ) ! % " or a control character), quoted or not."""
for word in words:
if CONTROL.search(word) or any(ch in CMD_SPECIAL for ch in word):
raise Refused(f"This cannot be passed to the Windows command interpreter, which reads & | < > ^ ( ) ! % \" and control "
f"characters as commands even inside quotes: {word[:80]!r}. Pass long text through standard input or a file "
f"if the program supports it, or point the setting at the program itself rather than a .cmd or .bat.")
return words


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. An npm .cmd shim runs as the node script it names; any
other .cmd or .bat goes through the command interpreter with words it reads only as text."""
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 words[0].lower().endswith((".cmd", ".bat")):
return words
direct = shim_target(words[0], env) if words[0].lower().endswith(".cmd") else None
if direct:
return [*direct, *words[1:]]
return [env.get("COMSPEC") or "cmd.exe", "/c", *cmd_words(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
18 changes: 14 additions & 4 deletions backend/app/services/pdf/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,11 +536,11 @@ def _norm_paras(v, font: dict) -> list[dict]:
v = [{"runs": [{"t": line}]} for line in v.replace("\r\n", "\n").split("\n")]
out = []
total = 0
for p in v or []:
for p in v if isinstance(v, (list, tuple)) else []:
if not isinstance(p, dict):
continue
runs = []
for r in p.get("runs") or []:
for r in p.get("runs") if isinstance(p.get("runs"), (list, tuple)) else []:
if not isinstance(r, dict):
continue
t = str(r.get("t") if r.get("t") is not None else r.get("text") or "").replace("\n", " ")[: MAX_TEXT - total]
Expand Down Expand Up @@ -909,6 +909,16 @@ def _merged(page_obj, arr) -> list[dict]:
return out


def _shown(v: dict) -> dict:
out = _public(v)
if out.get("kind") != "text":
return out
font = out.get("font") if isinstance(out.get("font"), dict) else {}
family = font.get("family") if isinstance(font.get("family"), str) else "sans"
clean = {**_norm_font({**font, "family": "sans"}), "family": family}
return {**out, "font": clean, "paras": _norm_paras(out.get("paras"), clean)}


def read(path, *, args: dict | None = None, pages=None, passwords: list[str] | None = None):
r = core.reader(path, passwords)
want = core.parse_pages(pages or (args or {}).get("pages"), len(r.pages))
Expand All @@ -919,9 +929,9 @@ def read(path, *, args: dict | None = None, pages=None, passwords: list[str] | N
for n in want:
p = Page(w, n)
for z, (_, v) in enumerate(p.items()):
items.append({**_public(v), "page": n, "z": z, "inside": bool(v.get("ctx"))})
items.append({**_shown(v), "page": n, "z": z, "inside": bool(v.get("ctx"))})
for v in _merged(p.page, p.arr):
items.append({**_public(v), "page": n, "z": -1, "merged": True})
items.append({**_shown(v), "page": n, "z": -1, "merged": True})
if not (args or {}).get("items_only"):
pics += p.pictures()
if (args or {}).get("text", True):
Expand Down
11 changes: 8 additions & 3 deletions backend/app/services/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import traceback
from pathlib import Path

from app.core import config
from app.core import config, seal
from app.services.pdf import actions

STATE: dict[str, dict] = {}
Expand Down Expand Up @@ -43,6 +43,10 @@ def _hash(folder: Path, m: dict) -> str:
return h.hexdigest()


def _consent(pid: str, digest: str) -> str:
return f"plugin:{pid}:{digest}"


def _consents() -> dict:
got = config.read_settings().get("plugins")
return got if isinstance(got, dict) else {}
Expand All @@ -58,7 +62,7 @@ def discover() -> list[dict]:
continue
digest = _hash(folder, m)
c = consents.get(pid) or {}
state = "on" if c.get("allowed") and c.get("hash") == digest else "changed" if c.get("hash") and c.get("hash") != digest else "off" if c.get("hash") else "new"
state = "on" if c.get("allowed") and c.get("hash") == digest and seal.vouched(_consent(pid, digest), c.get("seal")) else "changed" if c.get("hash") and c.get("hash") != digest else "off" if c.get("hash") else "new"
loaded = STATE.get(pid, {})
out.append({"id": pid, "name": str(m.get("name") or pid)[:80], "version": str(m.get("version") or "")[:20], "description": str(m.get("description") or "")[:400],
"author": str(m.get("author") or "")[:80], "engine": bool(_file(folder, m.get("engine"))), "window": bool(_file(folder, m.get("window"))),
Expand Down Expand Up @@ -116,7 +120,8 @@ def allow(pid: str, allowed: bool) -> dict:
if item is None:
raise ValueError(f"There is no plug-in {pid} in {plugins_dir()}")
consents = _consents()
consents[pid] = {"allowed": bool(allowed), "hash": item["hash"]}
mark = seal.vouch(_consent(pid, item["hash"])) if allowed else None
consents = {**consents, pid: {"allowed": bool(allowed), "hash": item["hash"], **({"seal": mark} if mark else {})}}
config.write_settings({"plugins": consents})
if allowed:
load(pid)
Expand Down
105 changes: 105 additions & 0 deletions backend/tests/test_agent_start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import pytest

from app.services import agent_lookup

NPM_SHIM = """@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0

IF EXIST "%dp0%\\node.exe" (
SET "_prog=%dp0%\\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)

endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\{target}" %*
"""

ENV = {"COMSPEC": "cmd.exe", "PATH": ""}


def _shim(tmp_path, target, make=True, node=True):
folder = tmp_path / "npm"
folder.mkdir(exist_ok=True)
shim = folder / "claude.cmd"
shim.write_text(NPM_SHIM.replace("{target}", target), encoding="utf-8")
if make:
script = folder.joinpath(*target.split("\\"))
script.parent.mkdir(parents=True, exist_ok=True)
script.write_text("", encoding="utf-8")
if node:
(folder / "node.exe").write_text("", encoding="utf-8")
return shim


def test_an_npm_shim_runs_its_script_with_node_and_no_command_interpreter(tmp_path):
shim = _shim(tmp_path, "node_modules\\@anthropic-ai\\claude-code\\cli.js")
got = agent_lookup.start_argv([str(shim), "-p", "line one\nline two & 100%"], ENV, "win32")
folder = shim.parent.resolve()
assert got == [str(folder / "node.exe"), str(folder / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js"), "-p", "line one\nline two & 100%"]


def test_a_shim_naming_a_script_outside_its_folder_is_not_followed(tmp_path):
(tmp_path / "elsewhere.js").write_text("", encoding="utf-8")
shim = _shim(tmp_path, "..\\elsewhere.js", make=False)
assert agent_lookup.start_argv([str(shim), "--version"], ENV, "win32") == ["cmd.exe", "/c", str(shim), "--version"]


@pytest.mark.parametrize("word", ["two\nlines", "tab\there", "nul\x00", "bell\x07", "esc\x1b", "del\x7f", "100%", "%PATH%", 'say "hi"', '"',
"a&b", "a|b", "a>b", "a<b", "a^b", "(a)", "a!b", "a & b", "x | y", "one > two", "(and dialogs)", "wow! yes", "50 %"])
def test_the_command_interpreter_gets_only_words_it_reads_as_text(tmp_path, word):
bat = tmp_path / "claude.bat"
with pytest.raises(agent_lookup.Refused):
agent_lookup.start_argv([str(bat), "-p", word], ENV, "win32")


def test_a_refusal_points_to_standard_input_or_a_file(tmp_path):
bat = tmp_path / "claude.bat"
with pytest.raises(agent_lookup.Refused, match="standard input or a file"):
agent_lookup.start_argv([str(bat), "--append-system-prompt", "tabs, panels (and dialogs) & more"], ENV, "win32")


def test_plain_words_with_spaces_reach_the_command_interpreter_unchanged(tmp_path):
bat = tmp_path / "claude.bat"
got = agent_lookup.start_argv([str(bat), "--append-system-prompt", "tabs, panels and dialogs: more.", ""], ENV, "win32")
assert got == ["cmd.exe", "/c", str(bat), "--append-system-prompt", "tabs, panels and dialogs: more.", ""]


def test_a_cmd_that_is_not_an_npm_shim_goes_through_the_strict_command_interpreter(tmp_path):
cmd = tmp_path / "claude.cmd"
cmd.write_text("@echo off\r\nreal.exe %*\r\n", encoding="utf-8")
assert agent_lookup.start_argv([str(cmd), "--version"], ENV, "win32") == ["cmd.exe", "/c", str(cmd), "--version"]
with pytest.raises(agent_lookup.Refused):
agent_lookup.start_argv([str(cmd), "-p", "a (b)"], ENV, "win32")


def test_an_npm_shim_naming_an_exe_runs_it_directly(tmp_path):
shim = _shim(tmp_path, "bin\\claude.exe", node=False)
got = agent_lookup.start_argv([str(shim), "-p", "a & b (100%)"], ENV, "win32")
assert got == [str(shim.parent.resolve() / "bin" / "claude.exe"), "-p", "a & b (100%)"]


def test_an_npm_shim_without_node_falls_back_to_the_strict_command_interpreter(tmp_path):
shim = _shim(tmp_path, "cli.js", node=False)
(tmp_path / "empty").mkdir()
env = ENV | {"PATH": str(tmp_path / "empty")}
assert agent_lookup.start_argv([str(shim), "--version"], env, "win32") == ["cmd.exe", "/c", str(shim), "--version"]
with pytest.raises(agent_lookup.Refused):
agent_lookup.start_argv([str(shim), "-p", "a & b"], env, "win32")


def test_a_program_that_is_not_a_script_starts_directly_on_windows(tmp_path):
exe = tmp_path / "claude.exe"
assert agent_lookup.start_argv([str(exe), "-p", "a&b\n%x%"], ENV, "win32") == [str(exe), "-p", "a&b\n%x%"]


def test_a_refused_start_is_reported_as_a_program_that_does_not_start(tmp_path):
found = agent_lookup.Found("claude", "Claude Code", path=str(tmp_path / "a&b" / "claude.bat"), state="found")
agent_lookup.check(found, ENV, 5.0, fresh=True, platform="win32")
assert found.state == "broken" and "command interpreter" in found.error
57 changes: 57 additions & 0 deletions backend/tests/test_item_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import io
import json

from pypdf import PdfWriter
from pypdf.generic import ArrayObject, DecodedStreamObject, NameObject, TextStringObject

from _pdfs import letter


def _with_item(tmp_path, item):
w = PdfWriter(clone_from=io.BytesIO(letter([["One"]])))
page = w.pages[0]
s = DecodedStreamObject()
s.set_data(b"")
s[NameObject("/FormpdfItem")] = TextStringObject(json.dumps(item))
refs = page.raw_get("/Contents")
obj = refs.get_object()
out = ArrayObject(list(obj) if isinstance(obj, ArrayObject) else [refs])
out.append(w._add_object(s))
page[NameObject("/Contents")] = out
path = tmp_path / "item.pdf"
with open(path, "wb") as f:
w.write(f)
return path


def test_text_items_read_from_a_file_come_back_with_clean_paragraphs(tmp_path):
from app.services.pdf import items

odd = '"><img src=x>'
item = {"v": 1, "id": "a1", "kind": "text", "page": 1, "x": 10, "y": 10, "w": 100, "h": 20, "rot": 0,
"font": {"family": "sans", "size": "12", "color": odd, "lineHeight": odd},
"paras": [{"align": odd, "list": odd, "level": odd, "start": odd, "runs": [{"t": "Hello", "color": odd}]},
{"align": "center", "list": "number", "level": 2, "start": 3, "runs": [{"t": "Two", "b": True}]}]}
_, got = items.read(_with_item(tmp_path, item), args={"items_only": True})
[text] = got["items"]
first, second = text["paras"]
assert (first["align"], first["list"], first["level"]) == ("left", "none", 0)
assert "start" not in first
assert first["runs"] == [{"t": "Hello", "color": "#111111"}]
assert (second["align"], second["list"], second["level"], second["start"]) == ("center", "number", 2, 3)
assert second["runs"] == [{"t": "Two", "b": True}]
assert text["font"]["color"] == "#111111"
assert isinstance(text["font"]["lineHeight"], float)
assert odd not in json.dumps(text)


def test_text_items_with_odd_paragraph_values_still_read(tmp_path):
from app.services.pdf import items

base = {"v": 1, "kind": "text", "page": 1, "x": 10, "y": 10, "w": 100, "h": 20, "rot": 0}
path = _with_item(tmp_path, {**base, "id": "a1", "paras": 5})
_, got = items.read(path, args={"items_only": True})
assert got["items"][0]["paras"] == [{"align": "left", "list": "none", "level": 0, "runs": [{"t": ""}]}]
path = _with_item(tmp_path, {**base, "id": "a2", "paras": [{"runs": 5}]})
_, got = items.read(path, args={"items_only": True})
assert got["items"][0]["paras"][0]["runs"] == [{"t": ""}]
Loading
Loading