From 5f462e42bda7cd8915a2c41c0cef1d89a0e069c0 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Thu, 19 Nov 2026 13:40:01 +0100 Subject: [PATCH] Serve the build stamp at /version pnpm build now writes the short HEAD hash to web/dist/version.txt (web/stamp-version.mjs). The web server serves it at GET /version as text/plain and answers 404 when the stamp is missing, so an unstamped build never passes a live-build check. Docstring now says Astro. Co-Authored-By: Claude Opus 5.5 --- screen_locker/_web_server.py | 32 +++++++++++++++++--- screen_locker/tests/test_web_server_part2.py | 27 +++++++++++++++++ web/package.json | 2 +- web/stamp-version.mjs | 24 +++++++++++++++ 4 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 web/stamp-version.mjs diff --git a/screen_locker/_web_server.py b/screen_locker/_web_server.py index 02f6bf5..cc5efa0 100644 --- a/screen_locker/_web_server.py +++ b/screen_locker/_web_server.py @@ -1,9 +1,11 @@ """Read-only localhost HTTP server for the status web UI. -Serves the status/decision/health payloads at ``/api/*`` and the built React -bundle (``web/dist``) as static files. Binds to loopback only and never exposes -a secret: every payload comes from :mod:`screen_locker._web_payload`, which -reads state files but never the sync token or the HMAC key. +Serves the status/decision/health payloads at ``/api/*``, the built Astro +bundle (``web/dist``) as static files, and ``/version``: the short git hash the +bundle was stamped with at build time (``web/stamp-version.mjs``), or 404 when +the build carries no stamp. Binds to loopback only and never exposes a secret: +every payload comes from :mod:`screen_locker._web_payload`, which reads state +files but never the sync token or the HMAC key. Read-only by construction, like the MCP server it sits beside: there is no route that logs a workout, clears a lock, or writes anything at all. A local @@ -51,6 +53,9 @@ DEFAULT_PORT = 8770 _API_STATUS = "/api/status" _API_DECISIONS = "/api/decisions" _API_HEALTH = "/api/health" +_VERSION = "/version" +# Written by web/stamp-version.mjs after `astro build`. +_VERSION_FILE = "version.txt" # Content types that are text but not under the ``text/`` prefix. _EXTRA_TEXT_TYPES = frozenset( @@ -108,6 +113,8 @@ class _Handler(BaseHTTPRequestHandler): self._serve_json("decisions", lambda: build_decisions_payload(limit=limit)) elif split.path == _API_HEALTH: self._serve_json("health", build_health_payload) + elif split.path == _VERSION: + self._serve_version() else: self._serve_static(split.path) @@ -132,6 +139,23 @@ class _Handler(BaseHTTPRequestHandler): return self._send(HTTPStatus.OK, body, "application/json") + def _serve_version(self) -> None: + """Send the bundle's build stamp, or a 404 when it has none. + + Never the SPA fallback: a dashboard page at ``/version`` would make an + unstamped build look like a live one to a deploy check. + """ + stamp = WEB_DIST / _VERSION_FILE + if not stamp.is_file(): + logger.warning("No build stamp at %s; /version answers 404", stamp) + self._send( + HTTPStatus.NOT_FOUND, + b"Build not stamped. Run: pnpm --dir web build", + "text/plain", + ) + return + self._send(HTTPStatus.OK, stamp.read_bytes().strip(), "text/plain") + def _serve_static(self, path: str) -> None: """Serve a file from ``WEB_DIST`` with SPA fallback and traversal guard. diff --git a/screen_locker/tests/test_web_server_part2.py b/screen_locker/tests/test_web_server_part2.py index eaa459a..771d67a 100644 --- a/screen_locker/tests/test_web_server_part2.py +++ b/screen_locker/tests/test_web_server_part2.py @@ -79,3 +79,30 @@ class TestStaticServing: status, body, _ = _get(port, "/") assert status == 404 assert b"npm --prefix web run build" in body + + +class TestVersionRoute: + """/version names the deployed build, and never fakes one.""" + + @pytest.fixture(autouse=True) + def _network(self, real_loopback: None) -> None: + """Every test in this class talks to the server over real HTTP.""" + + def test_the_stamped_hash_is_served_as_plain_text(self, tmp_path: Path) -> None: + """The stamp's hash comes back trimmed, as text/plain.""" + dist = _make_dist(tmp_path) + (dist / "version.txt").write_text("abc1234\n", encoding="utf-8") + with patch(f"{_PKG}.WEB_DIST", dist), _running() as port: + status, body, ctype = _get(port, "/version") + assert status == 200 + assert body == b"abc1234" + assert ctype.startswith("text/plain") + + def test_an_unstamped_build_is_a_404_not_the_dashboard( + self, tmp_path: Path + ) -> None: + """No stamp means 404, so an unstamped build never looks live.""" + with patch(f"{_PKG}.WEB_DIST", _make_dist(tmp_path)), _running() as port: + status, body, _ = _get(port, "/version") + assert status == 404 + assert b"INDEX" not in body diff --git a/web/package.json b/web/package.json index ab5a8ef..dc782ac 100644 --- a/web/package.json +++ b/web/package.json @@ -6,7 +6,7 @@ "type": "module", "scripts": { "dev": "astro dev", - "build": "astro check && astro build", + "build": "astro check && astro build && node stamp-version.mjs", "lint": "eslint .", "typecheck": "astro check", "preview": "astro preview", diff --git a/web/stamp-version.mjs b/web/stamp-version.mjs new file mode 100644 index 0000000..974a106 --- /dev/null +++ b/web/stamp-version.mjs @@ -0,0 +1,24 @@ +// Stamp the built bundle with the commit it was built from. +// +// Runs after `astro build` and writes `git rev-parse --short HEAD` to +// dist/version.txt. The Python server serves that file at /version, so a live +// check can compare the running build against HEAD; with no stamp it answers +// 404, so a build that skipped this step can never pass for live. +import { execFileSync } from 'node:child_process' +import { existsSync, writeFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +const dist = fileURLToPath(new URL('./dist/', import.meta.url)) +if (!existsSync(dist)) { + // Fail loudly: a stamp with no bundle beside it would name a build that + // does not exist. + throw new Error(`stamp-version: ${dist} is missing; run astro build first`) +} + +// execFileSync throws (non-zero exit) when git fails, which fails the build. +const hash = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { + cwd: fileURLToPath(new URL('.', import.meta.url)), + encoding: 'utf8', +}).trim() +writeFileSync(`${dist}version.txt`, `${hash}\n`) +console.log(`stamp-version: dist/version.txt = ${hash}`)