diff --git a/backend/app/core/files.py b/backend/app/core/files.py new file mode 100644 index 0000000..9354135 --- /dev/null +++ b/backend/app/core/files.py @@ -0,0 +1,26 @@ +import os +import tempfile +from pathlib import Path + +NEW_FILE_MODE = 0o644 + + +def write_atomic(path: Path, data: bytes) -> None: + path = Path(path) + if path.is_symlink(): + path = path.resolve() + fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".part", dir=str(path.parent)) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + try: + mode = path.stat().st_mode & 0o7777 + except OSError: + mode = NEW_FILE_MODE + os.chmod(tmp, mode) + os.replace(tmp, path) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise diff --git a/backend/app/engine/documents.py b/backend/app/engine/documents.py index 3280eef..b708af0 100644 --- a/backend/app/engine/documents.py +++ b/backend/app/engine/documents.py @@ -10,6 +10,7 @@ from app import __version__ from app.core import config +from app.core.files import write_atomic from app.engine.core import CoreError, core log = logging.getLogger("formdesign.documents") @@ -203,7 +204,7 @@ async def save(self, path: str | None = None, *, source: str = "engine", comment pack = packs.get(m.pack_id) if m.pack_id else None data = await self.serialize_fdes(pack) try: - p.write_bytes(data) + write_atomic(p, data) except OSError as exc: raise CoreError(f"cannot save to {p}: {exc.strerror or exc}") from exc m.path = str(p) diff --git a/backend/app/routers/website.py b/backend/app/routers/website.py index 19fc5ad..ad84c11 100644 --- a/backend/app/routers/website.py +++ b/backend/app/routers/website.py @@ -1,4 +1,5 @@ import os +import re import subprocess import sys import webbrowser @@ -15,6 +16,29 @@ sites = APIRouter() SANDBOX = "sandbox allow-scripts allow-popups allow-forms" _SITE_HEADERS = {"Cache-Control": "no-cache", "Content-Security-Policy": SANDBOX, "Access-Control-Allow-Origin": "*"} +REVIEW_CSP = "default-src 'none'; img-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" +_REVIEW_HEADERS = {"Cache-Control": "no-cache", "Content-Security-Policy": REVIEW_CSP} + + +REVIEW_FILES = frozenset({"index.html", "review.js", "review.css", "review.json", "404.html"}) +REVIEW_PAGE = re.compile(r"pages/p[0-9]+\.jpg") + + +def _review_file(root: Path, target: Path) -> bool: + try: + rel = target.relative_to(root).as_posix() + except ValueError: + return False + return rel in REVIEW_FILES or REVIEW_PAGE.fullmatch(rel) is not None + + +def _headers_for(root: Path, target: Path) -> dict: + from app.services.review import reviews + _, sep, token = root.name.rpartition("-review-") + rec = reviews.get(token) if sep and token else None + if rec and rec.get("open") and rec.get("slug") == root.name and _review_file(root, target): + return _REVIEW_HEADERS + return _SITE_HEADERS def _url(request: Request, slug: str) -> str: @@ -84,9 +108,9 @@ async def serve(slug: str, path: str = ""): if root not in target.parents or not target.is_file(): missing = root / "404.html" if missing.is_file(): - return FileResponse(missing, status_code=404, headers=_SITE_HEADERS) + return FileResponse(missing, status_code=404, headers=_headers_for(root, missing)) raise HTTPException(404, "not found") - return FileResponse(target, headers=_SITE_HEADERS) + return FileResponse(target, headers=_headers_for(root, target)) @sites.get("/sites/{slug}", include_in_schema=False) diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..41d1d57 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", @@ -359,13 +359,69 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class StartRefused(ValueError): + pass + + +CMD_CONTROL = re.compile(r"[\x00-\x1f\x7f]") +CMD_SPECIAL = frozenset('&|<>^()!%"') +CMD_REFUSAL = ("cannot pass through the Windows command interpreter, which rereads it even inside quotes; " + "pass long or special text through standard input or a file if the tool supports it") + + +def _shim_file(folder: Path, rel: str) -> Path: + return folder.joinpath(*[part for part in re.split(r"[\\/]", rel) if part]) + + +def shim_target(path: str, env: dict) -> list[str] | None: + """What an npm .cmd shim runs, so it can be started without the command interpreter: node beside the shim (or on PATH) + with the script the shim names, or the .exe the shim names. None when the file is not a shim of either shape.""" + try: + text = Path(path).read_text(encoding="utf-8", errors="replace") + except OSError: + return None + folder = Path(path).parent + script = re.search(r'"%_prog%"\s+"%dp0%\\([^"%]+)"\s+%\*', text) + if script: + target = _shim_file(folder, script.group(1)) + 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 and target.is_file() else None + exe = re.search(r'^\s*"%dp0%\\([^"%]+\.exe)"\s+%\*\s*$', text, re.M | re.I) + if exe: + target = _shim_file(folder, exe.group(1)) + return [str(target)] if target.is_file() else None + return None + + +def _cmd_word(word: str) -> str: + """A word for a command line the interpreter will read: refused when it holds a character the interpreter or a + batch file's %* would act on, quoted or not, with spaces or without.""" + if CMD_CONTROL.search(word): + raise StartRefused("this text has a line break or a control character and " + CMD_REFUSAL + ".") + found = sorted({ch for ch in word if ch in CMD_SPECIAL}) + if found: + raise StartRefused("this text has " + " ".join(found) + " and " + CMD_REFUSAL + ".") + return word + + +def _cmd_line(words: list[str]) -> list[str]: + return [_cmd_word(w) for w in 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. A .cmd shim is resolved to the program it runs; any other + .cmd or .bat goes through the command interpreter, and any word holding a character it would act on 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 words[0].lower().endswith((".cmd", ".bat")): + return words + target = shim_target(words[0], env) if words[0].lower().endswith(".cmd") else None + if target: + return [*target, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/d", "/v:off", "/c", *_cmd_line(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/agents.py b/backend/app/services/agents.py index 10cec30..caa0fe0 100644 --- a/backend/app/services/agents.py +++ b/backend/app/services/agents.py @@ -211,6 +211,8 @@ def gate_reason(name: str, args: dict) -> str | None: return f"overwrites {args['path']}" except (OSError, ValueError): return None + if name == "book" and args.get("action") in ("paginate", "sync"): + return "rewrites the chapter files of the book on disk" if name == "book" and args.get("action") == "export" and args.get("path"): try: if Path(str(args["path"])).expanduser().exists(): diff --git a/backend/app/services/books.py b/backend/app/services/books.py index 1cf0714..2f35940 100644 --- a/backend/app/services/books.py +++ b/backend/app/services/books.py @@ -7,6 +7,7 @@ from pathlib import Path from app.core import config +from app.core.files import write_atomic from app.engine.core import CoreError, core from app.engine.documents import INNER, documents @@ -124,12 +125,12 @@ def _inner(p: Path) -> bytes: def _write_back(p: Path, inner: bytes) -> bool: + data = p.read_bytes() if p.suffix.lower() != config.FDES_EXT: - if p.read_bytes() == inner: + if data == inner: return False - p.write_bytes(inner) + write_atomic(p, inner) return True - data = p.read_bytes() with zipfile.ZipFile(io.BytesIO(data)) as z: if z.read(INNER) == inner: return False @@ -138,10 +139,19 @@ def _write_back(p: Path, inner: bytes) -> bool: for info in z.infolist(): body = inner if info.filename == INNER else z.read(info.filename) out.writestr(info, body, compress_type=info.compress_type) - p.write_bytes(buf.getvalue()) + _keep_before(p, data) + write_atomic(p, buf.getvalue()) return True +def _keep_before(p: Path, data: bytes) -> None: + from app.services import versions + try: + versions.keep(str(p), data, "", "save") + except OSError as exc: + raise BookError(f"cannot keep a version of {p.name} before changing it: {exc.strerror or exc}") from exc + + async def _exec(command: str, params: dict): return (await core.call("exec", {"command": command, "params": params}, source="book")).result diff --git a/backend/app/services/claude_chat.py b/backend/app/services/claude_chat.py index c543611..fc82cbb 100644 --- a/backend/app/services/claude_chat.py +++ b/backend/app/services/claude_chat.py @@ -11,7 +11,7 @@ from app.core import config from app.engine.core import core -from app.services import claude_code +from app.services import agent_lookup, claude_code NOTE = (claude_code.NOTE + " You are answering in FormDesign's Claude Code panel, which shows Markdown to people who may never have used a terminal: " "write short paragraphs, use **bold** for panel and setting names and a bulleted list when you changed several things, avoid tables and long code blocks, " @@ -175,7 +175,7 @@ def drain() -> None: per = (ev.get("modelUsage") or {}).get(usage["model"]) or {} usage["window"] = int(per.get("contextWindow") or usage["window"] or 0) proc.wait(timeout=30) - except (OSError, subprocess.SubprocessError, claude_code.ClaudeError) as e: + except (OSError, subprocess.SubprocessError, claude_code.ClaudeError, agent_lookup.StartRefused) as e: reply["error"] = f"Claude Code could not run: {e}" finally: STATE["proc"] = None diff --git a/backend/app/services/commands.py b/backend/app/services/commands.py index bf7d75c..c4e7830 100644 --- a/backend/app/services/commands.py +++ b/backend/app/services/commands.py @@ -7,7 +7,7 @@ META_FILE = Path(__file__).resolve().parent.parent / "command_meta.json" RISKY_PREFIX = ("file.print", "file.package", "file.export", "book.export", "file.close", "layout.pages.delete") -RISKY_EXACT = {"file.save", "file.saveAs", "file.revert", "layer.delete", "document.close"} +RISKY_EXACT = {"file.save", "file.saveAs", "file.revert", "file.recovery.open", "file.recovery.save", "layer.delete", "document.close"} WAIT = 30.0 window: list[dict] = [] diff --git a/backend/app/services/pty.py b/backend/app/services/pty.py index 7377646..2ad1784 100644 --- a/backend/app/services/pty.py +++ b/backend/app/services/pty.py @@ -181,7 +181,7 @@ async def create(self, preset: str, cols: int, rows: int, prompt: str | None = N title = "Terminal" elif preset == "claude": title = "Claude Code (from Chat)" if resume else "Claude Code" - from app.services import claude_code + from app.services import agent_lookup, claude_code found = await asyncio.to_thread(claude_code.info, True) if not found["installed"]: raise ValueError(found["said"]) @@ -193,7 +193,11 @@ async def create(self, preset: str, cols: int, rows: int, prompt: str | None = N token, mcp_file = claude_code.issue() except claude_code.ClaudeError as exc: raise ValueError(str(exc)) from None - argv = claude_code.argv(found["path"], mcp_file, prompt or claude_code.prefs().get("claudeFirstMessage") or None, resume) + try: + argv = claude_code.argv(found["path"], mcp_file, prompt or claude_code.prefs().get("claudeFirstMessage") or None, resume) + except agent_lookup.StartRefused as exc: + claude_code.revoke(token) + raise ValueError(str(exc)) from None env = claude_code.child_env(found["path"]) else: from app.services import agent_programs diff --git a/backend/app/services/website.py b/backend/app/services/website.py index f5465a8..63bb72f 100644 --- a/backend/app/services/website.py +++ b/backend/app/services/website.py @@ -1438,7 +1438,8 @@ async def publish(self, options: dict | None = None, slug: str | None = None) -> options = dict(rec.get("options") or {}) site = await build_site(options) if rec is None: - used = {i.get("slug") for i in items} + from app.services.review import reviews + used = {i.get("slug") for i in items} | {r.get("slug") for r in reviews.entries()} slug = slugify(slug or site.title, set(used), fallback="site") rec = {"slug": slug, "created": time.time()} items.append(rec) diff --git a/backend/tests/test_reported_fixes.py b/backend/tests/test_reported_fixes.py index 2284789..0bb40ef 100644 --- a/backend/tests/test_reported_fixes.py +++ b/backend/tests/test_reported_fixes.py @@ -122,3 +122,254 @@ def test_in_app_token_is_never_on_the_claude_command_line(launch, monkeypatch): assert servers["formdesign_tab"]["headers"][INAPP_HEADER] == token if os.name != "nt": assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +@pytest.mark.parametrize("cid", ["file.recovery.open", "file.recovery.save"]) +def test_an_outside_agent_asks_before_running_recovery(cid): + from app.services import agents as A + assert A.gate_reason("run_command", {"id": cid, "params": {"dir": "/tmp/x"}}) + assert A.gate_reason("run_commands", {"commands": [{"command": cid, "params": {"dir": "/tmp/x"}}]}) + + +@pytest.mark.parametrize("action", ["paginate", "sync"]) +def test_an_outside_agent_asks_before_a_book_rewrites_its_chapters(action): + from app.services import agents as A + assert A.gate_reason("book", {"action": action, "book": "x.fdbook"}) + + +def chapter_bytes(inner): + import io + import zipfile + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as z: + z.writestr("document.fdoc", inner) + z.writestr("meta.json", "{}") + return buf.getvalue() + + +def test_a_book_keeps_the_chapter_as_it_was_before_rewriting_it(tmp_path): + import zipfile + from app.services import books, versions + chapter = tmp_path / "Chapter.fdes" + before = chapter_bytes(b"old") + chapter.write_bytes(before) + assert books._write_back(chapter, b"new") + with zipfile.ZipFile(chapter) as z: + assert z.read("document.fdoc") == b"new" + kept = versions.listing(str(chapter)) + assert kept and versions.read(str(chapter), kept[0]["id"]) == before + assert [p.name for p in tmp_path.iterdir()] == ["Chapter.fdes"] + + +def test_a_failed_write_leaves_the_file_whole(tmp_path, monkeypatch): + import os + from app.core import files + target = tmp_path / "Doc.fdes" + target.write_bytes(b"whole") + def broken(src, dst): + raise OSError(28, "No space left on device") + monkeypatch.setattr(files.os, "replace", broken) + with pytest.raises(OSError): + files.write_atomic(target, b"partial") + assert target.read_bytes() == b"whole" + assert [p.name for p in tmp_path.iterdir()] == ["Doc.fdes"] + assert os.access(target, os.R_OK) + + +def test_a_review_page_can_list_and_post_its_comments(client, bare): + new_document(client) + r = client.post("/api/review/share") + assert r.status_code == 200, r.text + view = r.json() + page = bare.get(f"/sites/{view['slug']}/") + assert page.status_code == 200 + csp = page.headers["content-security-policy"] + assert "sandbox" not in csp and "connect-src 'self'" in csp and "script-src 'self'" in csp + token = view["token"] + same = {"origin": own_origin(), "sec-fetch-site": "same-origin"} + listed = client.get(f"/api/review/public/{token}/comments", headers={"sec-fetch-site": "same-origin"}) + assert listed.status_code == 200, listed.text + posted = client.post(f"/api/review/public/{token}/comments", json={"name": "Sam", "text": "Looks good", "page": 0, "x": 0.5, "y": 0.5}, headers=same) + assert posted.status_code == 200, posted.text + assert client.post("/api/review/stop").status_code == 200 + + +def test_a_published_site_stays_sandboxed(client, bare, tmp_path): + from app.services.website import PUBLISHED_DIR + site = PUBLISHED_DIR / "plain-site" + site.mkdir(parents=True, exist_ok=True) + (site / "index.html").write_text("

hi

", encoding="utf-8") + try: + page = bare.get("/sites/plain-site/") + assert page.status_code == 200 + assert page.headers["content-security-policy"].startswith("sandbox") + finally: + (site / "index.html").unlink() + site.rmdir() + + +NPM_SHIM = """@ECHO off\r +GOTO start\r +:find_dp0\r +SET dp0=%~dp0\r +EXIT /b\r +:start\r +SETLOCAL\r +CALL :find_dp0\r +\r +IF EXIST "%dp0%\\node.exe" (\r + SET "_prog=%dp0%\\node.exe"\r +) ELSE (\r + SET "_prog=node"\r + SET PATHEXT=%PATHEXT:;.JS;=;%\r +)\r +\r +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %*\r +""" +AWKWARD = ['Make the headline say "Sale" & add a CTA', "first line\nsecond line", "100% of %USERPROFILE%", "a|b"] + + +def test_a_windows_npm_shim_runs_node_directly_with_the_text_untouched(tmp_path): + from app.services import agent_lookup + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + (tmp_path / "node.exe").write_bytes(b"") + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + for text in AWKWARD: + argv = agent_lookup.start_argv([str(shim), "-p", "--", text], env={"COMSPEC": "cmd.exe"}, platform="win32") + assert argv == [str(tmp_path / "node.exe"), str(script), "-p", "--", text] + + +def test_a_windows_shim_that_names_an_exe_runs_it_directly(tmp_path): + from app.services import agent_lookup + shim = tmp_path / "claude.cmd" + exe = tmp_path / "node_modules" / "pkg" / "bin" / "claude.exe" + exe.parent.mkdir(parents=True) + exe.write_bytes(b"") + shim.write_text('@ECHO off\r\n"%dp0%\\node_modules\\pkg\\bin\\claude.exe" %*\r\n', encoding="utf-8") + assert agent_lookup.start_argv([str(shim), "--", "a & b"], env={}, platform="win32") == [str(exe), "--", "a & b"] + + +CMD_REFUSED = ['say "Sale" now', '"quoted"', "first line\nsecond line", "100% done", "%USERPROFILE%", "a&b", "plain words & more", + "a|b", "a < b", "a > b", "^caret", "(group)", "wow!", "x\x7fy", "tab\there", "nul\x00byte", "esc\x1b"] + + +def _plain_bat(folder): + folder.mkdir(parents=True, exist_ok=True) + bat = folder / "claude.bat" + bat.write_text("@echo off\r\nsomething %*\r\n", encoding="utf-8") + return bat + + +@pytest.mark.parametrize("text", CMD_REFUSED) +def test_text_the_windows_command_interpreter_would_act_on_is_refused(tmp_path, text): + from app.services import agent_lookup + bat = _plain_bat(tmp_path) + with pytest.raises(agent_lookup.StartRefused, match="standard input or a file"): + agent_lookup.start_argv([str(bat), "--", text], env={"COMSPEC": "cmd.exe"}, platform="win32") + + +@pytest.mark.parametrize("folder", ["plain", "Program Files"]) +def test_spaces_do_not_let_special_characters_through_the_windows_command_interpreter(tmp_path, folder): + from app.services import agent_lookup + bat = _plain_bat(tmp_path / folder) + with pytest.raises(agent_lookup.StartRefused): + agent_lookup.start_argv([str(bat), "--", "plain words & more"], env={"COMSPEC": "cmd.exe"}, platform="win32") + with pytest.raises(agent_lookup.StartRefused): + agent_lookup.start_argv([str(bat), "--", "nospaces&more"], env={"COMSPEC": "cmd.exe"}, platform="win32") + + +def test_plain_words_pass_through_the_windows_command_interpreter(tmp_path): + from app.services import agent_lookup + bat = _plain_bat(tmp_path / "Program Files") + argv = agent_lookup.start_argv([str(bat), "--", "plain words", "--model=x.y"], env={"COMSPEC": "C:/Windows/cmd.exe"}, platform="win32") + assert argv == ["C:/Windows/cmd.exe", "/d", "/v:off", "/c", str(bat), "--", "plain words", "--model=x.y"] + + +def test_a_cmd_file_that_is_not_a_shim_goes_through_the_strict_interpreter_path(tmp_path): + from app.services import agent_lookup + cmd = tmp_path / "tool.cmd" + cmd.write_text("@echo off\r\nsomething %*\r\n", encoding="utf-8") + assert agent_lookup.start_argv([str(cmd), "ok"], env={}, platform="win32") == ["cmd.exe", "/d", "/v:off", "/c", str(cmd), "ok"] + with pytest.raises(agent_lookup.StartRefused): + agent_lookup.start_argv([str(cmd), "a&b"], env={}, platform="win32") + + +def test_a_program_path_with_a_special_character_is_refused_on_the_interpreter_path(tmp_path): + from app.services import agent_lookup + bat = _plain_bat(tmp_path / "Tools (x86)") + with pytest.raises(agent_lookup.StartRefused): + agent_lookup.start_argv([str(bat), "plain"], env={"COMSPEC": "cmd.exe"}, platform="win32") + + +def test_a_shim_whose_script_is_missing_falls_back_to_the_strict_interpreter_path(tmp_path): + from app.services import agent_lookup + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + (tmp_path / "node.exe").write_bytes(b"") + assert agent_lookup.start_argv([str(shim), "-p"], env={"COMSPEC": "cmd.exe"}, platform="win32")[:4] == ["cmd.exe", "/d", "/v:off", "/c"] + with pytest.raises(agent_lookup.StartRefused): + agent_lookup.start_argv([str(shim), "-p", "a & b"], env={"COMSPEC": "cmd.exe"}, platform="win32") + + +def test_a_shim_finds_node_on_path_when_none_sits_beside_it(tmp_path): + from app.services import agent_lookup + shim_dir = tmp_path / "npm" + shim_dir.mkdir() + shim = shim_dir / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + script = shim_dir / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + node_dir = tmp_path / "nodejs" + node_dir.mkdir() + node = node_dir / "node" + node.write_text("", encoding="utf-8") + node.chmod(0o755) + argv = agent_lookup.start_argv([str(shim), "--", "a & b %X%"], env={"PATH": str(node_dir)}, platform="win32") + assert argv == [str(node), str(script), "--", "a & b %X%"] + + +def test_a_windows_exe_is_started_as_it_is(tmp_path): + from app.services import agent_lookup + assert agent_lookup.start_argv(["C:/x/claude.exe", "--", "a\nb & 100%"], env={}, platform="win32") == ["C:/x/claude.exe", "--", "a\nb & 100%"] + + +def test_an_atomic_save_through_a_link_writes_the_linked_file(tmp_path): + from app.core import files + real = tmp_path / "real" / "Doc.fdes" + real.parent.mkdir() + real.write_bytes(b"before") + link = tmp_path / "Doc.fdes" + link.symlink_to(real) + files.write_atomic(link, b"after") + assert link.is_symlink() and real.read_bytes() == b"after" + + +def test_a_website_is_never_published_into_a_review_folder(client, bare): + new_document(client) + view = client.post("/api/review/share").json() + try: + r = client.post("/api/website/publish", json={"slug": view["slug"]}) + assert r.status_code == 200, r.text + assert r.json()["slug"] != view["slug"] + assert bare.get(f"/sites/{r.json()['slug']}/").headers["content-security-policy"].startswith("sandbox") + assert client.post("/api/website/unpublish", json={"slug": r.json()["slug"]}).status_code == 200 + finally: + assert client.post("/api/review/stop").status_code == 200 + + +def test_only_the_files_a_review_writes_get_its_page_policy(client, bare): + from app.services.website import PUBLISHED_DIR + new_document(client) + view = client.post("/api/review/share").json() + extra = PUBLISHED_DIR / view["slug"] / "extra.html" + extra.write_text("

hi

", encoding="utf-8") + try: + assert "sandbox" not in bare.get(f"/sites/{view['slug']}/review.js").headers["content-security-policy"] + assert bare.get(f"/sites/{view['slug']}/extra.html").headers["content-security-policy"].startswith("sandbox") + finally: + extra.unlink() + assert client.post("/api/review/stop").status_code == 200 diff --git a/native/formdesign-engine/src/cmd/file.rs b/native/formdesign-engine/src/cmd/file.rs index be3ddd2..6361fa5 100644 --- a/native/formdesign-engine/src/cmd/file.rs +++ b/native/formdesign-engine/src/cmd/file.rs @@ -948,9 +948,10 @@ fn recovery_entries(dir: &Path) -> Vec<(PathBuf, Value)> { .flatten() .map(|e| e.path()) .filter(|p| p.extension().and_then(|x| x.to_str()) == Some(NATIVE_EXT)) - .map(|p| { - let meta = std::fs::read_to_string(p.with_extension("json")).ok().and_then(|s| serde_json::from_str::(&s).ok()).unwrap_or(json!({})); - (p, meta) + .filter(|p| p.file_stem().and_then(|s| s.to_str()).is_some_and(|s| s.parse::().is_ok())) + .filter_map(|p| { + let meta = std::fs::read_to_string(p.with_extension("json")).ok().and_then(|s| serde_json::from_str::(&s).ok())?; + meta.is_object().then_some((p, meta)) }) .collect(); out.sort_by(|a, b| a.0.cmp(&b.0)); diff --git a/native/formdesign-engine/tests/native_files.rs b/native/formdesign-engine/tests/native_files.rs index 6b29d51..b6fcc63 100644 --- a/native/formdesign-engine/tests/native_files.rs +++ b/native/formdesign-engine/tests/native_files.rs @@ -104,3 +104,38 @@ fn idml_export_reopens_with_the_same_pages_and_text() { assert_eq!(doc.page_count(), 2); assert!(doc.stories.values().any(|s| s.text().trim() == text.trim()), "the story text survives"); } + +#[test] +fn recovery_open_leaves_ordinary_documents_in_the_folder_alone() { + let mut ses = session(); + sample(&mut ses); + let bytes = format::save(&ses.active().unwrap().doc).unwrap(); + let dir = scratch("recovery-mixed"); + std::fs::create_dir_all(&dir).unwrap(); + let own = dir.join("Brochure.fdoc"); + std::fs::write(&own, &bytes).unwrap(); + let named = dir.join("42.fdoc"); + std::fs::write(&named, &bytes).unwrap(); + let paired = dir.join("Flyer.fdoc"); + std::fs::write(&paired, &bytes).unwrap(); + std::fs::write(dir.join("Flyer.json"), json!({"title": "Flyer"}).to_string()).unwrap(); + let listed = run(&mut ses, "file.recovery.list", json!({"dir": dir})); + assert_eq!(listed, json!([])); + let opened = run(&mut ses, "file.recovery.open", json!({"dir": dir})); + assert_eq!(opened["opened"], json!(0)); + assert!(own.exists() && named.exists() && paired.exists()); +} + +#[test] +fn recovery_save_then_open_restores_and_clears_the_snapshot() { + let mut ses = session(); + sample(&mut ses); + let dir = scratch("recovery-round"); + run(&mut ses, "file.recovery.save", json!({"dir": dir})); + let listed = run(&mut ses, "file.recovery.list", json!({"dir": dir})); + assert_eq!(listed.as_array().map(Vec::len), Some(1)); + let mut fresh = session(); + let opened = run(&mut fresh, "file.recovery.open", json!({"dir": dir})); + assert_eq!(opened["opened"], json!(1)); + assert_eq!(run(&mut fresh, "file.recovery.list", json!({"dir": dir})), json!([])); +} diff --git a/setup/agents.py b/setup/agents.py index 9b88a54..51ef613 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -89,7 +89,7 @@ def templates_reference() -> str: DOCK = {"present": True, "positions": ["bottom", "right"], "tabs": ["chat", "terminal", "claude", "codex", "cursor", "antigravity"]} DOCK_FOLDER = ROOT / "frontend" / "src" / "dock" 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": "7388be518a6107d328512998acfcd5fb132e79f089b3ce8cdd657f23ed679589"} def lookup_problems() -> list[str]: