Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions backend/app/core/files.py
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion backend/app/engine/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down
28 changes: 26 additions & 2 deletions backend/app/routers/website.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import re
import subprocess
import sys
import webbrowser
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
62 changes: 59 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 Down Expand Up @@ -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)]
Expand Down
2 changes: 2 additions & 0 deletions backend/app/services/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
18 changes: 14 additions & 4 deletions backend/app/services/books.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down
4 changes: 2 additions & 2 deletions backend/app/services/claude_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, "
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion backend/app/services/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = []
Expand Down
8 changes: 6 additions & 2 deletions backend/app/services/pty.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion backend/app/services/website.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading