From 70f7d2befe2e2e6b4de4bed21131f4b9f3e01162 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:29:48 -0500 Subject: [PATCH 1/8] fix(window): build rich text paragraphs only from known values parasHtml now accepts only the known alignments and list kinds and whole-number levels and start numbers, so a text item's paragraph settings can never add markup to the editor. --- frontend/src/tools/richtext.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/frontend/src/tools/richtext.ts b/frontend/src/tools/richtext.ts index 737e45a..2c43425 100644 --- a/frontend/src/tools/richtext.ts +++ b/frontend/src/tools/richtext.ts @@ -37,11 +37,23 @@ function runHtml(r: Run): string { return h; } +const ALIGNS: readonly Align[] = ['left', 'center', 'right', 'justify']; +const LISTS: readonly ListKind[] = ['none', 'bullet', 'number']; + +function whole(v: unknown, lo: number, hi: number, fallback: number): number { + const n = Math.trunc(Number(v)); + return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback; +} + export function parasHtml(paras: Para[]): string { return paras.map((p) => { - const body = p.runs.map(runHtml).join('') || '
'; - const start = p.list === 'number' && p.start ? `;counter-set:n${p.level} ${p.start}" data-start="${p.start}` : ''; - return `
${body}
`; + const body = (Array.isArray(p.runs) ? p.runs : []).map(runHtml).join('') || '
'; + const align = ALIGNS.includes(p.align) ? p.align : 'left'; + const list = LISTS.includes(p.list) ? p.list : 'none'; + const level = whole(p.level, 0, 6, 0); + const first = p.start ? whole(p.start, 1, 9999, 1) : 0; + const start = list === 'number' && first ? `;counter-set:n${level} ${first}" data-start="${first}` : ''; + return `
${body}
`; }).join(''); } From 696ddbf2b614f81b0bcbdc0da54ed30252b7dd6b Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:29:49 -0500 Subject: [PATCH 2/8] fix(engine): clean text items read back from a file Text items stored in a PDF were returned as the file holds them, while the paragraph and font cleaning ran only on writes. Reading items now runs the same cleaning, so alignments, lists, levels, start numbers and colours come back as known values. Adds a test. --- backend/app/services/pdf/items.py | 14 ++++++++-- backend/tests/test_item_text.py | 45 +++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 backend/tests/test_item_text.py diff --git a/backend/app/services/pdf/items.py b/backend/app/services/pdf/items.py index 1be0011..3d3256e 100644 --- a/backend/app/services/pdf/items.py +++ b/backend/app/services/pdf/items.py @@ -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)) @@ -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): diff --git a/backend/tests/test_item_text.py b/backend/tests/test_item_text.py new file mode 100644 index 0000000..423c041 --- /dev/null +++ b/backend/tests/test_item_text.py @@ -0,0 +1,45 @@ +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 = '">' + 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) From 56dddc81400fe28e46457f7da32ce43a0187c437 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:30:39 -0500 Subject: [PATCH 3/8] fix(engine): seal plug-in consent with the settings key Turning a plug-in on in the window now stores a mark made with the keychain key that already seals agent access. A plug-in counts as on only when its mark matches, so a consent written into settings.json by hand leaves the plug-in off until the person turns it on in Preferences. Without a usable keychain the stored consent stands, as for the agent choice. Adds tests. --- backend/app/core/seal.py | 12 ++++++++++++ backend/app/services/plugins.py | 11 ++++++++--- backend/tests/test_seal.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/backend/app/core/seal.py b/backend/app/core/seal.py index b06d301..3bda6bd 100644 --- a/backend/app/core/seal.py +++ b/backend/app/core/seal.py @@ -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: diff --git a/backend/app/services/plugins.py b/backend/app/services/plugins.py index 148202f..2ec348f 100644 --- a/backend/app/services/plugins.py +++ b/backend/app/services/plugins.py @@ -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] = {} @@ -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 {} @@ -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"))), @@ -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) diff --git a/backend/tests/test_seal.py b/backend/tests/test_seal.py index 65978e5..a07333f 100644 --- a/backend/tests/test_seal.py +++ b/backend/tests/test_seal.py @@ -166,3 +166,36 @@ def test_the_other_programs_places_are_sealed_and_given_to_the_finder_first(clie _hand_edit(**{key: "/tmp/other-program"}) s = client.get("/api/settings").json() assert s[key] == "" and s["claudeBin"] == "" and s["sealBroken"] is True and s["outsideAgents"] == "ask" + + +def _plugin(name): + from app.services import plugins + + folder = plugins.plugins_dir() / name + folder.mkdir(parents=True, exist_ok=True) + (folder / "plugin.json").write_text(json.dumps({"name": name, "engine": "engine.py"}), encoding="utf-8") + (folder / "engine.py").write_text("def register(api):\n pass\n", encoding="utf-8") + return next(p for p in plugins.discover() if p["id"] == name) + + +def _plugin_state(name): + from app.services import plugins + + return next(p for p in plugins.discover() if p["id"] == name)["state"] + + +def test_a_plugin_turned_on_by_hand_edit_stays_off(client, keychain): + item = _plugin("handmade") + client.post("/api/settings", json={"outsideAgents": "ask"}, headers=window_headers()) + _hand_edit(plugins={"handmade": {"allowed": True, "hash": item["hash"]}}) + assert _plugin_state("handmade") == "off" + + +def test_a_plugin_turned_on_in_the_window_is_on(client, keychain): + _plugin("allowed-one") + r = client.post("/api/plugins/allowed-one", json={"allowed": True}, headers=window_headers()) + assert r.status_code == 200, r.text + assert _plugin_state("allowed-one") == "on" + stored = _stored()["plugins"]["allowed-one"] + _hand_edit(plugins={"allowed-one": {**stored, "hash": stored["hash"]}, "copied": {**stored}}) + assert _plugin_state("allowed-one") == "on" From 9fd638848c64713e28153b16b9e1cd47e161077c Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:42:56 -0500 Subject: [PATCH 4/8] fix(engine): read text items whose paragraphs are not lists Paragraph cleaning now treats paragraphs or runs that are not lists as empty, so one odd text item no longer stops a whole page of items from being read. Adds a test. --- backend/app/services/pdf/items.py | 4 ++-- backend/tests/test_item_text.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/backend/app/services/pdf/items.py b/backend/app/services/pdf/items.py index 3d3256e..92408c4 100644 --- a/backend/app/services/pdf/items.py +++ b/backend/app/services/pdf/items.py @@ -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] diff --git a/backend/tests/test_item_text.py b/backend/tests/test_item_text.py index 423c041..aeb1170 100644 --- a/backend/tests/test_item_text.py +++ b/backend/tests/test_item_text.py @@ -43,3 +43,15 @@ def test_text_items_read_from_a_file_come_back_with_clean_paragraphs(tmp_path): 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": ""}] From a69a6d4a01e5793c2a0b9d2a2407226e91a04a3f Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:42:56 -0500 Subject: [PATCH 5/8] fix(window): treat rich text run values as text parasHtml skips paragraphs and runs that are not objects and turns run text and colour into strings before escaping them. --- frontend/src/tools/richtext.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/frontend/src/tools/richtext.ts b/frontend/src/tools/richtext.ts index 2c43425..39a9f02 100644 --- a/frontend/src/tools/richtext.ts +++ b/frontend/src/tools/richtext.ts @@ -26,14 +26,14 @@ export async function loadFonts(family: string): Promise { } function runHtml(r: Run): string { - let h = escapeHtml(r.t); + let h = escapeHtml(String(r.t ?? '')); if (r.sup) h = `${h}`; if (r.sub) h = `${h}`; if (r.s) h = `${h}`; if (r.u) h = `${h}`; if (r.i) h = `${h}`; if (r.b) h = `${h}`; - if (r.color) h = `${h}`; + if (r.color) h = `${h}`; return h; } @@ -46,8 +46,8 @@ function whole(v: unknown, lo: number, hi: number, fallback: number): number { } export function parasHtml(paras: Para[]): string { - return paras.map((p) => { - const body = (Array.isArray(p.runs) ? p.runs : []).map(runHtml).join('') || '
'; + return (Array.isArray(paras) ? paras : []).filter((p) => p && typeof p === 'object').map((p) => { + const body = (Array.isArray(p.runs) ? p.runs : []).filter((r) => r && typeof r === 'object').map(runHtml).join('') || '
'; const align = ALIGNS.includes(p.align) ? p.align : 'left'; const list = LISTS.includes(p.list) ? p.list : 'none'; const level = whole(p.level, 0, 6, 0); From b4937b92ba1871190e0b31693e6ff863ffb1e78a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:42:56 -0500 Subject: [PATCH 6/8] test(engine): a plug-in mark belongs to one plug-in Checks that a mark made for one plug-in does not turn on another, and that turning a plug-in on stores its mark. --- backend/tests/test_seal.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/backend/tests/test_seal.py b/backend/tests/test_seal.py index a07333f..202f283 100644 --- a/backend/tests/test_seal.py +++ b/backend/tests/test_seal.py @@ -196,6 +196,14 @@ def test_a_plugin_turned_on_in_the_window_is_on(client, keychain): r = client.post("/api/plugins/allowed-one", json={"allowed": True}, headers=window_headers()) assert r.status_code == 200, r.text assert _plugin_state("allowed-one") == "on" - stored = _stored()["plugins"]["allowed-one"] - _hand_edit(plugins={"allowed-one": {**stored, "hash": stored["hash"]}, "copied": {**stored}}) + assert _stored()["plugins"]["allowed-one"]["seal"] + + +def test_a_plugin_mark_does_not_carry_over_to_another_plugin(client, keychain): + _plugin("allowed-one") + other = _plugin("other-one") + client.post("/api/plugins/allowed-one", json={"allowed": True}, headers=window_headers()) + stored = _stored()["plugins"] + _hand_edit(plugins={**stored, "other-one": {"allowed": True, "hash": other["hash"], "seal": stored["allowed-one"]["seal"]}}) assert _plugin_state("allowed-one") == "on" + assert _plugin_state("other-one") == "off" From f1f9abb4e2d6b081a145cf7c0a25951a7dec4a20 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:42:56 -0500 Subject: [PATCH 7/8] fix(engine): start Windows agent shims without the command interpreter On Windows an npm .cmd shim now runs as the node script it names, inside its own folder, so the words reach the program unchanged. Any other .cmd or .bat still goes through cmd.exe, which now refuses control characters, percent signs and double quotes, and its special characters in a word that is not quoted. A refused start reads as a program that does not start, and the dock answers 400. The shared finder becomes version 1.0.2 with its hash recorded. Adds tests. --- backend/app/routers/agentdock.py | 4 +- backend/app/services/agent_lookup.py | 60 ++++++++++++++++++++-- backend/tests/test_agent_start.py | 75 ++++++++++++++++++++++++++++ setup/agents.py | 2 +- 4 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 backend/tests/test_agent_start.py diff --git a/backend/app/routers/agentdock.py b/backend/app/routers/agentdock.py index 05834e6..3238faa 100644 --- a/backend/app/routers/agentdock.py +++ b/backend/app/routers/agentdock.py @@ -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"]) @@ -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") diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..49be9fd 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -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", @@ -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 = {} @@ -359,13 +363,63 @@ 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 the command interpreter would read any of them as more than text: control + characters, percent signs and double quotes always, and its special characters in a word that is not quoted.""" + for word in words: + if CONTROL.search(word) or "%" in word or '"' in word: + raise Refused(f"This cannot be passed to the Windows command interpreter: {word[:80]!r}") + quoted = not word or " " in word or "\t" in word + if not quoted and any(ch in CMD_SPECIAL for ch in word): + raise Refused(f"This cannot be passed to the Windows command interpreter: {word[:80]!r}") + 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)] diff --git a/backend/tests/test_agent_start.py b/backend/tests/test_agent_start.py new file mode 100644 index 0000000..e6d3f2c --- /dev/null +++ b/backend/tests/test_agent_start.py @@ -0,0 +1,75 @@ +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", "del\x7f", "100%", "%PATH%", 'say "hi"', "a&b", "a|b", "a>b", "a list: LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "5c3901a79154349c34a2b318ea4ee3461af654a7210cb94652642d7ca0b40c2d"} def lookup_problems() -> list: From 5a6449487e258771569dd84a1f7f6ebe52562b5a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:05:02 -0500 Subject: [PATCH 8/8] fix(engine): refuse command interpreter special characters in every word When a .cmd or .bat still has to start through cmd.exe, any word holding & | < > ^ ( ) ! % " or a control character is now refused, quoted or not, since the interpreter and a batch file's %* read them as commands even inside quotes. The refusal tells the caller to pass long text through standard input or a file, or to point the setting at the program itself. npm shims keep running as the node script or exe they name, with no interpreter. The recorded hash for the shared finder 1.0.2 is updated. Adds tests for both paths. --- backend/app/services/agent_lookup.py | 15 +++++------ backend/tests/test_agent_start.py | 38 +++++++++++++++++++++++++--- setup/agents.py | 2 +- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index 49be9fd..4fdfa76 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -46,7 +46,7 @@ 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("&|<>^()!") +CMD_SPECIAL = frozenset('&|<>^()!%"') SHIM = re.compile(r'"%(?:~dp0|dp0%)\\([^"%\r\n]+)"\s+%\*') SCRIPTS = (".js", ".mjs", ".cjs") @@ -396,14 +396,13 @@ def shim_target(path: str | os.PathLike, env: dict | None = None) -> list[str] | def cmd_words(words: list[str]) -> list[str]: - """The words for cmd.exe /c, refused when the command interpreter would read any of them as more than text: control - characters, percent signs and double quotes always, and its special characters in a word that is not quoted.""" + """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 "%" in word or '"' in word: - raise Refused(f"This cannot be passed to the Windows command interpreter: {word[:80]!r}") - quoted = not word or " " in word or "\t" in word - if not quoted and any(ch in CMD_SPECIAL for ch in word): - raise Refused(f"This cannot be passed to the Windows command interpreter: {word[:80]!r}") + 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 diff --git a/backend/tests/test_agent_start.py b/backend/tests/test_agent_start.py index e6d3f2c..6ab51df 100644 --- a/backend/tests/test_agent_start.py +++ b/backend/tests/test_agent_start.py @@ -51,17 +51,47 @@ def test_a_shim_naming_a_script_outside_its_folder_is_not_followed(tmp_path): 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", "del\x7f", "100%", "%PATH%", 'say "hi"', "a&b", "a|b", "a>b", "ab", "a 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_special_characters_inside_a_quoted_word_reach_the_program(tmp_path): +def test_a_refusal_points_to_standard_input_or_a_file(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", ""] + 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): diff --git a/setup/agents.py b/setup/agents.py index cf2ac06..d7492d9 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -38,7 +38,7 @@ def dock_strangers() -> list: LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "5c3901a79154349c34a2b318ea4ee3461af654a7210cb94652642d7ca0b40c2d"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "ca151079ab3a7b0ce1ba270d72cdf7be695b20da3d83bd6f6e4c7ecbbcbb27ea"} def lookup_problems() -> list: