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.
- egzos/__init__.py +11 -0
- egzos/_ids.py +29 -0
- egzos/_signals.py +39 -0
- egzos/_term.py +33 -0
- egzos/_types.py +1023 -0
- egzos/api/__init__.py +150 -0
- egzos/api/app.py +1574 -0
- egzos/api/blobs.py +92 -0
- egzos/api/throttle.py +190 -0
- egzos/auth.py +176 -0
- egzos/authz/__init__.py +5 -0
- egzos/authz/presence.py +778 -0
- egzos/authz/values.py +32 -0
- egzos/backends/__init__.py +8 -0
- egzos/backends/base.py +91 -0
- egzos/backends/postgres.py +490 -0
- egzos/backends/sqlite.py +524 -0
- egzos/binding.py +309 -0
- egzos/cli/__init__.py +1092 -0
- egzos/cli/__main__.py +11 -0
- egzos/confirm.py +455 -0
- egzos/container.py +222 -0
- egzos/identity.py +1104 -0
- egzos/ledger.py +167 -0
- egzos/mcp/__init__.py +3 -0
- egzos/mcp/http.py +90 -0
- egzos/mcp/server.py +287 -0
- egzos/model.py +242 -0
- egzos/py.typed +0 -0
- egzos/resolver.py +115 -0
- egzos/store/__init__.py +10 -0
- egzos/store/autotitle.py +31 -0
- egzos/store/blobs.py +120 -0
- egzos/store/find.py +120 -0
- egzos/store/items.py +233 -0
- egzos/store/nodes.py +193 -0
- egzos/store/objects.py +143 -0
- egzos/store/uploads.py +369 -0
- egzos/trust.py +675 -0
- egzos/web/__init__.py +88 -0
- egzos/web/app.py +965 -0
- egzos/web/static/htmx.LICENSE +13 -0
- egzos/web/static/htmx.min.js +1 -0
- egzos/web/static/lifeboat.css +140 -0
- egzos/web/static/lifeboat.js +12 -0
- egzos/web/strings.py +133 -0
- egzos/web/templates/_manifest_row.html +3 -0
- egzos/web/templates/_shell.html +29 -0
- egzos/web/templates/_window.html +7 -0
- egzos/web/templates/base.html +24 -0
- egzos/web/templates/error.html +10 -0
- egzos/web/templates/home.html +39 -0
- egzos/web/templates/item.html +91 -0
- egzos/web/templates/notfound.html +6 -0
- egzos/web/templates/pending.html +107 -0
- egzos/web/tokens.css +294 -0
- egzoscore-0.2.0.dist-info/METADATA +135 -0
- egzoscore-0.2.0.dist-info/RECORD +62 -0
- egzoscore-0.2.0.dist-info/WHEEL +4 -0
- egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
- egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
- egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
egzos/authz/presence.py
ADDED
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
# Copyright 2026 Ali Sasanian
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
|
|
3
|
+
"""
|
|
4
|
+
The step-up tap, MVP cut (spec/design/step-up-tap-and-pending-approval.md §2, lifeboat baseline).
|
|
5
|
+
|
|
6
|
+
A human-only act does not happen on a terminal's or a form's say-so. The container serves a
|
|
7
|
+
one-shot page at `/tap/<token>` (an opaque single-use token, no parameters, no referrer off-origin, no-store)
|
|
8
|
+
with §2.2's content — the container and viewer lines, what moves, who will see it and the
|
|
9
|
+
consequence, the presence block — and waits for a decision: *Sign and approve* then *Confirm
|
|
10
|
+
signature* within 10 s, *Approve without a window* then the same confirm, or *Deny* (one press).
|
|
11
|
+
|
|
12
|
+
The CLI (`trust approve` / `trust deny`) opens a loopback server just for the page. `Tap` is
|
|
13
|
+
host-agnostic (`get` / `post` / `live`), so the lifeboat can serve the same page when it lands.
|
|
14
|
+
|
|
15
|
+
Every presence check is one `step_up` entry, whatever its outcome (`approved`, `denied`, `expired`,
|
|
16
|
+
`unavailable`, or `window` when an open window covered it), with the source → destination ring
|
|
17
|
+
pair. With `step_up.window_seconds` set, a signature opens a window for that ring pair BOUNDED TO
|
|
18
|
+
THE MANIFEST'S SHAPE (up to K items of the signed kinds), read back from the chain; `egzoscore trust
|
|
19
|
+
close-window` appends the entry that ends every window. The policy defaults to the contract's 300 s
|
|
20
|
+
(container.md §8); `EGZOS_STEP_UP_WINDOW_SECONDS=0` makes every act tap, and #117 holds the default.
|
|
21
|
+
|
|
22
|
+
The CLI's page opens in the browser; its URL is printed only when no browser could be opened AND
|
|
23
|
+
stdout is a terminal: an agent's shell tool is not a terminal, so it never receives a URL to press.
|
|
24
|
+
|
|
25
|
+
The page is a plain `<form method=post>` two-step on a loopback `http.server`: the tap spec's
|
|
26
|
+
baseline, which "works without htmx" (§18); the htmx enhancement is optional there.
|
|
27
|
+
|
|
28
|
+
Residuals, named: a process running as the user that drives a browser, fakes a terminal, or appends
|
|
29
|
+
to the chain directly can do what the user can — a shell running as the user is the user. The URL
|
|
30
|
+
travels in the browser launcher's argv, readable by other local users on a shared host, as the
|
|
31
|
+
client secret does in `claude mcp add`'s argv under `connect --apply`. The armed confirm reverts
|
|
32
|
+
on 10 s only: §2.3 also names Escape and focus leaving the control, which a page with no script
|
|
33
|
+
cannot observe — design-gap #119 holds the choice. This CLI host serves one answer after a
|
|
34
|
+
decision and closes: the window's close time is stated once in the outcome line and *Close window
|
|
35
|
+
now* is `egzoscore trust close-window`; the spec frames only the lifeboat and flagship hosts, so the
|
|
36
|
+
CLI host's post-decision state, title wrap and measure are design-gap #126. Audience
|
|
37
|
+
chips carry no contractor / external flag: tokens record no principal class yet. OS-backed
|
|
38
|
+
presence (WebAuthn / platform authenticator) is the stronger tier the spec names for later.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import html
|
|
44
|
+
import os
|
|
45
|
+
import secrets
|
|
46
|
+
import sys
|
|
47
|
+
import threading
|
|
48
|
+
import time
|
|
49
|
+
import webbrowser
|
|
50
|
+
from datetime import UTC, datetime
|
|
51
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
52
|
+
from typing import Any
|
|
53
|
+
from urllib.parse import parse_qs
|
|
54
|
+
|
|
55
|
+
from egzos._term import safe
|
|
56
|
+
from egzos._types import CONTAINER_CONFIG_DEFAULTS
|
|
57
|
+
from egzos.authz import values
|
|
58
|
+
from egzos.container import OWNER, Container
|
|
59
|
+
from egzos.model import Token
|
|
60
|
+
|
|
61
|
+
# The one default, from the typed contract (container.md §8, 300 s for a window bounded to the
|
|
62
|
+
# manifest's shape): no second constant beside it. `EGZOS_STEP_UP_WINDOW_SECONDS=0` opts out.
|
|
63
|
+
DEFAULT_WINDOW_SECONDS = CONTAINER_CONFIG_DEFAULTS["step_up_window_seconds"]
|
|
64
|
+
ARM_SECONDS = 10
|
|
65
|
+
CHIPS = 6
|
|
66
|
+
ROWS = 12 # §2.2 item 5: 12 rows, then `+ N more`
|
|
67
|
+
REASON_MAX = 480 # §2.2 item 4: then `…` and *Show full reason*
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def window_seconds() -> int:
|
|
71
|
+
"""`step_up.window_seconds` (container.md §8). `0` is a value: no window, every act taps."""
|
|
72
|
+
raw = os.environ.get("EGZOS_STEP_UP_WINDOW_SECONDS")
|
|
73
|
+
if raw is None or raw == "":
|
|
74
|
+
return DEFAULT_WINDOW_SECONDS
|
|
75
|
+
seconds = max(0, int(raw))
|
|
76
|
+
# The policy is in whole minutes (§13 `presence.text` has only the N-minute form): round up.
|
|
77
|
+
return -(-seconds // 60) * 60
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def tap_timeout() -> float:
|
|
81
|
+
return float(os.environ.get("EGZOS_TAP_TIMEOUT_SECONDS") or 180)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def is_terminal() -> bool:
|
|
85
|
+
"""Whether a printed URL would reach a person at a terminal rather than a program's pipe."""
|
|
86
|
+
try:
|
|
87
|
+
return sys.stdout.isatty()
|
|
88
|
+
except (AttributeError, ValueError):
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _now() -> float:
|
|
93
|
+
return time.time()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _iso(ts: float) -> str:
|
|
97
|
+
return datetime.fromtimestamp(ts, UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _clock(ts: float) -> str:
|
|
101
|
+
return datetime.fromtimestamp(ts).astimezone().strftime("%H:%M:%S")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _local(iso: str | None) -> str:
|
|
105
|
+
"""A stored UTC stamp as the page's other clocks read: local `HH:MM:SS`."""
|
|
106
|
+
try:
|
|
107
|
+
return _clock(datetime.strptime(iso or "", "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC).timestamp())
|
|
108
|
+
except ValueError:
|
|
109
|
+
return ""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _since(ts: float) -> str:
|
|
113
|
+
"""`HH:MM (UTC−07:00)` — local time with its zone, as `shell.viewer` renders it."""
|
|
114
|
+
t = datetime.fromtimestamp(ts).astimezone()
|
|
115
|
+
off = t.strftime("%z") or "+0000"
|
|
116
|
+
sign = "−" if off[0] == "-" else "+"
|
|
117
|
+
return f"{t.strftime('%H:%M')} (UTC{sign}{off[1:3]}:{off[3:5]})"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def pair_of(act: dict[str, Any]) -> tuple[str, str]:
|
|
121
|
+
"""The source → destination RING pair (types, not paths) a window is keyed on."""
|
|
122
|
+
pair = act.get("pair") or (act["from"], act["to"])
|
|
123
|
+
return (pair[0], pair[1])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def shape_of(act: dict[str, Any]) -> dict[str, Any]:
|
|
127
|
+
"""The manifest's shape a window is bounded to: how many items, of which kinds."""
|
|
128
|
+
items = act.get("items", [])
|
|
129
|
+
return {"max_items": len(items), "kinds": sorted({str(r.get("kind")) for r in items})}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _fits(shape: dict[str, Any], bound: dict[str, Any] | None) -> bool:
|
|
133
|
+
if not bound:
|
|
134
|
+
return False # a window with no recorded shape covers nothing
|
|
135
|
+
return shape["max_items"] <= bound.get("max_items", 0) and set(shape["kinds"]) <= set(
|
|
136
|
+
bound.get("kinds", [])
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# --- what a decision is about ---------------------------------------------------------------------
|
|
141
|
+
def short_id(value: str) -> str:
|
|
142
|
+
"""The tap spec §5 id: first 8 characters, ` … `, last 4; the full id goes in `title`."""
|
|
143
|
+
return f"{value[:8]} … {value[-4:]}" if len(value) > 12 else value
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def build_act(c: Container, ref: str, *, token: Token) -> dict[str, Any] | None:
|
|
147
|
+
"""The tap's content for an open proposal or an unverified item; None if there is nothing to
|
|
148
|
+
decide. Everything the page shows comes from here, for the CLI and the lifeboat alike.
|
|
149
|
+
|
|
150
|
+
`token` is the deciding token, and the content is scoped to it (#131): a proposal whose ends
|
|
151
|
+
it does not both cover, or an item it does not cover, is None, the answer for no ref at all.
|
|
152
|
+
The page shows paths, titles and the audience, so building it is a read."""
|
|
153
|
+
prop = c.backend.get_proposal(ref)
|
|
154
|
+
if prop and prop.get("status") == "open":
|
|
155
|
+
if not c.trust.decides_over(token, prop):
|
|
156
|
+
return None
|
|
157
|
+
frm, to = c.backend.get_node(prop["from"]), c.backend.get_node(prop["to"])
|
|
158
|
+
items = [i for i in (c.backend.get(x) for x in prop["items"]) if i]
|
|
159
|
+
by = prop.get("proposed_by", {})
|
|
160
|
+
return {
|
|
161
|
+
"kind": "proposal",
|
|
162
|
+
"subject": prop["id"],
|
|
163
|
+
"ref": "PROPOSAL",
|
|
164
|
+
"filed": _local(prop.get("created_at")),
|
|
165
|
+
"title": f"Move {len(items)} items outward: {prop['from_path']} → {prop['to_path']}",
|
|
166
|
+
"requester": f"agent:{by['client']}" if by.get("principal") == "client" else "you",
|
|
167
|
+
"reason": prop.get("reason"),
|
|
168
|
+
"items": [
|
|
169
|
+
{"kind": i.kind, "title": i.content.get("auto_title", i.id),
|
|
170
|
+
"quarantined": i.status == "quarantined",
|
|
171
|
+
"now": i.status,
|
|
172
|
+
"reset": by.get("principal") != "interactive" and i.status == "verified",
|
|
173
|
+
"after": (
|
|
174
|
+
"unverified"
|
|
175
|
+
if by.get("principal") != "interactive" and i.status == "verified"
|
|
176
|
+
else i.status
|
|
177
|
+
),
|
|
178
|
+
"trust": (
|
|
179
|
+
"verified → unverified · agent-run move resets"
|
|
180
|
+
if by.get("principal") != "interactive" and i.status == "verified"
|
|
181
|
+
else f"{i.status} → {i.status}"
|
|
182
|
+
)}
|
|
183
|
+
for i in items
|
|
184
|
+
],
|
|
185
|
+
"audience": prop.get("audience", []),
|
|
186
|
+
"dest": prop["to_path"],
|
|
187
|
+
# §4 R6: the sentence follows the destination's ring — an exo room's audience is
|
|
188
|
+
# its named external parties, not a subtree.
|
|
189
|
+
"consequence": (
|
|
190
|
+
TAP_COPY["consequence.exo"].format(name=to.name)
|
|
191
|
+
if to and to.type == "exo"
|
|
192
|
+
else TAP_COPY["consequence"].format(destination=prop["to_path"])
|
|
193
|
+
),
|
|
194
|
+
"from": prop["from_path"],
|
|
195
|
+
"to": prop["to_path"],
|
|
196
|
+
"pair": (frm.type if frm else "?", to.type if to else "?"),
|
|
197
|
+
"blocked": (
|
|
198
|
+
"Contains a quarantined item. It cannot move." if any(i.status == "quarantined" for i in items) else None
|
|
199
|
+
),
|
|
200
|
+
}
|
|
201
|
+
item = c.backend.get(ref)
|
|
202
|
+
node = c.backend.get_node(item.scope) if item else None
|
|
203
|
+
if item and node and item.status == "unverified" and c.trust.covers(token, node):
|
|
204
|
+
path = c.nodes.path(node)
|
|
205
|
+
client = (item.provenance or {}).get("client")
|
|
206
|
+
return {
|
|
207
|
+
"kind": "item",
|
|
208
|
+
"subject": item.id,
|
|
209
|
+
"ref": "ITEM",
|
|
210
|
+
"filed": None,
|
|
211
|
+
# Interim, named on design-gap #122: the tap spec's §2.2 item 3 titles a proposal
|
|
212
|
+
# (a ring pair) and has no title for approve.pending.
|
|
213
|
+
"title": f"Mark verified: “{item.content.get('auto_title', item.id)}” at {path}",
|
|
214
|
+
"requester": f"agent:{client}" if client and client != "cli" else "you",
|
|
215
|
+
"reason": None,
|
|
216
|
+
"items": [{"kind": item.kind, "title": item.content.get("auto_title", item.id),
|
|
217
|
+
"trust": "unverified → verified", "now": "unverified",
|
|
218
|
+
"after": "verified", "reset": False, "quarantined": False}],
|
|
219
|
+
"audience": c.trust.audience(node),
|
|
220
|
+
"dest": path,
|
|
221
|
+
"consequence": None,
|
|
222
|
+
"from": path,
|
|
223
|
+
"to": path,
|
|
224
|
+
"pair": (node.type, node.type),
|
|
225
|
+
}
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class Presence:
|
|
230
|
+
def __init__(self, container: Container):
|
|
231
|
+
self.c = container
|
|
232
|
+
|
|
233
|
+
# -- windows, read back from the chain ---------------------------------------------------------
|
|
234
|
+
def _recent_step_ups(self, seconds: int) -> list[dict[str, Any]]:
|
|
235
|
+
"""`step_up` entries newer than `seconds` ago, newest first. Pages back through the tail
|
|
236
|
+
until it is older than that, so a busy chain cannot hide a window or a close."""
|
|
237
|
+
since = _iso(_now() - seconds - 1)
|
|
238
|
+
n = 256
|
|
239
|
+
while True:
|
|
240
|
+
rows = self.c.ledger.tail(n)
|
|
241
|
+
if len(rows) < n or not rows or rows[0]["ts"] < since:
|
|
242
|
+
break
|
|
243
|
+
n *= 4
|
|
244
|
+
return [r for r in reversed(rows) if r["ts"] >= since and r["event"] == "step_up"]
|
|
245
|
+
|
|
246
|
+
def window_open(self, pair: tuple[str, str], shape: dict[str, Any] | None = None) -> bool:
|
|
247
|
+
"""Whether an open window covers this ring pair — and, given a shape, this many items of
|
|
248
|
+
these kinds. A window only ever covers what fits the shape that was signed."""
|
|
249
|
+
seconds = window_seconds()
|
|
250
|
+
if seconds == 0:
|
|
251
|
+
return False
|
|
252
|
+
now = _iso(_now())
|
|
253
|
+
for e in self._recent_step_ups(seconds):
|
|
254
|
+
d = e.get("details") or {}
|
|
255
|
+
if d.get("outcome") == "closed":
|
|
256
|
+
return False # Close window now ends every window opened before it
|
|
257
|
+
if (
|
|
258
|
+
d.get("outcome") == "approved"
|
|
259
|
+
and d.get("pair") == list(pair)
|
|
260
|
+
and (d.get("window_closes") or "") > now
|
|
261
|
+
and (shape is None or _fits(shape, d.get("shape")))
|
|
262
|
+
):
|
|
263
|
+
return True
|
|
264
|
+
return False
|
|
265
|
+
|
|
266
|
+
def window_status(self) -> dict[str, Any] | None:
|
|
267
|
+
"""For the lifeboat shell (R1): the newest signed window, open or lapsed. A lapsed window
|
|
268
|
+
shows until the next act or tap, i.e. until a newer presence check is on the chain."""
|
|
269
|
+
seconds = window_seconds()
|
|
270
|
+
if seconds == 0:
|
|
271
|
+
return None
|
|
272
|
+
now = _iso(_now())
|
|
273
|
+
for e in self._recent_step_ups(max(seconds, 3600)):
|
|
274
|
+
d = e.get("details") or {}
|
|
275
|
+
if d.get("outcome") == "window":
|
|
276
|
+
continue # a pass inside the window; the window itself is further back
|
|
277
|
+
if d.get("outcome") != "approved" or not d.get("window_closes"):
|
|
278
|
+
return None # the newest act opened no window, or closed them
|
|
279
|
+
if d["window_closes"] > now:
|
|
280
|
+
return {"state": "open", "pair": d.get("pair"), "closes": d["window_closes"]}
|
|
281
|
+
return {"state": "lapsed", "at": d["window_closes"]}
|
|
282
|
+
return None
|
|
283
|
+
|
|
284
|
+
def covers(self, act: dict[str, Any]) -> bool:
|
|
285
|
+
# A manifest holding a quarantined item cannot be approved (R5): no window stands in for it.
|
|
286
|
+
if act.get("blocked"):
|
|
287
|
+
return False
|
|
288
|
+
return self.window_open(pair_of(act), shape_of(act))
|
|
289
|
+
|
|
290
|
+
def act_failed(self, act: dict[str, Any], error: BaseException, *,
|
|
291
|
+
reason: str = "act failed", actor: str = OWNER) -> None:
|
|
292
|
+
"""The presence was proven and the act did not land: it failed and rolled back whole, or
|
|
293
|
+
the engine refused it. The chain says so, and the window that signature opened closes
|
|
294
|
+
with it, so neither a failure nor a refusal leaves one open."""
|
|
295
|
+
self.c.ledger.append(
|
|
296
|
+
"step_up", actor=actor, principal="interactive", subject=act.get("subject"),
|
|
297
|
+
via="tap", outcome="closed", reason=reason, error=type(error).__name__,
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
def close_windows(self, *, actor: str = OWNER) -> None:
|
|
301
|
+
self.c.ledger.append(
|
|
302
|
+
"step_up", actor=actor, principal="interactive", via="close", outcome="closed"
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
def record(
|
|
306
|
+
self,
|
|
307
|
+
act: dict[str, Any],
|
|
308
|
+
*,
|
|
309
|
+
via: str,
|
|
310
|
+
outcome: str,
|
|
311
|
+
windowed: bool = False,
|
|
312
|
+
actor: str = OWNER,
|
|
313
|
+
) -> str | None:
|
|
314
|
+
"""One `step_up` per presence check, whatever the outcome. Returns the window's close."""
|
|
315
|
+
closes = None
|
|
316
|
+
seconds = window_seconds()
|
|
317
|
+
if outcome == "approved" and windowed and seconds:
|
|
318
|
+
closes = _iso(_now() + seconds)
|
|
319
|
+
self.c.ledger.append(
|
|
320
|
+
"step_up",
|
|
321
|
+
actor=actor,
|
|
322
|
+
principal="interactive",
|
|
323
|
+
subject=act.get("subject"),
|
|
324
|
+
via=via,
|
|
325
|
+
outcome=outcome,
|
|
326
|
+
pair=list(pair_of(act)),
|
|
327
|
+
shape=shape_of(act) if closes else None,
|
|
328
|
+
window_closes=closes,
|
|
329
|
+
)
|
|
330
|
+
return closes
|
|
331
|
+
|
|
332
|
+
# -- the CLI's tap: a loopback server for one page ----------------------------------------------
|
|
333
|
+
def require(self, act: dict[str, Any], *, timeout: float | None = None, opener=None,
|
|
334
|
+
decide=None) -> str:
|
|
335
|
+
"""Ask for presence. Returns "window", "approved", "denied", "expired" or "unavailable".
|
|
336
|
+
|
|
337
|
+
`decide(outcome, windowed, closes) -> str` performs the decision while the page waits and returns
|
|
338
|
+
the outcome line the page then shows — the container's answer, never a prediction. The
|
|
339
|
+
`step_up` entry is appended first, so the chain reads presence, then the act."""
|
|
340
|
+
if timeout is None:
|
|
341
|
+
timeout = tap_timeout()
|
|
342
|
+
if self.covers(act):
|
|
343
|
+
self.record(act, via="window", outcome="window")
|
|
344
|
+
return "window"
|
|
345
|
+
httpd = HTTPServer(("127.0.0.1", 0), BaseHTTPRequestHandler)
|
|
346
|
+
host = f"127.0.0.1:{httpd.server_address[1]}"
|
|
347
|
+
def decided(outcome: str, windowed: bool) -> str:
|
|
348
|
+
closes = self.record(act, via="tap", outcome=outcome, windowed=windowed)
|
|
349
|
+
try:
|
|
350
|
+
if decide is not None:
|
|
351
|
+
return decide(outcome, windowed, closes)
|
|
352
|
+
return outcome_text(act, outcome, closes=closes)
|
|
353
|
+
except Exception as e:
|
|
354
|
+
self.act_failed(act, e)
|
|
355
|
+
print(safe(f"That didn't go through. Nothing changed. ({e})"),
|
|
356
|
+
file=sys.stderr, flush=True)
|
|
357
|
+
raise
|
|
358
|
+
|
|
359
|
+
tap = Tap(act, container=self.c.home.name, host=host, decide=decided)
|
|
360
|
+
httpd.RequestHandlerClass = tap.handler()
|
|
361
|
+
url = f"http://{host}/tap/{tap.token}"
|
|
362
|
+
# The opener runs on its own thread: some browsers' launchers wait for the browser, and the
|
|
363
|
+
# page cannot be served until this thread starts answering requests below.
|
|
364
|
+
result: list[bool] = []
|
|
365
|
+
launcher = threading.Thread(
|
|
366
|
+
target=lambda: result.append(bool((opener or webbrowser.open)(url))), daemon=True
|
|
367
|
+
)
|
|
368
|
+
launcher.start()
|
|
369
|
+
launcher.join(2.0)
|
|
370
|
+
opened = result[0] if result else True
|
|
371
|
+
if opened:
|
|
372
|
+
print("A presence check opened in your browser. Decide there.", flush=True)
|
|
373
|
+
elif is_terminal():
|
|
374
|
+
print(f"Open this to decide (it works once):\n {url}", flush=True)
|
|
375
|
+
else:
|
|
376
|
+
httpd.server_close()
|
|
377
|
+
print(
|
|
378
|
+
"No browser could be opened and this is not a terminal, so the presence check "
|
|
379
|
+
"cannot be shown. Run the command from a terminal on this machine.",
|
|
380
|
+
flush=True,
|
|
381
|
+
)
|
|
382
|
+
self.record(act, via="tap", outcome="unavailable")
|
|
383
|
+
return "unavailable"
|
|
384
|
+
httpd.timeout = 1.0
|
|
385
|
+
deadline = _now() + timeout
|
|
386
|
+
while tap.outcome is None and _now() < deadline:
|
|
387
|
+
httpd.handle_request()
|
|
388
|
+
httpd.server_close()
|
|
389
|
+
if tap.outcome is None:
|
|
390
|
+
self.record(act, via="tap", outcome="expired")
|
|
391
|
+
return tap.outcome or "expired"
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
# --- the page --------------------------------------------------------------------------------------
|
|
395
|
+
# The page consumes the design tokens (spec/design/tokens.css, vendored at egzos/web/tokens.css) as
|
|
396
|
+
# CSS variables, inlined because the page's CSP loads nothing; the scheme follows tokens.css's own
|
|
397
|
+
# rule (data-scheme, else prefers-color-scheme). No literal colour lives here.
|
|
398
|
+
TAP_STYLE = """
|
|
399
|
+
body{margin:0;background:var(--egz-canvas);color:var(--egz-ink);font-family:var(--egz-font-ui);
|
|
400
|
+
line-height:var(--egz-lh)}
|
|
401
|
+
main{max-width:720px;margin:var(--egz-sp-6) auto;padding:0 var(--egz-sp-4)}
|
|
402
|
+
h1{font-size:var(--egz-fs-6);font-weight:var(--egz-w-semibold)}
|
|
403
|
+
h2{font-size:var(--egz-fs-4);font-weight:var(--egz-w-semibold)}
|
|
404
|
+
.stamp{font-family:var(--egz-font-mono);font-size:var(--egz-fs-1);text-transform:uppercase;
|
|
405
|
+
padding:0 var(--egz-sp-1);
|
|
406
|
+
border:var(--egz-hair) solid var(--egz-ink)}
|
|
407
|
+
.stamp--verified{background:var(--egz-ink);color:var(--egz-canvas)}
|
|
408
|
+
.stamp--quarantined{color:var(--egz-alarm);border-color:var(--egz-alarm)}
|
|
409
|
+
.ink3{color:var(--egz-ink-3)}
|
|
410
|
+
.chips{list-style:none;padding:0;display:flex;flex-wrap:wrap;gap:var(--egz-sp-2)}
|
|
411
|
+
.attr{font-family:var(--egz-font-mono);font-size:var(--egz-fs-2)}
|
|
412
|
+
summary{cursor:pointer;font-family:var(--egz-font-mono);font-size:var(--egz-fs-2);min-height:44px;
|
|
413
|
+
padding:var(--egz-sp-3) 0;box-sizing:border-box}
|
|
414
|
+
.ref,.shell{font-family:var(--egz-font-mono);text-transform:uppercase;
|
|
415
|
+
letter-spacing:var(--egz-tracking-caps);font-size:var(--egz-fs-1);
|
|
416
|
+
font-feature-settings:var(--egz-tabular)}
|
|
417
|
+
.ref code{font:inherit}
|
|
418
|
+
.shell{text-transform:none;letter-spacing:0;border-bottom:var(--egz-hair) solid var(--egz-rule-soft);
|
|
419
|
+
margin:0;padding:var(--egz-sp-1) 0}
|
|
420
|
+
.box,.note,.alarm,button{box-shadow:var(--egz-off) var(--egz-off) 0 var(--egz-shadow-ink)}
|
|
421
|
+
button,summary,.box,.note,.alarm,.chip,.stamp,table{border-radius:var(--egz-radius)}
|
|
422
|
+
button{-webkit-appearance:none;appearance:none}
|
|
423
|
+
.box{border:var(--egz-bw) solid var(--egz-rule);padding:var(--egz-sp-4);
|
|
424
|
+
margin:var(--egz-sp-4) var(--egz-off) calc(var(--egz-sp-4) + var(--egz-off)) 0}
|
|
425
|
+
.chip{display:inline-block;border:var(--egz-hair) solid var(--egz-rule);
|
|
426
|
+
padding:var(--egz-sp-1) var(--egz-sp-2);margin:0 var(--egz-sp-2) var(--egz-sp-2) 0;
|
|
427
|
+
font-family:var(--egz-font-mono);font-size:var(--egz-fs-2)}
|
|
428
|
+
table{width:100%;border-collapse:collapse}
|
|
429
|
+
th{text-align:left;padding:var(--egz-sp-2) var(--egz-sp-1)}
|
|
430
|
+
td{padding:var(--egz-sp-2) var(--egz-sp-1);border-bottom:var(--egz-hair) solid var(--egz-rule-soft)}
|
|
431
|
+
button{min-height:44px;padding:0 var(--egz-sp-4);border:var(--egz-bw) solid var(--egz-rule);
|
|
432
|
+
background:var(--egz-canvas);color:var(--egz-ink);font:inherit;cursor:pointer;
|
|
433
|
+
margin:0 var(--egz-sp-2) var(--egz-sp-2) 0}
|
|
434
|
+
button.act{background:var(--egz-act);color:var(--egz-act-on);border-color:var(--egz-act)}
|
|
435
|
+
button.ghost{border-color:transparent;text-decoration:underline;box-shadow:none}
|
|
436
|
+
button:active{transform:translate(var(--egz-off),var(--egz-off));box-shadow:none}
|
|
437
|
+
button:focus-visible,a:focus-visible{outline:var(--egz-focus);outline-offset:3px} /* tokens.css --egz-focus */
|
|
438
|
+
.note{border:var(--egz-bw) solid var(--egz-act);padding:var(--egz-sp-3);
|
|
439
|
+
margin:0 var(--egz-off) var(--egz-sp-4) 0}
|
|
440
|
+
.alarm{border:var(--egz-bw) solid var(--egz-alarm);color:var(--egz-alarm);padding:var(--egz-sp-3);
|
|
441
|
+
margin:0 var(--egz-off) var(--egz-sp-4) 0}
|
|
442
|
+
.qrow td{color:var(--egz-alarm)}
|
|
443
|
+
.terms{font-family:var(--egz-font-mono);font-feature-settings:var(--egz-tabular);
|
|
444
|
+
font-size:var(--egz-fs-2)}
|
|
445
|
+
"""
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def tap_css() -> str:
|
|
449
|
+
"""The tap page's whole stylesheet: the tokens and TAP_STYLE, for a host that serves it."""
|
|
450
|
+
return _tokens_css() + TAP_STYLE
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _style(stylesheet: str | None) -> str:
|
|
454
|
+
"""Inline for the CLI's own one-page server; a link to the host's copy of `tap_css()` when the
|
|
455
|
+
lifeboat hosts the page, so the lifeboat's CSP stays `style-src 'self'` (lifeboat.md §18)."""
|
|
456
|
+
if stylesheet:
|
|
457
|
+
return f'<link rel=stylesheet href="{_e(stylesheet)}">'
|
|
458
|
+
return f"<style>{_tokens_css()}{TAP_STYLE}</style>"
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _tokens_css() -> str:
|
|
462
|
+
from importlib import resources
|
|
463
|
+
|
|
464
|
+
return resources.files("egzos.web").joinpath("tokens.css").read_text(encoding="utf-8")
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _e(value: Any) -> str:
|
|
468
|
+
return html.escape("" if value is None else str(value), quote=True)
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def presence_text(act: dict[str, Any], seconds: int) -> str:
|
|
472
|
+
"""§13 `presence.text` / `presence.zero`, verbatim."""
|
|
473
|
+
if not seconds:
|
|
474
|
+
return "Signing proves you are here. No window opens."
|
|
475
|
+
frm, to = act["from"], act["to"]
|
|
476
|
+
shape = shape_of(act)
|
|
477
|
+
return (
|
|
478
|
+
f"Approving is a human-only act. Signing proves you are here and opens a "
|
|
479
|
+
f"{seconds // 60}-minute window "
|
|
480
|
+
f"for {frm} → {to}, bounded to this shape: up to {shape['max_items']} items of kinds "
|
|
481
|
+
f"{', '.join(shape['kinds'])}. Moves inside the window pass without asking and are logged."
|
|
482
|
+
)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
TAP_COPY = {
|
|
486
|
+
"outcome.approved": "Signed at {at} by {user}. {n} items at {destination}, {trust}. "
|
|
487
|
+
"Window open until {closes}.",
|
|
488
|
+
"outcome.approved.nowindow": "Signed at {at} by {user}. {n} items at {destination}, {trust}. "
|
|
489
|
+
"No window opened.",
|
|
490
|
+
"outcome.denied": "Denied at {at} by {user}. The items never existed at {destination}. "
|
|
491
|
+
"Logged. Staged bytes kept 30 days cold.",
|
|
492
|
+
"outcome.invalid": "This proposal is no longer valid.",
|
|
493
|
+
"act.promoted": "Promoted at {at} by {user}. Served as verified from now on.",
|
|
494
|
+
"tap.invalid": "This request is no longer valid.",
|
|
495
|
+
"tap.empty": "Nothing is waiting for you.",
|
|
496
|
+
"act.confirm.sr": "Press again to confirm.",
|
|
497
|
+
"act.error": "That didn't go through. Nothing changed. Try again.",
|
|
498
|
+
"consequence": "Consequence. Everything under {destination} inherits this — every team, "
|
|
499
|
+
"project and thread, now and in future.",
|
|
500
|
+
"consequence.exo": "Consequence. Everything in the exo room {name} sees this — every named "
|
|
501
|
+
"external party, now and in future.",
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def outcome_text(act: dict[str, Any], outcome: str, *, closes: str | None,
|
|
506
|
+
landed: list[str] | None = None) -> str:
|
|
507
|
+
"""The canonical outcome line for a decision the container has answered."""
|
|
508
|
+
at = _clock(_now())
|
|
509
|
+
if outcome == "denied":
|
|
510
|
+
if act.get("kind") == "proposal":
|
|
511
|
+
return TAP_COPY["outcome.denied"].format(at=at, user=OWNER, destination=act["dest"])
|
|
512
|
+
return TAP_COPY["tap.invalid"]
|
|
513
|
+
if act.get("kind") != "proposal":
|
|
514
|
+
# lifeboat.md §13's string for this act; the tap spec's §13 has none (#122).
|
|
515
|
+
return TAP_COPY["act.promoted"].format(at=at, user=OWNER)
|
|
516
|
+
trust = ", ".join(sorted(set(landed or [r.get("after", "unverified")
|
|
517
|
+
for r in act.get("items", [])])))
|
|
518
|
+
key = "outcome.approved" if closes else "outcome.approved.nowindow"
|
|
519
|
+
return TAP_COPY[key].format(at=at, user=OWNER, n=len(act.get("items", [])),
|
|
520
|
+
destination=act["dest"], trust=trust,
|
|
521
|
+
closes=_local(closes) if closes else "")
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _chip(a: dict[str, Any]) -> str:
|
|
525
|
+
who = a.get("owner") if a.get("principal") == "interactive" else f"agent:{a.get('client')}"
|
|
526
|
+
return f"{who} · {a.get('role')}"
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
class Tap:
|
|
530
|
+
"""One page, one decision. The token is single-use: after a decision every request is refused."""
|
|
531
|
+
|
|
532
|
+
def __init__(self, act: dict[str, Any], *, container: str = "egzos", host: str = "",
|
|
533
|
+
decide=None, stylesheet: str | None = None):
|
|
534
|
+
self.act = act
|
|
535
|
+
self.stylesheet = stylesheet
|
|
536
|
+
# The host's callback: performs the decision and returns the container's outcome line, so
|
|
537
|
+
# the page never shows an outcome before the container has answered (lifeboat.md §15).
|
|
538
|
+
self.decide = decide
|
|
539
|
+
self.token = secrets.token_urlsafe(32)
|
|
540
|
+
self.container = container
|
|
541
|
+
self.host = host
|
|
542
|
+
self.opened = _now()
|
|
543
|
+
self.outcome: str | None = None
|
|
544
|
+
self.windowed = True
|
|
545
|
+
self.armed_until = 0.0
|
|
546
|
+
self.armed_mode = "window"
|
|
547
|
+
|
|
548
|
+
@property
|
|
549
|
+
def gate(self) -> bool:
|
|
550
|
+
"""A parked proposal (gate.confirm: approve or deny), not an item promotion."""
|
|
551
|
+
return self.act.get("kind") == "proposal"
|
|
552
|
+
|
|
553
|
+
def page(self, armed: bool, note: str = "", error: str = "") -> str:
|
|
554
|
+
a = self.act
|
|
555
|
+
e = _e
|
|
556
|
+
seconds = window_seconds()
|
|
557
|
+
def stamp(word: str) -> str:
|
|
558
|
+
return f"<span class='stamp stamp--{e(word)}'>{e(word)}</span>"
|
|
559
|
+
|
|
560
|
+
def row(r: dict[str, Any]) -> str:
|
|
561
|
+
if r.get("quarantined"): # R5: the row carries its stamp and reads red
|
|
562
|
+
return (f"<tr class=qrow><td>{e(r.get('kind'))}</td><td>{e(r.get('title'))}</td>"
|
|
563
|
+
f"<td>{stamp('quarantined')}</td><td>{stamp('quarantined')}</td></tr>")
|
|
564
|
+
now = r.get("now") or ""
|
|
565
|
+
after = r.get("after") or ""
|
|
566
|
+
note = " <span class=ink3>agent-run move resets</span>" if r.get("reset") else ""
|
|
567
|
+
return (f"<tr><td>{e(r.get('kind'))}</td><td>{e(r.get('title'))}</td>"
|
|
568
|
+
f"<td>{stamp(now)}</td><td>{stamp(after)}{note}</td></tr>")
|
|
569
|
+
|
|
570
|
+
head = ("<thead><tr><th scope=col>kind</th><th scope=col>item</th>"
|
|
571
|
+
"<th scope=col>trust now</th><th scope=col>after move</th></tr></thead>")
|
|
572
|
+
manifest = [row(r) for r in a.get("items", [])]
|
|
573
|
+
rows = f"<table>{head}<tbody>{''.join(manifest[:ROWS])}</tbody></table>"
|
|
574
|
+
if len(manifest) > ROWS: # expands in place, no script: a disclosure element
|
|
575
|
+
rows += (
|
|
576
|
+
f"<details><summary>+ {len(manifest) - ROWS} more</summary>"
|
|
577
|
+
f"<table><tbody>{''.join(manifest[ROWS:])}</tbody></table></details>"
|
|
578
|
+
)
|
|
579
|
+
reason = a.get("reason") or "(no reason given)"
|
|
580
|
+
said = f"“{e(reason)}”"
|
|
581
|
+
if len(reason) > REASON_MAX:
|
|
582
|
+
said = (
|
|
583
|
+
f"“{e(reason[:REASON_MAX])}…”<details><summary>Show full reason</summary>"
|
|
584
|
+
f"<p>“{e(reason)}”</p></details>"
|
|
585
|
+
)
|
|
586
|
+
audience = a.get("audience", [])
|
|
587
|
+
people = sum(1 for x in audience if x.get("principal") == "interactive")
|
|
588
|
+
agents = len(audience) - people
|
|
589
|
+
chips = "<ul class=chips aria-label=Audience>" + "".join(
|
|
590
|
+
f"<li>{e(_chip(x))}</li>" for x in audience[:CHIPS]
|
|
591
|
+
) + "</ul>"
|
|
592
|
+
if len(audience) > CHIPS:
|
|
593
|
+
chips += (
|
|
594
|
+
f"<details><summary>+ {len(audience) - CHIPS} more</summary><ul class=chips>"
|
|
595
|
+
+ "".join(f"<li>{e(_chip(x))}</li>" for x in audience[CHIPS:])
|
|
596
|
+
+ "</ul></details>"
|
|
597
|
+
)
|
|
598
|
+
consequence = (
|
|
599
|
+
f"<div class=box><p>{e(a['consequence'])}</p></div>" if a.get("consequence") else ""
|
|
600
|
+
)
|
|
601
|
+
terms = ""
|
|
602
|
+
if seconds:
|
|
603
|
+
terms = (
|
|
604
|
+
f"<p class=terms>window would close {_clock(_now() + seconds)} · org policy "
|
|
605
|
+
f"{seconds // 60}:{seconds % 60:02d} · close early at any time</p>"
|
|
606
|
+
)
|
|
607
|
+
blocked = a.get("blocked")
|
|
608
|
+
if blocked: # R5: the approve acts are absent, replaced by the red line
|
|
609
|
+
acts = f"<p class=alarm role=status>{e(blocked)}</p>"
|
|
610
|
+
elif armed:
|
|
611
|
+
acts = "<button name=step value=confirm class=act>Confirm signature</button>"
|
|
612
|
+
else:
|
|
613
|
+
acts = "<button name=step value=arm class=act>Sign and approve</button>"
|
|
614
|
+
if self.gate: # Deny is gate.confirm's; approve.pending has no deny (capabilities.md §4)
|
|
615
|
+
acts += "<button name=step value=deny>Deny</button>"
|
|
616
|
+
if seconds and not armed and not blocked:
|
|
617
|
+
acts += "<button name=step value=arm_once class=ghost>Approve without a window</button>"
|
|
618
|
+
return (
|
|
619
|
+
"<!doctype html><html lang=en><head><meta charset=utf-8>"
|
|
620
|
+
'<meta name=viewport content="width=device-width,initial-scale=1">'
|
|
621
|
+
# §2.3's 10 s revert, without script: the armed page reloads itself after the arm
|
|
622
|
+
# lapses, and the server (which enforces the 10 s regardless) answers un-armed.
|
|
623
|
+
# Escape and focus-loss need script; the baseline has none (design-gap #119).
|
|
624
|
+
+ (f'<meta http-equiv=refresh content="{ARM_SECONDS}">' if armed else "")
|
|
625
|
+
+ f"<title>egzos · presence</title>{_style(self.stylesheet)}</head>"
|
|
626
|
+
"<body><main>"
|
|
627
|
+
f"<p class=shell>egzos · container {e(self.container)} · {e(self.host)}</p>"
|
|
628
|
+
f"<p class=shell>you · {e(OWNER)} · principal: interactive · present since "
|
|
629
|
+
f"{e(_since(self.opened))}</p>"
|
|
630
|
+
# §2.2 item 2 defines the reference line for a proposal; the item-promotion tap's
|
|
631
|
+
# line is design-gap #122, so it renders none rather than an invented one.
|
|
632
|
+
+ (f"<p class=ref>PROPOSAL <code title=\"{e(a['subject'])}\">"
|
|
633
|
+
f"{e(short_id(a['subject']))}</code> · filed {e(a.get('filed') or '')}</p>"
|
|
634
|
+
if self.gate else "")
|
|
635
|
+
# §2.2 item 8: initial focus on the page heading, never on an act.
|
|
636
|
+
+ f"<h1 tabindex=-1 autofocus>{e(a['title'])}</h1>"
|
|
637
|
+
# §2.2 item 4 is the requester's stated reason: a proposal has one; approve.pending is
|
|
638
|
+
# the owner's own act and has none to state (design-gap #122).
|
|
639
|
+
+ (f"<p><span class=attr>{e(a.get('requester', 'you'))} states:</span> {said}</p>"
|
|
640
|
+
if self.gate else "")
|
|
641
|
+
+ f"<h2>what moves</h2>{rows}"
|
|
642
|
+
f"<h2>who will see it at {e(a.get('dest', a['to']))}</h2>"
|
|
643
|
+
f"<p>{people} people · {agents} agents · resolved from token grants and scope "
|
|
644
|
+
f"membership</p>{chips}{consequence}"
|
|
645
|
+
"<section role=region aria-labelledby=presence-h class=box>"
|
|
646
|
+
f"<h2 id=presence-h>presence</h2><p>{e(presence_text(a, seconds))}</p>{terms}"
|
|
647
|
+
+ (f"<p class=note aria-live=polite>{e(note)}</p>" if note else "")
|
|
648
|
+
+ (f"<p class=alarm role=status>{e(error)}</p>" if error else "")
|
|
649
|
+
+ f"<form method=post>{acts}</form></section></main></body></html>"
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
def outcome_page(self, text: str, back: str | None = None) -> str:
|
|
653
|
+
link = f'<p><a href="{_e(back)}">Return to pending</a></p>' if back else ""
|
|
654
|
+
return (
|
|
655
|
+
"<!doctype html><html lang=en><head><meta charset=utf-8>"
|
|
656
|
+
f"<title>egzos · presence</title>{_style(self.stylesheet)}</head>"
|
|
657
|
+
f"<body><main><div class=box><p role=status>{_e(text)}</p></div>{link}</main>"
|
|
658
|
+
"</body></html>"
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
# -- the decision, independent of which server hosts the page ------------------------------------
|
|
662
|
+
def live(self, path: str) -> bool:
|
|
663
|
+
return (
|
|
664
|
+
self.outcome is None
|
|
665
|
+
and path.startswith("/tap/")
|
|
666
|
+
and values.same(path[len("/tap/"):], self.token) # a latin-1 path must not raise
|
|
667
|
+
)
|
|
668
|
+
|
|
669
|
+
def get(self) -> tuple[int, str]:
|
|
670
|
+
return 200, self.page(armed=self.armed_until > _now())
|
|
671
|
+
|
|
672
|
+
def post(self, step: str) -> tuple[int, str]:
|
|
673
|
+
"""Apply one press. On a decision, the host's `decide` performs it and the page shows the
|
|
674
|
+
container's answer in §13's canonical copy."""
|
|
675
|
+
if step == "deny" and self.gate:
|
|
676
|
+
self.outcome = "denied"
|
|
677
|
+
return self._answer()
|
|
678
|
+
if self.act.get("blocked") and step in ("arm", "arm_once", "confirm"):
|
|
679
|
+
return 200, self.page(armed=False)
|
|
680
|
+
if step in ("arm", "arm_once"):
|
|
681
|
+
self.armed_until = _now() + ARM_SECONDS
|
|
682
|
+
self.armed_mode = "once" if step == "arm_once" else "window"
|
|
683
|
+
return 200, self.page(armed=True, note=TAP_COPY["act.confirm.sr"])
|
|
684
|
+
if step == "confirm" and self.armed_until > _now():
|
|
685
|
+
self.windowed = self.armed_mode == "window"
|
|
686
|
+
self.outcome = "approved"
|
|
687
|
+
return self._answer()
|
|
688
|
+
# R9: a confirm after the 10 s, or any other press, reverts to Sign and approve, un-armed.
|
|
689
|
+
self.armed_until = 0.0
|
|
690
|
+
return 200, self.page(armed=False)
|
|
691
|
+
|
|
692
|
+
def _answer(self) -> tuple[int, str]:
|
|
693
|
+
"""The container's answer; or, if the act failed, R9's error row: back to ready, nothing
|
|
694
|
+
changed, the page still live so the person can try again."""
|
|
695
|
+
try:
|
|
696
|
+
return 200, self.outcome_page(self._decided())
|
|
697
|
+
except Exception:
|
|
698
|
+
self.outcome = None
|
|
699
|
+
self.armed_until = 0.0
|
|
700
|
+
return 200, self.page(armed=False, error=TAP_COPY["act.error"])
|
|
701
|
+
|
|
702
|
+
def _decided(self) -> str:
|
|
703
|
+
if self.decide is not None:
|
|
704
|
+
return self.decide(self.outcome, self.windowed)
|
|
705
|
+
seconds = window_seconds()
|
|
706
|
+
closes = (_iso(_now() + seconds)
|
|
707
|
+
if self.outcome == "approved" and self.windowed and seconds else None)
|
|
708
|
+
return outcome_text(self.act, self.outcome or "", closes=closes)
|
|
709
|
+
|
|
710
|
+
def handler(self):
|
|
711
|
+
tap = self
|
|
712
|
+
|
|
713
|
+
class Handler(BaseHTTPRequestHandler):
|
|
714
|
+
server_version = "egzos"
|
|
715
|
+
sys_version = ""
|
|
716
|
+
|
|
717
|
+
def log_message(self, *args):
|
|
718
|
+
return
|
|
719
|
+
|
|
720
|
+
def _send(self, status: int, body: str) -> None:
|
|
721
|
+
send_page(self, status, body)
|
|
722
|
+
|
|
723
|
+
def do_GET(self): # noqa: N802
|
|
724
|
+
if not tap.live(self.path):
|
|
725
|
+
return self._send(404, empty_page())
|
|
726
|
+
self._send(*tap.get())
|
|
727
|
+
|
|
728
|
+
def do_POST(self): # noqa: N802
|
|
729
|
+
if not tap.live(self.path):
|
|
730
|
+
return self._send(404, empty_page())
|
|
731
|
+
if not same_origin(self.headers):
|
|
732
|
+
return self._send(403, "<p>Refused.</p>")
|
|
733
|
+
self._send(*tap.post(read_step(self)))
|
|
734
|
+
|
|
735
|
+
return Handler
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def empty_page() -> str:
|
|
739
|
+
"""R11: one page for an unknown, foreign, expired or used token — §13 `tap.empty` as the
|
|
740
|
+
heading, the body empty, nothing on it depending on which cause it was."""
|
|
741
|
+
return (
|
|
742
|
+
"<!doctype html><html lang=en><head><meta charset=utf-8>"
|
|
743
|
+
'<meta name=viewport content="width=device-width,initial-scale=1">'
|
|
744
|
+
f"<title>egzos · presence</title><style>{_tokens_css()}{TAP_STYLE}</style></head>"
|
|
745
|
+
f"<body><main><h1 tabindex=-1 autofocus>{_e(TAP_COPY['tap.empty'])}</h1></main>"
|
|
746
|
+
"</body></html>"
|
|
747
|
+
)
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def same_origin(headers) -> bool:
|
|
751
|
+
"""A state-changing request must name this origin. A MISSING Origin is refused too: every
|
|
752
|
+
browser sends one on a form POST, so its absence means something that is not a browser form."""
|
|
753
|
+
return headers.get("Origin") == f"http://{headers.get('Host', '')}"
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def read_step(request: BaseHTTPRequestHandler) -> str:
|
|
757
|
+
# Bounded both ways: a negative length would read until the sender closed the connection.
|
|
758
|
+
length = max(0, min(int(request.headers.get("Content-Length") or 0), 4096))
|
|
759
|
+
return parse_qs(request.rfile.read(length).decode()).get("step", [""])[0]
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def send_page(request: BaseHTTPRequestHandler, status: int, body: str) -> None:
|
|
763
|
+
data = body.encode()
|
|
764
|
+
request.send_response(status)
|
|
765
|
+
request.send_header("Content-Type", "text/html; charset=utf-8")
|
|
766
|
+
request.send_header("Content-Length", str(len(data)))
|
|
767
|
+
request.send_header("Cache-Control", "no-store")
|
|
768
|
+
# same-origin, not no-referrer: under no-referrer a browser sends a form POST's Origin as
|
|
769
|
+
# `null`, and same_origin() refuses it, so the tap's own buttons would never land (#130).
|
|
770
|
+
request.send_header("Referrer-Policy", "same-origin")
|
|
771
|
+
request.send_header("X-Frame-Options", "DENY")
|
|
772
|
+
request.send_header(
|
|
773
|
+
"Content-Security-Policy",
|
|
774
|
+
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; "
|
|
775
|
+
"frame-ancestors 'none'; base-uri 'none'",
|
|
776
|
+
)
|
|
777
|
+
request.end_headers()
|
|
778
|
+
request.wfile.write(data)
|