driverkit 0.1.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.
- driverkit/__init__.py +93 -0
- driverkit/asgi.py +277 -0
- driverkit/auth.py +508 -0
- driverkit/client.py +413 -0
- driverkit/fastmcp_server.py +374 -0
- driverkit/mcp_core.py +988 -0
- driverkit/mcp_server.py +262 -0
- driverkit/relay.py +1531 -0
- driverkit/render.py +486 -0
- driverkit/serve_relay.py +670 -0
- driverkit/types.py +943 -0
- driverkit-0.1.0.dist-info/METADATA +11 -0
- driverkit-0.1.0.dist-info/RECORD +15 -0
- driverkit-0.1.0.dist-info/WHEEL +4 -0
- driverkit-0.1.0.dist-info/entry_points.txt +4 -0
driverkit/relay.py
ADDED
|
@@ -0,0 +1,1531 @@
|
|
|
1
|
+
"""
|
|
2
|
+
driverkit — the relay, in Python, stdlib only.
|
|
3
|
+
|
|
4
|
+
This is a port of ``packages/driverkit/src/relay/relay.ts``, frame for frame and status
|
|
5
|
+
for status. It exists because the backend half of a driverkit deployment is
|
|
6
|
+
often already Python: PROTOCOL.md's argument for SSE is that *the relay belongs
|
|
7
|
+
inside a server you already run*, and "already run" is a FastAPI or Django
|
|
8
|
+
process far more often than it is a Node one. Two relays that differ would be
|
|
9
|
+
worse than either, so where this file and the TypeScript one could plausibly
|
|
10
|
+
diverge there is a comment saying which way it went.
|
|
11
|
+
|
|
12
|
+
Two properties are worth stating before the code, because both are easy to
|
|
13
|
+
break with a change that looks like a cleanup:
|
|
14
|
+
|
|
15
|
+
THE RELAY GRANTS NO AUTHORITY. It forwards a verb name to a tab that is
|
|
16
|
+
already logged in as a person. It never decides whether a call is allowed,
|
|
17
|
+
never rewrites args, never interprets ``rev``. Every refusal it originates
|
|
18
|
+
is about reachability — "no tab", "the tab went away", "the tab never
|
|
19
|
+
answered" — and never about the verb. The moment the relay has an opinion
|
|
20
|
+
about a verb there are two sets of rules and one of them is wrong.
|
|
21
|
+
|
|
22
|
+
EVERY ANSWER FROM ``/call`` IS A ``WireResult``, AND THE BODY IS
|
|
23
|
+
AUTHORITATIVE. An agent gets the same shape at 200 whether the tab refused,
|
|
24
|
+
the tab vanished, or the tab id was a typo. A 4xx there would conflate a
|
|
25
|
+
transport failure with a business rule, and those want opposite handling:
|
|
26
|
+
one is retry-elsewhere, the other is rephrase-and-retry. So a non-2xx from
|
|
27
|
+
this relay means no ``WireResult`` was produced at all — malformed body,
|
|
28
|
+
unroutable path — and never "the app said no".
|
|
29
|
+
|
|
30
|
+
A relay refusal carries NO ``snapshot``. The three it can originate are a
|
|
31
|
+
closed set (:data:`driverkit.types.RELAY_REFUSALS`), and in none of them did
|
|
32
|
+
anything run or anybody look. Inventing an empty snapshot would tell an
|
|
33
|
+
agent the app has no rows, which is a lie about the app rather than about
|
|
34
|
+
the call. :meth:`Result.to_dict` omits an absent snapshot, which is why the
|
|
35
|
+
refusals here are built through it rather than as hand-written dicts.
|
|
36
|
+
|
|
37
|
+
A TAB BELONGS TO A PRINCIPAL, AND THE REGISTRY KEY SAYS SO. Tabs are
|
|
38
|
+
stored under ``(principal, tab id)``, not under the tab id alone. That is
|
|
39
|
+
not a check, it is a shape: there is no lookup by bare tab id anywhere in
|
|
40
|
+
this file, so a caller cannot reach another principal's tab through a code
|
|
41
|
+
path somebody adds next year and forgets to guard. It also removes the
|
|
42
|
+
question of what to do when two people mint the same tab id — nothing, they
|
|
43
|
+
are two tabs — and with it an existence oracle for other people's ids.
|
|
44
|
+
|
|
45
|
+
Isolation is NOT authorisation. A credential buys its holder nothing they
|
|
46
|
+
could not already do in their own browser; it tells the relay which
|
|
47
|
+
hundredth of its registry to show them. See :mod:`driverkit.auth`.
|
|
48
|
+
|
|
49
|
+
CHOICES PROTOCOL.md LEAVES TO THE RELAY, carried over from the TS version so
|
|
50
|
+
the two cannot drift:
|
|
51
|
+
|
|
52
|
+
- A second ``/dk/events`` stream for a known tab id SUPERSEDES the first. The
|
|
53
|
+
id is minted by the tab so a reconnect resumes identity; treating the
|
|
54
|
+
second stream as a new tab would defeat the only reason the id exists.
|
|
55
|
+
- Calls in flight CARRY ACROSS that supersede. A tab that was mid-verb when
|
|
56
|
+
its stream blinked can still POST the result on the new one, and failing
|
|
57
|
+
those would turn a recovered hiccup into an error the agent must handle.
|
|
58
|
+
- ``hello`` UPSERTS FIELD BY FIELD. It arrives again after every reconnect
|
|
59
|
+
and the app may have navigated in between, so the later one wins on each
|
|
60
|
+
field it carries and leaves the others alone.
|
|
61
|
+
- Everything in ``hello`` but ``tab`` is OPTIONAL, which leaves a real
|
|
62
|
+
window: a tab enters the registry when its stream opens and ``hello`` lands
|
|
63
|
+
a moment later on a separate POST. During it ``/manifest`` answers 404
|
|
64
|
+
rather than an empty verb list, because an empty list is a false claim that
|
|
65
|
+
the app has no verbs.
|
|
66
|
+
- Watchers live OUTSIDE the tab record. A tab record dies with its stream and
|
|
67
|
+
a watcher must survive the page reloading — that reload is one of the
|
|
68
|
+
things it is watching for.
|
|
69
|
+
|
|
70
|
+
TRANSPORT IS SOMEBODY ELSE'S PROBLEM. :meth:`Relay.handle` takes five plain
|
|
71
|
+
values and returns a :class:`Response`, so it can be driven by
|
|
72
|
+
:mod:`driverkit.serve_relay` (``http.server``), by
|
|
73
|
+
:func:`driverkit.asgi.relay_asgi`, or by a test with no socket at all. The TS
|
|
74
|
+
version made its ``dispatch`` pure for the same reason: a relay whose
|
|
75
|
+
correctness is asserted by calling internals would pass with a missing blank
|
|
76
|
+
line between SSE frames, and that blank line is the entire framing.
|
|
77
|
+
|
|
78
|
+
THREADS. ``handle`` blocks: a ``POST /dk/tabs/:tab/call`` is not a ticket to
|
|
79
|
+
poll, it *is* the call, and it returns when the matching ``result`` frame
|
|
80
|
+
arrives. So every adapter must call it on a thread of its own, and an SSE
|
|
81
|
+
response must be streamed from a thread of its own too — an endless body on a
|
|
82
|
+
single-threaded server is every other request hanging. The registry below is
|
|
83
|
+
guarded by one re-entrant lock and no lock is ever held across a blocking wait;
|
|
84
|
+
see :class:`Stream` for why writing to a stream cannot block.
|
|
85
|
+
|
|
86
|
+
Zero runtime dependencies: this module imports only the standard library.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
from __future__ import annotations
|
|
90
|
+
|
|
91
|
+
import json
|
|
92
|
+
import queue
|
|
93
|
+
import threading
|
|
94
|
+
import time
|
|
95
|
+
from dataclasses import dataclass, field
|
|
96
|
+
from datetime import datetime, timezone
|
|
97
|
+
from typing import Any, Callable, Iterator, Mapping, Sequence
|
|
98
|
+
from urllib.parse import parse_qsl, unquote
|
|
99
|
+
|
|
100
|
+
from .auth import LOCAL_PRINCIPAL, AuthError, Principal, TabAuth
|
|
101
|
+
from .types import RELAY_REFUSALS, Result
|
|
102
|
+
|
|
103
|
+
__all__ = [
|
|
104
|
+
"Relay",
|
|
105
|
+
"Response",
|
|
106
|
+
"Stream",
|
|
107
|
+
"MAX_BODY",
|
|
108
|
+
"SSE_HEADERS",
|
|
109
|
+
"bad_request",
|
|
110
|
+
"TabAuth",
|
|
111
|
+
"Principal",
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
#: The body size limit PROTOCOL.md pins: 1 MiB, and over it is a 413. A
|
|
115
|
+
#: snapshot approaching that size is a bug in the app's ``visible()``, not a
|
|
116
|
+
#: limit to raise — the whole design says an agent sees a screenful. Enforced by
|
|
117
|
+
#: the adapters, which are the only code that knows how many bytes arrived.
|
|
118
|
+
MAX_BODY = 1 << 20
|
|
119
|
+
|
|
120
|
+
#: The backstop above which an oversized body stops being read at all.
|
|
121
|
+
#:
|
|
122
|
+
#: Between ``MAX_BODY`` and here, an adapter keeps READING and discarding so it
|
|
123
|
+
#: can answer the 413 after the sender has finished. That is not politeness:
|
|
124
|
+
#: hanging up mid-upload resets the connection, the sender gets ECONNRESET on
|
|
125
|
+
#: its own socket before it reads anything back, and a sender that cannot learn
|
|
126
|
+
#: WHY it failed retries identically — which is the opposite of what a limit is
|
|
127
|
+
#: for. Above this, reading all of it politely is the attack succeeding, so the
|
|
128
|
+
#: connection is dropped and the sender is left to guess.
|
|
129
|
+
ABORT_BODY = 64 << 20
|
|
130
|
+
|
|
131
|
+
SSE_HEADERS: tuple[tuple[str, str], ...] = (
|
|
132
|
+
("Content-Type", "text/event-stream; charset=utf-8"),
|
|
133
|
+
("Cache-Control", "no-cache, no-transform"),
|
|
134
|
+
("Connection", "keep-alive"),
|
|
135
|
+
# Nginx buffers proxied responses by default, which turns a live stream
|
|
136
|
+
# into one that arrives when it ends. The ping comments keep the connection
|
|
137
|
+
# open; this keeps the bytes moving.
|
|
138
|
+
("X-Accel-Buffering", "no"),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
_JSON_HEADERS: tuple[tuple[str, str], ...] = (
|
|
142
|
+
("Content-Type", "application/json; charset=utf-8"),
|
|
143
|
+
# A tab id is a capability, so nothing here is cacheable by anything.
|
|
144
|
+
("Cache-Control", "no-store"),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
#: The 401's challenge header. ``Bearer`` names the scheme an agent should use;
|
|
148
|
+
#: the realm is fixed, because a realm that named the app or the principal
|
|
149
|
+
#: would be a 401 that leaks who else is here.
|
|
150
|
+
_AUTH_HEADERS: tuple[tuple[str, str], ...] = _JSON_HEADERS + (
|
|
151
|
+
("WWW-Authenticate", 'Bearer realm="driverkit"'),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
#: The hint on every ``no-such-tab``, whatever the real reason.
|
|
155
|
+
#:
|
|
156
|
+
#: One string, with no tab id in it, because the four reasons an agent can get
|
|
157
|
+
#: this — never minted, closed, somebody else's, outside a tab-bound
|
|
158
|
+
#: credential's reach — must be one answer. A hint that said "no tab `abc` is
|
|
159
|
+
#: connected" for one and something else for another would make the endpoint
|
|
160
|
+
#: the membership test the status code was carefully chosen not to be.
|
|
161
|
+
NO_SUCH_TAB_HINT = "no such tab is connected"
|
|
162
|
+
|
|
163
|
+
#: The principal every request is, with auth off.
|
|
164
|
+
_LOCAL = Principal(id=LOCAL_PRINCIPAL)
|
|
165
|
+
|
|
166
|
+
_OPENING = b": driverkit\n\n"
|
|
167
|
+
_PING = b": ping\n\n"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# --- what an adapter gets back ---------------------------------------------
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass(frozen=True)
|
|
174
|
+
class Response:
|
|
175
|
+
"""One answer, either a whole body or an open stream — never both.
|
|
176
|
+
|
|
177
|
+
``headers`` excludes ``Content-Length``; the adapter adds it for a body
|
|
178
|
+
response and must *not* add one for a stream, whose length is unknowable up
|
|
179
|
+
front. A client that waited for a length on an SSE body would hang forever.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
status: int
|
|
183
|
+
headers: tuple[tuple[str, str], ...] = _JSON_HEADERS
|
|
184
|
+
body: bytes = b""
|
|
185
|
+
stream: "Stream | None" = None
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def streaming(self) -> bool:
|
|
189
|
+
return self.stream is not None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class Stream:
|
|
193
|
+
"""An open SSE response: a queue of chunks, drained by whoever owns the socket.
|
|
194
|
+
|
|
195
|
+
Writes never block and never raise. That is the property the locking rests
|
|
196
|
+
on — :meth:`Relay.handle` and the ingest path write frames to streams while
|
|
197
|
+
holding the registry lock, and if a write could block on a slow consumer
|
|
198
|
+
then one wedged reader would freeze the whole relay. The cost is that a
|
|
199
|
+
consumer which stops reading grows a queue; it is bounded in practice by
|
|
200
|
+
the fact that a tab with no reader is a tab whose socket is about to be
|
|
201
|
+
closed, and :meth:`close` drops the queue.
|
|
202
|
+
|
|
203
|
+
The keep-alive is produced here rather than by a timer thread: the consumer
|
|
204
|
+
waits at most ``ping_s`` for a chunk and emits a ``: ping`` comment when
|
|
205
|
+
nothing arrives. PROTOCOL.md asks for a comment every 20s on an *idle*
|
|
206
|
+
stream, and this is that, with no per-stream thread and no timer to leak.
|
|
207
|
+
(The TS relay runs a fixed interval instead, so it also pings a busy
|
|
208
|
+
stream. The difference is invisible to a client: a comment carries nothing
|
|
209
|
+
and a conforming reader drops it.)
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
__slots__ = ("_q", "_ping_s", "_closed", "_on_close", "_lock")
|
|
213
|
+
|
|
214
|
+
def __init__(self, ping_s: float) -> None:
|
|
215
|
+
self._q: queue.SimpleQueue[bytes | None] = queue.SimpleQueue()
|
|
216
|
+
self._ping_s = ping_s
|
|
217
|
+
self._closed = False
|
|
218
|
+
self._on_close: list[Callable[[], None]] = []
|
|
219
|
+
self._lock = threading.Lock()
|
|
220
|
+
# A first comment byte makes the browser fire `open` now rather than
|
|
221
|
+
# when the first real frame happens to arrive, and `open` is where the
|
|
222
|
+
# page sends `hello`. Without it a freshly loaded tab is connected but
|
|
223
|
+
# unidentifiable until somebody tries to drive it.
|
|
224
|
+
self._q.put(_OPENING)
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def closed(self) -> bool:
|
|
228
|
+
return self._closed
|
|
229
|
+
|
|
230
|
+
def write(self, chunk: bytes) -> bool:
|
|
231
|
+
"""Queue one chunk. False means the stream is gone — see ``send`` in the
|
|
232
|
+
TS relay, where a failed write is what turns into ``tab-went-away``."""
|
|
233
|
+
with self._lock:
|
|
234
|
+
if self._closed:
|
|
235
|
+
return False
|
|
236
|
+
self._q.put(chunk)
|
|
237
|
+
return True
|
|
238
|
+
|
|
239
|
+
def on_close(self, fn: Callable[[], None]) -> None:
|
|
240
|
+
with self._lock:
|
|
241
|
+
already = self._closed
|
|
242
|
+
if not already:
|
|
243
|
+
self._on_close.append(fn)
|
|
244
|
+
if already:
|
|
245
|
+
fn()
|
|
246
|
+
|
|
247
|
+
def close(self) -> None:
|
|
248
|
+
"""Hang up. Idempotent: a shutdown path that throws on a second call is
|
|
249
|
+
one that gets wrapped in try/except everywhere it is used."""
|
|
250
|
+
with self._lock:
|
|
251
|
+
if self._closed:
|
|
252
|
+
return
|
|
253
|
+
self._closed = True
|
|
254
|
+
callbacks, self._on_close = self._on_close, []
|
|
255
|
+
self._q.put(None)
|
|
256
|
+
for fn in callbacks:
|
|
257
|
+
fn()
|
|
258
|
+
|
|
259
|
+
def chunks(self) -> Iterator[bytes]:
|
|
260
|
+
"""The bytes to write to the socket, blocking between them.
|
|
261
|
+
|
|
262
|
+
Ends when the stream is closed. Single-consumer: the adapter that owns
|
|
263
|
+
the socket is the only caller.
|
|
264
|
+
"""
|
|
265
|
+
while True:
|
|
266
|
+
try:
|
|
267
|
+
chunk = self._q.get(timeout=self._ping_s)
|
|
268
|
+
except queue.Empty:
|
|
269
|
+
# A comment line, per PROTOCOL.md: it carries nothing, and a
|
|
270
|
+
# comment cannot be mistaken for a frame by a client that has
|
|
271
|
+
# never heard of it. That is what lets the keep-alive exist
|
|
272
|
+
# without a version bump.
|
|
273
|
+
yield _PING
|
|
274
|
+
continue
|
|
275
|
+
if chunk is None:
|
|
276
|
+
return
|
|
277
|
+
yield chunk
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# --- the registry -----------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@dataclass
|
|
284
|
+
class _Pending:
|
|
285
|
+
"""One call waiting for its ``result`` frame.
|
|
286
|
+
|
|
287
|
+
An :class:`threading.Event` rather than a polled deadline: the call returns
|
|
288
|
+
the instant the frame lands, and a relay that polled would add half its
|
|
289
|
+
interval to every round trip an agent makes.
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
event: threading.Event = field(default_factory=threading.Event)
|
|
293
|
+
result: dict[str, Any] | None = None
|
|
294
|
+
#: Who asked, which tab and verb they asked for, and when the relay took
|
|
295
|
+
#: the call -- everything ``on_audit`` needs, carried on the record because
|
|
296
|
+
#: two of the five places a call can be settled are nowhere near the
|
|
297
|
+
#: dispatch: a stream closing, and the relay shutting down.
|
|
298
|
+
principal: str = ""
|
|
299
|
+
tab: str = ""
|
|
300
|
+
verb: str = ""
|
|
301
|
+
started: float = 0.0
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
@dataclass
|
|
305
|
+
class _Tab:
|
|
306
|
+
tab: str
|
|
307
|
+
#: Who this tab belongs to. The other half of the registry key, kept on the
|
|
308
|
+
#: record too so a summary and a watcher fan-out can find it without
|
|
309
|
+
#: carrying the key around.
|
|
310
|
+
principal: str
|
|
311
|
+
#: ISO 8601, formatted once at connect rather than on every listing.
|
|
312
|
+
since: str
|
|
313
|
+
stream: Stream
|
|
314
|
+
pending: dict[str, _Pending] = field(default_factory=dict)
|
|
315
|
+
# Stored as the raw dicts the tab sent, NOT as parsed dataclasses.
|
|
316
|
+
# PROTOCOL.md promises a field may be added without a version bump, and
|
|
317
|
+
# that promise is only kept if every hop forwards what it does not
|
|
318
|
+
# understand. Re-serialising a `Manifest` here would silently drop a
|
|
319
|
+
# `kind`, or a `count`, or whatever the next field turns out to be.
|
|
320
|
+
app: str | None = None
|
|
321
|
+
title: str | None = None
|
|
322
|
+
url: str | None = None
|
|
323
|
+
#: Where the tab said its person's attention is: ``focused``, ``visible``
|
|
324
|
+
#: or ``hidden``. Stored as the tab sent it and never computed — the relay
|
|
325
|
+
#: cannot see ``document.hasFocus()``, which is the whole reason the page
|
|
326
|
+
#: reports it.
|
|
327
|
+
focus: str | None = None
|
|
328
|
+
manifest: dict[str, Any] | None = None
|
|
329
|
+
snapshot: dict[str, Any] | None = None
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
class Relay:
|
|
333
|
+
"""The one place both parties can reach.
|
|
334
|
+
|
|
335
|
+
``timeout_s`` is how long ``POST /dk/tabs/:tab/call`` waits for the matching
|
|
336
|
+
``result``. PROTOCOL.md has no queue on purpose: a call either reaches a
|
|
337
|
+
connected tab or fails cleanly, and the deadline is the other half of that
|
|
338
|
+
promise. Without it a tab whose JavaScript died — stream still open, event
|
|
339
|
+
loop wedged — holds the agent's request forever, which is the one failure
|
|
340
|
+
mode worse than a refusal, because an agent cannot retry what has not
|
|
341
|
+
returned. It is the relay's property, not the protocol's, and **the default
|
|
342
|
+
is 60 seconds** — the same number the TypeScript relay uses, because
|
|
343
|
+
PROTOCOL.md's own rule is that two conforming relays disagreeing on a
|
|
344
|
+
default is worse than either choice.
|
|
345
|
+
|
|
346
|
+
**Why 60 and not the 15 this used to be.** 15s was tuned for a button
|
|
347
|
+
click, where it is a margin of three hundred times. It is no margin at all
|
|
348
|
+
for the verb an adopter reaches for this library to drive — a report fetch,
|
|
349
|
+
an export, a cross-system lookup — and a legitimate 20-second fetch came
|
|
350
|
+
back ``timeout``, which PROTOCOL.md defines as **outcome unknown**: a
|
|
351
|
+
commit that answers that way may already have run and the agent is told
|
|
352
|
+
not to retry it. The deadline was converting successes into the most
|
|
353
|
+
expensive answer in the system, and the two errors are not symmetric.
|
|
354
|
+
Firing late costs latency; firing early costs a task nobody can safely
|
|
355
|
+
resume.
|
|
356
|
+
|
|
357
|
+
**Why not much longer.** The deadline is the only thing that answers an
|
|
358
|
+
agent when a tab is alive but wedged — ``tab-went-away`` covers a tab that
|
|
359
|
+
died, and nothing else covers one that is merely stuck. Past about a minute
|
|
360
|
+
an intermediary gives up first: proxies and load balancers cut an idle
|
|
361
|
+
response at 30 to 60 seconds, so a longer server-side deadline is answered
|
|
362
|
+
by a socket error at the client, which is an unknown outcome with no slug
|
|
363
|
+
and no ``Result`` shape at all. A verb that genuinely needs longer wants a
|
|
364
|
+
handle-and-poll pair of verbs, not a bigger number here.
|
|
365
|
+
|
|
366
|
+
``allow_remote`` serves requests that did not come from loopback. Off by
|
|
367
|
+
default, and that default is the security model rather than a convenience.
|
|
368
|
+
A tab's own session is what the app checks, so a relay someone else can
|
|
369
|
+
reach is that person driving your logged-in session — not a scoped token
|
|
370
|
+
they could be given, your actual account. There is nothing to revoke
|
|
371
|
+
because nothing was ever granted.
|
|
372
|
+
|
|
373
|
+
``auth`` is a :class:`driverkit.auth.TabAuth` and is how the relay learns
|
|
374
|
+
which person a request is from. ``resolve_principal`` is the other door:
|
|
375
|
+
a function from the request's headers to a principal id, for a relay
|
|
376
|
+
embedded in an app that already has sessions and can simply say who the
|
|
377
|
+
caller is. It is consulted first and falling through it (returning ``None``)
|
|
378
|
+
hands the request to ``auth``.
|
|
379
|
+
|
|
380
|
+
With neither configured, auth is OFF and every request resolves to one
|
|
381
|
+
principal — the unconfigured loopback relay one developer runs, where
|
|
382
|
+
scoping by principal is a no-op and nothing needs setting up.
|
|
383
|
+
|
|
384
|
+
**``allow_remote`` without one of them raises.** That combination is the
|
|
385
|
+
one this whole file exists to prevent: an exposed relay with no notion of
|
|
386
|
+
who is calling publishes a hundred people's logged-in sessions to each
|
|
387
|
+
other and to anybody who can reach the port. It used to be reachable by
|
|
388
|
+
setting one flag that reads like a convenience, so now it is not reachable
|
|
389
|
+
at all — turning on remote access means naming how callers are identified,
|
|
390
|
+
in the same call, or the relay refuses to exist.
|
|
391
|
+
|
|
392
|
+
``on_error`` is called with anything raised while writing to a stream.
|
|
393
|
+
|
|
394
|
+
``on_audit`` is where this relay's own audit records go: one mapping per
|
|
395
|
+
``/call`` it handled, with the keys ``at``, ``ms``, ``principal``, ``tab``,
|
|
396
|
+
``verb`` and ``outcome``, identical in name and meaning to the
|
|
397
|
+
``RelayAuditEvent`` the TypeScript relay emits.
|
|
398
|
+
|
|
399
|
+
It exists for the one fact an in-page audit hook cannot know and this relay
|
|
400
|
+
cannot help knowing: WHICH PRINCIPAL asked. A driver sees a call and has no
|
|
401
|
+
idea whether it came from the panel in front of a person, a cron job, or
|
|
402
|
+
somebody else's agent holding a token; the relay resolved the credential, so
|
|
403
|
+
it is the only place in the library where "who" is a fact rather than a
|
|
404
|
+
guess.
|
|
405
|
+
|
|
406
|
+
And it says no more than that. It does not report what the verb DID: the
|
|
407
|
+
driver decided that, in another process, and a copy of somebody else's
|
|
408
|
+
decision is a second source of truth that can disagree with the first — a
|
|
409
|
+
relay logging ``ok`` for a call whose tab died mid-commit would be asserting
|
|
410
|
+
an outcome nobody observed. So ``outcome`` is the RELAY's verdict and is one
|
|
411
|
+
of ``delivered`` (the tab answered; what it answered is in the driver's own
|
|
412
|
+
record), ``no-such-tab``, ``tab-went-away`` or ``timeout``. The last three
|
|
413
|
+
are the calls no other log will ever mention, because they never reached, or
|
|
414
|
+
never returned from, a driver. **Count commits from the drivers' records**
|
|
415
|
+
and read this one for who asked; that is the line that keeps the two from
|
|
416
|
+
being two countings of one call.
|
|
417
|
+
|
|
418
|
+
It is called and not awaited, and a throw goes to ``on_error``: a 500
|
|
419
|
+
because the logging backend is down would turn an audit trail into an
|
|
420
|
+
outage.
|
|
421
|
+
"""
|
|
422
|
+
|
|
423
|
+
def __init__(
|
|
424
|
+
self,
|
|
425
|
+
timeout_s: float = 60.0,
|
|
426
|
+
ping_s: float = 20.0,
|
|
427
|
+
allow_remote: bool = False,
|
|
428
|
+
on_error: Callable[[BaseException], None] | None = None,
|
|
429
|
+
*,
|
|
430
|
+
auth: TabAuth | None = None,
|
|
431
|
+
resolve_principal: Callable[[Mapping[str, str]], str | None] | None = None,
|
|
432
|
+
on_audit: Callable[[Mapping[str, Any]], None] | None = None,
|
|
433
|
+
) -> None:
|
|
434
|
+
if allow_remote and auth is None and resolve_principal is None:
|
|
435
|
+
# Raised in the constructor, before a socket exists, for the same
|
|
436
|
+
# reason `serve()` refuses a non-loopback host there: a
|
|
437
|
+
# misconfiguration that surfaced later is one somebody forgot to
|
|
438
|
+
# check, and the failure mode of forgetting is a listening public
|
|
439
|
+
# port that drives strangers' browsers.
|
|
440
|
+
raise ValueError(
|
|
441
|
+
"driverkit: allow_remote needs auth= or resolve_principal=. A relay that "
|
|
442
|
+
"serves non-loopback callers and cannot tell them apart is every connected "
|
|
443
|
+
'tab offered to every caller. Read "Who is allowed to do this" in '
|
|
444
|
+
"PROTOCOL.md, then pass auth=TabAuth(secret=..., audience=...)."
|
|
445
|
+
)
|
|
446
|
+
self.timeout_s = timeout_s
|
|
447
|
+
self.ping_s = ping_s
|
|
448
|
+
self.allow_remote = allow_remote
|
|
449
|
+
self._auth = auth
|
|
450
|
+
self._resolve = resolve_principal
|
|
451
|
+
self._on_error = on_error or (lambda _err: None)
|
|
452
|
+
self._on_audit = on_audit
|
|
453
|
+
|
|
454
|
+
# One re-entrant lock over the whole registry. A lock per tab would be
|
|
455
|
+
# the obvious refinement and would buy nothing: every critical section
|
|
456
|
+
# here is a dict lookup and a queue put, and the one operation that
|
|
457
|
+
# blocks — waiting for a `result` — deliberately holds no lock at all.
|
|
458
|
+
self._lock = threading.RLock()
|
|
459
|
+
#: Connected tabs, keyed by ``(principal, tab id)``.
|
|
460
|
+
#:
|
|
461
|
+
#: The pair, never the bare id. Two principals using the same tab id
|
|
462
|
+
#: string are two tabs and neither can see the other, so there is no
|
|
463
|
+
#: collision to resolve and no refusal that would tell a prober which
|
|
464
|
+
#: ids are taken. Every lookup in this file goes through
|
|
465
|
+
#: :meth:`_owned`, which is the only place the pair is assembled.
|
|
466
|
+
self._tabs: dict[tuple[str, str], _Tab] = {}
|
|
467
|
+
#: ``GET /dk/tabs/:tab/watch`` subscribers, keyed the same way.
|
|
468
|
+
#:
|
|
469
|
+
#: A set, because PROTOCOL.md requires every watcher to get the frames:
|
|
470
|
+
#: two agents beside one human is the shared-presence case, and a
|
|
471
|
+
#: single-slot registry would silently make the second one blind rather
|
|
472
|
+
#: than refuse it.
|
|
473
|
+
#:
|
|
474
|
+
#: Kept OUTSIDE the tab record on purpose — see the module docstring.
|
|
475
|
+
self._watchers: dict[tuple[str, str], set[Stream]] = {}
|
|
476
|
+
#: The rev last broadcast per tab, so a refusal that moved nothing is quiet.
|
|
477
|
+
self._broadcast: dict[tuple[str, str], int] = {}
|
|
478
|
+
self._next_call = 1
|
|
479
|
+
self._closed = False
|
|
480
|
+
|
|
481
|
+
# ---- the public surface ------------------------------------------------
|
|
482
|
+
|
|
483
|
+
def tabs(self) -> list[dict[str, Any]]:
|
|
484
|
+
"""The connected tabs, as ``GET /dk/tabs`` reports them.
|
|
485
|
+
|
|
486
|
+
Rows rather than :class:`driverkit.types.Tab` instances, because this is
|
|
487
|
+
the wire shape and ``Tab.to_dict`` fills absent strings with ``""``.
|
|
488
|
+
The pre-``hello`` window is real, and a row claiming ``app: ""`` is a
|
|
489
|
+
worse answer than a row that simply does not mention the app yet. Parse
|
|
490
|
+
these with ``Tab.from_dict`` if you want the dataclass.
|
|
491
|
+
"""
|
|
492
|
+
with self._lock:
|
|
493
|
+
return [self._summary(t) for t in self._tabs.values()]
|
|
494
|
+
|
|
495
|
+
def tabs_for(self, principal: str, tab: str | None = None) -> list[dict[str, Any]]:
|
|
496
|
+
"""The tabs ONE principal owns — what ``GET /dk/tabs`` actually serves.
|
|
497
|
+
|
|
498
|
+
:meth:`tabs` stays the whole registry because it is the operator's
|
|
499
|
+
in-process view: a process that embeds the relay may legitimately want
|
|
500
|
+
to know what is connected. Nothing reachable over HTTP uses it. The
|
|
501
|
+
cross-principal listing was the inventory of other people's sessions —
|
|
502
|
+
titles, URLs and all — that this split exists to remove.
|
|
503
|
+
|
|
504
|
+
``tab`` narrows further, for a credential bound to one tab.
|
|
505
|
+
"""
|
|
506
|
+
with self._lock:
|
|
507
|
+
return [
|
|
508
|
+
self._summary(t)
|
|
509
|
+
for t in self._tabs.values()
|
|
510
|
+
if t.principal == principal and (tab is None or t.tab == tab)
|
|
511
|
+
]
|
|
512
|
+
|
|
513
|
+
def close(self) -> None:
|
|
514
|
+
"""Hang up every stream and fail every call in flight. Idempotent."""
|
|
515
|
+
with self._lock:
|
|
516
|
+
self._closed = True
|
|
517
|
+
tabs, self._tabs = list(self._tabs.values()), {}
|
|
518
|
+
watchers = [s for group in self._watchers.values() for s in group]
|
|
519
|
+
self._watchers.clear()
|
|
520
|
+
self._broadcast.clear()
|
|
521
|
+
for tab in tabs:
|
|
522
|
+
for pending in tab.pending.values():
|
|
523
|
+
self._settle(
|
|
524
|
+
pending,
|
|
525
|
+
self._refusal("tab-went-away", "the relay is shutting down"),
|
|
526
|
+
"tab-went-away",
|
|
527
|
+
)
|
|
528
|
+
tab.pending.clear()
|
|
529
|
+
for stream in [*(t.stream for t in tabs), *watchers]:
|
|
530
|
+
try:
|
|
531
|
+
stream.close()
|
|
532
|
+
except Exception as err: # pragma: no cover - close() does not raise
|
|
533
|
+
self._on_error(err)
|
|
534
|
+
|
|
535
|
+
def handle(
|
|
536
|
+
self,
|
|
537
|
+
method: str,
|
|
538
|
+
path: str,
|
|
539
|
+
query: Mapping[str, str] | Sequence[tuple[str, str]] | str | None = None,
|
|
540
|
+
body: bytes | None = None,
|
|
541
|
+
peer: str | None = None,
|
|
542
|
+
headers: Mapping[str, str] | Sequence[tuple[str, str]] | None = None,
|
|
543
|
+
) -> Response | None:
|
|
544
|
+
"""Handle one request, or return ``None`` when the path is not ours.
|
|
545
|
+
|
|
546
|
+
``None`` rather than a 404 is what makes embedding possible: deciding
|
|
547
|
+
that an unknown path is an error is the host server's business, and a
|
|
548
|
+
relay that answered 404 for everything could not sit in front of the app
|
|
549
|
+
it was embedded in. The standalone server turns ``None`` into a 404
|
|
550
|
+
itself, because there it *is* the whole process.
|
|
551
|
+
|
|
552
|
+
``body`` is the raw request bytes, unparsed, because reading them is
|
|
553
|
+
where a malformed call turns into a 400 rather than into a refusal.
|
|
554
|
+
``peer`` is the remote address of *this* request; see the loopback guard.
|
|
555
|
+
``headers`` is where the caller's credential is read from, and is
|
|
556
|
+
optional so that a test or an adapter with nothing to say about identity
|
|
557
|
+
still compiles — with auth off there is nothing to read.
|
|
558
|
+
"""
|
|
559
|
+
# Exactly the TS relay's test: the trailing slash is required, so a
|
|
560
|
+
# host app owning `/dkstuff` or even `/dk` itself is left alone.
|
|
561
|
+
if not path.startswith("/dk/"):
|
|
562
|
+
return None
|
|
563
|
+
|
|
564
|
+
if self._closed:
|
|
565
|
+
return _json(503, {"error": "relay closed"})
|
|
566
|
+
|
|
567
|
+
if not self.allow_remote and not _is_loopback(peer):
|
|
568
|
+
# Refused here rather than by not binding, because an embedded
|
|
569
|
+
# relay does not own the listening socket and so cannot choose an
|
|
570
|
+
# interface. "Bind to loopback" is advice it is unable to follow,
|
|
571
|
+
# and taken as the whole story it leaves a relay inside a public app
|
|
572
|
+
# server with no guard at all. The check has to live where the
|
|
573
|
+
# requests are.
|
|
574
|
+
return _json(
|
|
575
|
+
403,
|
|
576
|
+
{
|
|
577
|
+
# `forbidden`, as the status table pins it. The slug names
|
|
578
|
+
# the outcome rather than the reason, because with
|
|
579
|
+
# allow_remote on and the app's own auth in front, the next
|
|
580
|
+
# thing to refuse a caller here is not loopback at all.
|
|
581
|
+
"error": "forbidden",
|
|
582
|
+
"hint": "this relay drives a logged-in browser session; set allow_remote "
|
|
583
|
+
"and put your app's own auth in front of it",
|
|
584
|
+
},
|
|
585
|
+
)
|
|
586
|
+
|
|
587
|
+
params = _query(query)
|
|
588
|
+
head = _headers(headers)
|
|
589
|
+
method = (method or "GET").upper()
|
|
590
|
+
|
|
591
|
+
# Identity BEFORE routing. A caller who cannot be identified is told
|
|
592
|
+
# that and nothing else — not which methods a path takes, not whether
|
|
593
|
+
# the path exists. Authenticating after routing is how an unauthorised
|
|
594
|
+
# caller gets to map the surface.
|
|
595
|
+
who = self._whoami(head, params)
|
|
596
|
+
if isinstance(who, Response):
|
|
597
|
+
return who
|
|
598
|
+
|
|
599
|
+
# --- the two the tab uses -------------------------------------------
|
|
600
|
+
if path == "/dk/events":
|
|
601
|
+
if method != "GET":
|
|
602
|
+
return _bad_method("GET")
|
|
603
|
+
tab_id = params.get("tab")
|
|
604
|
+
if not tab_id:
|
|
605
|
+
return bad_request(400, "GET /dk/events needs ?tab=")
|
|
606
|
+
if who.tab is not None and who.tab != tab_id:
|
|
607
|
+
# 403 and not `no-such-tab`, and the difference is the point.
|
|
608
|
+
# The oracle rule is about ADDRESSING somebody else's tab; this
|
|
609
|
+
# caller is opening its own and presented a credential bound to
|
|
610
|
+
# a different id, which it already knows. Telling it so leaks
|
|
611
|
+
# nothing and is the only answer it can act on.
|
|
612
|
+
return _json(
|
|
613
|
+
403,
|
|
614
|
+
{
|
|
615
|
+
"error": "forbidden",
|
|
616
|
+
"hint": "this credential is bound to another tab id",
|
|
617
|
+
},
|
|
618
|
+
)
|
|
619
|
+
return self._open_stream(who, tab_id)
|
|
620
|
+
|
|
621
|
+
if path == "/dk/result":
|
|
622
|
+
if method != "POST":
|
|
623
|
+
return _bad_method("POST")
|
|
624
|
+
frame = _loads(body)
|
|
625
|
+
if not isinstance(frame, Mapping):
|
|
626
|
+
return bad_request(400, "expected a JSON frame", "bad-frame")
|
|
627
|
+
if frame.get("t") not in ("hello", "result", "snapshot"):
|
|
628
|
+
return bad_request(400, f"unknown frame `t`: {frame.get('t')!r}", "bad-frame")
|
|
629
|
+
return self._ingest(who, frame, params.get("tab"))
|
|
630
|
+
|
|
631
|
+
# --- the four the agent uses ----------------------------------------
|
|
632
|
+
if path == "/dk/tabs":
|
|
633
|
+
if method != "GET":
|
|
634
|
+
return _bad_method("GET")
|
|
635
|
+
# The caller's own tabs, and never anybody else's. A listing of
|
|
636
|
+
# every connected tab is an inventory of other people's sessions
|
|
637
|
+
# with their titles and URLs attached, which is the single worst
|
|
638
|
+
# thing on this surface and was the default.
|
|
639
|
+
return _json(200, {"tabs": self.tabs_for(who.id, who.tab)})
|
|
640
|
+
|
|
641
|
+
parts = [p for p in path.split("/") if p] # dk, tabs, :tab, leaf
|
|
642
|
+
if len(parts) == 4 and parts[1] == "tabs":
|
|
643
|
+
tab_id = unquote(parts[2])
|
|
644
|
+
leaf = parts[3]
|
|
645
|
+
|
|
646
|
+
if leaf in ("manifest", "snapshot"):
|
|
647
|
+
if method != "GET":
|
|
648
|
+
return _bad_method("GET")
|
|
649
|
+
with self._lock:
|
|
650
|
+
tab = self._owned(who, tab_id)
|
|
651
|
+
value = (tab.manifest if leaf == "manifest" else tab.snapshot) if tab else None
|
|
652
|
+
# Not Result-shaped, and that asymmetry is on purpose. A Result
|
|
653
|
+
# is the outcome of a CALL; these two read state, and wrapping
|
|
654
|
+
# "there is no such tab" in a fake {ok:false, snapshot} would
|
|
655
|
+
# hand the agent a snapshot that describes nothing. Only /call
|
|
656
|
+
# promises one shape, because only /call is the thing an agent
|
|
657
|
+
# must be able to handle uniformly.
|
|
658
|
+
if tab is None:
|
|
659
|
+
# A tab somebody else owns answers exactly this, byte for
|
|
660
|
+
# byte, so the endpoint cannot be used to probe for other
|
|
661
|
+
# people's tab ids. Note this is checked BEFORE the
|
|
662
|
+
# `no-manifest` case below: a foreign tab that has sent no
|
|
663
|
+
# manifest must not answer `no-manifest`, which would
|
|
664
|
+
# confirm it exists.
|
|
665
|
+
return _json(404, {"error": "no-such-tab", "hint": NO_SUCH_TAB_HINT})
|
|
666
|
+
if value is None:
|
|
667
|
+
return _json(
|
|
668
|
+
404,
|
|
669
|
+
{"error": f"no-{leaf}", "hint": f"tab `{tab_id}` has sent no {leaf}"},
|
|
670
|
+
)
|
|
671
|
+
return _json(200, value)
|
|
672
|
+
|
|
673
|
+
if leaf == "watch":
|
|
674
|
+
if method != "GET":
|
|
675
|
+
return _bad_method("GET")
|
|
676
|
+
with self._lock:
|
|
677
|
+
known = self._owned(who, tab_id) is not None
|
|
678
|
+
# 404 for a tab that is not connected, rather than an open
|
|
679
|
+
# stream that may never carry anything. Consistent with
|
|
680
|
+
# /snapshot, and it is the answer that tells a client to re-read
|
|
681
|
+
# /dk/tabs instead of waiting on a subscription to a screen that
|
|
682
|
+
# does not exist.
|
|
683
|
+
if not known:
|
|
684
|
+
return _json(404, {"error": "no-such-tab", "hint": NO_SUCH_TAB_HINT})
|
|
685
|
+
return self._open_watch(who, tab_id)
|
|
686
|
+
|
|
687
|
+
if leaf == "call":
|
|
688
|
+
if method != "POST":
|
|
689
|
+
return _bad_method("POST")
|
|
690
|
+
return self._call(who, tab_id, body)
|
|
691
|
+
|
|
692
|
+
return bad_request(404, f"no driverkit route {method} {path}", "no-route")
|
|
693
|
+
|
|
694
|
+
# ---- the tab's end -----------------------------------------------------
|
|
695
|
+
|
|
696
|
+
def _open_stream(self, who: Principal, tab_id: str) -> Response:
|
|
697
|
+
"""Open a tab's stream and BIND the tab to the caller's principal.
|
|
698
|
+
|
|
699
|
+
The binding happens here, at first contact, rather than on ``hello``.
|
|
700
|
+
PROTOCOL.md already describes the window between a stream opening and
|
|
701
|
+
its ``hello`` landing on a separate POST; binding at ``hello`` would
|
|
702
|
+
make that window one in which a tab exists and belongs to nobody, and
|
|
703
|
+
an unowned tab is one every principal either can or cannot see, both of
|
|
704
|
+
which are wrong. Binding at open leaves no such state.
|
|
705
|
+
|
|
706
|
+
What this means for a credential that expires MID-SESSION: nothing. The
|
|
707
|
+
binding is the relay's record and lasts as long as the stream, not as
|
|
708
|
+
long as the token. A relay that hung up at ``exp`` would disconnect
|
|
709
|
+
every tab in the deployment once per token lifetime, mid-verb, while a
|
|
710
|
+
person watched — and the fix people reach for, a longer lifetime, is
|
|
711
|
+
strictly worse because it also widens the window a leaked token is
|
|
712
|
+
useful in. Short tokens plus a binding that outlives them gives both.
|
|
713
|
+
|
|
714
|
+
The credential is still needed for ``POST /dk/result``, which is a new
|
|
715
|
+
request and carries its own; see ``connect``'s token getter, which is a
|
|
716
|
+
function for exactly this reason.
|
|
717
|
+
"""
|
|
718
|
+
stream = Stream(self.ping_s)
|
|
719
|
+
key = (who.id, tab_id)
|
|
720
|
+
with self._lock:
|
|
721
|
+
existing = self._tabs.get(key)
|
|
722
|
+
if existing is not None:
|
|
723
|
+
# A second stream for a known id is a reconnect, not a new tab:
|
|
724
|
+
# the id is minted by the tab precisely so it survives one.
|
|
725
|
+
# Carry the known facts and the calls in flight across — a tab
|
|
726
|
+
# that was mid-verb when its stream blinked can still POST the
|
|
727
|
+
# result on the new one, and failing those calls would turn a
|
|
728
|
+
# recovered hiccup into an error the agent has to handle.
|
|
729
|
+
tab = _Tab(
|
|
730
|
+
tab=tab_id,
|
|
731
|
+
principal=who.id,
|
|
732
|
+
since=existing.since,
|
|
733
|
+
stream=stream,
|
|
734
|
+
pending=existing.pending,
|
|
735
|
+
app=existing.app,
|
|
736
|
+
title=existing.title,
|
|
737
|
+
url=existing.url,
|
|
738
|
+
manifest=existing.manifest,
|
|
739
|
+
snapshot=existing.snapshot,
|
|
740
|
+
)
|
|
741
|
+
else:
|
|
742
|
+
tab = _Tab(tab=tab_id, principal=who.id, since=_now(), stream=stream)
|
|
743
|
+
self._tabs[key] = tab
|
|
744
|
+
|
|
745
|
+
if existing is not None:
|
|
746
|
+
existing.stream.close()
|
|
747
|
+
|
|
748
|
+
def gone() -> None:
|
|
749
|
+
with self._lock:
|
|
750
|
+
# Only drop the registry entry if it is still OURS. A reconnect
|
|
751
|
+
# replaces the record first and then ends the old stream, so the
|
|
752
|
+
# old close fires afterwards and would otherwise delete the live
|
|
753
|
+
# tab.
|
|
754
|
+
if self._tabs.get(key) is not tab:
|
|
755
|
+
return
|
|
756
|
+
del self._tabs[key]
|
|
757
|
+
# Fail what is in flight instead of letting each call sit out
|
|
758
|
+
# its own deadline. The answer is already known — nobody is
|
|
759
|
+
# going to reply — and "no queue" means the agent learns that
|
|
760
|
+
# now, while it still has the context to try something else.
|
|
761
|
+
for pending in tab.pending.values():
|
|
762
|
+
self._settle(
|
|
763
|
+
pending,
|
|
764
|
+
self._refusal("tab-went-away", f"tab `{tab_id}` closed its stream"),
|
|
765
|
+
"tab-went-away",
|
|
766
|
+
)
|
|
767
|
+
tab.pending.clear()
|
|
768
|
+
|
|
769
|
+
stream.on_close(gone)
|
|
770
|
+
return Response(200, SSE_HEADERS, stream=stream)
|
|
771
|
+
|
|
772
|
+
def _ingest(
|
|
773
|
+
self, who: Principal, frame: Mapping[str, Any], tab_from_query: str | None
|
|
774
|
+
) -> Response:
|
|
775
|
+
"""One tab→relay frame, and the answer to the POST that carried it.
|
|
776
|
+
|
|
777
|
+
The statuses are the pinned ones, and the split between them is the
|
|
778
|
+
point: ``400 unplaceable`` and ``400 bad-frame`` say the frame could
|
|
779
|
+
never have been accepted by anybody, so the tab has a bug;
|
|
780
|
+
``409 no-such-tab`` says the frame was fine and the relay's state made
|
|
781
|
+
it unacceptable, so reconnecting and retrying is reasonable. Answering
|
|
782
|
+
both with one slug would make a tab author guess which they had.
|
|
783
|
+
|
|
784
|
+
Every tab→relay frame carries ``tab``, because ``POST /dk/result`` has
|
|
785
|
+
no path parameter and the relay serves many tabs at once. A ``?tab=`` on
|
|
786
|
+
the URL is accepted too, and a tab may send both — but ``hello`` is the
|
|
787
|
+
frame that defines the identity, so its own field wins there.
|
|
788
|
+
|
|
789
|
+
**A tab may not answer another tab's call**, and two things enforce it.
|
|
790
|
+
A tab the caller does not own is not found at all (:meth:`_owned`), so
|
|
791
|
+
the cross-PERSON case is the same 409 as a tab that is not connected.
|
|
792
|
+
Within one person, who legitimately has several tabs open, the pending
|
|
793
|
+
map is per-tab-record and call ids are unique across the relay, so a
|
|
794
|
+
``result`` for a call issued to another of their tabs finds nothing to
|
|
795
|
+
settle and is dropped as a late answer. A credential carrying a ``tab``
|
|
796
|
+
claim closes that case cryptographically as well; without one, the
|
|
797
|
+
pending map is what holds, which is a weaker statement and is said here
|
|
798
|
+
rather than left to be assumed.
|
|
799
|
+
"""
|
|
800
|
+
kind = frame.get("t")
|
|
801
|
+
tab_id = frame.get("tab") if kind == "hello" else (tab_from_query or frame.get("tab"))
|
|
802
|
+
if not tab_id or not isinstance(tab_id, str):
|
|
803
|
+
# Unplaceable, and that is a 400: no state of this relay could have
|
|
804
|
+
# accepted it, because a frame that names nobody cannot be routed
|
|
805
|
+
# even in principle. `POST /dk/result` has no path parameter and the
|
|
806
|
+
# relay serves many tabs at once.
|
|
807
|
+
return bad_request(400, "no tab id: pass ?tab= or a `tab` field", "unplaceable")
|
|
808
|
+
with self._lock:
|
|
809
|
+
tab = self._owned(who, tab_id)
|
|
810
|
+
if tab is None:
|
|
811
|
+
# 409, not 400: the frame is fine and the relay's state is what
|
|
812
|
+
# makes it unacceptable. The tab may reasonably reconnect — it
|
|
813
|
+
# probably just did, and its `hello` lost a race with this.
|
|
814
|
+
#
|
|
815
|
+
# A tab that belongs to someone else lands here too, with the
|
|
816
|
+
# same body, which is the oracle rule applied to the tab's own
|
|
817
|
+
# endpoint: "not yours" and "not connected" must be one answer.
|
|
818
|
+
return _json(409, {"error": "no-such-tab", "hint": NO_SUCH_TAB_HINT})
|
|
819
|
+
|
|
820
|
+
if kind == "hello":
|
|
821
|
+
# Upsert, not insert. `hello` arrives again after every
|
|
822
|
+
# reconnect, and the app may have navigated in between, so the
|
|
823
|
+
# later one wins on every field it carries and leaves the rest
|
|
824
|
+
# alone.
|
|
825
|
+
for name in ("app", "title", "url", "focus", "manifest"):
|
|
826
|
+
if name in frame and frame[name] is not None:
|
|
827
|
+
setattr(tab, name, frame[name])
|
|
828
|
+
snapshot = frame.get("snapshot")
|
|
829
|
+
if isinstance(snapshot, Mapping):
|
|
830
|
+
tab.snapshot = dict(snapshot)
|
|
831
|
+
self._push(tab)
|
|
832
|
+
return _accepted()
|
|
833
|
+
|
|
834
|
+
if kind == "snapshot":
|
|
835
|
+
snapshot = frame.get("snapshot")
|
|
836
|
+
if not isinstance(snapshot, Mapping):
|
|
837
|
+
# Same reasoning as a `result` that is not an object: the
|
|
838
|
+
# discriminator was checked and the payload was not, which
|
|
839
|
+
# is exactly the assumption a relay is not entitled to make.
|
|
840
|
+
return bad_request(
|
|
841
|
+
400, "a `snapshot` frame needs a `snapshot` object", "bad-frame"
|
|
842
|
+
)
|
|
843
|
+
tab.snapshot = dict(snapshot)
|
|
844
|
+
# The same upsert rule `hello` uses, on the two fields a push
|
|
845
|
+
# may now carry. `url` is here because it had no other way of
|
|
846
|
+
# ever being right: it came from `hello` alone, and a
|
|
847
|
+
# single-page app navigates without reconnecting, so a tab's
|
|
848
|
+
# url in `/dk/tabs` was whatever it had been at page load.
|
|
849
|
+
# Absent leaves the stored value alone, which is what keeps a
|
|
850
|
+
# tab connected by a hand-written loop — or by a driverkit
|
|
851
|
+
# older than this field — reading exactly as it did.
|
|
852
|
+
for name in ("url", "focus"):
|
|
853
|
+
if frame.get(name) is not None:
|
|
854
|
+
setattr(tab, name, frame[name])
|
|
855
|
+
# Always forwarded, even at an unchanged rev. This frame is the
|
|
856
|
+
# tab SAYING the page moved, and second-guessing it here would
|
|
857
|
+
# make the relay the thing that decides what counts as a change
|
|
858
|
+
# — which is the app's judgement, carried in `rev`, not the
|
|
859
|
+
# relay's.
|
|
860
|
+
self._push(tab, force=True)
|
|
861
|
+
return _accepted()
|
|
862
|
+
|
|
863
|
+
# kind == "result"
|
|
864
|
+
call_id = frame.get("id")
|
|
865
|
+
result = frame.get("result")
|
|
866
|
+
if not isinstance(result, Mapping):
|
|
867
|
+
# Rejected BEFORE the pending call is touched, and that order is
|
|
868
|
+
# the whole fix. Settling it with whatever this was would answer
|
|
869
|
+
# the agent a body that is not a `WireResult`, and that is the
|
|
870
|
+
# one promise /call makes. Leaving the call pending means it
|
|
871
|
+
# ends as an honest `timeout` — "no answer arrived" is exactly
|
|
872
|
+
# what happened, and the tab is told its frame was the problem.
|
|
873
|
+
#
|
|
874
|
+
# The cause is worth naming because it is a general trap: the
|
|
875
|
+
# frame's discriminator `t` was validated and the frame's
|
|
876
|
+
# payload was trusted, which is an assumption a relay is not
|
|
877
|
+
# entitled to make about anything on the wire.
|
|
878
|
+
return bad_request(400, "a `result` frame needs a `result` object", "bad-frame")
|
|
879
|
+
pending = tab.pending.pop(str(call_id), None)
|
|
880
|
+
# An id the relay is not waiting on is DROPPED, not an error. It
|
|
881
|
+
# means the call already timed out and the tab answered late;
|
|
882
|
+
# resurrecting it would deliver an answer to a request that has
|
|
883
|
+
# already been responded to — and a 4xx would make a slow verb look
|
|
884
|
+
# like a broken one.
|
|
885
|
+
if pending is None:
|
|
886
|
+
return _accepted(f"no call `{call_id}` in flight")
|
|
887
|
+
# Forwarded byte for byte. A `stale` refusal the driver produced
|
|
888
|
+
# must reach the agent as the driver wrote it, hint and snapshot
|
|
889
|
+
# included — that hint is how the agent knows to re-read instead of
|
|
890
|
+
# retrying the same dead rev.
|
|
891
|
+
snapshot = result.get("snapshot")
|
|
892
|
+
if isinstance(snapshot, Mapping):
|
|
893
|
+
tab.snapshot = dict(snapshot)
|
|
894
|
+
# Watchers hear about an agent's change too, not only a human's.
|
|
895
|
+
# /watch exists so a watcher need not poll; one that learned
|
|
896
|
+
# only about human-caused moves would still have to poll for the
|
|
897
|
+
# rest, which is the cost the endpoint was added to remove.
|
|
898
|
+
# Deduped on `rev`, so a refusal that moved nothing stays quiet.
|
|
899
|
+
self._push(tab)
|
|
900
|
+
# `delivered`, and nothing more. The tab answered; what it
|
|
901
|
+
# answered is the driver's own record to make, in the process where
|
|
902
|
+
# it was decided. The tab's own elapsed time rides along on the
|
|
903
|
+
# answer and is NOT in the record: see :func:`_timed`, and
|
|
904
|
+
# :meth:`_audit` for the argument.
|
|
905
|
+
self._settle(pending, _timed(result, frame), "delivered")
|
|
906
|
+
return _accepted()
|
|
907
|
+
|
|
908
|
+
# ---- the agent's end ---------------------------------------------------
|
|
909
|
+
|
|
910
|
+
def _call(self, who: Principal, tab_id: str, body: bytes | None) -> Response:
|
|
911
|
+
parsed = _loads(body)
|
|
912
|
+
name = parsed.get("name") if isinstance(parsed, Mapping) else None
|
|
913
|
+
if not isinstance(name, str) or not name:
|
|
914
|
+
# A body with no `name` is MALFORMED, not refused: there is no verb
|
|
915
|
+
# to have said no, so dressing it as a WireResult would teach an
|
|
916
|
+
# agent to look for a `bad-request` slug the closed set does not
|
|
917
|
+
# contain, and would make it rephrase a request that never reached
|
|
918
|
+
# an app.
|
|
919
|
+
return bad_request(400, "a call needs a `name`")
|
|
920
|
+
assert isinstance(parsed, Mapping)
|
|
921
|
+
|
|
922
|
+
# Before the lookup, so `ms` is the time the agent actually waited and
|
|
923
|
+
# not the time minus whatever the registry cost.
|
|
924
|
+
started = time.time()
|
|
925
|
+
|
|
926
|
+
with self._lock:
|
|
927
|
+
tab = self._owned(who, tab_id)
|
|
928
|
+
if tab is None:
|
|
929
|
+
# Shaped like every other answer. An agent holding a tab id from
|
|
930
|
+
# a closed window gets a refusal it can read with the same code
|
|
931
|
+
# path it uses for "that row is not deletable".
|
|
932
|
+
#
|
|
933
|
+
# And a tab belonging to another principal gets THIS, not a 403:
|
|
934
|
+
# a refusal an agent reads as "that window is gone", identical
|
|
935
|
+
# in status, slug and hint to one for an id that was never
|
|
936
|
+
# minted. A 403 here would turn `/call` into a membership test
|
|
937
|
+
# for other people's tab ids.
|
|
938
|
+
# Recorded, and this is the half of the trail the driver cannot
|
|
939
|
+
# have: nothing reached a tab, so no `on_audit` anywhere else in
|
|
940
|
+
# the library will ever hear about this call. An agent working
|
|
941
|
+
# through tab ids it does not own leaves its marks only here.
|
|
942
|
+
self._audit(who.id, tab_id, name, started, "no-such-tab")
|
|
943
|
+
return _json(
|
|
944
|
+
200,
|
|
945
|
+
self._refusal("no-such-tab", NO_SUCH_TAB_HINT + "; GET /dk/tabs to list them"),
|
|
946
|
+
)
|
|
947
|
+
call_id = f"c-{self._next_call}"
|
|
948
|
+
self._next_call += 1
|
|
949
|
+
pending = _Pending(
|
|
950
|
+
principal=who.id, tab=tab_id, verb=name, started=started
|
|
951
|
+
)
|
|
952
|
+
tab.pending[call_id] = pending
|
|
953
|
+
frame: dict[str, Any] = {"t": "call", "id": call_id, "name": name}
|
|
954
|
+
args = parsed.get("args")
|
|
955
|
+
if isinstance(args, Mapping):
|
|
956
|
+
frame["args"] = dict(args)
|
|
957
|
+
rev = parsed.get("rev")
|
|
958
|
+
# Forwarded only when the agent sent one. Defaulting it would
|
|
959
|
+
# silently opt an agent into a staleness check it did not ask for;
|
|
960
|
+
# dropping it would silently opt it out of one it did. Neither is
|
|
961
|
+
# the relay's call.
|
|
962
|
+
if isinstance(rev, (int, float)) and not isinstance(rev, bool):
|
|
963
|
+
frame["rev"] = rev
|
|
964
|
+
screen = parsed.get("screen")
|
|
965
|
+
# `screen` on exactly the same terms, and with the same restraint:
|
|
966
|
+
# this relay does not know which screen the tab is on, does not
|
|
967
|
+
# compare it and does not refuse it. It is the agent's claim and the
|
|
968
|
+
# driver's check. An empty string is dropped rather than forwarded,
|
|
969
|
+
# because it is not the id of any screen and no app should be asked
|
|
970
|
+
# to refuse a call over a field left blank. Behaviourally identical
|
|
971
|
+
# to the TypeScript relay, which is the standing promise about these
|
|
972
|
+
# two files.
|
|
973
|
+
if isinstance(screen, str) and screen:
|
|
974
|
+
frame["screen"] = screen
|
|
975
|
+
plan = parsed.get("plan")
|
|
976
|
+
# `plan` on the same terms again, and here the restraint is not even
|
|
977
|
+
# a choice: the token is opaque to everything but the core that
|
|
978
|
+
# minted it, so a relay has nothing to compare it against and could
|
|
979
|
+
# only ever get the comparison wrong. Dropped when blank, like
|
|
980
|
+
# `screen`, because an empty string is not a token and the core's
|
|
981
|
+
# refusal should name the field the agent actually left out.
|
|
982
|
+
# Behaviourally identical to the TypeScript relay, which is the
|
|
983
|
+
# standing promise about these two files.
|
|
984
|
+
if isinstance(plan, str) and plan:
|
|
985
|
+
frame["plan"] = plan
|
|
986
|
+
sent = tab.stream.write(_sse(frame))
|
|
987
|
+
if not sent:
|
|
988
|
+
tab.pending.pop(call_id, None)
|
|
989
|
+
self._audit(who.id, tab_id, name, started, "tab-went-away")
|
|
990
|
+
return _json(200, self._refusal("tab-went-away", f"writing to tab `{tab_id}` failed"))
|
|
991
|
+
|
|
992
|
+
# NO LOCK HELD. This is the blocking half of the relay, and holding
|
|
993
|
+
# anything across it would mean one wedged tab freezes every other.
|
|
994
|
+
if not pending.event.wait(self.timeout_s):
|
|
995
|
+
with self._lock:
|
|
996
|
+
# The deadline and the frame can race. If the answer landed in
|
|
997
|
+
# that window it is the answer, and discarding it to report a
|
|
998
|
+
# timeout would be inventing a failure.
|
|
999
|
+
if pending.result is None:
|
|
1000
|
+
tab.pending.pop(call_id, None)
|
|
1001
|
+
# NOT a promise the call did not happen. The tab may have
|
|
1002
|
+
# run the verb and died before answering, so a `commit`
|
|
1003
|
+
# that times out has an unknown outcome and the agent must
|
|
1004
|
+
# read the screen before retrying. The relay says only "no
|
|
1005
|
+
# answer arrived"; guessing further here is how every client
|
|
1006
|
+
# ends up inventing a different guess.
|
|
1007
|
+
self._settle(
|
|
1008
|
+
pending,
|
|
1009
|
+
self._refusal(
|
|
1010
|
+
"timeout",
|
|
1011
|
+
f"tab `{tab_id}` did not answer `{name}` within {self.timeout_s}s",
|
|
1012
|
+
),
|
|
1013
|
+
"timeout",
|
|
1014
|
+
)
|
|
1015
|
+
assert pending.result is not None
|
|
1016
|
+
# 200 even for a refusal. The HTTP layer succeeded: the question was
|
|
1017
|
+
# asked and answered. `ok: false` is the answer, not a transport
|
|
1018
|
+
# failure, and conflating the two is how an agent ends up retrying a
|
|
1019
|
+
# refusal it should have read.
|
|
1020
|
+
return _json(200, pending.result)
|
|
1021
|
+
|
|
1022
|
+
def _open_watch(self, who: Principal, tab_id: str) -> Response:
|
|
1023
|
+
"""Subscribe an agent to a tab's ``snapshot`` frames.
|
|
1024
|
+
|
|
1025
|
+
The same SSE shape the tab's own stream uses, down to the opening
|
|
1026
|
+
comment and the ping, so a client needs one parser for both directions
|
|
1027
|
+
rather than two that drift.
|
|
1028
|
+
"""
|
|
1029
|
+
stream = Stream(self.ping_s)
|
|
1030
|
+
key = (who.id, tab_id)
|
|
1031
|
+
with self._lock:
|
|
1032
|
+
self._watchers.setdefault(key, set()).add(stream)
|
|
1033
|
+
tab = self._tabs.get(key)
|
|
1034
|
+
known = tab.snapshot if tab else None
|
|
1035
|
+
if known is not None:
|
|
1036
|
+
# The current snapshot goes out immediately. A watcher that
|
|
1037
|
+
# attached to an idle screen would otherwise know nothing at all
|
|
1038
|
+
# until the next click, and would have to fetch /snapshot anyway
|
|
1039
|
+
# — which is the poll the endpoint exists to remove.
|
|
1040
|
+
stream.write(_sse({"t": "snapshot", "tab": tab_id, "snapshot": known}))
|
|
1041
|
+
|
|
1042
|
+
def gone() -> None:
|
|
1043
|
+
with self._lock:
|
|
1044
|
+
live = self._watchers.get(key)
|
|
1045
|
+
if live is None:
|
|
1046
|
+
return
|
|
1047
|
+
live.discard(stream)
|
|
1048
|
+
if not live:
|
|
1049
|
+
del self._watchers[key]
|
|
1050
|
+
|
|
1051
|
+
stream.on_close(gone)
|
|
1052
|
+
return Response(200, SSE_HEADERS, stream=stream)
|
|
1053
|
+
|
|
1054
|
+
# ---- who is calling ----------------------------------------------------
|
|
1055
|
+
|
|
1056
|
+
def _whoami(self, headers: Mapping[str, str], params: Mapping[str, str]) -> "Principal | Response":
|
|
1057
|
+
"""The caller's principal, or the 401 to answer instead.
|
|
1058
|
+
|
|
1059
|
+
Three doors, in this order:
|
|
1060
|
+
|
|
1061
|
+
1. **Auth off.** Neither ``auth`` nor ``resolve_principal`` configured:
|
|
1062
|
+
everything is one principal and nothing is scoped. This is the
|
|
1063
|
+
unconfigured loopback relay a single developer runs, and it needs no
|
|
1064
|
+
tokens, no keys and no setup — the combination ``allow_remote``
|
|
1065
|
+
makes impossible is the one where this is also exposed.
|
|
1066
|
+
2. **``resolve_principal``.** The embedded case: an app that already
|
|
1067
|
+
has sessions answers from its own middleware. Returning ``None``
|
|
1068
|
+
falls through, so it can handle its logged-in users and leave
|
|
1069
|
+
anonymous visitors to the token path.
|
|
1070
|
+
3. **The credential.** See :func:`_credential` for where it is read
|
|
1071
|
+
from and :mod:`driverkit.auth` for what it proves.
|
|
1072
|
+
|
|
1073
|
+
**No credential and a bad credential are different answers**, and
|
|
1074
|
+
neither is "anonymous". A request with nothing to present gets
|
|
1075
|
+
``no-credential``; one whose credential does not check out gets
|
|
1076
|
+
``bad-credential`` *for every reason it might not check out*. Silently
|
|
1077
|
+
treating an unreadable credential as a fresh anonymous visitor was the
|
|
1078
|
+
tempting shape and is the wrong one twice over: a user whose token
|
|
1079
|
+
lapsed would quietly become a stranger and lose their own tabs, and an
|
|
1080
|
+
agent with a misconfigured key would be told "you have no tabs" rather
|
|
1081
|
+
than "your key is wrong". Anonymous is a credential of its own kind, so
|
|
1082
|
+
it is never what the absence of one means.
|
|
1083
|
+
"""
|
|
1084
|
+
if self._auth is None and self._resolve is None:
|
|
1085
|
+
return _LOCAL
|
|
1086
|
+
|
|
1087
|
+
if self._resolve is not None:
|
|
1088
|
+
try:
|
|
1089
|
+
resolved = self._resolve(headers)
|
|
1090
|
+
except Exception as err:
|
|
1091
|
+
# A host hook that throws must not become a 500 that mentions
|
|
1092
|
+
# the app's internals, and must certainly not become an
|
|
1093
|
+
# authenticated request. It is an unidentified caller.
|
|
1094
|
+
self._on_error(err)
|
|
1095
|
+
resolved = None
|
|
1096
|
+
if resolved:
|
|
1097
|
+
return Principal(id=str(resolved))
|
|
1098
|
+
|
|
1099
|
+
if self._auth is None:
|
|
1100
|
+
return _unauthorized("no-credential", "this relay identifies callers by session")
|
|
1101
|
+
|
|
1102
|
+
credential = _credential(headers, params)
|
|
1103
|
+
if not credential:
|
|
1104
|
+
return _unauthorized(
|
|
1105
|
+
"no-credential",
|
|
1106
|
+
"present a tab token: Authorization: Bearer, X-DK-Token, the dk_token cookie, "
|
|
1107
|
+
"or ?dk_token= (the last of those ends up in proxy access logs)",
|
|
1108
|
+
)
|
|
1109
|
+
try:
|
|
1110
|
+
return self._auth.principal(credential)
|
|
1111
|
+
except AuthError:
|
|
1112
|
+
# ONE slug for every way a credential can fail, and the hint is
|
|
1113
|
+
# fixed. "The signature verified but the audience was wrong" tells
|
|
1114
|
+
# a forger that the forgery worked; "expired" and "not yet valid"
|
|
1115
|
+
# tell a prober the clock. A legitimate client's move is the same
|
|
1116
|
+
# in every case — mint a fresh token, retry once — so the
|
|
1117
|
+
# distinction buys it nothing and buys an attacker a test harness.
|
|
1118
|
+
# The reason is never logged either: it would be a log line about a
|
|
1119
|
+
# credential.
|
|
1120
|
+
return _unauthorized("bad-credential", "present a fresh tab token")
|
|
1121
|
+
|
|
1122
|
+
def _owned(self, who: Principal, tab_id: str) -> "_Tab | None":
|
|
1123
|
+
"""The caller's tab, or ``None``. The ONLY way this file finds a tab.
|
|
1124
|
+
|
|
1125
|
+
``None`` covers three cases on purpose — no such tab, somebody else's
|
|
1126
|
+
tab, and a tab outside what a tab-bound credential may address — and
|
|
1127
|
+
every caller turns it into the same ``no-such-tab``. Collapsing them
|
|
1128
|
+
here rather than at each endpoint is what makes the property hold for
|
|
1129
|
+
an endpoint added later: there is no lookup by bare tab id to reach
|
|
1130
|
+
for. Called with the lock.
|
|
1131
|
+
"""
|
|
1132
|
+
if who.tab is not None and who.tab != tab_id:
|
|
1133
|
+
return None
|
|
1134
|
+
return self._tabs.get((who.id, tab_id))
|
|
1135
|
+
|
|
1136
|
+
# ---- plumbing ----------------------------------------------------------
|
|
1137
|
+
|
|
1138
|
+
def _push(self, tab: _Tab, force: bool = False) -> None:
|
|
1139
|
+
"""Fan a tab's current snapshot out to its watchers. Called with the lock."""
|
|
1140
|
+
snapshot = tab.snapshot
|
|
1141
|
+
if snapshot is None:
|
|
1142
|
+
return
|
|
1143
|
+
rev = snapshot.get("rev")
|
|
1144
|
+
key = (tab.principal, tab.tab)
|
|
1145
|
+
if not force and self._broadcast.get(key, object()) == rev:
|
|
1146
|
+
return
|
|
1147
|
+
if isinstance(rev, int):
|
|
1148
|
+
self._broadcast[key] = rev
|
|
1149
|
+
chunk = _sse({"t": "snapshot", "tab": tab.tab, "snapshot": snapshot})
|
|
1150
|
+
# A copy, because a watcher that has hung up removes itself from the set
|
|
1151
|
+
# through its own close callback, which runs on another thread.
|
|
1152
|
+
for stream in list(self._watchers.get(key, ())):
|
|
1153
|
+
try:
|
|
1154
|
+
stream.write(chunk)
|
|
1155
|
+
except Exception as err: # pragma: no cover - write() does not raise
|
|
1156
|
+
self._on_error(err)
|
|
1157
|
+
|
|
1158
|
+
def _settle(self, pending: _Pending, result: dict[str, Any], outcome: str) -> None:
|
|
1159
|
+
"""Answer a waiting call once, saying what the RELAY decided.
|
|
1160
|
+
|
|
1161
|
+
``outcome`` is required rather than derived from ``result``, for the
|
|
1162
|
+
reason the TypeScript relay's is: a relay refusal is recognisable from a
|
|
1163
|
+
``WireResult`` only by its missing ``snapshot``, and an audit record
|
|
1164
|
+
must not rest on an invariant the wire can violate. Required also means
|
|
1165
|
+
a sixth place to settle a call cannot be added without saying what it
|
|
1166
|
+
is.
|
|
1167
|
+
|
|
1168
|
+
One record per call, from the one place a call can be answered: the
|
|
1169
|
+
``pending.result is not None`` guard above is what makes it one, because
|
|
1170
|
+
the deadline and a late ``result`` frame race and the loser must not log
|
|
1171
|
+
a second outcome for a call already answered.
|
|
1172
|
+
"""
|
|
1173
|
+
if pending.result is not None:
|
|
1174
|
+
return
|
|
1175
|
+
pending.result = result
|
|
1176
|
+
pending.event.set()
|
|
1177
|
+
self._audit(pending.principal, pending.tab, pending.verb, pending.started, outcome)
|
|
1178
|
+
|
|
1179
|
+
def _audit(self, principal: str, tab: str, verb: str, started: float, outcome: str) -> None:
|
|
1180
|
+
"""Hand one record to the host, and survive the host.
|
|
1181
|
+
|
|
1182
|
+
Byte for byte the same event the TypeScript relay emits -- same five
|
|
1183
|
+
field names, same four outcomes, ``at`` and ``ms`` in milliseconds since
|
|
1184
|
+
the epoch because that is what ``Date.now()`` is and an operator reading
|
|
1185
|
+
both logs must not have to convert one. A throw goes to ``on_error``,
|
|
1186
|
+
where everything else this relay cannot help goes: a 500 because the
|
|
1187
|
+
logging backend is down would turn an audit trail into an outage.
|
|
1188
|
+
|
|
1189
|
+
THE TAB'S OWN ``tookMs`` IS DELIBERATELY NOT HERE, although the relay
|
|
1190
|
+
now carries one to the agent. It is a figure measured in another
|
|
1191
|
+
process, and copying somebody else's measurement into this record is the
|
|
1192
|
+
same mistake as copying their verdict: ``outcome`` says ``delivered``
|
|
1193
|
+
rather than ``ok`` because "a relay logging ``ok`` for a call whose tab
|
|
1194
|
+
died mid-commit asserts an outcome nobody observed", and a duration the
|
|
1195
|
+
relay cannot check is in that category. It would also invite the one
|
|
1196
|
+
subtraction nobody should make: ``ms - tookMs`` is not "the network", it
|
|
1197
|
+
is the network plus however long the frame sat in the tab's event loop
|
|
1198
|
+
plus whatever a proxy buffered.
|
|
1199
|
+
"""
|
|
1200
|
+
if self._on_audit is None:
|
|
1201
|
+
return
|
|
1202
|
+
at = time.time()
|
|
1203
|
+
try:
|
|
1204
|
+
self._on_audit(
|
|
1205
|
+
{
|
|
1206
|
+
"at": int(at * 1000),
|
|
1207
|
+
"ms": int((at - started) * 1000),
|
|
1208
|
+
"principal": principal,
|
|
1209
|
+
"tab": tab,
|
|
1210
|
+
"verb": verb,
|
|
1211
|
+
"outcome": outcome,
|
|
1212
|
+
}
|
|
1213
|
+
)
|
|
1214
|
+
except Exception as err:
|
|
1215
|
+
self._on_error(err)
|
|
1216
|
+
|
|
1217
|
+
def _refusal(self, refused: str, hint: str) -> dict[str, Any]:
|
|
1218
|
+
"""A refusal the relay originated: one of a closed set, and with NO
|
|
1219
|
+
``snapshot``.
|
|
1220
|
+
|
|
1221
|
+
The missing field is the whole signal. ``Result`` requires a snapshot
|
|
1222
|
+
because a driver mounted in a page always has one; the relay often does
|
|
1223
|
+
not — a call to a tab that never connected has no screen behind it at
|
|
1224
|
+
all — so the shape holds and ``snapshot`` goes missing, which is the
|
|
1225
|
+
truthful thing to say: nothing ran and nobody looked.
|
|
1226
|
+
|
|
1227
|
+
An invented snapshot would be worse than a missing one in both
|
|
1228
|
+
directions. An empty one tells an agent the app has no rows, which is a
|
|
1229
|
+
lie about the app rather than about the call. A sentinel like
|
|
1230
|
+
``{"where": "(not connected)"}`` is still a snapshot, so some client
|
|
1231
|
+
eventually renders it to a model as though it were a screen. Absence
|
|
1232
|
+
cannot be mistaken for either. The TS relay carried such a sentinel in
|
|
1233
|
+
its first draft and it was removed for exactly this reason; this is the
|
|
1234
|
+
one place the port must not be creative.
|
|
1235
|
+
"""
|
|
1236
|
+
assert refused in RELAY_REFUSALS, f"{refused!r} is not a relay refusal"
|
|
1237
|
+
# Built through Result rather than by hand, because Result.to_dict is
|
|
1238
|
+
# already the code that omits an absent snapshot — and a second place
|
|
1239
|
+
# that decides what a refusal looks like is a second place to get it
|
|
1240
|
+
# wrong.
|
|
1241
|
+
return Result(ok=False, refused=refused, hint=hint).to_dict()
|
|
1242
|
+
|
|
1243
|
+
def _summary(self, tab: _Tab) -> dict[str, Any]:
|
|
1244
|
+
"""One row of ``GET /dk/tabs``. Called with the lock."""
|
|
1245
|
+
out: dict[str, Any] = {"tab": tab.tab}
|
|
1246
|
+
if tab.app is not None:
|
|
1247
|
+
out["app"] = tab.app
|
|
1248
|
+
if tab.title is not None:
|
|
1249
|
+
out["title"] = tab.title
|
|
1250
|
+
if tab.url is not None:
|
|
1251
|
+
out["url"] = tab.url
|
|
1252
|
+
# Forwarded exactly as the tab said it, including not at all. Absence
|
|
1253
|
+
# is "the tab did not say", which a client must not read as "not the
|
|
1254
|
+
# one". The relay has no opinion here and originates no value, for the
|
|
1255
|
+
# same reason it does not interpret ``rev``.
|
|
1256
|
+
if tab.focus is not None:
|
|
1257
|
+
out["focus"] = tab.focus
|
|
1258
|
+
if isinstance(tab.manifest, Mapping):
|
|
1259
|
+
# The version, not the manifest. Listing tabs is the cheap call an
|
|
1260
|
+
# agent makes often; inlining every manifest would make it the
|
|
1261
|
+
# expensive one, and the version is all a cache needs to learn its
|
|
1262
|
+
# copy went stale.
|
|
1263
|
+
out["manifestVersion"] = tab.manifest.get("version")
|
|
1264
|
+
if isinstance(tab.snapshot, Mapping) and "rev" in tab.snapshot:
|
|
1265
|
+
out["rev"] = tab.snapshot["rev"]
|
|
1266
|
+
out["since"] = tab.since
|
|
1267
|
+
return out
|
|
1268
|
+
|
|
1269
|
+
|
|
1270
|
+
# --- small helpers ----------------------------------------------------------
|
|
1271
|
+
|
|
1272
|
+
|
|
1273
|
+
def _timed(result: Mapping[str, Any], frame: Mapping[str, Any]) -> dict[str, Any]:
|
|
1274
|
+
"""The tab's answer, plus the two timing fields the tab sent beside it.
|
|
1275
|
+
|
|
1276
|
+
THE RELAY DOES NOT MEASURE, AND MUST NOT. It has one number of its own —
|
|
1277
|
+
the round trip it held the call open for, which is in the audit record —
|
|
1278
|
+
and that number is the network out, plus the tab's work, plus any question
|
|
1279
|
+
the page put to a person, plus the network back. Substituting it for a
|
|
1280
|
+
missing ``tookMs`` would hand an agent exactly the sum ``tookMs`` exists to
|
|
1281
|
+
take apart. So this copies, validates and otherwise has no opinion, the
|
|
1282
|
+
same restraint ``rev``, ``screen``, ``plan`` and ``focus`` get on their way
|
|
1283
|
+
through.
|
|
1284
|
+
|
|
1285
|
+
WHY THE KEYS ARE STRIPPED FIRST. They are reserved on this body.
|
|
1286
|
+
``result`` is what the APP returned, and an app that filled in ``tookMs``
|
|
1287
|
+
itself would be making a claim about its own speed where the agent is
|
|
1288
|
+
entitled to an observation — so a value found in there is dropped and only
|
|
1289
|
+
the frame's own field, written by the page-side harness around its one call
|
|
1290
|
+
into the driver, is forwarded. The copy is shallow and touches nothing
|
|
1291
|
+
else: every other field of the ``result``, a ``stale`` hint and the
|
|
1292
|
+
snapshot included, is forwarded byte for byte as before.
|
|
1293
|
+
|
|
1294
|
+
ABSENT MEANS UNKNOWN. A tab from before this existed, or one that cannot
|
|
1295
|
+
say honestly, sends nothing, and nothing is what the agent gets: never a
|
|
1296
|
+
zero, which every client would render as "instant". A figure that is not a
|
|
1297
|
+
finite number at or above zero is dropped on the way through, the rule
|
|
1298
|
+
``Tab.from_dict`` already has for a ``focus`` that is not a string.
|
|
1299
|
+
|
|
1300
|
+
Behaviourally identical to the TypeScript relay's ``timed``, field for
|
|
1301
|
+
field and name for name, by the standing promise that governs both files.
|
|
1302
|
+
"""
|
|
1303
|
+
out = dict(result)
|
|
1304
|
+
out.pop("tookMs", None)
|
|
1305
|
+
out.pop("waitedMs", None)
|
|
1306
|
+
took = _ms(frame.get("tookMs"))
|
|
1307
|
+
if took is not None:
|
|
1308
|
+
out["tookMs"] = took
|
|
1309
|
+
# Only beside a `tookMs`, never on its own. `waitedMs` is defined as
|
|
1310
|
+
# the amount already subtracted from it, so without one it is a
|
|
1311
|
+
# quantity relative to nothing — and a reader might well subtract it a
|
|
1312
|
+
# second time.
|
|
1313
|
+
waited = _ms(frame.get("waitedMs"))
|
|
1314
|
+
if waited is not None:
|
|
1315
|
+
out["waitedMs"] = waited
|
|
1316
|
+
return out
|
|
1317
|
+
|
|
1318
|
+
|
|
1319
|
+
def _ms(value: Any) -> int | None:
|
|
1320
|
+
"""A duration off the wire, or None for anything that is not one.
|
|
1321
|
+
|
|
1322
|
+
``bool`` is excluded explicitly, as everywhere else in this package that
|
|
1323
|
+
reads a number off JSON: ``True`` is an ``int`` in Python and
|
|
1324
|
+
``tookMs: true`` is not a measurement. Whole milliseconds, because a float
|
|
1325
|
+
survives JSON and nothing downstream wants tenths of a millisecond.
|
|
1326
|
+
"""
|
|
1327
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
1328
|
+
return None
|
|
1329
|
+
if value != value or value in (float("inf"), float("-inf")) or value < 0:
|
|
1330
|
+
return None
|
|
1331
|
+
return int(value)
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
def bad_request(status: int, hint: str, error: str = "bad-request") -> Response:
|
|
1335
|
+
"""A non-2xx with ``{"error", "hint"}`` — deliberately NOT ``WireResult``-shaped.
|
|
1336
|
+
|
|
1337
|
+
The slugs are the ones PROTOCOL.md's status table pins, and the ``400`` /
|
|
1338
|
+
``409`` split behind them is the distinction worth keeping: **400 means the
|
|
1339
|
+
frame could never have been accepted by anyone; 409 means the frame was fine
|
|
1340
|
+
and the relay's state is what made it unacceptable.** A tab that gets a 409
|
|
1341
|
+
may reasonably reconnect and retry. A tab that gets a 400 has a bug. Reusing
|
|
1342
|
+
one slug for both takes that away, which is why ``bad-request`` is no longer
|
|
1343
|
+
the answer to everything.
|
|
1344
|
+
|
|
1345
|
+
Exported because the adapters need it: a body over :data:`MAX_BODY` never
|
|
1346
|
+
reaches :meth:`Relay.handle`, and the answer to it must look like every
|
|
1347
|
+
other transport failure.
|
|
1348
|
+
"""
|
|
1349
|
+
return _json(status, {"error": error, "hint": hint})
|
|
1350
|
+
|
|
1351
|
+
|
|
1352
|
+
def _unauthorized(error: str, hint: str) -> Response:
|
|
1353
|
+
"""A 401 with the challenge header, so an agent is told HOW to authenticate.
|
|
1354
|
+
|
|
1355
|
+
401 rather than 403, and the split is worth keeping: a 401 says "present a
|
|
1356
|
+
different credential and this will work", which is actionable, while the
|
|
1357
|
+
403 the loopback guard answers says "nothing you can present will help".
|
|
1358
|
+
An agent that cannot tell them apart either retries a hopeless request or
|
|
1359
|
+
gives up on a fixable one.
|
|
1360
|
+
"""
|
|
1361
|
+
return Response(
|
|
1362
|
+
401,
|
|
1363
|
+
_AUTH_HEADERS,
|
|
1364
|
+
json.dumps({"error": error, "hint": hint}).encode("utf-8"),
|
|
1365
|
+
)
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def _credential(headers: Mapping[str, str], params: Mapping[str, str]) -> str | None:
|
|
1369
|
+
"""The caller's credential, from the four places it can arrive.
|
|
1370
|
+
|
|
1371
|
+
In order, and the order is the order of preference:
|
|
1372
|
+
|
|
1373
|
+
1. ``Authorization: Bearer`` — what an agent, an MCP server or any HTTP
|
|
1374
|
+
client should use. Standard, and not logged by anything by default.
|
|
1375
|
+
2. ``X-DK-Token`` — for a client whose ``Authorization`` header is already
|
|
1376
|
+
spoken for by the app the relay is embedded in.
|
|
1377
|
+
3. The ``dk_token`` cookie (``__Host-`` prefixed or not) — the one that
|
|
1378
|
+
works for ``EventSource``, which cannot set a header at all. In the
|
|
1379
|
+
deployment PROTOCOL.md recommends, where the relay is same-origin with
|
|
1380
|
+
the app, this is the best option available to a page: the app sets the
|
|
1381
|
+
cookie and the browser attaches it to the stream request with no token
|
|
1382
|
+
anywhere in a URL.
|
|
1383
|
+
4. ``?dk_token=`` — the last resort, for a cross-origin ``EventSource``
|
|
1384
|
+
where no cookie will be sent. **A query parameter ends up in every
|
|
1385
|
+
reverse proxy's access log**, which is the one place a token must not
|
|
1386
|
+
be. It is accepted because refusing it would mean cross-origin pages
|
|
1387
|
+
could not connect at all, and it is listed last and documented as a
|
|
1388
|
+
liability. Short token lifetimes are what make a logged one survivable.
|
|
1389
|
+
"""
|
|
1390
|
+
raw = headers.get("authorization", "")
|
|
1391
|
+
if raw[:7].lower() == "bearer ":
|
|
1392
|
+
return raw[7:].strip() or None
|
|
1393
|
+
|
|
1394
|
+
direct = headers.get("x-dk-token")
|
|
1395
|
+
if direct and direct.strip():
|
|
1396
|
+
return direct.strip()
|
|
1397
|
+
|
|
1398
|
+
cookie = headers.get("cookie")
|
|
1399
|
+
if cookie:
|
|
1400
|
+
for part in cookie.split(";"):
|
|
1401
|
+
name, _, value = part.strip().partition("=")
|
|
1402
|
+
if name in ("dk_token", "__Host-dk_token") and value.strip():
|
|
1403
|
+
return unquote(value.strip())
|
|
1404
|
+
|
|
1405
|
+
return params.get("dk_token") or None
|
|
1406
|
+
|
|
1407
|
+
|
|
1408
|
+
def _headers(
|
|
1409
|
+
headers: Mapping[str, str] | Sequence[tuple[str, str]] | None,
|
|
1410
|
+
) -> dict[str, str]:
|
|
1411
|
+
"""Request headers, lowercased, in the many shapes an adapter has them.
|
|
1412
|
+
|
|
1413
|
+
A repeated header is joined with ``", "`` rather than having one copy win.
|
|
1414
|
+
``Cookie`` is the one that arrives repeated in practice (HTTP/2 splits it),
|
|
1415
|
+
and keeping only the first would silently drop the credential in a jar with
|
|
1416
|
+
several entries.
|
|
1417
|
+
"""
|
|
1418
|
+
if not headers:
|
|
1419
|
+
return {}
|
|
1420
|
+
pairs = headers.items() if isinstance(headers, Mapping) else headers
|
|
1421
|
+
out: dict[str, str] = {}
|
|
1422
|
+
for key, value in pairs:
|
|
1423
|
+
# BOTH halves may be bytes. ASGI hands over raw byte pairs, and
|
|
1424
|
+
# `str(b"authorization")` is the seven-character string
|
|
1425
|
+
# `b'authorization'` — which matches nothing, silently, so every
|
|
1426
|
+
# credential in the deployment PROTOCOL.md recommends would be
|
|
1427
|
+
# invisible and every caller would be told it presented none.
|
|
1428
|
+
name = (key.decode("latin-1") if isinstance(key, bytes) else str(key)).lower()
|
|
1429
|
+
text = value.decode("latin-1") if isinstance(value, bytes) else str(value)
|
|
1430
|
+
if name in out:
|
|
1431
|
+
# `Cookie` joins with `; ` and everything else with `, `. That is
|
|
1432
|
+
# not cosmetic: a cookie jar is `;`-separated, so joining its copies
|
|
1433
|
+
# with a comma produces one pair whose VALUE is the rest of the jar,
|
|
1434
|
+
# and the credential inside it is unreachable.
|
|
1435
|
+
out[name] = out[name] + ("; " if name == "cookie" else ", ") + text
|
|
1436
|
+
else:
|
|
1437
|
+
out[name] = text
|
|
1438
|
+
return out
|
|
1439
|
+
|
|
1440
|
+
|
|
1441
|
+
def too_large(limit: int = MAX_BODY) -> Response:
|
|
1442
|
+
"""The pinned answer to a body over the limit. Used by the adapters.
|
|
1443
|
+
|
|
1444
|
+
Read :data:`ABORT_BODY` before changing how an adapter gets here: the status
|
|
1445
|
+
is worthless if the sender never reads it.
|
|
1446
|
+
"""
|
|
1447
|
+
return bad_request(413, f"a request body over {limit} bytes is a bug, not a call", "too-large")
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
def _accepted(note: str | None = None) -> Response:
|
|
1451
|
+
"""The pinned answer to a frame the relay took: ``202 {"ok": true}``.
|
|
1452
|
+
|
|
1453
|
+
202, not 200, and with nothing in the body but that. The answer to a call
|
|
1454
|
+
travels to the AGENT, not back up this POST, so a payload here would be an
|
|
1455
|
+
invitation to build a second, divergent return path.
|
|
1456
|
+
"""
|
|
1457
|
+
return _json(202, {"ok": True} if note is None else {"ok": True, "note": note})
|
|
1458
|
+
|
|
1459
|
+
|
|
1460
|
+
def _bad_method(allowed: str) -> Response:
|
|
1461
|
+
return bad_request(405, f"{allowed} only", "bad-method")
|
|
1462
|
+
|
|
1463
|
+
|
|
1464
|
+
def _json(status: int, payload: Any) -> Response:
|
|
1465
|
+
return Response(status, _JSON_HEADERS, json.dumps(payload).encode("utf-8"))
|
|
1466
|
+
|
|
1467
|
+
|
|
1468
|
+
def _sse(frame: Mapping[str, Any]) -> bytes:
|
|
1469
|
+
"""One SSE frame.
|
|
1470
|
+
|
|
1471
|
+
The event name matters: the page listens for `call` specifically, so an
|
|
1472
|
+
unnamed `message` would be silently dropped by ``EventSource``. So would a
|
|
1473
|
+
frame missing the blank line that terminates it.
|
|
1474
|
+
"""
|
|
1475
|
+
return f"event: {frame['t']}\ndata: {json.dumps(frame)}\n\n".encode("utf-8")
|
|
1476
|
+
|
|
1477
|
+
|
|
1478
|
+
def _loads(body: bytes | None) -> Any:
|
|
1479
|
+
"""The request body as JSON, or ``None`` when it is not JSON at all.
|
|
1480
|
+
|
|
1481
|
+
An empty body parses as ``{}``, matching the TS relay: a POST with no body
|
|
1482
|
+
is a malformed *call*, which is reported by the missing ``name`` rather than
|
|
1483
|
+
by a different status.
|
|
1484
|
+
"""
|
|
1485
|
+
if body is None or not body.strip():
|
|
1486
|
+
return {}
|
|
1487
|
+
try:
|
|
1488
|
+
return json.loads(body)
|
|
1489
|
+
except (ValueError, UnicodeDecodeError):
|
|
1490
|
+
return None
|
|
1491
|
+
|
|
1492
|
+
|
|
1493
|
+
def _query(query: Mapping[str, str] | Sequence[tuple[str, str]] | str | None) -> dict[str, str]:
|
|
1494
|
+
"""Normalise the many shapes an adapter has a query string in."""
|
|
1495
|
+
if query is None:
|
|
1496
|
+
return {}
|
|
1497
|
+
if isinstance(query, str):
|
|
1498
|
+
return dict(parse_qsl(query.lstrip("?"), keep_blank_values=True))
|
|
1499
|
+
if isinstance(query, Mapping):
|
|
1500
|
+
return {str(k): str(v) for k, v in query.items()}
|
|
1501
|
+
return {str(k): str(v) for k, v in query}
|
|
1502
|
+
|
|
1503
|
+
|
|
1504
|
+
def _is_loopback(address: str | None) -> bool:
|
|
1505
|
+
"""Whether this peer is proven local.
|
|
1506
|
+
|
|
1507
|
+
An unknown peer is NOT, which is the whole point: a Unix socket, a proxy
|
|
1508
|
+
that did not pass the address along, or an ASGI scope with no ``client``
|
|
1509
|
+
are all cases where the relay cannot tell, and "cannot tell" must not
|
|
1510
|
+
resolve to "allowed".
|
|
1511
|
+
"""
|
|
1512
|
+
if not address:
|
|
1513
|
+
return False
|
|
1514
|
+
address = address.strip("[]")
|
|
1515
|
+
if "%" in address: # fe80::1%en0 — a scoped v6 address
|
|
1516
|
+
address = address.split("%", 1)[0]
|
|
1517
|
+
return (
|
|
1518
|
+
address == "::1"
|
|
1519
|
+
or address == "::ffff:127.0.0.1"
|
|
1520
|
+
or address.startswith("127.")
|
|
1521
|
+
or address.startswith("::ffff:127.")
|
|
1522
|
+
)
|
|
1523
|
+
|
|
1524
|
+
|
|
1525
|
+
def _now() -> str:
|
|
1526
|
+
"""ISO 8601 with a ``Z``, the spelling ``GET /dk/tabs`` shows.
|
|
1527
|
+
|
|
1528
|
+
A string on purpose: nothing computes with it, and it is read by a human
|
|
1529
|
+
choosing between two tabs.
|
|
1530
|
+
"""
|
|
1531
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|