diff --git a/backend/tests/mocks/hosts/host_mocks.py b/backend/tests/mocks/hosts/host_mocks.py index 1c21ec8f..db8fb2fa 100644 --- a/backend/tests/mocks/hosts/host_mocks.py +++ b/backend/tests/mocks/hosts/host_mocks.py @@ -57,6 +57,13 @@ class _Handler(http.server.BaseHTTPRequestHandler): def log_message(self, *args): pass + def parse_request(self): # noqa: D401 - record a verb that has no do_ handler (TRACE, CONNECT, extensions) + parsed = super().parse_request() + if parsed and not hasattr(self, "do_" + self.command): + server: MockHost = self.server # type: ignore[assignment] + server.requests.append({"method": self.command, "path": self.path.split("?", 1)[0], "headers": {}}) + return parsed + def _send(self, status: int, body: bytes = b"", extra: dict | None = None): self.send_response(status) self.send_header("Content-Type", "application/json") @@ -82,12 +89,12 @@ def do_GET(self): # noqa: N802 status, body = hit self._send(status, json.dumps(body).encode("utf-8")) - def do_POST(self): # noqa: N802 - mocks never accept writes; a POST is recorded and refused + def do_POST(self): # noqa: N802 - mocks never accept writes; any other verb is recorded as sent and refused server: MockHost = self.server # type: ignore[assignment] - server.requests.append({"method": "POST", "path": self.path.split("?", 1)[0], "headers": {}}) + server.requests.append({"method": self.command, "path": self.path.split("?", 1)[0], "headers": {}}) self._send(405, b"{}") - do_PUT = do_DELETE = do_PATCH = do_POST + do_PUT = do_DELETE = do_PATCH = do_HEAD = do_OPTIONS = do_POST def make_moonraker(fixture_bundle: dict, *, octoprint_compat: bool = True) -> MockHost: diff --git a/backend/tests/recovery/test_routes.py b/backend/tests/recovery/test_routes.py index a74fcadf..cadab718 100644 --- a/backend/tests/recovery/test_routes.py +++ b/backend/tests/recovery/test_routes.py @@ -81,6 +81,23 @@ def test_monitoring_route_refuses_public_host_and_bad_input(api): assert api("/monitoring/history", {})[0] == 400 +@pytest.mark.parametrize("port", [0, 65536, -1, 7125.5, True, "not-a-port"]) +def test_monitoring_routes_reject_invalid_ports(api, port): + assert api("/monitoring/read", {"host": "127.0.0.1", "port": port})[0] == 400 + assert api("/monitoring/history", {"host": "127.0.0.1", "port": port})[0] == 400 + + +def test_monitoring_custom_loopback_port_stays_within_the_read_only_boundary(api): + mock = MockHost({"/printer/objects/query": (200, STATUS)}).start() + try: + code, _ = api("/monitoring/read", {"host": "127.0.0.1", "port": mock.server_address[1]}) + requests = list(mock.requests) + finally: + mock.stop() + assert code == 200 + assert [(request["method"], request["path"]) for request in requests] == [("GET", "/printer/objects/query")] + + def test_malformed_monitoring_host_is_a_400_not_a_500(api): for host in ("evil.com/path", "user@host", "http://x"): code, _ = api("/monitoring/read", {"host": host}) diff --git a/backend/tests/test_crosstrack_journey.py b/backend/tests/test_crosstrack_journey.py new file mode 100644 index 00000000..aa58935a --- /dev/null +++ b/backend/tests/test_crosstrack_journey.py @@ -0,0 +1,193 @@ +"""Test 11: synthetic cross-track journey through route dispatch, the Prepare service and the real passport CLI. + +Not covered: the HTTP transport and token, the HTTP /convert handler, /creative/prepare, the desktop UI, and a process crash or restart. +""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +import http.client +import socket +import struct +from pathlib import Path +import zipfile + +CRLF = chr(13) + chr(10) + +from snapstudio_api import ext_routes +from snapstudio_api import service +from snapstudio_core.stl_wrap import wrap_stl +from tests.mocks.hosts.host_mocks import MockHost + + +class _Dispatch: + def __init__(self): + self.result = None + + def _send(self, status, body): + self.result = status, body + + +def _post(path: str, data: dict) -> tuple[int, dict]: + handler = _Dispatch() + assert ext_routes.dispatch(handler, path, data) + assert handler.result is not None + return handler.result + + +def _forca_project(path: Path) -> Path: + """Add a published FOrca key to a synthetic project archive used by Prepare.""" + staged = path.with_suffix(".staged.3mf") + with zipfile.ZipFile(path) as src, zipfile.ZipFile(staged, "w", zipfile.ZIP_DEFLATED) as dst: + for item in src.infolist(): + data = src.read(item.filename) + if item.filename == "Metadata/project_settings.config": + settings = json.loads(data) + settings["fos_physical_nozzle_diameter"] = [0.4] + data = json.dumps(settings).encode() + dst.writestr(item, data) + staged.replace(path) + return path + + +def _synthetic_project(path: Path) -> Path: + """Build a tiny geometry archive entirely from synthetic tetrahedron bytes.""" + stl = path.with_suffix(".stl") + head = b"\0" * 80 + struct.pack(" Prepare -> passport CLI -> checkpoint -> mutation -> preview.""" + monkeypatch.setenv("SNAPSTUDIO_DATA_DIR", str(tmp_path / "studio-data")) + monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local")) + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg")) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + # (a) A synthetic FOrca-tagged creative project enters via the real route dispatch. + original = _synthetic_project(tmp_path / "synthetic-project.3mf") + before = original.read_bytes() + code, inspected = _post("/creative/inspect", {"path": str(original), "format": "forcaslicer"}) + assert code == 200 and inspected["origin"]["generator"] == "forcaslicer" + assert inspected["source"]["unchanged"] is True and original.read_bytes() == before + + # (b) Prepare calls the same service entry used by the HTTP /convert handler. + result = service.convert(str(original), str(tmp_path)) + prepared = Path(result["output_path"]) + assert result["validated_ok"] is True and prepared != original and prepared.is_file() + assert original.read_bytes() == before + + # (c) Build a declared original -> prepared chain and verify through the real CLI module. + code, built = _post("/passport/build", {"entries": [ + {"path": str(original), "role": "original"}, + {"path": str(prepared), "role": "prepared", "parents": [0]}, + ]}) + assert code == 200 and built["passport"] + passport_file = tmp_path / "job.passport.json" + passport_file.write_text(json.dumps(built["passport"]), encoding="utf-8") + cli = subprocess.run( + [sys.executable, "-m", "u1convert.cli", "passport", "verify", str(passport_file), + "--base-dir", str(tmp_path)], cwd=Path(__file__).resolve().parents[1], + env={**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1])}, + capture_output=True, text=True, timeout=120, check=False, + ) + initial_verification = json.loads(cli.stdout) + assert cli.returncode == 0 and initial_verification["ok"] is True + assert initial_verification["verification"]["summary"]["all_intact"] is True + + # (d) Checkpoint the original, the prepared copy and an additional synthetic tracked file (three files). + extra = tmp_path / "synthetic-sliced.gcode" + extra.write_text("synthetic sliced stand-in", encoding="utf-8") + code, checkpoint = _post("/recovery/checkpoint", {"workspace": {"name": "Synthetic demo"}, + "files": [{"name": p.name, "path": str(p)} for p in (original, prepared, extra)], + "jobs": [{"job_id": "synthetic-job", "state": "running"}]}) + assert code == 200 and checkpoint["file_count"] == 3 + + # (e) Mutate prepared bytes, delete an extra file, then replace the original by the same name. + prepared.write_bytes(prepared.read_bytes() + b"synthetic post-checkpoint mutation") + extra.unlink() + original.unlink() + original.write_bytes(b"different synthetic file with the same name") + cli = subprocess.run( + [sys.executable, "-m", "u1convert.cli", "passport", "verify", str(passport_file), + "--base-dir", str(tmp_path)], cwd=Path(__file__).resolve().parents[1], + env={**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[1])}, + capture_output=True, text=True, timeout=120, check=False, + ) + changed_verification = json.loads(cli.stdout) + summary = changed_verification["verification"]["summary"] + assert cli.returncode == 1 and changed_verification["ok"] is False + assert summary["all_intact"] is False and summary["invalidated"] + assert all(item["bytes"] != "same" for item in changed_verification["verification"]["artifacts"]) + + # Monitoring is the sole network capability used here. The sentinel records every verb/path. + mock = MockHost({ + "/printer/objects/query": (200, {"result": {"status": {"print_stats": {"state": "standby"}}}}), + "/server/history/list": (200, {"result": {"jobs": []}}), + }).start() + try: + for endpoint in ("/monitoring/read", "/monitoring/history"): + code, _ = _post(endpoint, {"host": "127.0.0.1", "port": mock.server_address[1]}) + assert code == 200 + before_restore_requests = len(mock.requests) + code, preview = _post("/recovery/restore", {}) + after_restore_requests = len(mock.requests) + assert code == 200 and after_restore_requests == before_restore_requests + finally: + mock.stop() + + # (f) The original path now resolves to different bytes; the prepared file changed; extra is missing. + states = {item["name"]: item["state"] for item in preview["files"]} + assert states == {original.name: "changed", prepared.name: "changed", extra.name: "missing"} + assert preview["jobs"][0] == {"job_id": "synthetic-job", "state": "interrupted", "replayed": False} + observed = [(request["method"], request["path"]) for request in mock.requests] + # Sentinel: any non-GET or unapproved GET reaches this assertion and fails the journey. + assert observed == [("GET", "/printer/objects/query"), ("GET", "/server/history/list")] + + + +def test_11_sentinel_records_verbs_that_have_no_handler_too(): + """TRACE, CONNECT and an extension verb are unsupported by the server and must still be recorded.""" + mock = MockHost({}).start() + try: + port = mock.server_address[1] + for method in ("TRACE", "CONNECT", "BREW"): + raw = socket.create_connection(("127.0.0.1", port), timeout=5) + raw.sendall(CRLF.join([f"{method} /printer/gcode/script HTTP/1.1", "Host: x", + "Connection: close", "", ""]).encode()) + raw.recv(4096) + raw.close() + observed = [(request["method"], request["path"]) for request in mock.requests] + finally: + mock.stop() + assert observed == [("TRACE", "/printer/gcode/script"), ("CONNECT", "/printer/gcode/script"), + ("BREW", "/printer/gcode/script")] + + +def test_11_sentinel_records_every_verb_it_would_have_to_reject(): + """The request sentinel used by test 11 must see HEAD, OPTIONS, write verbs and unapproved paths.""" + mock = MockHost({"/printer/objects/query": (200, {"result": {}})}).start() + try: + port = mock.server_address[1] + for method, path in (("HEAD", "/printer/objects/query"), ("OPTIONS", "/printer/objects/query"), + ("PUT", "/printer/objects/query"), ("DELETE", "/x"), ("POST", "/printer/print/start"), + ("GET", "/printer/gcode/script")): + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=5) + connection.request(method, path) + connection.getresponse().read() + connection.close() + observed = [(request["method"], request["path"]) for request in mock.requests] + finally: + mock.stop() + assert observed == [("HEAD", "/printer/objects/query"), ("OPTIONS", "/printer/objects/query"), + ("PUT", "/printer/objects/query"), ("DELETE", "/x"), ("POST", "/printer/print/start"), + ("GET", "/printer/gcode/script")] + assert observed != [("GET", "/printer/objects/query"), ("GET", "/server/history/list")] diff --git a/desktop/src/lib/recovery/RecoveryPanel.test.tsx b/desktop/src/lib/recovery/RecoveryPanel.test.tsx index 7e815b1b..f9aed0ed 100644 --- a/desktop/src/lib/recovery/RecoveryPanel.test.tsx +++ b/desktop/src/lib/recovery/RecoveryPanel.test.tsx @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import { MonitorSummary, RestorePreview } from "./RecoveryPanel"; +import { isValidPort } from "./api"; import type { RestoreResult } from "./api"; const base: RestoreResult = { @@ -45,3 +46,12 @@ describe("MonitorSummary", () => { expect(renderToStaticMarkup()).toBe(""); }); }); + +describe("monitor port validation", () => { + it("accepts only whole-number ports in the TCP range", () => { + for (const value of ["1", "7125", "65535"]) expect(isValidPort(value)).toBe(true); + for (const value of ["", "0", "65536", "7125.5", "1e3", " 7125", "port"]) { + expect(isValidPort(value)).toBe(false); + } + }); +}); diff --git a/desktop/src/lib/recovery/RecoveryView.test.tsx b/desktop/src/lib/recovery/RecoveryView.test.tsx new file mode 100644 index 00000000..5afd619b --- /dev/null +++ b/desktop/src/lib/recovery/RecoveryView.test.tsx @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; +import { RecoveryView } from "./RecoveryView"; + +describe("RecoveryView monitoring port", () => { + it("renders a configured port field with the default and browser range", () => { + const html = renderToStaticMarkup(); + expect(html).toContain('aria-label="Configured printer port"'); + expect(html).toContain('type="number"'); + expect(html).toContain('min="1"'); + expect(html).toContain('max="65535"'); + expect(html).toContain('value="7125"'); + }); +}); diff --git a/desktop/src/lib/recovery/RecoveryView.tsx b/desktop/src/lib/recovery/RecoveryView.tsx index 5a7247f4..f7132d17 100644 --- a/desktop/src/lib/recovery/RecoveryView.tsx +++ b/desktop/src/lib/recovery/RecoveryView.tsx @@ -2,7 +2,7 @@ import { useEffect, useState, useSyncExternalStore } from "react"; import { RotateCcw } from "lucide-react"; import { Button } from "@/components/ui/button"; import { PageHeader } from "@/components/ui/layout"; -import { legacyJobSnapshot, readMonitoring, saveCheckpoint, type MonitoringRead } from "@/lib/recovery/api"; +import { isValidPort, legacyJobSnapshot, readMonitoring, saveCheckpoint, type MonitoringRead } from "@/lib/recovery/api"; import { MonitorSummary, RestorePreview } from "@/lib/recovery/RecoveryPanel"; import { getPreview, refreshPreview, registerRecoverySubscriber, subscribePreview } from "@/lib/recovery/subscriber"; @@ -13,6 +13,7 @@ export function RecoveryView() { const [busy, setBusy] = useState(false); const [message, setMessage] = useState(""); const [host, setHost] = useState(""); + const [port, setPort] = useState("7125"); const [monitor, setMonitor] = useState(null); // Registered through the lifecycle seam (extLifecycle), not App.tsx; app start only reads the checkpoint. @@ -31,8 +32,9 @@ export function RecoveryView() { finally { setBusy(false); } }; const monitorRead = async () => { + if (!isValidPort(port)) { setMonitor(null); setMessage("Enter a port from 1 to 65535."); return; } setBusy(true); setMessage(""); - try { setMonitor(await readMonitoring(host, "7125")); } + try { setMonitor(await readMonitoring(host, port)); } catch (error) { setMonitor(null); setMessage(error instanceof Error ? error.message : "Monitoring read failed"); } finally { setBusy(false); } }; @@ -52,10 +54,15 @@ export function RecoveryView() {

Read monitoring context

One bounded, read-only request to your configured printer host. A filename match stays unverified.

-
+
setHost(e.target.value)} /> - + +
+ {!isValidPort(port) &&

Enter a whole-number port from 1 to 65535.

}
; diff --git a/desktop/src/lib/recovery/api.ts b/desktop/src/lib/recovery/api.ts index 25148a4f..39226524 100644 --- a/desktop/src/lib/recovery/api.ts +++ b/desktop/src/lib/recovery/api.ts @@ -20,6 +20,13 @@ export type HistoryRead = { last_job: { filename: string | null; outcome: string } | null; }; +/** Accept only an integer port in the range the backend monitoring route allows. */ +export function isValidPort(value: string): boolean { + if (!/^\d+$/.test(value)) return false; + const port = Number(value); + return Number.isInteger(port) && port >= 1 && port <= 65535; +} + export const saveCheckpoint = (body: unknown) => callExt<{ revision: number; checkpointed_at: string; file_count: number }>( "/recovery/checkpoint", body, "Could not save the checkpoint"); export const restoreCheckpoint = () => callExt("/recovery/restore", {}, "Could not read the checkpoint"); diff --git a/docs/internal/RECOVERY.md b/docs/internal/RECOVERY.md index f306db57..f1e4900a 100644 --- a/docs/internal/RECOVERY.md +++ b/docs/internal/RECOVERY.md @@ -12,4 +12,6 @@ Monitoring uses two bounded, read-only GETs through `foundation.netguard.local_r Evidence: **fixture-tested** and **mock-service-tested** (in-process loopback mock that counts requests). All names and values are synthetic. No real printer or local monitoring service was queried. -Roadmap, not a capability: the end-to-end chain (generate, inspect, compare, passport, checkpoint, terminate, restore; test 11) is not built or tested. Camera context and websocket event streams are not implemented. +Test 11 is DONE for a deterministic synthetic cross-track journey: `/creative/inspect` reads a synthetic FOrca-tagged project, Prepare writes a new file through `service.convert`, `/passport/build` records the declared original-to-prepared chain, `python -m u1convert.cli passport verify` verifies it, and `/recovery/checkpoint` records the original, the prepared copy and a stand-in third file. After mutating the prepared bytes, deleting a third tracked file, and replacing the original at the same path with different bytes, CLI verification reports the chain invalidated and restore preview reports changed/missing files. A loopback Moonraker sentinel confirms monitoring uses only its two allowed GET endpoints and restore preview adds no request. The original archive is checked unchanged after inspection and Prepare; recovery records interrupted work and does not replay it. + +Test 11 does **not** cover real hardware, real generators, or generated archive formats from third-party software. It also does not cover the HTTP transport and token (routes are dispatched in-process), the HTTP `/convert` handler (it calls `service.convert` directly), `/creative/prepare`, the desktop UI, or a process crash and restart. The request sentinel observes only the one loopback mock host it was given, and a separate test shows it records HEAD, OPTIONS, write verbs and unapproved paths; a request sent to any other host would not be seen by it. All archive contents and names in the journey are synthetic. Camera context and websocket event streams are not implemented. diff --git a/docs/internal/screens/recovery/README.md b/docs/internal/screens/recovery/README.md index bf10656b..9c6c2989 100644 --- a/docs/internal/screens/recovery/README.md +++ b/docs/internal/screens/recovery/README.md @@ -1,8 +1,9 @@ # Recovery screenshots -Captured with `capture.mjs` (real engine, this checkout's vite dev UI, headless Edge) using synthetic data only. Run from the repo root: `ACCEPTANCE_DIR= node docs/internal/screens/recovery/capture.mjs`. The script also starts a loopback mock on 127.0.0.1:7125 that answers the two read-only monitoring GETs. No real printer or private path appears. +Captured with `capture.mjs` (real engine, this checkout's vite dev UI, headless Edge) using synthetic data only. Run from the repo root: `ACCEPTANCE_DIR= node docs/internal/screens/recovery/capture.mjs`. The script also starts a loopback mock on a free non-default port (typed into the Port field) that answers the read-only monitoring GET; the run fails if any other request reaches it. No real printer or private path appears. -- `restore-preview.png`: checkpoint of three synthetic files, then one edited and one deleted. Shows one unchanged, one changed, one missing file, an interrupted job (recorded, not resumed), and the "Historical, re-read needed" notice. Filename matches are labelled unverified. +- `restore-preview.png`: checkpoint of three synthetic files (the original, its prepared copy and a stand-in sliced file), then the prepared copy and original are changed and the sliced stand-in deleted. Shows two changed files, one missing file, an interrupted job (recorded, not resumed), the Port field set to a non-default value, one read-only status request to the loopback mock, and the "Historical, re-read needed" notice. Filename matches are labelled unverified. +- `passport-invalidated.png`: the Job passport page after the same mutation: both files are Invalidated with their bytes-changed reasons, and the declared derivation says the parent differs. File path inputs are hidden by the script so no local path is shown. - `after-new-checkpoint.png`: the page after "Save sample checkpoint" from the built-in sample workspace (revision 2, no tracked files). - `monitoring-unverified.png`: one read-only status request to the mock. Printer state and reported filename are shown with the match to a local file marked unverified, and the camera as unknown. diff --git a/docs/internal/screens/recovery/capture.mjs b/docs/internal/screens/recovery/capture.mjs index 4683b78b..a28fef27 100644 --- a/docs/internal/screens/recovery/capture.mjs +++ b/docs/internal/screens/recovery/capture.mjs @@ -1,14 +1,8 @@ #!/usr/bin/env node -// Captures the Recovery screenshots (Windows). Real engine + this checkout's own UI (vite dev server) + headless Edge. -// -// ACCEPTANCE_DIR= node docs/internal/screens/recovery/capture.mjs -// -// Starts and stops, all on this machine: the engine (throwaway data folder), a vite dev server, and a tiny -// loopback mock that answers the two read-only monitoring GETs on 127.0.0.1:7125. No printer, no provider. -// Every name and value is synthetic. -import { createRequire } from "node:module"; +// Captures the recovery and passport screens (real engine + this checkout's Vite UI + headless Edge). +// Every artifact and mock stays on loopback or in a throwaway local folder. import { spawn, spawnSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs"; import http from "node:http"; import net from "node:net"; import { tmpdir } from "node:os"; @@ -17,84 +11,203 @@ import { fileURLToPath } from "node:url"; const here = dirname(fileURLToPath(import.meta.url)); const repo = resolve(here, "..", "..", "..", ".."); -const acceptance = process.env.ACCEPTANCE_DIR || join(repo, "tools", "acceptance"); -const { chromium } = createRequire(join(acceptance, "package.json"))("playwright-core"); +const backendDir = join(repo, "backend"); const out = here; -const work = mkdtempSync(join(tmpdir(), "recovery-shot-")); +const external = process.env.SNAPSTUDIO_CAPTURE_EXTERNAL === "1"; +const work = external ? process.env.CAPTURE_WORK : mkdtempSync(join(tmpdir(), "recovery-shot-")); +if (!work) throw new Error("CAPTURE_WORK is required in external-service mode"); +const files = external ? process.env.CAPTURE_FILES : join(work, "files"); +if (!files) throw new Error("CAPTURE_FILES is required in external-service mode"); +if (!external) mkdirSync(files); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const children = []; -const cleanup = () => { for (const c of children) { try { spawnSync("taskkill", ["/PID", String(c.pid), "/T", "/F"], { stdio: "ignore" }); } catch { /* gone */ } } }; +let mockServer; +const cleanup = () => { + for (const c of children) { + try { spawnSync("taskkill", ["/PID", String(c.pid), "/T", "/F"], { stdio: "ignore" }); } catch { /* gone */ } + } + try { mockServer?.close(); } catch { /* already closed */ } + if (!external) { try { rmSync(work, { recursive: true, force: true }); } catch { /* temporary data only */ } } +}; process.on("exit", cleanup); -const backend = spawn(process.env.PYTHON || "py", ["-m", "snapstudio_api"], { - cwd: join(repo, "backend"), stdio: ["ignore", "pipe", "pipe"], - env: { ...process.env, SNAPSTUDIO_DATA_DIR: join(work, "data"), SNAPSTUDIO_ORCA_DATA_DIR: join(work, "orca"), - PYTHONPATH: join(repo, "backend"), PYTHONUNBUFFERED: "1" }, -}); -children.push(backend); -const hs = await new Promise((ok, fail) => { - let buf = ""; - backend.stdout.on("data", (d) => { buf += d; const m = buf.match(/\{[^{}]*\}/); if (m) { try { ok(JSON.parse(m[0])); } catch { /* keep reading */ } } }); - setTimeout(() => fail(new Error("engine did not report its port")), 60000); -}); +let hs; +if (external) { + hs = { port: Number(process.env.ENGINE_PORT), token: process.env.ENGINE_TOKEN }; + if (!hs.port || !hs.token) throw new Error("ENGINE_PORT and ENGINE_TOKEN are required in external-service mode"); +} else { + const backend = spawn(process.env.PYTHON || "py", ["-3.13", "-m", "snapstudio_api"], { + cwd: backendDir, stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env, SNAPSTUDIO_DATA_DIR: join(work, "data"), SNAPSTUDIO_ORCA_DATA_DIR: join(work, "orca"), + PYTHONPATH: backendDir, PYTHONUNBUFFERED: "1" }, + }); + children.push(backend); + hs = await new Promise((ok, fail) => { + let buf = ""; + backend.stdout.on("data", (d) => { buf += d; const m = buf.match(/\{[^{}]*\}/); if (m) { try { ok(JSON.parse(m[0])); } catch { /* keep reading */ } } }); + setTimeout(() => fail(new Error("engine did not report its port")), 60000); + }); +} const post = async (path, body) => { const res = await fetch(`http://127.0.0.1:${hs.port}${path}`, { method: "POST", headers: { "Content-Type": "application/json", "X-Auth-Token": hs.token }, body: JSON.stringify(body) }); - return res.json(); + const payload = await res.json(); + if (!res.ok) throw new Error(`${path} returned ${res.status}: ${JSON.stringify(payload)}`); + return payload; }; -// Synthetic tracked files: one stays, one is replaced, one is removed after the checkpoint. -const files = join(work, "files"); mkdirSync(files); -for (const n of ["bracket.3mf", "lid.3mf", "gear.3mf"]) writeFileSync(join(files, n), `synthetic ${n}`); -console.log("checkpoint", await post("/recovery/checkpoint", { - workspace: { project: "Synthetic demo", stage: "review" }, observations: [], - files: ["bracket.3mf", "lid.3mf", "gear.3mf"].map((n) => ({ name: n, path: join(files, n) })), - jobs: [{ job_id: "job-demo-1", state: "running" }], -})); -writeFileSync(join(files, "lid.3mf"), "synthetic lid, edited after the checkpoint"); -rmSync(join(files, "gear.3mf")); +// Reuse the deterministic synthetic tetrahedron and add only an established FOrca key. +if (!external) { + const built = spawnSync(process.env.PYTHON || "py", ["-3.13", "-c", + "import sys; from pathlib import Path; from tests.test_crosstrack_journey import _synthetic_project; _synthetic_project(Path(sys.argv[1]))", + join(files, "synthetic-project.3mf")], { + cwd: backendDir, env: { ...process.env, PYTHONPATH: backendDir }, encoding: "utf8", timeout: 30000, + }); + if (built.status !== 0) throw new Error(`could not build synthetic project: ${built.stderr}`); +} +const original = process.env.SOURCE_FILE || join(files, "synthetic-project.3mf"); +const prepared = (await post("/convert", { path: original, out_dir: files })).output_path; +const extra = join(files, "synthetic-sliced.gcode"); +writeFileSync(extra, "synthetic sliced stand-in"); +await post("/recovery/checkpoint", { + workspace: { name: "Synthetic demo", stage: "review" }, observations: [], + files: [original, prepared, extra].map((path) => ({ name: path.split(/[\\/]/).at(-1), path })), + jobs: [{ job_id: "synthetic-job", state: "running" }], +}); +// A loopback mock on an ephemeral, non-default port. Only the two documented GET paths answer. +const mockRequests = []; const mock = http.createServer((req, res) => { + const path = new URL(req.url, "http://127.0.0.1").pathname; + mockRequests.push([req.method, path]); res.setHeader("Content-Type", "application/json"); - if (req.url.startsWith("/printer/objects/query")) res.end(JSON.stringify({ result: { status: { print_stats: { filename: "bracket.gcode", state: "printing" } } } })); - else res.writeHead(404).end("{}"); + if (req.method !== "GET") { res.writeHead(405).end("{}"); return; } + if (path === "/printer/objects/query") { + res.end(JSON.stringify({ result: { status: { print_stats: { filename: "synthetic-job.gcode", state: "standby" } } } })); + } else if (path === "/server/history/list") { + res.end(JSON.stringify({ result: { jobs: [] } })); + } else res.writeHead(404).end("{}"); }); -let mocked = true; -await new Promise((ok) => { mock.once("error", () => { mocked = false; ok(); }); mock.listen(7125, "127.0.0.1", ok); }); -console.log("mock on 7125:", mocked); +mockServer = mock; +await new Promise((ok) => mock.listen(0, "127.0.0.1", ok)); +const monitorPort = mock.address().port; +if (monitorPort === 7125) throw new Error("mock unexpectedly received the default monitoring port"); -const port = await new Promise((ok, fail) => { +const vitePort = external ? Number(process.env.VITE_PORT) : await new Promise((ok, fail) => { const p = net.createServer(); p.once("error", fail); p.listen(0, "127.0.0.1", () => { const { port } = p.address(); p.close(() => ok(port)); }); }); -const UI = `http://localhost:${port}`; -children.push(spawn("npx.cmd", ["vite", "--port", String(port), "--strictPort", "--host", "localhost"], { cwd: join(repo, "desktop"), stdio: "ignore", shell: true })); +const UI = `http://localhost:${vitePort}`; +if (!external) children.push(spawn("npx.cmd", ["vite", "--port", String(vitePort), "--strictPort", "--host", "localhost"], { + cwd: join(repo, "desktop"), stdio: "ignore", shell: true, +})); let ready = false; for (let i = 0; i < 80 && !ready; i++) { try { ready = (await fetch(UI + "/")).ok; } catch { /* not yet */ } if (!ready) await sleep(500); } -if (!ready) { console.error("UI did not come up"); process.exit(2); } +if (!ready) throw new Error("UI did not come up"); -const browser = await chromium.launch({ channel: "msedge", headless: true }); -const ctx = await browser.newContext({ viewport: { width: 1280, height: 1100 }, colorScheme: "dark" }); -await ctx.addInitScript(() => { localStorage.setItem("theme", "dark"); }); -const page = await ctx.newPage(); -page.on("pageerror", (e) => console.log("PAGEERROR", e.message)); -await page.goto(`${UI}/recovery?api=${hs.port}:${hs.token}`); -await page.getByTestId("restore-preview").waitFor({ timeout: 20000 }); -await sleep(300); -console.log(await page.getByTestId("restore-preview").innerText()); -await page.screenshot({ path: join(out, "restore-preview.png"), fullPage: true }); +const debugPort = external ? Number(process.env.EDGE_DEBUG_PORT) : await new Promise((ok, fail) => { + const p = net.createServer(); p.once("error", fail); + p.listen(0, "127.0.0.1", () => { const { port } = p.address(); p.close(() => ok(port)); }); +}); +if (!external) { + const edgeCandidates = ["C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe", + "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe"]; + const edge = edgeCandidates.find(existsSync); + if (!edge) throw new Error("Microsoft Edge was not found"); + children.push(spawn(edge, ["--headless=new", "--disable-gpu", "--no-first-run", "--no-default-browser-check", + "--remote-debugging-address=127.0.0.1", `--remote-debugging-port=${debugPort}`, + `--user-data-dir=${join(work, "edge-profile")}`, "about:blank"], { stdio: "ignore" })); +} +const debugUrl = `http://127.0.0.1:${debugPort}`; +let target; +for (let i = 0; i < 80 && !target; i++) { + try { target = await fetch(debugUrl + "/json/new?about:blank", { method: "PUT" }).then((r) => r.json()); } + catch { await sleep(250); } +} +if (!target?.webSocketDebuggerUrl) throw new Error("Edge DevTools target did not start"); +const socket = new WebSocket(target.webSocketDebuggerUrl); +await new Promise((ok, fail) => { socket.addEventListener("open", ok, { once: true }); socket.addEventListener("error", fail, { once: true }); }); +let commandId = 0; +const pending = new Map(); +socket.addEventListener("message", (event) => { + const response = JSON.parse(event.data); + if (response.id && pending.has(response.id)) { + const { resolve: done, reject } = pending.get(response.id); pending.delete(response.id); + if (response.error) reject(new Error(response.error.message)); else done(response.result); + } +}); +const cdp = (method, params = {}) => new Promise((resolve, reject) => { + const id = ++commandId; pending.set(id, { resolve, reject }); socket.send(JSON.stringify({ id, method, params })); +}); +const evaluate = async (expression) => { + const result = await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }); + if (result.exceptionDetails) throw new Error(result.exceptionDetails.text || "browser evaluation failed"); + return result.result?.value; +}; +const waitFor = async (expression, label) => { + for (let i = 0; i < 100; i++) { if (await evaluate(expression)) return; await sleep(200); } + throw new Error(`timed out waiting for ${label}`); +}; +const navigate = async (url) => { await cdp("Page.navigate", { url }); await waitFor("document.readyState === 'complete'", "page navigation"); }; +const fill = async (label, value) => evaluate(`(() => { const e = [...document.querySelectorAll('input')].find(x => x.getAttribute('aria-label') === ${JSON.stringify(label)}); if (!e) throw Error('missing input'); const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; setter.call(e, ${JSON.stringify(value)}); e.dispatchEvent(new Event('input', { bubbles: true })); e.dispatchEvent(new Event('change', { bubbles: true })); return true; })()`); +const clickText = async (text) => evaluate(`(() => { const e = [...document.querySelectorAll('button')].find(x => x.textContent.trim() === ${JSON.stringify(text)}); if (!e) throw Error('missing button: ' + ${JSON.stringify(text)}); e.click(); return true; })()`); +// Fail the capture if the page text or any visible input value shows a local path. Inputs whose label names a +// path are allowed to hold one only when they are rendered transparent (the CSS mask added before capture). +const assertNoLocalPath = async () => { + const text = await evaluate("document.body.innerText"); + const inputs = await evaluate(`[...document.querySelectorAll('input,textarea')].map(e => ({ + value: e.value || '', masked: /path/.test(e.getAttribute('aria-label') || '') && getComputedStyle(e).color === 'rgba(0, 0, 0, 0)' }))`); + const visible = [text, ...inputs.filter((i) => !i.masked).map((i) => i.value)]; + const needles = [tmpdir(), tmpdir().replace(/\\/g, "/"), dirname(original), dirname(original).replace(/\\/g, "/"), + dirname(prepared), dirname(prepared).replace(/\\/g, "/"), "AppData", "\\Users\\", "/Users/", "/home/"]; + const drive = /(^|[^A-Za-z])[A-Za-z]:[\\/]/; + for (const shown of visible) { + if (needles.some((needle) => needle && shown.includes(needle)) || drive.test(shown)) { + throw new Error("a local path is visible on the page; refusing to capture"); + } + } +}; +const screenshot = async (path) => { + await assertNoLocalPath(); + const png = await cdp("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, fromSurface: true }); + writeFileSync(path, Buffer.from(png.data, "base64")); +}; +await cdp("Page.enable"); await cdp("Runtime.enable"); +await cdp("Emulation.setDeviceMetricsOverride", { width: 1280, height: 1100, deviceScaleFactor: 1, mobile: false }); +await cdp("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: "dark" }] }); -await page.getByRole("button", { name: "Save sample checkpoint" }).click(); -await page.getByText(/Checkpoint saved/).waitFor({ timeout: 15000 }); -await sleep(400); -await page.screenshot({ path: join(out, "after-new-checkpoint.png"), fullPage: true }); +// Build a passport in the real UI, then change both inputs and check it again. +await navigate(`${UI}/passport?api=${hs.port}:${hs.token}`); +await fill("Original file path", original); +await fill("Prepared copy path", prepared); +await clickText("Build passport"); +await waitFor("!!document.querySelector('[data-testid=passport-report]')", "passport report"); +writeFileSync(prepared, Buffer.concat([readFileSync(prepared), Buffer.from("\nsynthetic mutation")])); +rmSync(original); +writeFileSync(original, "different synthetic file with the same name"); +rmSync(extra); // a tracked file that is now missing from its recorded location +await clickText("Check the files again"); +await waitFor("document.querySelector('[data-testid=chain-summary]')?.textContent.includes('no longer match what the passport recorded')", "invalidated passport summary"); +await evaluate("(() => { const s=document.createElement('style'); s.textContent='input[aria-label*=\\\"path\\\"] { color: transparent !important; }'; document.head.append(s); return true; })()"); +await screenshot(join(out, "passport-invalidated.png")); -if (mocked) { - await page.getByLabel("Configured printer host").fill("127.0.0.1"); - await page.getByRole("button", { name: "Read status" }).click(); - await page.getByTestId("monitor-summary").waitFor({ timeout: 15000 }); - console.log(await page.getByTestId("monitor-summary").innerText()); - await page.screenshot({ path: join(out, "monitoring-unverified.png"), fullPage: true }); +// Recovery preview uses the pre-mutation checkpoint and the configured non-default port. +await navigate(`${UI}/recovery?api=${hs.port}:${hs.token}`); +await waitFor("!!document.querySelector('[data-testid=restore-preview]')", "recovery preview"); +const previewText = await evaluate("document.querySelector('[data-testid=restore-preview]').innerText"); +if (!previewText.includes("changed since the checkpoint") || !previewText.includes("missing from its recorded location")) { + throw new Error(`unexpected recovery preview: ${previewText}`); +} +await fill("Configured printer host", "127.0.0.1"); +await fill("Configured printer port", String(monitorPort)); +await clickText("Read status"); +await waitFor("!!document.querySelector('[data-testid=monitor-summary]')", "monitor response"); +const monitorText = await evaluate("document.querySelector('[data-testid=monitor-summary]').innerText"); +if (!monitorText.includes("standby") || !monitorText.includes("synthetic-job.gcode")) throw new Error("configured mock port did not return monitoring data"); +await screenshot(join(out, "restore-preview.png")); +if (mockRequests.some(([method, path]) => method !== "GET" || path !== "/printer/objects/query")) { + throw new Error(`monitor sentinel observed an unapproved request: ${JSON.stringify(mockRequests)}`); } -await browser.close(); +console.log(JSON.stringify({ monitorPort, mockRequests, previewText })); +socket.close(); mock.close(); process.exit(0); diff --git a/docs/internal/screens/recovery/passport-invalidated.png b/docs/internal/screens/recovery/passport-invalidated.png new file mode 100644 index 00000000..42752a81 Binary files /dev/null and b/docs/internal/screens/recovery/passport-invalidated.png differ diff --git a/docs/internal/screens/recovery/restore-preview.png b/docs/internal/screens/recovery/restore-preview.png index 0965e18c..1e4afb75 100644 Binary files a/docs/internal/screens/recovery/restore-preview.png and b/docs/internal/screens/recovery/restore-preview.png differ