egzoscore 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. egzos/__init__.py +11 -0
  2. egzos/_ids.py +29 -0
  3. egzos/_signals.py +39 -0
  4. egzos/_term.py +33 -0
  5. egzos/_types.py +1023 -0
  6. egzos/api/__init__.py +150 -0
  7. egzos/api/app.py +1574 -0
  8. egzos/api/blobs.py +92 -0
  9. egzos/api/throttle.py +190 -0
  10. egzos/auth.py +176 -0
  11. egzos/authz/__init__.py +5 -0
  12. egzos/authz/presence.py +778 -0
  13. egzos/authz/values.py +32 -0
  14. egzos/backends/__init__.py +8 -0
  15. egzos/backends/base.py +91 -0
  16. egzos/backends/postgres.py +490 -0
  17. egzos/backends/sqlite.py +524 -0
  18. egzos/binding.py +309 -0
  19. egzos/cli/__init__.py +1092 -0
  20. egzos/cli/__main__.py +11 -0
  21. egzos/confirm.py +455 -0
  22. egzos/container.py +222 -0
  23. egzos/identity.py +1104 -0
  24. egzos/ledger.py +167 -0
  25. egzos/mcp/__init__.py +3 -0
  26. egzos/mcp/http.py +90 -0
  27. egzos/mcp/server.py +287 -0
  28. egzos/model.py +242 -0
  29. egzos/py.typed +0 -0
  30. egzos/resolver.py +115 -0
  31. egzos/store/__init__.py +10 -0
  32. egzos/store/autotitle.py +31 -0
  33. egzos/store/blobs.py +120 -0
  34. egzos/store/find.py +120 -0
  35. egzos/store/items.py +233 -0
  36. egzos/store/nodes.py +193 -0
  37. egzos/store/objects.py +143 -0
  38. egzos/store/uploads.py +369 -0
  39. egzos/trust.py +675 -0
  40. egzos/web/__init__.py +88 -0
  41. egzos/web/app.py +965 -0
  42. egzos/web/static/htmx.LICENSE +13 -0
  43. egzos/web/static/htmx.min.js +1 -0
  44. egzos/web/static/lifeboat.css +140 -0
  45. egzos/web/static/lifeboat.js +12 -0
  46. egzos/web/strings.py +133 -0
  47. egzos/web/templates/_manifest_row.html +3 -0
  48. egzos/web/templates/_shell.html +29 -0
  49. egzos/web/templates/_window.html +7 -0
  50. egzos/web/templates/base.html +24 -0
  51. egzos/web/templates/error.html +10 -0
  52. egzos/web/templates/home.html +39 -0
  53. egzos/web/templates/item.html +91 -0
  54. egzos/web/templates/notfound.html +6 -0
  55. egzos/web/templates/pending.html +107 -0
  56. egzos/web/tokens.css +294 -0
  57. egzoscore-0.2.0.dist-info/METADATA +135 -0
  58. egzoscore-0.2.0.dist-info/RECORD +62 -0
  59. egzoscore-0.2.0.dist-info/WHEEL +4 -0
  60. egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
  61. egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
  62. egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
egzos/web/app.py ADDED
@@ -0,0 +1,965 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The lifeboat (spec/design/lifeboat.md): `egzoscore web` — FastAPI + Jinja + htmx, server-rendered,
5
+ in-process with the container, loopback only, no JS toolchain, tokens as CSS variables only.
6
+
7
+ Pages: home / search (`/`), item detail (`/items/<id>`), the scheme switch (`/prefs`), the uniform
8
+ not-found page, and — rendered to the tap spec's L column (lifeboat.md R11) — the pending pages
9
+ (`/pending`, `/pending/<id>`) and the tap page (`/tap/<token>`).
10
+
11
+ The session is three values, none of them in a URL after the first visit: a launch key that works
12
+ once (the first visit trades it for the session); the session itself, an HttpOnly, SameSite=Strict
13
+ cookie that every request needs and no page carries; and a form key, a hidden field every POST
14
+ carries alongside the cookie and an exact Origin (a missing Origin is refused). The tap POST
15
+ carries its path token in place of the form key. A caller without the session gets one static
16
+ page and nothing on the chain. The lifeboat is the owner's: it is served to the interactive
17
+ principal only (lifeboat.md §14.6).
18
+
19
+ Every page the session sees is an audited read (`context.fetch`), the not-found page included.
20
+ Human-only acts take two presses: the first issues a server-held nonce, single-use, valid 10 s and
21
+ bound to the act, the item and its version; promoting an item then asks the container, which
22
+ passes an open window or redirects to `/tap/<token>`; the pending page embeds the tap block itself
23
+ (the tap spec §3.2). Every decision appends `step_up`.
24
+
25
+ Not here yet, named: blob grants (`blob.grant` is decided, not running — F5), so artifacts offer a
26
+ Download that pulls through `ItemStore.blob_pull` (audited `blob.pull`) and R7's image, pdf, grant
27
+ error and oversize rows do not render — tracked on contract-change #138; search relevance order
28
+ (the grammar returns recency only).
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import hashlib
34
+ import hmac
35
+ import json
36
+ import re
37
+ import secrets
38
+ import time
39
+ from datetime import UTC, datetime
40
+ from importlib import resources
41
+ from typing import Any
42
+ from urllib.parse import urlencode, urlsplit
43
+
44
+ from fastapi import FastAPI, Request
45
+ from fastapi.exceptions import RequestValidationError
46
+ from fastapi.responses import HTMLResponse, RedirectResponse, Response
47
+ from fastapi.templating import Jinja2Templates
48
+ from starlette.exceptions import HTTPException as StarletteHTTPException
49
+
50
+ from egzos.authz.presence import (
51
+ ARM_SECONDS,
52
+ Presence,
53
+ Tap,
54
+ build_act,
55
+ presence_text,
56
+ tap_css,
57
+ tap_timeout,
58
+ window_seconds,
59
+ )
60
+ from egzos.authz.values import same as _same
61
+ from egzos.container import OWNER, Container
62
+ from egzos.store.find import QueryError, find, shown
63
+ from egzos.trust import TrustError
64
+ from egzos.web.strings import S, around, number_free, t
65
+
66
+ COOKIE = "egzos_k"
67
+ SCHEME_COOKIE = "egz-scheme"
68
+ SCHEMES = {
69
+ "light": {"scheme": "light", "canvas": None},
70
+ "dark-neutral": {"scheme": "dark", "canvas": "neutral"},
71
+ "dark-violet": {"scheme": "dark", "canvas": "violet"},
72
+ }
73
+ PAGE = 50 # lifeboat.md §5
74
+ BODY_CUT = 4000
75
+ REASON_CUT = 480
76
+ CHIPS = 6
77
+ ROWS = 12
78
+ TEXT_KINDS = {"memory", "preference", "skill", "integration", "alias", "rule"}
79
+ _UNRESERVED = re.compile(r"[A-Za-z0-9\-._~]+")
80
+
81
+ _TEMPLATES = Jinja2Templates(directory=str(resources.files("egzos.web").joinpath("templates")))
82
+
83
+
84
+ # --- formats (lifeboat.md §5) ----------------------------------------------------------------------
85
+ def short_id(i: str) -> str:
86
+ return f"{i[:8]} … {i[-4:]}" if len(i) > 12 else i
87
+
88
+
89
+ def clock(iso: str | None) -> str:
90
+ try:
91
+ return (
92
+ datetime.strptime(iso or "", "%Y-%m-%dT%H:%M:%SZ")
93
+ .replace(tzinfo=UTC)
94
+ .astimezone()
95
+ .strftime("%H:%M:%S")
96
+ )
97
+ except ValueError:
98
+ return ""
99
+
100
+
101
+ def age(iso: str | None) -> str:
102
+ try:
103
+ then = datetime.strptime(iso or "", "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC).timestamp()
104
+ except ValueError:
105
+ return ""
106
+ secs = max(0, int(time.time() - then))
107
+ if secs < 60:
108
+ return "just now"
109
+ if secs < 3600:
110
+ return f"{secs // 60} min ago"
111
+ if secs < 86400:
112
+ return f"{secs // 3600} h ago"
113
+ return f"{secs // 86400} d ago"
114
+
115
+
116
+ def since(ts: float) -> str:
117
+ t_ = datetime.fromtimestamp(ts).astimezone()
118
+ off = t_.strftime("%z") or "+0000"
119
+ sign = "−" if off[0] == "-" else "+"
120
+ return f"{t_.strftime('%H:%M')} (UTC{sign}{off[1:3]}:{off[3:5]})"
121
+
122
+
123
+ def size(n: int | None) -> str:
124
+ if n is None:
125
+ return S["prov.null"]
126
+ for unit in ("B", "KB", "MB", "GB"):
127
+ if n < 1024 or unit == "GB":
128
+ return f"{n} B" if unit == "B" else f"{n:.1f} {unit}"
129
+ n /= 1024 # type: ignore[assignment]
130
+ return f"{n} B"
131
+
132
+
133
+ def item_title(item) -> str:
134
+ c = item.content or {}
135
+ return c.get("auto_title") or c.get("title") or item.key or S["row.untitled"]
136
+
137
+
138
+ def return_target(value: str | None) -> str:
139
+ """consent.md D-C5, the four steps: reject before parsing; match the parsed path exactly against
140
+ `/` · `/items/<id>` · `/pending` · `/pending/<id>`; carry the query (still encoded) only to `/`;
141
+ anything else is `/`."""
142
+ v = value or ""
143
+ if (
144
+ not v.startswith("/")
145
+ or v.startswith("//")
146
+ or v.startswith("/\\")
147
+ or "\\" in v
148
+ or any(ord(ch) < 32 or ord(ch) == 127 for ch in v)
149
+ ):
150
+ return "/"
151
+ parts = urlsplit(v)
152
+ path = parts.path
153
+ if path == "/":
154
+ return "/" + (f"?{parts.query}" if parts.query else "")
155
+ if path == "/pending":
156
+ return path
157
+ for prefix in ("/items/", "/pending/"):
158
+ if path.startswith(prefix):
159
+ ident = path[len(prefix) :]
160
+ if _UNRESERVED.fullmatch(ident) and ident not in (".", ".."):
161
+ return path
162
+ return "/"
163
+
164
+
165
+ class Lifeboat:
166
+ """Request handling, independent of the socket server so tests drive it through TestClient."""
167
+
168
+ def __init__(self, container: Container, *, key: str | None = None, host: str = "127.0.0.1",
169
+ launch_host: str | None = None):
170
+ self.c = container
171
+ # Three values, none of which stands in for another:
172
+ # - the launch key rides the URL once and is exchanged for a session, then is dead;
173
+ # - the session is the HttpOnly cookie, and never appears in a page;
174
+ # - the form key is in every page, and is never a credential on its own.
175
+ # Cursors are signed with a secret that never leaves this process.
176
+ #
177
+ # Two hosts when `launch_host` is set (`egzoscore web` always sets it). A browser does not
178
+ # isolate cookies by port, so a cookie for 127.0.0.1 would also reach any other server
179
+ # on 127.0.0.1 the owner's browser visits. The session therefore lives on `host`, a
180
+ # per-launch random `<label>.localhost`, minted here and never printed or put in argv:
181
+ # the launch key is redeemed on `launch_host` (127.0.0.1), which answers only with a
182
+ # single-use handoff to `host`, where the host-only cookie is set.
183
+ self.key = key or secrets.token_urlsafe(32)
184
+ self.redeemed = False
185
+ self.launch_host = launch_host
186
+ self._handoff: tuple[str, float] | None = None
187
+ self.session = secrets.token_urlsafe(32)
188
+ self.form_key = secrets.token_urlsafe(32)
189
+ self._signing = secrets.token_bytes(32)
190
+ # nonce → (purpose, ref, version, until, armed while a window covered the act)
191
+ self._arms: dict[str, tuple[str, str, str, float, bool]] = {}
192
+ self.host = host
193
+ self.since = time.time()
194
+ self.presence = Presence(container)
195
+ self.taps: dict[str, dict[str, Any]] = {} # token → {tap, return}
196
+ self.outcomes: dict[str, tuple[str, str]] = {} # subject → (state, text), shown once
197
+
198
+ def hand_off(self) -> str:
199
+ """The single-use value that carries the redeemed launch to the session host (10 s)."""
200
+ token = secrets.token_urlsafe(32)
201
+ self._handoff = (token, time.time() + ARM_SECONDS)
202
+ return token
203
+
204
+ def take_handoff(self, token: str) -> bool:
205
+ held, self._handoff = self._handoff, None
206
+ return bool(held) and _same(token, held[0]) and held[1] >= time.time()
207
+
208
+ # -- arming: a server-held nonce, single-use, valid 10 s, bound to one act (the tap's model) ---
209
+ def arm(self, purpose: str, ref: str, version: object, *, windowed: bool = False) -> str:
210
+ now = time.time()
211
+ for nonce in [n for n, a in self._arms.items() if a[3] < now]:
212
+ del self._arms[nonce]
213
+ nonce = secrets.token_urlsafe(24)
214
+ self._arms[nonce] = (purpose, ref, str(version), now + ARM_SECONDS, windowed)
215
+ return nonce
216
+
217
+ def arm_was_windowed(self, token: str | None) -> bool:
218
+ """Whether a window covered the act when this nonce was armed (R9 lapsed needs it)."""
219
+ entry = self._arms.get(token or "")
220
+ return bool(entry) and entry[4]
221
+
222
+ def armed(self, purpose: str, ref: str, version: object, token: str | None) -> bool:
223
+ """True once for the nonce `arm` issued for exactly this act, within its 10 s."""
224
+ entry = self._arms.pop(token or "", None)
225
+ return bool(entry) and entry[:3] == (purpose, ref, str(version)) and entry[3] >= time.time()
226
+
227
+ # -- cursors: opaque, signed, carrying no scope or count in the clear (§15) ---------------------
228
+ def cursor(self, q: str, offset: int) -> str:
229
+ sig = hmac.new(self._signing, f"cursor|{q}|{offset}".encode(), hashlib.sha256)
230
+ return f"{offset:x}.{sig.hexdigest()[:24]}"
231
+
232
+ def offset(self, q: str, cursor: str | None) -> int:
233
+ try:
234
+ off_s, sig = (cursor or "").split(".", 1)
235
+ off = int(off_s, 16)
236
+ except ValueError:
237
+ return 0
238
+ good = hmac.new(self._signing, f"cursor|{q}|{off}".encode(), hashlib.sha256)
239
+ return off if _same(sig, good.hexdigest()[:24]) else 0 # R5: first page
240
+
241
+ # -- reads ------------------------------------------------------------------------------------
242
+ def token(self):
243
+ return self.c.require_token()
244
+
245
+ def open_proposals(self) -> list[dict[str, Any]]:
246
+ """Open proposals this viewer's token decides over (`Trust.decides_over`, the rule
247
+ `build_act` already applies to a single id). The nav count and the queue page share
248
+ this one filter so they cannot disagree (F33); a token covering only one end of a
249
+ proposal does not see it, as if it did not exist (silence-not-errors)."""
250
+ token = self.token()
251
+ return [p for p in self.c.backend.list_proposals(status="open")
252
+ if self.c.trust.decides_over(token, p)]
253
+
254
+ def pending_count(self) -> int:
255
+ return len(self.open_proposals())
256
+
257
+ def read(self, view: str, **details: Any) -> None:
258
+ """Every page is a read: one `context.fetch`, the nav's pending count included."""
259
+ token = self.token()
260
+ self.c.ledger.append(
261
+ "context.fetch",
262
+ actor=OWNER,
263
+ principal=token.principal,
264
+ subject=details.pop("subject", None),
265
+ scope=details.pop("scope", None),
266
+ client="web",
267
+ view=view,
268
+ pending_count=self.pending_count(),
269
+ layers=details.pop("layers", []),
270
+ withheld=0,
271
+ **details,
272
+ )
273
+
274
+ def shell(self, request: Request, *, current: str | None, nav: bool = True,
275
+ scheme: bool = True, here: str | None = None) -> dict[str, Any]:
276
+ n = self.pending_count()
277
+ status = self.presence.window_status()
278
+ window = None
279
+ if status and status["state"] == "open":
280
+ pair = status.get("pair") or ["?", "?"]
281
+ window = {"state": "open", "text": t("shell.window", source=pair[0],
282
+ destination=pair[1],
283
+ closes=clock(status["closes"]))}
284
+ elif status:
285
+ window = {"state": "lapsed", "text": t("shell.lapsed", at=clock(status["at"]))}
286
+ if here is None:
287
+ here = request.url.path + (f"?{request.url.query}" if request.url.query else "")
288
+ return {
289
+ "container_line": t("shell.container", name=self.c.home.name, host=self.host),
290
+ "viewer_line": t("shell.viewer", user=OWNER, since=since(self.since)),
291
+ "nav": (
292
+ [
293
+ {"href": "/", "label": S["nav.search"], "current": current == "search"},
294
+ {
295
+ "href": "/pending",
296
+ "label": t("nav.pending", n=n) if n else S["nav.pending.zero"],
297
+ "current": current == "pending",
298
+ },
299
+ ]
300
+ if nav
301
+ else None
302
+ ),
303
+ "scheme": (
304
+ {"current": self.scheme_of(request), "return": here, "csrf": self.form_key}
305
+ if scheme
306
+ else None
307
+ ),
308
+ "window": window,
309
+ }
310
+
311
+ @staticmethod
312
+ def scheme_of(request: Request) -> str | None:
313
+ value = request.cookies.get(SCHEME_COOKIE)
314
+ return value if value in SCHEMES else None # R10: an invalid value is no cookie
315
+
316
+ def render(self, request: Request, template: str, context: dict[str, Any],
317
+ status: int = 200) -> HTMLResponse:
318
+ scheme = SCHEMES.get(self.scheme_of(request) or "")
319
+ return _TEMPLATES.TemplateResponse(
320
+ request,
321
+ template,
322
+ {
323
+ "S": S,
324
+ "t": t,
325
+ "around": around,
326
+ "scheme": scheme,
327
+ "printed": time.strftime("%H:%M:%S"),
328
+ "container_name": self.c.home.name,
329
+ **context,
330
+ },
331
+ status_code=status,
332
+ )
333
+
334
+ def not_found(self, request: Request, cause: str = "not-found") -> HTMLResponse:
335
+ """R12: one page for not-found, not-yours, tombstoned, quarantined and malformed ids. The
336
+ cause goes to the owner's ledger, never to the page (R6, the tap spec D-T8); the shape of
337
+ that field in `details` is lifeboat.md R6's [GAP→a1p]."""
338
+ self.read("not-found", cause=cause)
339
+ return self.render(
340
+ request,
341
+ "notfound.html",
342
+ # R12: one page for five causes — nothing on it depends on what was asked for.
343
+ {"shell": self.shell(request, current=None, here="/"), "title": S["title.notfound"]},
344
+ status=404,
345
+ )
346
+
347
+ # -- the decision, shared by the pending page and the lifeboat-hosted tap ---------------------
348
+ def decide(self, act: dict[str, Any], outcome: str, *, windowed: bool,
349
+ via: str, version: object = None) -> tuple[str, str]:
350
+ """Perform the decision; returns (state, text): the state is what actually happened —
351
+ approved, denied, or invalid for a refusal — so a refusal never reads as a success. A
352
+ promote carries the version that was armed, and an item changed since is refused: the
353
+ act is the one the person saw (tap spec §2.5)."""
354
+ token = self.token()
355
+ at = time.strftime("%H:%M:%S")
356
+ closes = self.presence.record(act, via=via, outcome=outcome, windowed=windowed)
357
+ try:
358
+ if outcome == "denied":
359
+ if act["kind"] == "proposal":
360
+ self.c.trust.deny(act["subject"], token=token, actor=OWNER)
361
+ return "denied", t("outcome.denied", at=at, user=OWNER,
362
+ destination=act["dest"])
363
+ return "invalid", t("tap.invalid")
364
+ if outcome not in ("approved", "window"):
365
+ return "invalid", t("tap.invalid")
366
+ if act["kind"] == "proposal":
367
+ p = self.c.trust.execute(act["subject"], token=token, actor=OWNER)
368
+ landed = {i.status for i in (self.c.backend.get(x) for x in p["items"]) if i}
369
+ trust = ", ".join(sorted(landed)) or "unverified"
370
+ if closes:
371
+ return "approved", t("outcome.approved", at=at, user=OWNER,
372
+ n=len(p["items"]), destination=act["dest"],
373
+ trust=trust, closes=clock(closes))
374
+ return "approved", t("outcome.approved.nowindow", at=at, user=OWNER,
375
+ n=len(p["items"]), destination=act["dest"], trust=trust)
376
+ item = self.c.backend.get(act["subject"])
377
+ if item is None or item.status != "unverified":
378
+ raise TrustError("no longer pending")
379
+ if version is not None and str(item.lifecycle.get("version", 1)) != str(version):
380
+ raise TrustError("changed since it was armed")
381
+ self.c.trust.promote(item, token=token, actor=OWNER)
382
+ return "approved", t("act.promoted", at=at, user=OWNER)
383
+ except TrustError as e:
384
+ # Presence was proven and the act was refused: on the chain, and the window that
385
+ # signature opened closes with it — as the CLI does (presence.act_failed).
386
+ self.presence.act_failed(act, e, reason="refused")
387
+ return "invalid", (t("outcome.invalid") if act["kind"] == "proposal"
388
+ else t("tap.invalid"))
389
+ except Exception as e:
390
+ # The act rolled back whole; the chain says so and the signature's window closes.
391
+ self.presence.act_failed(act, e)
392
+ raise
393
+
394
+ def sweep(self) -> None:
395
+ """A tap left undecided past its timeout expires, and says so on the record."""
396
+ for token, entry in list(self.taps.items()):
397
+ tap = entry["tap"]
398
+ if tap.outcome is None and time.time() - tap.opened > tap_timeout():
399
+ self.presence.record(tap.act, via="tap", outcome="expired")
400
+ del self.taps[token]
401
+
402
+
403
+ def proposal_state(c: Container, pid: str) -> str:
404
+ """A digest of the proposal as stored: what a pending arm is bound to."""
405
+ p = c.backend.get_proposal(pid) or {}
406
+ return hashlib.sha256(json.dumps(p, sort_keys=True, default=str).encode()).hexdigest()[:16]
407
+
408
+
409
+ def who_wrote(item) -> str:
410
+ """Principals as §5 renders them: an agent by `agent:<client>`, the owner as `you`."""
411
+ prov = item.provenance or {}
412
+ return f"agent:{prov.get('client')}" if prov.get("principal") == "client" else "you"
413
+
414
+
415
+ def create_app(boat: Lifeboat, origin: str) -> FastAPI:
416
+ app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
417
+ static = resources.files("egzos.web")
418
+
419
+ @app.middleware("http")
420
+ async def guard(request: Request, call_next):
421
+ path = request.url.path
422
+ host = request.headers.get("host")
423
+ key = request.query_params.get("k")
424
+ # Every refusal before the session is proven is the same static page: no shell, no
425
+ # container state, nothing written to the chain. Only the bound hosts are served, so a
426
+ # page elsewhere that rebinds a name to 127.0.0.1 reaches nothing.
427
+ if boat.launch_host is not None and host == boat.launch_host:
428
+ # The launch host does one thing: redeem the key, once, by handing the browser to the
429
+ # session host. It sets no cookie and serves no page.
430
+ if (request.method == "GET" and key is not None and not boat.redeemed
431
+ and _same(key, boat.key)):
432
+ boat.redeemed = True
433
+ to = f"http://{boat.host}/?{urlencode({'h': boat.hand_off()})}"
434
+ return _harden(RedirectResponse(to, status_code=303), path)
435
+ return _harden(HTMLResponse(_LOCKED, status_code=403), path)
436
+ if host != boat.host:
437
+ return _harden(HTMLResponse(_LOCKED, status_code=403), path)
438
+ handoff = request.query_params.get("h")
439
+ if boat.launch_host is not None and request.method == "GET" and handoff is not None:
440
+ if boat.take_handoff(handoff):
441
+ resp = RedirectResponse("/", status_code=303)
442
+ # Host-only (no Domain): sent to this label host alone, never to 127.0.0.1.
443
+ resp.set_cookie(COOKIE, boat.session, httponly=True, samesite="strict", path="/")
444
+ return _harden(resp, path)
445
+ return _harden(HTMLResponse(_LOCKED, status_code=403), path)
446
+ if boat.launch_host is None and request.method == "GET" and key is not None:
447
+ # The launch key works once: whoever redeems it first holds the session, and a copy
448
+ # read later from a launcher's argv or a terminal opens nothing.
449
+ if not boat.redeemed and _same(key, boat.key):
450
+ boat.redeemed = True
451
+ resp: Response = RedirectResponse(path or "/", status_code=303)
452
+ resp.set_cookie(COOKIE, boat.session, httponly=True, samesite="strict", path="/")
453
+ return _harden(resp, path)
454
+ return _harden(HTMLResponse(_LOCKED, status_code=403), path)
455
+ if not _same(request.cookies.get(COOKIE, ""), boat.session):
456
+ return _harden(HTMLResponse(_LOCKED, status_code=403), path)
457
+ if request.method == "POST":
458
+ # A missing Origin is refused too: every browser sends one on a form POST.
459
+ if request.headers.get("origin") != origin:
460
+ return _harden(HTMLResponse(_REFUSED, status_code=403), path)
461
+ try:
462
+ response = await call_next(request)
463
+ if request.method == "POST" and request.headers.get("hx-request") == "true":
464
+ response = _for_htmx(response)
465
+ except Exception: # noqa: BLE001 — R12: never a code, path or exception text
466
+ try:
467
+ boat.read("error") # the card is a view too, when the chain can still take it
468
+ except Exception: # noqa: BLE001 — a broken container still gets its card
469
+ pass
470
+ response = boat.render(request, "error.html",
471
+ {"shell": boat.shell(request, current=None),
472
+ "title": S["title.notfound"],
473
+ # D-C5: the retry link is a validated return, never the
474
+ # raw path (a `//host` path would leave this origin).
475
+ "retry": return_target(str(request.url.path))}, status=500)
476
+ return _harden(response, path)
477
+
478
+ async def form_of(request: Request) -> dict[str, str] | None:
479
+ form = {k: str(v) for k, v in (await request.form()).items()}
480
+ if not _same(form.get("csrf", ""), boat.form_key):
481
+ return None
482
+ return form
483
+
484
+ # -- static: the one stylesheet, the token file, htmx (vendored) -------------------------------
485
+ @app.get("/static/{name}")
486
+ async def static_file(request: Request, name: str):
487
+ files = {
488
+ "tokens.css": ("tokens.css", "text/css; charset=utf-8"),
489
+ "lifeboat.css": ("static/lifeboat.css", "text/css; charset=utf-8"),
490
+ "htmx.min.js": ("static/htmx.min.js", "text/javascript; charset=utf-8"),
491
+ "lifeboat.js": ("static/lifeboat.js", "text/javascript; charset=utf-8"),
492
+ }
493
+ if name == "tap.css": # the hosted tap's styles, linked so no page needs inline style
494
+ return Response(tap_css(), media_type="text/css; charset=utf-8")
495
+ if name not in files:
496
+ return boat.not_found(request)
497
+ rel, ctype = files[name]
498
+ return Response(static.joinpath(rel).read_bytes(), media_type=ctype)
499
+
500
+ # -- home / search (lifeboat.md §2, R2–R5) ------------------------------------------------------
501
+ @app.get("/", response_class=HTMLResponse)
502
+ async def home(request: Request, q: str = "", cursor: str | None = None):
503
+ token = boat.token()
504
+ invalid = False
505
+ try:
506
+ hits = find(boat.c, token, q)
507
+ except QueryError:
508
+ hits, invalid = [], True
509
+ start = boat.offset(q, cursor)
510
+ if start >= len(hits):
511
+ start = 0
512
+ page = hits[start : start + PAGE]
513
+ boat.read("search", query=q or None, items=[i.id for _, i in page])
514
+ rows = []
515
+ for node, item in page:
516
+ path = boat.c.nodes.path(node)
517
+ rows.append({
518
+ "id": item.id,
519
+ "kind": item.kind,
520
+ "title": item_title(item),
521
+ "untitled": item_title(item) == S["row.untitled"],
522
+ "scope": path,
523
+ "status": item.status,
524
+ "age": age(item.lifecycle.get("updated_at")),
525
+ "updated": item.lifecycle.get("updated_at"),
526
+ "who": who_wrote(item),
527
+ "version": item.lifecycle.get("version", 1),
528
+ "tags": item.tags or [],
529
+ })
530
+ if invalid:
531
+ header = None
532
+ elif not hits:
533
+ header = S["results.uncounted"] if q else number_free("results.recent") # R3 empty
534
+ else:
535
+ header = t("results.count", n=len(hits)) if q else t("results.recent", n=len(hits))
536
+ nxt = boat.cursor(q, start + PAGE) if start + PAGE < len(hits) else None
537
+ return boat.render(request, "home.html", {
538
+ "shell": boat.shell(request, current="search"),
539
+ "title": S["title.home"],
540
+ "q": q,
541
+ "invalid": invalid,
542
+ "header": header,
543
+ "rows": rows,
544
+ "empty": not invalid and not hits,
545
+ "next": f"/?{urlencode({'q': q, 'cursor': nxt})}" if nxt else None,
546
+ })
547
+
548
+ # -- item detail (lifeboat.md §3, R6–R9) ------------------------------------------------------
549
+ def item_or_none(item_id: str):
550
+ """(item, node, None) for an item this page may show, else (None, None, cause). Search's
551
+ predicate (`find.shown`), so the two views never disagree on one item."""
552
+ token = boat.token()
553
+ if not _UNRESERVED.fullmatch(item_id or ""):
554
+ return None, None, "malformed"
555
+ item = boat.c.backend.get(item_id)
556
+ node = boat.c.backend.get_node(item.scope) if item else None
557
+ if not item or not node:
558
+ return None, None, "not-found"
559
+ if item.lifecycle.get("tombstoned"):
560
+ return None, None, "tombstoned"
561
+ if item.status == "quarantined":
562
+ return None, None, "quarantined"
563
+ if not boat.c.trust.covers(token, node) or not shown(boat.c, token, item, node):
564
+ return None, None, "not-yours"
565
+ return item, node, None
566
+
567
+ def item_context(request: Request, item, node, *, full: bool, arm: str | None,
568
+ message: tuple[str, str] | None) -> dict[str, Any]:
569
+ content = item.content or {}
570
+ body = content.get("body") or content.get("inline") or ""
571
+ cut = (not full) and len(body) > BODY_CUT
572
+ path = boat.c.nodes.path(node)
573
+ derived = (item.provenance or {}).get("derived_from")
574
+ derived_link = None
575
+ if derived:
576
+ d_item = boat.c.backend.get(derived)
577
+ d_node = boat.c.backend.get_node(d_item.scope) if d_item else None
578
+ if (d_item and d_node and d_item.status != "quarantined"
579
+ and boat.c.trust.covers(boat.token(), d_node)):
580
+ derived_link = derived
581
+ trust = item.trust or {}
582
+ prov = item.provenance or {}
583
+ return {
584
+ "shell": boat.shell(request, current=None),
585
+ "title": S["title.item"],
586
+ "item": item,
587
+ "ref": t("item.ref", id=short_id(item.id), kind=item.kind,
588
+ version=item.lifecycle.get("version", 1)),
589
+ "heading": item_title(item),
590
+ "untitled": item_title(item) == S["row.untitled"],
591
+ "scope": path,
592
+ "ring": None if node.type == "user" else node.type,
593
+ "engine": content.get("title_engine"),
594
+ "text_kind": item.kind in TEXT_KINDS,
595
+ "body": body[:BODY_CUT] if cut else body,
596
+ "cut": cut,
597
+ "artifact": {
598
+ "filename": content.get("filename"),
599
+ "size": size(content.get("size")),
600
+ "mime": content.get("mime") or S["prov.null"],
601
+ "sha": (f"sha256 {content['sha256'][:4]}…{content['sha256'][-4:]}"
602
+ if content.get("sha256") else S["prov.null"]),
603
+ } if item.kind == "artifact" else None,
604
+ "prov": [
605
+ (S["prov.actor"], prov.get("actor")),
606
+ (S["prov.principal"], prov.get("principal")),
607
+ (S["prov.client"], prov.get("client")),
608
+ (S["prov.derived"], derived),
609
+ (S["prov.imported"], prov.get("imported_from")),
610
+ (S["prov.approved"], prov.get("approved_by")),
611
+ ],
612
+ "derived_link": derived_link,
613
+ "promoted": (t("trust.promoted", at=clock(trust.get("promoted_at")),
614
+ prefix=(trust.get("manifest") or "")[:8])
615
+ if item.status == "verified" and trust.get("promoted_at") else None),
616
+ "life": [
617
+ (S["life.created"], clock(item.lifecycle.get("created_at")) or S["prov.null"]),
618
+ (S["life.updated"], clock(item.lifecycle.get("updated_at")) or S["prov.null"]),
619
+ (S["life.version"], f"v{item.lifecycle.get('version', 1)}"),
620
+ ],
621
+ "tags": item.tags or [],
622
+ "key": item.key,
623
+ "can_promote": item.status == "unverified",
624
+ "arm": arm,
625
+ "version": item.lifecycle.get("version", 1),
626
+ "csrf": boat.form_key,
627
+ "message": message,
628
+ }
629
+
630
+ @app.get("/items/{item_id}", response_class=HTMLResponse)
631
+ async def item_page(request: Request, item_id: str, full: int = 0):
632
+ item, node, cause = item_or_none(item_id)
633
+ if item is None:
634
+ return boat.not_found(request, cause)
635
+ boat.read("item", subject=item.id, scope=item.scope, items=[item.id], layers=[node.id])
636
+ message = boat.outcomes.pop(item.id, None)
637
+ return boat.render(request, "item.html",
638
+ item_context(request, item, node, full=bool(full), arm=None,
639
+ message=message))
640
+
641
+ @app.post("/items/{item_id}/promote", response_class=HTMLResponse)
642
+ async def promote(request: Request, item_id: str):
643
+ form = await form_of(request)
644
+ if form is None:
645
+ return HTMLResponse(_REFUSED, status_code=403)
646
+ item, node, cause = item_or_none(item_id)
647
+ if item is None:
648
+ return boat.not_found(request, cause)
649
+ version = item.lifecycle.get("version", 1)
650
+ if str(form.get("version")) != str(version):
651
+ boat.read("item", subject=item.id, scope=item.scope, items=[item.id])
652
+ return boat.render(request, "item.html", item_context(
653
+ request, item, node, full=False, arm=None,
654
+ message=("invalid", S["act.invalid"])))
655
+ under_window = boat.arm_was_windowed(form.get("arm"))
656
+ if not boat.armed("promote", item.id, version, form.get("arm")):
657
+ # The first press — or a confirm whose 10 s lapsed — arms in place (R9 confirming).
658
+ boat.read("item", subject=item.id, scope=item.scope, items=[item.id])
659
+ act = build_act(boat.c, item.id, token=boat.token())
660
+ covered = act is not None and boat.presence.covers(act)
661
+ ctx = item_context(request, item, node, full=False, message=None,
662
+ arm=boat.arm("promote", item.id, version, windowed=covered))
663
+ return boat.render(request, "item.html", {**ctx, "refresh": ARM_SECONDS})
664
+ act = build_act(boat.c, item.id, token=boat.token())
665
+ if act is None:
666
+ return boat.not_found(request)
667
+ if boat.presence.covers(act):
668
+ try:
669
+ boat.outcomes[item.id] = boat.decide(act, "window", windowed=False, via="window",
670
+ version=version)
671
+ except Exception: # noqa: BLE001 — R9 error: decide recorded it; back to ready
672
+ boat.outcomes[item.id] = ("error", S["act.error"])
673
+ return RedirectResponse(f"/items/{item.id}", status_code=303)
674
+ status = boat.presence.window_status()
675
+ if under_window and status and status["state"] == "lapsed":
676
+ # R9 lapsed: the window that covered the first press closed before the second.
677
+ # Nothing changed; the acts return un-armed, and the next press asks for presence.
678
+ boat.outcomes[item.id] = ("lapsed", t("act.lapsed", at=clock(status["at"])))
679
+ return RedirectResponse(f"/items/{item.id}", status_code=303)
680
+ # Step-up required: a one-shot tap, its return bound now (the tap spec D-T9 (a)).
681
+ boat.sweep()
682
+
683
+ def perform(outcome: str, windowed: bool) -> str:
684
+ # Runs inside the tap's own request: the container answers before anything is shown.
685
+ state, text = boat.decide(act, outcome, windowed=windowed, via="tap",
686
+ version=version)
687
+ boat.outcomes[act["subject"]] = (state, text)
688
+ return text
689
+
690
+ tap = Tap(act, container=boat.c.home.name, host=boat.host, decide=perform,
691
+ stylesheet="/static/tap.css")
692
+ boat.taps[tap.token] = {"tap": tap, "return": return_target(f"/items/{item.id}")}
693
+ return RedirectResponse(f"/tap/{tap.token}", status_code=303)
694
+
695
+ @app.get("/items/{item_id}/download")
696
+ async def download(request: Request, item_id: str):
697
+ item, node, cause = item_or_none(item_id)
698
+ token = boat.token()
699
+ data = (boat.c.store.blob_pull(item, token=token, actor=OWNER, principal=token.principal)
700
+ if item is not None and item.kind == "artifact" else None)
701
+ if data is None:
702
+ return boat.not_found(request, cause or "not-found")
703
+ name = re.sub(r"[^A-Za-z0-9._-]", "_", (item.content or {}).get("filename") or item.id)
704
+ return Response(data, media_type="application/octet-stream",
705
+ headers={"Content-Disposition": f'attachment; filename="{name}"'})
706
+
707
+ # -- the tap, hosted here for the promote's step-up ----------------------------------------------
708
+ @app.get("/tap/{token}", response_class=HTMLResponse)
709
+ async def tap_get(request: Request, token: str):
710
+ boat.sweep()
711
+ entry = boat.taps.get(token)
712
+ if not entry or not entry["tap"].live(f"/tap/{token}"):
713
+ return HTMLResponse(_tap_empty(), status_code=404)
714
+ status, page = entry["tap"].get()
715
+ return HTMLResponse(page, status_code=status)
716
+
717
+ @app.post("/tap/{token}", response_class=HTMLResponse)
718
+ async def tap_post(request: Request, token: str):
719
+ # Guarded by the session cookie, this origin's Origin, and in place of the form key the
720
+ # tap's own path token: unguessable, single-use, bound at issue (the tap page is the
721
+ # shared presence.Tap, which carries no lifeboat form key).
722
+ boat.sweep()
723
+ entry = boat.taps.get(token)
724
+ if not entry or not entry["tap"].live(f"/tap/{token}"):
725
+ return HTMLResponse(_tap_empty(), status_code=404)
726
+ step = str((await request.form()).get("step", ""))
727
+ tap = entry["tap"]
728
+ status, page = tap.post(step)
729
+ if tap.outcome is None:
730
+ return HTMLResponse(page, status_code=status)
731
+ # Decided: `perform` has run and parked the container's answer for the item page.
732
+ del boat.taps[token]
733
+ return RedirectResponse(entry["return"], status_code=303)
734
+
735
+ # -- the pending pages (the tap spec §3, §4, §18 — L column) -----------------------------------
736
+ def queue() -> list[dict[str, Any]]:
737
+ rows = []
738
+ for p in sorted(boat.open_proposals(), key=lambda p: p.get("created_at", "")):
739
+ by = p.get("proposed_by") or {}
740
+ rows.append({
741
+ "id": p["id"],
742
+ "label": S["kind.publish"],
743
+ "title": f"{len(p['items'])} items · {p['from_path']} → {p['to_path']}",
744
+ "meta": " · ".join(x for x in (
745
+ f"agent:{by['client']}" if by.get("principal") == "client" else "you",
746
+ age(p.get("created_at")),
747
+ ) if x),
748
+ })
749
+ return rows
750
+
751
+ def notices() -> list[dict[str, Any]]:
752
+ """Quarantine notices, pinned at the end of the queue (the tap spec §3.1, R3): an item
753
+ that stopped serving because what it was derived from was quarantined. A notice, not an
754
+ act — lifting a quarantine is the CLI's in this lifeboat (§0) — so it has no link."""
755
+ token = boat.token()
756
+ out = []
757
+ for node in boat.c.backend.list_nodes():
758
+ if not boat.c.trust.covers(token, node):
759
+ continue
760
+ for item in boat.c.backend.query([node.id]):
761
+ source = (item.provenance or {}).get("derived_from")
762
+ if item.status == "quarantined" and source and \
763
+ str((item.trust or {}).get("reason", "")).startswith("derived from"):
764
+ out.append({"id": item.id, "title": item_title(item), "meta": t(
765
+ "queue.quarantine.meta", id=f"{source[:8]}…",
766
+ at=clock((item.trust or {}).get("at"))[:5])})
767
+ return out
768
+
769
+ def pending_context(request: Request, pid: str | None, *, arm: dict[str, str] | None,
770
+ message: tuple[str, str] | None) -> dict[str, Any] | None:
771
+ rows = queue()
772
+ open_id = pid or (rows[0]["id"] if rows else None)
773
+ detail = None
774
+ if open_id:
775
+ act = build_act(boat.c, open_id, token=boat.token())
776
+ if act is None or act["kind"] != "proposal":
777
+ if pid and message is None:
778
+ return None
779
+ else:
780
+ p = boat.c.backend.get_proposal(open_id)
781
+ reason = act.get("reason") or ""
782
+ audience = act.get("audience", [])
783
+ people = sum(1 for a in audience if a.get("principal") == "interactive")
784
+ seconds = window_seconds()
785
+ detail = {
786
+ "id": open_id,
787
+ "ref": t("ref.proposal", id=short_id(open_id),
788
+ at=clock(p.get("created_at"))),
789
+ "title": t("title.move", n=len(act["items"]), source=act["from"],
790
+ destination=act["to"]),
791
+ "who": act.get("requester") or "you",
792
+ "reason": reason,
793
+ "reason_cut": reason[:REASON_CUT] if len(reason) > REASON_CUT else None,
794
+ "moves": act["items"][:ROWS],
795
+ "more_moves": act["items"][ROWS:],
796
+ "dest": act["dest"],
797
+ "count": t("audience.count", people=people, agents=len(audience) - people),
798
+ "chips": audience[:CHIPS],
799
+ "more_chips": audience[CHIPS:],
800
+ "consequence": act.get("consequence"),
801
+ "presence": presence_text(act, seconds),
802
+ "terms": (
803
+ f"window would close {time.strftime('%H:%M:%S', time.localtime(time.time() + seconds))}"
804
+ f" · org policy {seconds // 60}:{seconds % 60:02d} · close early at any time"
805
+ if seconds else None
806
+ ),
807
+ "nowindow": bool(seconds),
808
+ "blocked": act.get("blocked"),
809
+ "arm": arm,
810
+ "csrf": boat.form_key,
811
+ }
812
+ status = boat.presence.window_status()
813
+ return {
814
+ "shell": boat.shell(request, current="pending", scheme=False),
815
+ "title": S["title.pending"],
816
+ "rows": rows,
817
+ "notices": notices(),
818
+ "open_id": open_id,
819
+ "detail": detail,
820
+ "message": message,
821
+ "window": status if status and status["state"] == "open" else None,
822
+ "window_text": (t("window.open", closes=clock(status["closes"]))
823
+ if status and status["state"] == "open" else None),
824
+ }
825
+
826
+ @app.get("/pending", response_class=HTMLResponse)
827
+ async def pending(request: Request):
828
+ ctx = pending_context(request, None, arm=None, message=None)
829
+ boat.read("pending", proposals=[r["id"] for r in ctx["rows"]],
830
+ notices=[n["id"] for n in ctx["notices"]])
831
+ return boat.render(request, "pending.html", ctx)
832
+
833
+ @app.get("/pending/{pid}", response_class=HTMLResponse)
834
+ async def pending_one(request: Request, pid: str):
835
+ message = boat.outcomes.pop(pid, None)
836
+ ctx = pending_context(request, pid, arm=None, message=message)
837
+ if ctx is None:
838
+ return boat.not_found(request)
839
+ boat.read("pending", subject=pid, proposals=[r["id"] for r in ctx["rows"]],
840
+ notices=[n["id"] for n in ctx["notices"]])
841
+ return boat.render(request, "pending.html", ctx)
842
+
843
+ @app.get("/pending/{pid}/window", response_class=HTMLResponse)
844
+ async def pending_window(request: Request, pid: str):
845
+ # Not an audited read, on purpose: the 15 s poll shows only the window line (open, and
846
+ # when it closes), which the chain already holds as the step_up that opened it, and no
847
+ # item. The page that embeds it is the audited read.
848
+ status = boat.presence.window_status()
849
+ text = (t("window.open", closes=clock(status["closes"]))
850
+ if status and status["state"] == "open" else None)
851
+ return boat.render(request, "_window.html", {"pid": pid, "window_text": text})
852
+
853
+ @app.post("/pending/{pid}", response_class=HTMLResponse)
854
+ async def pending_act(request: Request, pid: str):
855
+ form = await form_of(request)
856
+ if form is None:
857
+ return HTMLResponse(_REFUSED, status_code=403)
858
+ act = build_act(boat.c, pid, token=boat.token())
859
+ if act is None or act["kind"] != "proposal":
860
+ return boat.not_found(request)
861
+ step = form.get("step", "")
862
+ # The arm binds to the proposal as it stands: any change between the presses (its items,
863
+ # target or status) is a different state, and the confirm re-arms instead of acting.
864
+ state = proposal_state(boat.c, pid)
865
+ if step == "deny": # one press: deny is the safe direction
866
+ try:
867
+ boat.outcomes[pid] = boat.decide(act, "denied", windowed=False, via="lifeboat")
868
+ except Exception: # noqa: BLE001 — the tap spec R9 error: decide recorded it
869
+ boat.outcomes[pid] = ("error", S["act.error"])
870
+ return RedirectResponse(f"/pending/{pid}", status_code=303)
871
+ if act.get("blocked"):
872
+ return RedirectResponse(f"/pending/{pid}", status_code=303)
873
+ if step in ("arm", "arm_once"):
874
+ mode = "once" if step == "arm_once" else "window"
875
+ ctx = pending_context(request, pid, arm={"mode": mode,
876
+ "token": boat.arm(mode, pid, state)},
877
+ message=None)
878
+ # The armed page shows the whole proposal again: a read on the chain like any view.
879
+ boat.read("pending", subject=pid, proposals=[r["id"] for r in ctx["rows"]],
880
+ notices=[n["id"] for n in ctx["notices"]])
881
+ return boat.render(request, "pending.html", {**ctx, "refresh": ARM_SECONDS})
882
+ mode = form.get("mode", "window")
883
+ if step == "confirm" and mode in ("once", "window") and boat.armed(
884
+ mode, pid, state, form.get("arm")
885
+ ):
886
+ try:
887
+ boat.outcomes[pid] = boat.decide(act, "approved", windowed=mode == "window",
888
+ via="lifeboat")
889
+ except Exception: # noqa: BLE001 — the tap spec R9 error: decide recorded it
890
+ boat.outcomes[pid] = ("error", S["act.error"])
891
+ return RedirectResponse(f"/pending/{pid}", status_code=303)
892
+ return RedirectResponse(f"/pending/{pid}", status_code=303) # lapsed arm: un-armed
893
+
894
+ # -- the scheme switch (R10) --------------------------------------------------------------------
895
+ @app.post("/prefs")
896
+ async def prefs(request: Request):
897
+ form = await form_of(request)
898
+ if form is None:
899
+ return HTMLResponse(_REFUSED, status_code=403)
900
+ resp = RedirectResponse(return_target(form.get("return")), status_code=303)
901
+ value = form.get("scheme", "")
902
+ if value in SCHEMES:
903
+ resp.set_cookie(SCHEME_COOKIE, value, httponly=True, samesite="strict", path="/")
904
+ return resp
905
+
906
+ @app.api_route("/{rest:path}", methods=["GET", "POST"], include_in_schema=False)
907
+ async def anything_else(request: Request, rest: str):
908
+ return boat.not_found(request)
909
+
910
+ @app.exception_handler(StarletteHTTPException)
911
+ async def no_other_shape(request: Request, exc: StarletteHTTPException):
912
+ # R12: a method no route declares (PUT, DELETE, ...) answers with the one not-found page,
913
+ # never the framework's own 405 body. Behind the guard, like every route.
914
+ return boat.not_found(request, "method")
915
+
916
+ @app.exception_handler(RequestValidationError)
917
+ async def no_validation_shape(request: Request, exc: RequestValidationError):
918
+ # And a parameter that does not parse (`?full=x`) gets that page too, not a 422 JSON body.
919
+ return boat.not_found(request, "malformed")
920
+
921
+ return app
922
+
923
+
924
+ def _for_htmx(resp: Response) -> Response:
925
+ """An act posted through htmx swaps its acts block only when the answer is a page. A redirect
926
+ (an outcome, or the step-up's `/tap/<token>`) is a whole-page navigation instead, and a refusal
927
+ reloads the page, so a swap never lands a fragment the act did not render."""
928
+ if 300 <= resp.status_code < 400 and resp.headers.get("location"):
929
+ return Response(status_code=200, headers={"HX-Redirect": resp.headers["location"]})
930
+ if resp.status_code >= 400:
931
+ resp.headers["HX-Refresh"] = "true"
932
+ return resp
933
+
934
+
935
+ def _harden(resp: Response, path: str) -> Response:
936
+ """lifeboat.md §18 (v1.23): no referrer leaves this origin; no-store, nosniff, framed by no one.
937
+
938
+ `same-origin`, never `no-referrer`: under `no-referrer` a browser serialises a form POST's
939
+ Origin as `null` (Fetch, "serializing a request origin"), and the guard refuses any POST whose
940
+ Origin is not this one, so every act would fail in Chromium and Firefox (#130)."""
941
+ resp.headers["Referrer-Policy"] = "same-origin"
942
+ resp.headers["Cache-Control"] = "no-store"
943
+ resp.headers["X-Content-Type-Options"] = "nosniff"
944
+ resp.headers["X-Frame-Options"] = "DENY"
945
+ # One CSP for every response (§18): styles and scripts from this origin only. The hosted
946
+ # tap links /static/tap.css rather than carrying the CLI tap page's inline style.
947
+ resp.headers["Content-Security-Policy"] = (
948
+ "default-src 'none'; script-src 'self'; connect-src 'self'; style-src 'self'; "
949
+ "img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
950
+ )
951
+ return resp
952
+
953
+
954
+ def _tap_empty() -> str:
955
+ return (
956
+ "<!doctype html><html lang=en><head><meta charset=utf-8><title>egzos · presence</title>"
957
+ f"</head><body><main><h1>{S['tap.empty']}</h1></main></body></html>"
958
+ )
959
+
960
+
961
+ _LOCKED = (
962
+ "<!doctype html><html lang=en><head><meta charset=utf-8><title>egzos</title></head><body>"
963
+ "<main><h1>Nothing here.</h1></main></body></html>"
964
+ )
965
+ _REFUSED = _LOCKED