Add icon word ledger and API

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq
This commit is contained in:
Krzysztof Rudnicki 2026-11-16 10:07:38 +01:00
parent 5990b46f5d
commit 79478225be
12 changed files with 941 additions and 10 deletions

View File

@ -243,3 +243,14 @@ hard-codes it.
to anything pytest did not spawn and Steam/kill argv in real `Popen`,
and fails any test that hits it (a stale demo test once killed the
live game).
## Icon words (`/api/icon-words`)
`GET /api/icon-words` → `IconLedger`; `POST` or `PUT /api/icon-words/{icon_id}` with `{word?, glyph?}` → `IconLedger` (200). Writes need Host, Origin and `X-SBE-Token` like every non-GET. TS mirror: `web/src/api/iconWordsContract.ts`.
- **Ledger** `web/src/ui/icon_words.json` (a repo file the user commits; `SBE_ICON_WORDS` overrides the path): `{"version":1,"icons":{"<id>":{"word":"<text>"|null,"glyph":"<emoji>"|null}}}`. Absent id = unanswered; no `word` key = only a glyph chosen; `word: null` = skipped (no label); `glyph: null` = default. The server reads it per request and never builds from it (`_web_build` ignores it); writes go to a sibling temp file, then rename.
- **Registry** `web/src/icons/registry.json`: id → default glyph, spoken name, description, 3 suggested words, 3 alternative glyphs (`registry.ts` types it).
- **`word`**: any text; casing kept, whitespace runs collapsed; 1–40 characters, no control characters, else `invalid_params`. `null` skips. **`glyph`**: the default or one of the icon's 3 alternatives (the default is stored as `null`), else `invalid_params`. Unknown id → `not_found`; empty body or unknown key → `invalid_params`.
- Every served `.html` page carries the ledger as `<script type="application/json" id="sbe-icon-words">` (`<` escaped), so a pick shows on the next page load.
- **Corrupt ledger** (bad JSON or schema): copied to `<ledger>.corrupt` (an older copy is never overwritten) and left in place; every read and write answers `op_failed` (500) naming the copy until someone fixes it. Pages then carry that error body and draw no words.
- UI: a word is drawn right of its icon in sentence case (`web/src/icons/textCase.ts` holds the acronym list); the `/words` picker (palette → Icon words) sets words and glyphs; `localStorage["sbe-icon-words-hidden"] = "1"` hides all words.

View File

@ -0,0 +1,139 @@
"""The icon-word ledger file: the words (and glyph swaps) the user picked.
``{"version": 1, "icons": {"<icon id>": {"word": "<text>" | null,
"glyph": "<emoji>" | null}}}``. An absent id is unanswered; an entry without
a ``word`` key has a glyph choice but no word decision yet; ``word: null``
is a skip (no label); ``glyph: null`` keeps the registry's default.
It lives in the repo (``web/src/ui/icon_words.json``, committed by the user)
and is read by the web server at runtime, never by the build: a pick shows
on the next page load. ``SBE_ICON_WORDS`` points a scratch server at a copy.
Writes go to a sibling temp file and are renamed over the ledger, so a crash
mid-write leaves the previous file whole. A file that does not parse or does
not match the schema is copied aside as ``.corrupt`` (never over an older
copy) and every read fails loudly until someone fixes it: dropping it and
starting empty would silently lose the user's picks.
"""
from __future__ import annotations
import contextlib
import json
import os
from pathlib import Path
import tempfile
import time
from typing import Any, Final
LEDGER_ENV: Final = "SBE_ICON_WORDS"
LEDGER_NAME: Final = "icon_words.json"
DEFAULT_LEDGER: Final = (
Path(__file__).resolve().parent.parent / "web" / "src" / "ui" / LEDGER_NAME
)
VERSION: Final = 1
# A repo file: world-readable like its neighbours (mkstemp would make it 0600).
FILE_MODE: Final = 0o644
_ENTRY_KEYS: Final = frozenset({"word", "glyph"})
type Ledger = dict[str, Any]
class LedgerCorruptError(Exception):
"""The ledger does not parse; *kept* holds the copy set aside."""
def __init__(self, path: Path, kept: Path, why: str) -> None:
"""Name the broken file, its kept copy and what is wrong with it."""
super().__init__(
f"The icon-word ledger {path} is unreadable ({why}); a copy was kept "
f"as {kept}. Fix or restore it (git checkout) to use icon words."
)
self.path = path
self.kept = kept
def ledger_path() -> Path:
"""The ledger this process reads: ``$SBE_ICON_WORDS`` or the repo file."""
override = os.environ.get(LEDGER_ENV)
return Path(override) if override else DEFAULT_LEDGER
def is_ledger_file(path: Path) -> bool:
"""True for a ledger, its temp files and its corrupt copies (runtime data)."""
name = path.name.lstrip(".")
return name == LEDGER_NAME or name.startswith(f"{LEDGER_NAME}.")
def empty_ledger() -> Ledger:
"""A ledger with nothing answered."""
return {"version": VERSION, "icons": {}}
def _schema_problem(data: object) -> str | None:
"""Why *data* is not a ledger, or None when it is one."""
if not isinstance(data, dict) or set(data) != {"version", "icons"}:
return "not a {version, icons} object"
if data["version"] != VERSION:
return f"version {data['version']!r} is not {VERSION}"
if not isinstance(data["icons"], dict):
return "icons is not an object"
for icon, entry in data["icons"].items():
if not isinstance(entry, dict) or not set(entry) <= _ENTRY_KEYS:
return f"entry {icon!r} is not a {{word, glyph}} object"
for key, value in entry.items():
if value is not None and not isinstance(value, str):
return f"{icon}.{key} is neither text nor null"
return None
def _keep_aside(path: Path, raw: bytes) -> Path:
"""Copy *raw* next to *path* as ``.corrupt``; never overwrite an older copy."""
kept = path.with_name(f"{path.name}.corrupt")
if kept.exists():
if kept.read_bytes() == raw:
return kept
kept = path.with_name(f"{path.name}.corrupt.{time.time_ns()}")
kept.write_bytes(raw)
return kept
def load_ledger(path: Path) -> Ledger:
"""Read the ledger at *path*; a missing file is an empty ledger.
Raises:
LedgerCorruptError: the file does not parse or match the schema
(it is kept aside first, and left in place).
"""
try:
raw = path.read_bytes()
except FileNotFoundError:
return empty_ledger()
try:
data = json.loads(raw)
except ValueError as exc:
raise LedgerCorruptError(path, _keep_aside(path, raw), str(exc)) from None
why = _schema_problem(data)
if why is not None:
raise LedgerCorruptError(path, _keep_aside(path, raw), why)
return data
def save_ledger(path: Path, ledger: Ledger) -> None:
"""Write *ledger* atomically: sibling temp file, fsync, rename over *path*.
Sorted keys and a trailing newline keep the user's commits diffable.
"""
text = json.dumps(ledger, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as out:
out.write(text)
out.flush()
os.fsync(out.fileno())
Path(tmp).chmod(FILE_MODE)
Path(tmp).replace(path)
except BaseException:
with contextlib.suppress(FileNotFoundError):
Path(tmp).unlink()
raise

View File

@ -13,6 +13,7 @@ from pathlib import Path
import shutil
import subprocess
from steam_backlog_enforcer._icon_ledger import is_ledger_file
from steam_backlog_enforcer.game_install import _echo
WEB_DIR = (Path(__file__).resolve().parent.parent / "web").resolve()
@ -61,7 +62,13 @@ def frontend_is_stale() -> bool:
sources = list(_SOURCE_FILES)
for source_dir in _SOURCE_DIRS:
if source_dir.is_dir():
sources.extend(path for path in source_dir.rglob("*") if path.is_file())
sources.extend(
path
for path in source_dir.rglob("*")
# The icon-word ledger lives in src/ but the server reads it per
# page; counting it would rebuild on every pick.
if path.is_file() and not is_ledger_file(path)
)
return any(_mtime(path) > built for path in sources)

View File

@ -0,0 +1,168 @@
"""``/api/icon-words``: the words the user puts next to the UI's icons.
The UI is text-free except for these: every icon has a registry entry
(``web/src/icons/registry.json``: default glyph, 3 suggested words, 3
alternative glyphs) and the user picks a word and optionally a glyph for each
on the ``/words`` page. Picks land in the ledger (:mod:`._icon_ledger`) and
every served page carries the ledger as a JSON ``<script>``, so a pick shows
on the next page load without a rebuild.
Manual words are always accepted, whatever they say: casing is kept,
whitespace runs collapse to one space, and only empty, over-40-character or
control-character text is refused. A glyph must be the icon's default or one
of its three registered alternatives.
"""
from __future__ import annotations
from http import HTTPStatus
import json
import logging
from pathlib import Path
import re
import threading
from typing import TYPE_CHECKING, Any, Final
from steam_backlog_enforcer import _icon_ledger
from steam_backlog_enforcer._web_errors import ApiError, not_found
from steam_backlog_enforcer._web_io import Reply, ok
if TYPE_CHECKING:
from steam_backlog_enforcer._web_io import Request
logger = logging.getLogger(__name__)
REGISTRY_FILE: Final = (
Path(__file__).resolve().parent.parent / "web" / "src" / "icons" / "registry.json"
)
# The <script id> the UI reads at boot (ICON_WORDS_SCRIPT in iconWordsContract.ts).
SCRIPT_ID: Final = "sbe-icon-words"
MAX_WORD: Final = 40
# The same classes as web/src/icons/wordRules.ts, spelled out so Python's
# wider ``\s`` (it counts \x1c-\x1f as space) cannot make the two disagree.
_SPACE: Final = re.compile(r"[\t\n\v\f\r \u00a0\u2000-\u200a\u2028\u2029\u202f\u3000]+")
_CONTROL: Final = re.compile(r"[\x00-\x1f\x7f-\x9f]")
_HEAD_TAG: Final = re.compile(rb"<head[^>]*>", re.IGNORECASE)
_BODY_KEYS: Final = frozenset({"word", "glyph"})
# One writer at a time: the server is threaded and a save is read-modify-write.
_WRITE_LOCK = threading.Lock()
def _failed(message: str) -> ApiError:
"""A loud 500: the ledger or registry cannot be used as it is."""
return ApiError(message, code="op_failed", status=HTTPStatus.INTERNAL_SERVER_ERROR)
def _load() -> _icon_ledger.Ledger:
"""The current ledger; a corrupt one is logged and refused."""
try:
return _icon_ledger.load_ledger(_icon_ledger.ledger_path())
except _icon_ledger.LedgerCorruptError as exc:
failure = exc
# Logged outside the handler: the message is the whole story, no traceback.
logger.error("%s", failure)
raise _failed(str(failure))
def load_registry() -> dict[str, dict[str, Any]]:
"""Every registered icon by id (its default glyph and alternatives)."""
try:
return json.loads(REGISTRY_FILE.read_text("utf-8"))["icons"]
except (OSError, ValueError, KeyError, TypeError) as exc:
msg = f"The icon registry {REGISTRY_FILE} is unreadable: {exc}."
raise _failed(msg) from None
def normalize_word(raw: object) -> str:
"""The word to store for *raw*: collapsed whitespace, casing kept.
Raises:
ApiError: ``invalid_params`` for non-text, empty, over-long or
control-character input.
"""
if not isinstance(raw, str):
msg = "word must be text, or null to skip."
raise ApiError(msg, code="invalid_params")
word = _SPACE.sub(" ", raw).strip()
if not word:
msg = "word is empty; send null to skip this icon instead."
raise ApiError(msg, code="invalid_params")
if len(word) > MAX_WORD:
msg = f"word is {len(word)} characters; at most {MAX_WORD} fit next to an icon."
raise ApiError(msg, code="invalid_params")
if _CONTROL.search(word):
msg = "word holds a control character."
raise ApiError(msg, code="invalid_params")
return word
def _glyph(raw: object, entry: dict[str, Any]) -> str | None:
"""The glyph to store: null for the default, else a registered alternative.
Raises:
ApiError: ``invalid_params`` for anything else.
"""
if raw is None or raw == entry["glyph"]:
return None
if isinstance(raw, str) and raw in entry["alts"]:
return raw
allowed = " ".join(entry["alts"])
msg = f"glyph must be the default {entry['glyph']} or one of {allowed}."
raise ApiError(msg, code="invalid_params")
def _update(body: dict[str, Any], entry: dict[str, Any]) -> dict[str, Any]:
"""The validated changes in *body* (``word`` and/or ``glyph``)."""
unknown = set(body) - _BODY_KEYS
if unknown or not body:
msg = (
"Send word (text, or null to skip) and/or glyph (an alternative, or null)."
)
raise ApiError(msg, code="invalid_params")
out: dict[str, Any] = {}
if "word" in body:
out["word"] = None if body["word"] is None else normalize_word(body["word"])
if "glyph" in body:
out["glyph"] = _glyph(body["glyph"], entry)
return out
def icon_words_view(_request: Request) -> Reply:
"""``GET /api/icon-words`` — the whole ledger."""
return ok(_load())
def set_icon_word_view(request: Request) -> Reply:
"""``POST|PUT /api/icon-words/{icon}`` — save a word, skip or glyph."""
(icon,) = request.args
entry = load_registry().get(icon)
if entry is None:
msg = f"No icon {icon!r} is registered."
raise not_found(msg)
changes = _update(request.body, entry)
with _WRITE_LOCK:
ledger = _load()
saved = ledger["icons"].setdefault(icon, {})
saved.update(changes)
saved.setdefault("glyph", None)
_icon_ledger.save_ledger(_icon_ledger.ledger_path(), ledger)
return ok(ledger)
def inject_icon_words(html: bytes) -> bytes:
"""Insert the ledger as ``<script type="application/json">`` after ``<head>``.
A corrupt ledger never breaks the page: the script then carries the
error body, which the UI reports. ``<`` is escaped, so no word can close
the script element early.
"""
try:
payload: object = _load()
except ApiError as exc:
payload = exc.body()
text = json.dumps(payload, ensure_ascii=False).replace("<", "\\u003c")
tag = f'<script type="application/json" id="{SCRIPT_ID}">{text}</script>'.encode()
match = _HEAD_TAG.search(html)
if match is None:
return tag + html
return html[: match.end()] + tag + html[match.end() :]

View File

@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Final
from steam_backlog_enforcer import (
_web_art,
_web_daemon,
_web_icon_words,
_web_jobs,
_web_library,
_web_process,
@ -29,6 +30,8 @@ if TYPE_CHECKING:
type Route = Callable[[Request], Reply]
_ID = r"([0-9A-Za-z_-]{1,64})"
# Icon ids are dotted (``job.state.waiting_input``); the registry re-checks them.
_ICON = r"([a-z][a-z0-9_.-]{0,63})"
# Matched before the table by the server: it streams instead of replying.
EVENTS_PATH: Final = re.compile(rf"^/api/jobs/{_ID}/events$")
@ -43,8 +46,9 @@ class _Entry:
def _r(method: str, path: str, route: Route) -> _Entry:
"""Build an entry; ``{id}`` in *path* captures one id segment."""
return _Entry(method, re.compile("^" + path.replace("{id}", _ID) + "$"), route)
"""Build an entry; ``{id}`` / ``{icon}`` in *path* capture one segment."""
pattern = path.replace("{id}", _ID).replace("{icon}", _ICON)
return _Entry(method, re.compile("^" + pattern + "$"), route)
ROUTES: Final[tuple[_Entry, ...]] = (
@ -71,6 +75,9 @@ ROUTES: Final[tuple[_Entry, ...]] = (
_r("POST", "/api/pending/{id}/heartbeat", _web_daemon.heartbeat_view),
_r("POST", "/api/pending/{id}/commit", _web_daemon.commit_view),
_r("DELETE", "/api/pending/{id}", _web_daemon.cancel_pending_view),
_r("GET", "/api/icon-words", _web_icon_words.icon_words_view),
_r("POST", "/api/icon-words/{icon}", _web_icon_words.set_icon_word_view),
_r("PUT", "/api/icon-words/{icon}", _web_icon_words.set_icon_word_view),
)

View File

@ -5,7 +5,7 @@ DNS-rebinding guard, :mod:`._web_auth`), fails closed on stale code
(:mod:`._serve_stale`), checks ``Origin`` and the per-launch token on
anything that is not a GET (and on the SSE stream), then hands off to a
route from :mod:`._web_routes`, the SSE streamer (:mod:`._web_sse`) or the
static bundle (``web/dist``, with the token injected into every ``.html`` page).
static bundle (``web/dist``; ``.html`` pages get the token and icon words).
Binds to loopback only; never serves secrets and never sends CORS headers.
In development the Vite dev server proxies ``/api`` here; in production the
@ -21,7 +21,7 @@ import mimetypes
from pathlib import Path
from urllib.parse import parse_qs, urlsplit
from steam_backlog_enforcer import _web_auth, _web_process
from steam_backlog_enforcer import _web_auth, _web_icon_words, _web_process
from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS
from steam_backlog_enforcer._serve_stale import outdated_source
from steam_backlog_enforcer._web_errors import ApiError, not_found
@ -88,6 +88,10 @@ class _Handler(BaseHTTPRequestHandler):
"""Handle a DELETE."""
self._handle("DELETE")
def do_PUT(self) -> None:
"""Handle a PUT (``/api/icon-words/{icon}`` takes PUT or POST)."""
self._handle("PUT")
def _handle(self, method: str) -> None:
"""Run the checks, then dispatch; every refusal is a JSON error."""
split = urlsplit(self.path)
@ -184,9 +188,9 @@ class _Handler(BaseHTTPRequestHandler):
body = candidate.read_bytes()
headers: dict[str, str] = {}
if candidate.suffix == ".html":
# Carries this launch's token: never cache it.
body = _web_auth.inject_token(body, self.server.token)
headers["Cache-Control"] = "no-store"
body = _web_icon_words.inject_icon_words(body)
headers["Cache-Control"] = "no-store" # carries token + icon words
send_bytes(self, status, body, ctype, headers)

View File

@ -0,0 +1,23 @@
"""A two-icon registry the icon-word tests use instead of the real one."""
from __future__ import annotations
REGISTRY: dict[str, object] = {
"version": 1,
"icons": {
"nav.dashboard": {
"glyph": "🏠",
"spoken": "Dashboard",
"desc": "d",
"words": ["home", "dashboard", "overview"],
"alts": ["🏡", "🧭", "📟"],
},
"cmd.done": {
"glyph": "🏆",
"spoken": "Done",
"desc": "d",
"words": ["done", "finished", "next"],
"alts": ["🥇", "🎉", "🏁"],
},
},
}

View File

@ -1,9 +1,9 @@
"""Autouse isolation of the control plane and the HLTB endpoint memo.
Redirects the web cover-art caches, the daemon control socket, restart
markers, backups and web job store (all under ``/var/lib``, ``/run`` or the
real ``~/.local/state``) into ``tmp_path``, and forgets the remembered HLTB
search URL around every test.
markers, backups, web job store (all under ``/var/lib``, ``/run`` or the
real ``~/.local/state``) and the repo's icon-word ledger into
``tmp_path``, and forgets the remembered HLTB search URL around every test.
Split out of ``conftest.py`` to keep every file inside the 250-line cap;
``conftest`` imports the fixtures by name, which is what registers them.
@ -18,6 +18,7 @@ import pytest
from steam_backlog_enforcer._hltb_failures import reset_failures
from steam_backlog_enforcer._hltb_search_api import forget_hltb_search_url
from steam_backlog_enforcer._icon_ledger import LEDGER_ENV
if TYPE_CHECKING:
from collections.abc import Iterator
@ -38,6 +39,8 @@ def _isolate_control_plane(
"""
state = tmp_path / "ctl_state"
monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path / "xdg_runtime"))
# The icon-word ledger is a committed repo file: never write the real one.
monkeypatch.setenv(LEDGER_ENV, str(tmp_path / "icon_words.json"))
with (
patch("steam_backlog_enforcer._ctl_gap.RESTART_EXIT_FILE", state / "exit.json"),
patch(

View File

@ -0,0 +1,180 @@
"""Tests for _icon_ledger: the icon-word ledger file (load, atomic save, corrupt)."""
from __future__ import annotations
import json
import os
from pathlib import Path
import stat
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _icon_ledger as mod
_GOOD = {
"version": 1,
"icons": {
"nav.dashboard": {"word": "Home", "glyph": None},
"cmd.done": {"word": None, "glyph": "🥇"},
"cmd.scan": {"glyph": "📡"},
},
}
@pytest.fixture(name="home")
def fixture_home(tmp_path: Path) -> Path:
"""An empty directory of its own (conftest fixtures also use tmp_path)."""
path = tmp_path / "ledger_home"
path.mkdir()
return path
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
class TestPath:
"""Where the ledger lives."""
def test_default_is_the_repo_file(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""Without the env override the ledger is web/src/ui/icon_words.json."""
monkeypatch.delenv(mod.LEDGER_ENV, raising=False)
repo = Path(mod.__file__).resolve().parent.parent
assert repo / "web" / "src" / "ui" / "icon_words.json" == mod.DEFAULT_LEDGER
assert mod.ledger_path() == mod.DEFAULT_LEDGER
def test_env_override_wins(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""SBE_ICON_WORDS points the server at another file (scratch copies)."""
monkeypatch.setenv(mod.LEDGER_ENV, str(tmp_path / "copy.json"))
assert mod.ledger_path() == tmp_path / "copy.json"
def test_tests_never_see_the_repo_file(self) -> None:
"""The autouse isolation redirects the ledger into tmp_path."""
assert mod.ledger_path() != mod.DEFAULT_LEDGER
@pytest.mark.parametrize(
("name", "expected"),
[
("icon_words.json", True),
("icon_words.json.corrupt", True),
(".icon_words.json.x1y2.tmp", True),
("icon_words.ts", False),
("registry.json", False),
],
)
def test_is_ledger_file(self, name: str, *, expected: bool) -> None:
"""The ledger, its temp files and corrupt copies are runtime data."""
assert mod.is_ledger_file(Path("/x") / name) is expected
class TestLoad:
"""load_ledger: missing, valid and corrupt files."""
def test_missing_file_is_an_empty_ledger(self, home: Path) -> None:
"""No file yet means nothing answered."""
assert mod.load_ledger(home / "none.json") == {"version": 1, "icons": {}}
def test_valid_file_round_trips(self, home: Path) -> None:
"""A valid file loads as written, a missing word key included."""
path = home / "l.json"
_write(path, json.dumps(_GOOD))
assert mod.load_ledger(path) == _GOOD
@pytest.mark.parametrize(
"text",
[
"{not json",
"[]",
'{"version": 2, "icons": {}}',
'{"version": 1, "icons": []}',
'{"version": 1, "icons": {"a.b": "word"}}',
'{"version": 1, "icons": {"a.b": {"word": 5}}}',
'{"version": 1, "icons": {"a.b": {"glyph": ["x"]}}}',
'{"version": 1, "icons": {"a.b": {"word": "x", "extra": 1}}}',
],
)
def test_corrupt_file_is_kept_aside_and_fails_loudly(
self, home: Path, text: str
) -> None:
"""Bad JSON or schema: copied to .corrupt, original untouched, raises."""
path = home / "l.json"
_write(path, text)
with pytest.raises(mod.LedgerCorruptError) as err:
mod.load_ledger(path)
kept = home / "l.json.corrupt"
assert err.value.kept == kept
assert kept.read_text("utf-8") == text
assert path.read_text("utf-8") == text
assert str(kept) in str(err.value)
def test_same_corrupt_bytes_are_kept_once(self, home: Path) -> None:
"""Re-reading the same broken file does not pile up copies."""
path = home / "l.json"
_write(path, "{bad")
for _ in range(2):
with pytest.raises(mod.LedgerCorruptError):
mod.load_ledger(path)
assert sorted(p.name for p in home.iterdir()) == [
"l.json",
"l.json.corrupt",
]
def test_older_corrupt_copy_is_never_overwritten(self, home: Path) -> None:
"""A different broken file gets its own copy; the first one survives."""
path = home / "l.json"
_write(home / "l.json.corrupt", "{first")
_write(path, "{second")
with pytest.raises(mod.LedgerCorruptError) as err:
mod.load_ledger(path)
assert (home / "l.json.corrupt").read_text("utf-8") == "{first"
assert err.value.kept.name.startswith("l.json.corrupt.")
assert err.value.kept.read_text("utf-8") == "{second"
class TestSave:
"""save_ledger: atomic, stable, readable."""
def test_writes_sorted_indented_json_with_newline(self, home: Path) -> None:
"""Stable output so the user's commits diff cleanly; emoji kept raw."""
path = home / "l.json"
mod.save_ledger(path, _GOOD)
text = path.read_text("utf-8")
assert text.endswith("}\n")
assert "🥇" in text
assert json.loads(text) == _GOOD
assert text.index('"cmd.done"') < text.index('"nav.dashboard"')
assert stat.S_IMODE(path.stat().st_mode) == mod.FILE_MODE
def test_replace_failure_leaves_the_old_file_and_no_temp(self, home: Path) -> None:
"""A failed rename keeps the previous ledger intact and cleans up."""
path = home / "l.json"
_write(path, json.dumps({"version": 1, "icons": {}}))
with (
patch.object(mod.os, "replace", side_effect=OSError("disk")),
pytest.raises(OSError, match="disk"),
):
mod.save_ledger(path, _GOOD)
assert json.loads(path.read_text("utf-8")) == {"version": 1, "icons": {}}
assert [p.name for p in home.iterdir()] == ["l.json"]
def test_goes_through_a_temp_file_in_the_same_dir(self, home: Path) -> None:
"""The new content lands by rename from a sibling temp file."""
path = home / mod.LEDGER_NAME
seen: list[tuple[str, str]] = []
real = os.replace
def spy(src: str, dst: str) -> None:
seen.append((src, dst))
real(src, dst)
with patch.object(mod.os, "replace", side_effect=spy):
mod.save_ledger(path, _GOOD)
assert len(seen) == 1
src, dst = seen[0]
assert Path(dst) == path
assert Path(src).parent == home
assert mod.is_ledger_file(Path(src))

View File

@ -108,6 +108,22 @@ class TestFrontendIsStale:
_touch(web / "dist" / "index.html", 2000.0)
assert _web_build.frontend_is_stale() is False
def test_icon_word_ledger_is_runtime_data_not_a_build_input(
self, web: Path
) -> None:
# The server reads the ledger per page; a pick must not make the
# next `serve` rebuild (a unit without pnpm on PATH would crash-loop).
"""The ledger, its temp files and corrupt copies never mark dist stale."""
_touch(web / "src" / "app.tsx", 1000.0)
_touch(web / "dist" / "index.html", 2000.0)
for name in (
"icon_words.json",
".icon_words.json.ab.tmp",
"icon_words.json.corrupt",
):
_touch(web / "src" / "ui" / name, 3000.0)
assert _web_build.frontend_is_stale() is False
def test_directories_in_src_are_skipped(self, web: Path) -> None:
# A directory's own mtime bumps whenever a file inside it is added or
# removed, so counting it would report staleness after a build.

View File

@ -0,0 +1,212 @@
"""Tests for _web_icon_words: the icon-word endpoints and the page injection."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _icon_ledger, _web_icon_words, _web_routes
from steam_backlog_enforcer._web_errors import ApiError
from steam_backlog_enforcer.tests._icon_registry import REGISTRY
from steam_backlog_enforcer.tests._web_request import make_request, payload_of
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
@pytest.fixture(autouse=True, name="registry")
def fixture_registry(tmp_path: Path) -> Iterator[Path]:
"""A two-icon registry instead of the real one."""
path = tmp_path / "registry.json"
path.write_text(json.dumps(REGISTRY), encoding="utf-8")
with patch.object(_web_icon_words, "REGISTRY_FILE", path):
yield path
def _set(icon: str, **body: object) -> dict[str, object]:
reply = _web_icon_words.set_icon_word_view(
make_request(icon, body=body, method="POST")
)
return payload_of(reply)
def _stored() -> dict[str, dict[str, object]]:
return json.loads(_icon_ledger.ledger_path().read_text("utf-8"))["icons"]
def _refused(icon: str, code: str, **body: object) -> ApiError:
with pytest.raises(ApiError) as err:
_set(icon, **body)
assert err.value.code == code
return err.value
class TestWords:
"""POST /api/icon-words/<id> with a word."""
def test_suggestion_is_saved_and_the_ledger_returned(self) -> None:
"""A picked word is stored and the whole ledger comes back."""
out = _set("nav.dashboard", word="home")
assert out == {
"version": 1,
"icons": {"nav.dashboard": {"word": "home", "glyph": None}},
}
assert _stored() == {"nav.dashboard": {"word": "home", "glyph": None}}
def test_manual_multi_word_keeps_casing_and_collapses_spaces(self) -> None:
"""Any words are accepted; whitespace runs become one space."""
_set("cmd.done", word=" I got\tan HLTB\n win ")
assert _stored()["cmd.done"] == {"word": "I got an HLTB win", "glyph": None}
def test_forty_characters_is_the_limit(self) -> None:
"""40 characters pass; 41 are refused."""
_set("cmd.done", word="x" * 40)
_refused("cmd.done", "invalid_params", word="x" * 41)
assert _stored()["cmd.done"]["word"] == "x" * 40
@pytest.mark.parametrize(
"word", ["", " ", "bad\x00word", "esc\x1b", "del\x7f", 5, ["a"]]
)
def test_bad_words_are_refused(self, word: object) -> None:
"""Empty, control characters and non-strings are invalid_params (400)."""
err = _refused("cmd.done", "invalid_params", word=word)
assert err.status == 400
assert not _icon_ledger.ledger_path().exists()
def test_skip_stores_null(self) -> None:
"""word: null means skipped (no label), and counts as answered."""
_set("cmd.done", word=None)
assert _stored()["cmd.done"] == {"word": None, "glyph": None}
class TestGlyphs:
"""POST /api/icon-words/<id> with a glyph."""
def test_alternative_is_saved_without_answering_the_word(self) -> None:
"""A glyph alone leaves the word unanswered (no word key)."""
_set("cmd.done", glyph="🎉")
assert _stored()["cmd.done"] == {"glyph": "🎉"}
def test_word_survives_a_later_glyph_choice(self) -> None:
"""Word and glyph are independent."""
_set("cmd.done", word="won")
_set("cmd.done", glyph="🏁")
assert _stored()["cmd.done"] == {"word": "won", "glyph": "🏁"}
@pytest.mark.parametrize("glyph", ["🏆", None])
def test_default_or_null_resets_to_default(self, glyph: object) -> None:
"""Choosing the default glyph is stored as null (keep default)."""
_set("cmd.done", glyph="🎉")
_set("cmd.done", glyph=glyph)
assert _stored()["cmd.done"] == {"glyph": None}
@pytest.mark.parametrize("glyph", ["🍕", "🏡", "", 3])
def test_unregistered_glyph_is_refused(self, glyph: object) -> None:
"""Only the default or this icon's own 3 alternatives are accepted."""
_refused("cmd.done", "invalid_params", glyph=glyph)
class TestRequestShape:
"""Unknown ids, empty and unknown bodies."""
def test_unknown_id_is_not_found(self) -> None:
"""An id the registry lacks is a 404."""
assert _refused("cmd.nope", "not_found", word="x").status == 404
def test_empty_body_is_refused(self) -> None:
"""Neither word nor glyph: nothing to save."""
_refused("cmd.done", "invalid_params")
def test_unknown_key_is_refused(self) -> None:
"""A typo'd key is never silently ignored."""
_refused("cmd.done", "invalid_params", word="x", colour="red")
def test_missing_registry_fails_loudly(self, registry: Path) -> None:
"""Without the registry no glyph or id can be checked: op_failed."""
registry.unlink()
assert _refused("cmd.done", "op_failed", word="x").status == 500
class TestCorruptLedger:
"""A corrupt ledger is kept aside, reads and writes fail loudly."""
def test_get_and_post_fail_and_the_file_is_untouched(self) -> None:
"""Nothing is overwritten while the ledger does not parse."""
path = _icon_ledger.ledger_path()
path.write_text("{broken", encoding="utf-8")
with pytest.raises(ApiError) as err:
_web_icon_words.icon_words_view(make_request())
assert (err.value.code, err.value.status) == ("op_failed", 500)
assert ".corrupt" in err.value.message
_refused("cmd.done", "op_failed", word="x")
assert path.read_text("utf-8") == "{broken"
assert path.with_name(path.name + ".corrupt").read_text("utf-8") == "{broken"
class TestGetAndInject:
"""GET /api/icon-words and the ledger carried by every served page."""
def test_get_returns_the_ledger(self) -> None:
"""GET serves the stored ledger, ids the registry lacks included."""
ledger = {"version": 1, "icons": {"old.id": {"word": "kept", "glyph": None}}}
_icon_ledger.save_ledger(_icon_ledger.ledger_path(), ledger)
assert payload_of(_web_icon_words.icon_words_view(make_request())) == ledger
def test_page_carries_the_ledger_with_script_breakouts_escaped(self) -> None:
"""Words are free text: '<' is escaped so a word cannot close the script."""
_set("cmd.done", word="</script><b>x")
html = _web_icon_words.inject_icon_words(
b"<html><head><title>t</title></head></html>"
)
text = html.decode("utf-8")
start = text.index(
f'<script type="application/json" id="{_web_icon_words.SCRIPT_ID}">'
)
assert start < text.index("<title>")
body = text[start:].split(">", 1)[1].split("</script>", 1)[0]
assert "<" not in body
assert json.loads(body)["icons"]["cmd.done"]["word"] == "</script><b>x"
def test_page_carries_the_error_when_corrupt(self) -> None:
"""A corrupt ledger never breaks the page: it carries the error instead."""
_icon_ledger.ledger_path().write_text("{broken", encoding="utf-8")
html = _web_icon_words.inject_icon_words(b"<head></head>").decode("utf-8")
body = html.split('">', 1)[1].split("</script>", 1)[0]
assert json.loads(body)["error"] == "op_failed"
def test_page_without_head_gets_the_script_first(self) -> None:
"""A fragment without <head> still carries the ledger."""
html = _web_icon_words.inject_icon_words(b"<p>x</p>").decode("utf-8")
assert html.startswith(
f'<script type="application/json" id="{_web_icon_words.SCRIPT_ID}">'
)
assert html.endswith("<p>x</p>")
class TestRoutes:
"""The route table knows both endpoints; ids may contain dots."""
def test_get_route(self) -> None:
"""GET /api/icon-words is the ledger view."""
assert _web_routes.resolve("GET", "/api/icon-words") == (
_web_icon_words.icon_words_view,
(),
)
@pytest.mark.parametrize("method", ["POST", "PUT"])
def test_set_route_captures_a_dotted_id(self, method: str) -> None:
"""POST and PUT /api/icon-words/job.state.waiting_input capture the id."""
found = _web_routes.resolve(method, "/api/icon-words/job.state.waiting_input")
assert found == (
_web_icon_words.set_icon_word_view,
("job.state.waiting_input",),
)
@pytest.mark.parametrize("path", ["/api/icon-words/a b", "/api/icon-words/../x"])
def test_malformed_ids_do_not_route(self, path: str) -> None:
"""Spaces or path tricks never reach the view."""
assert _web_routes.resolve("POST", path) is None

View File

@ -0,0 +1,161 @@
"""The icon-word endpoints over real HTTP: auth rules and the served page."""
from __future__ import annotations
from http.client import HTTPConnection
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _icon_ledger, _web_icon_words, _web_server
from steam_backlog_enforcer.tests._icon_registry import REGISTRY
from steam_backlog_enforcer.tests._web_process_state import (
clean_process_state,
running_server,
)
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
@pytest.fixture(autouse=True)
def _clean_process_state() -> Iterator[None]:
"""Never "stale": other edits to the tree must not leak in."""
yield from clean_process_state()
@pytest.fixture(name="server")
def fixture_server(tmp_path: Path) -> Iterator[_web_server.WebServer]:
"""A live server on an ephemeral port with a one-page bundle."""
dist = (tmp_path / "dist").resolve()
dist.mkdir()
(dist / "index.html").write_text("<html><head></head>X</html>", "utf-8")
registry = tmp_path / "registry.json"
registry.write_text(json.dumps(REGISTRY), "utf-8")
with (
patch.object(_web_server, "WEB_DIST", dist),
patch.object(_web_icon_words, "REGISTRY_FILE", registry),
running_server() as server,
):
yield server
def _call(
server: _web_server.WebServer,
method: str,
path: str,
body: object = None,
headers: dict[str, str] | None = None,
) -> tuple[int, dict[str, object] | str]:
host = f"127.0.0.1:{server.port}"
sent = {"Host": host, **(headers or {})}
data = None
if body is not None:
data = json.dumps(body).encode()
sent["Content-Type"] = "application/json"
conn = HTTPConnection("127.0.0.1", server.port, timeout=5)
try:
conn.request(method, path, body=data, headers=sent)
resp = conn.getresponse()
raw = resp.read().decode("utf-8")
ctype = resp.headers.get("Content-Type", "")
return resp.status, json.loads(raw) if "json" in ctype else raw
finally:
conn.close()
def _authed(server: _web_server.WebServer) -> dict[str, str]:
return {"Origin": f"http://127.0.0.1:{server.port}", "X-SBE-Token": server.token}
class TestAuth:
"""Writes follow the server's Host, Origin and token rules."""
@pytest.mark.parametrize(
("headers", "code"),
[
({}, "bad_origin"),
({"Origin": "http://evil.example"}, "bad_origin"),
({"Origin": "ORIGIN"}, "bad_token"),
],
)
def test_post_without_origin_or_token_is_refused(
self, server: _web_server.WebServer, headers: dict[str, str], code: str
) -> None:
"""No Origin, a foreign one, or no token: 403 and nothing written."""
sent = {
k: v.replace("ORIGIN", f"http://127.0.0.1:{server.port}")
for k, v in headers.items()
}
status, body = _call(
server, "POST", "/api/icon-words/cmd.done", {"word": "x"}, sent
)
assert status == 403
assert isinstance(body, dict)
assert body["error"] == code
assert not _icon_ledger.ledger_path().exists()
def test_foreign_host_is_refused_even_for_get(
self, server: _web_server.WebServer
) -> None:
"""The DNS-rebinding guard covers the ledger too."""
status, _ = _call(
server, "GET", "/api/icon-words", headers={"Host": "evil.example"}
)
assert status == 403
@pytest.mark.parametrize("method", ["POST", "PUT"])
def test_authed_write_saves_and_get_reads_it(
self, server: _web_server.WebServer, method: str
) -> None:
"""With Origin and token a write lands; a token-less GET reads it."""
status, body = _call(
server,
method,
"/api/icon-words/cmd.done",
{"word": "My win"},
_authed(server),
)
assert status == 200
assert isinstance(body, dict)
assert body["icons"] == {"cmd.done": {"word": "My win", "glyph": None}}
status, body = _call(server, "GET", "/api/icon-words")
assert (status, body) == (
200,
{"version": 1, "icons": {"cmd.done": {"word": "My win", "glyph": None}}},
)
def test_bad_word_is_a_400(self, server: _web_server.WebServer) -> None:
"""Validation errors are invalid_params over HTTP too."""
status, body = _call(
server,
"POST",
"/api/icon-words/cmd.done",
{"word": "x" * 41},
_authed(server),
)
assert status == 400
assert isinstance(body, dict)
assert body["error"] == "invalid_params"
class TestServedPage:
"""Every served page carries the current ledger: no rebuild needed."""
def test_a_pick_shows_on_the_next_page_load(
self, server: _web_server.WebServer
) -> None:
"""Save a word, reload the page: the injected ledger has it."""
_call(
server, "POST", "/api/icon-words/cmd.done", {"word": "Yay"}, _authed(server)
)
status, html = _call(server, "GET", "/")
assert status == 200
assert isinstance(html, str)
marker = f'<script type="application/json" id="{_web_icon_words.SCRIPT_ID}">'
payload = html.split(marker, 1)[1].split("</script>", 1)[0]
assert json.loads(payload)["icons"]["cmd.done"]["word"] == "Yay"
assert f'content="{server.token}"' in html