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/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..4fdfa76 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,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)] diff --git a/backend/app/services/pdf/items.py b/backend/app/services/pdf/items.py index 1be0011..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] @@ -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/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_agent_start.py b/backend/tests/test_agent_start.py new file mode 100644 index 0000000..6ab51df --- /dev/null +++ b/backend/tests/test_agent_start.py @@ -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 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 diff --git a/backend/tests/test_item_text.py b/backend/tests/test_item_text.py new file mode 100644 index 0000000..aeb1170 --- /dev/null +++ b/backend/tests/test_item_text.py @@ -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 = '">' + 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": ""}] diff --git a/backend/tests/test_seal.py b/backend/tests/test_seal.py index 65978e5..202f283 100644 --- a/backend/tests/test_seal.py +++ b/backend/tests/test_seal.py @@ -166,3 +166,44 @@ 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" + 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" diff --git a/frontend/src/tools/richtext.ts b/frontend/src/tools/richtext.ts index 737e45a..39a9f02 100644 --- a/frontend/src/tools/richtext.ts +++ b/frontend/src/tools/richtext.ts @@ -26,22 +26,34 @@ 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; } +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}
`; + 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); + 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(''); } diff --git a/setup/agents.py b/setup/agents.py index 21a5c66..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"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "ca151079ab3a7b0ce1ba270d72cdf7be695b20da3d83bd6f6e4c7ecbbcbb27ea"} def lookup_problems() -> list: