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.
@@ -0,0 +1,670 @@
1
+ """
2
+ Run the relay on its own.
3
+
4
+ driverkit-relay
5
+ DK_PORT=7777 driverkit-relay
6
+ python -m driverkit.serve_relay --port 7777
7
+
8
+ Most deployments should not use this. PROTOCOL.md's argument for SSE is that
9
+ the relay belongs inside a server you already run — one real deployment has it in a Rust
10
+ kernel — and an extra process is an extra thing to supervise. If you have a
11
+ FastAPI, Starlette or Django app, mount :func:`driverkit.asgi.relay_asgi`
12
+ instead and the relay shares that process's socket, lifecycle and auth. This
13
+ file exists for the case where there is no such server yet: a local dev loop,
14
+ or a static page you want to drive today.
15
+
16
+ Why ``ThreadingHTTPServer`` and not ``HTTPServer``: ``/dk/events`` is a body
17
+ that never ends, and ``POST /dk/tabs/:tab/call`` blocks until the tab answers.
18
+ On the single-threaded server the first open tab would wedge every other
19
+ request forever — the relay would deadlock against itself on the very first
20
+ connection, before any agent made a call. One thread per connection is not an
21
+ optimisation here, it is the only way the surface works at all.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import os
28
+ import select
29
+ import socket
30
+ import sys
31
+ import threading
32
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
33
+ from typing import Any
34
+ from urllib.parse import urlsplit
35
+
36
+ from .auth import TabAuth
37
+ from .relay import ABORT_BODY, MAX_BODY, Relay, Response, bad_request, too_large
38
+
39
+ __all__ = ["RelayServer", "serve", "main"]
40
+
41
+ #: Host values that need no ``allow_remote``, spelled as a person would type one.
42
+ LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1", "")
43
+
44
+ #: Returned by the body readers to mean "this request has already been answered".
45
+ #:
46
+ #: A sentinel rather than ``None`` because ``None`` is a real body value here —
47
+ #: ``_serve(None)`` is how a GET says "there was no body" — and conflating the
48
+ #: two would make a 413 or a 400 fall through into the router and be answered
49
+ #: twice on one connection.
50
+ _ANSWERED: Any = object()
51
+
52
+ #: The longest chunk-size or trailer line this relay will buffer.
53
+ #:
54
+ #: A size line is a handful of hex digits; this is generous by three orders of
55
+ #: magnitude and exists only so a sender that never sends a newline cannot make
56
+ #: the relay buffer until the process dies.
57
+ _MAX_FRAMING_LINE = 8 << 10
58
+
59
+
60
+ def _handler_class(relay: Relay) -> type[BaseHTTPRequestHandler]:
61
+ class RelayHTTPRequestHandler(BaseHTTPRequestHandler):
62
+ # HTTP/1.1 so a client may keep the connection alive between the many
63
+ # small requests an agent makes. A streaming response opts out of that
64
+ # per response; see `_stream`.
65
+ protocol_version = "HTTP/1.1"
66
+ server_version = "driverkit-relay"
67
+
68
+ def log_message(self, *args: Any) -> None:
69
+ # Silent by default: the paths carry tab ids, and PROTOCOL.md says a
70
+ # tab id is a capability — "do not log it anywhere a tab id becomes
71
+ # a password". An access log of /dk/tabs/<id>/call is exactly that.
72
+ pass
73
+
74
+ def do_GET(self) -> None:
75
+ self._serve(None)
76
+
77
+ def do_POST(self) -> None:
78
+ body = self._request_body()
79
+ if body is _ANSWERED:
80
+ return
81
+ self._serve(body) # type: ignore[arg-type]
82
+
83
+ def _request_body(self) -> Any:
84
+ """The request body, or :data:`_ANSWERED` when this request is finished.
85
+
86
+ Reading the body is not optional even when the route is going to
87
+ refuse the request, and that is the whole reason this is a method
88
+ rather than two lines in ``do_POST``. On a keep-alive connection the
89
+ bytes of an unread body are still in the socket when the next
90
+ request is parsed off it, so they become that request — and a
91
+ browser or a Node client POSTing JSON gets
92
+ ``Parse Error: Expected HTTP/, RTSP/ or ICE/`` on a connection that
93
+ was fine a moment ago. The first request's answer is wrong and
94
+ every later one on that socket is destroyed.
95
+
96
+ Which is exactly what ``Transfer-Encoding: chunked`` did here.
97
+ ``Content-Length`` is absent on a chunked request — that is the
98
+ point of chunking — so the old
99
+ ``int(self.headers.get("Content-Length") or 0)`` read ZERO bytes,
100
+ the relay answered a call with no ``name`` (400), and the
101
+ undrained chunk framing was then parsed as the next request.
102
+ ``relay_asgi`` never showed it because an ASGI server de-chunks
103
+ before the app sees a byte; ``http.server`` does not de-chunk
104
+ anything, so the only implementation that had to care is this one.
105
+
106
+ Nothing exotic sends chunked, either: any client that streams a
107
+ body without counting it first does, which includes Node's own
108
+ ``http.request`` whenever ``content-length`` is not set by hand —
109
+ and ``packages/driverkit/test/sse-client.ts`` is such a client.
110
+ """
111
+ encodings = [
112
+ part.strip().lower()
113
+ for part in (self.headers.get("Transfer-Encoding") or "").split(",")
114
+ if part.strip()
115
+ ]
116
+ if "chunked" in encodings:
117
+ return self._chunked_body()
118
+
119
+ raw = self.headers.get("Content-Length")
120
+ try:
121
+ length = int(raw) if raw is not None and raw != "" else 0
122
+ except ValueError:
123
+ # A length we cannot parse means we cannot know where this body
124
+ # ends, so the connection cannot be reused — there is no way to
125
+ # find the start of the next request. 400 and hang up, for the
126
+ # same reason as unparseable chunk framing below.
127
+ return self._unframable(f"{raw!r} is not a Content-Length")
128
+ if length < 0:
129
+ return self._unframable(f"{raw!r} is not a Content-Length")
130
+ if length > MAX_BODY:
131
+ self._refuse_oversized(length)
132
+ return _ANSWERED
133
+ try:
134
+ body = self.rfile.read(length) if length else b""
135
+ except OSError:
136
+ self.close_connection = True
137
+ return _ANSWERED
138
+ return body
139
+
140
+ def _chunked_body(self) -> Any:
141
+ """Decode ``Transfer-Encoding: chunked`` under the same two limits.
142
+
143
+ The limits are the interesting part. With a ``Content-Length`` the
144
+ size is known before a byte is read, so :data:`MAX_BODY` is checked
145
+ once up front. Chunked has no length, so the only way to know is to
146
+ add the chunks up as they arrive — which means the decision is
147
+ reached partway through a body that is already being read.
148
+
149
+ So, matching :meth:`_refuse_oversized` and
150
+ :func:`driverkit.asgi._read_body` rather than inventing a third
151
+ behaviour: past :data:`MAX_BODY` what has been buffered is dropped
152
+ and the rest is read and counted so the sender gets to READ the
153
+ 413, since a sender that takes ECONNRESET instead never learns why
154
+ it failed and retries byte for byte. Past :data:`ABORT_BODY` that
155
+ courtesy is the attack succeeding, so the connection goes.
156
+ """
157
+ kept: list[bytes] = []
158
+ size = 0
159
+ over = False
160
+ while True:
161
+ head = self._framing_line()
162
+ if head is None:
163
+ return self._unframable("a chunk size line that never ended")
164
+ # Chunk extensions (`1a;name=value`) are legal and carry nothing
165
+ # this relay wants, so they are cut off rather than refused.
166
+ digits = head.split(b";", 1)[0].strip()
167
+ try:
168
+ chunk = int(digits, 16)
169
+ except ValueError:
170
+ return self._unframable(f"{digits!r} is not a chunk size")
171
+ if chunk < 0:
172
+ return self._unframable(f"{digits!r} is not a chunk size")
173
+ if chunk == 0:
174
+ break
175
+ size += chunk
176
+ if size > ABORT_BODY:
177
+ self.close_connection = True
178
+ return _ANSWERED
179
+ if size > MAX_BODY and not over:
180
+ over = True
181
+ kept.clear()
182
+ piece = self._read_exactly(chunk, keep=not over)
183
+ if piece is None:
184
+ # The sender stopped mid-chunk. There is nobody left to
185
+ # answer and the framing is unrecoverable either way.
186
+ self.close_connection = True
187
+ return _ANSWERED
188
+ if not over:
189
+ kept.append(piece)
190
+ # Every chunk is followed by its own CRLF. A chunk that is not
191
+ # must not be guessed at: the next bytes would be read as a
192
+ # size line and the whole body would shift.
193
+ if self._framing_line() not in (b"", None):
194
+ return self._unframable("a chunk not terminated by CRLF")
195
+
196
+ # Trailers, then the blank line that ends them. Read and discarded:
197
+ # nothing in PROTOCOL.md travels in a trailer, but leaving them in
198
+ # the socket is the same keep-alive corruption as leaving the body.
199
+ while True:
200
+ trailer = self._framing_line()
201
+ if trailer is None:
202
+ return self._unframable("trailers that never ended")
203
+ if trailer == b"":
204
+ break
205
+
206
+ if over:
207
+ self.close_connection = True
208
+ self._respond(too_large())
209
+ return _ANSWERED
210
+ return b"".join(kept)
211
+
212
+ def _framing_line(self) -> bytes | None:
213
+ """One CRLF-terminated framing line without its terminator.
214
+
215
+ ``None`` means the line was missing, truncated or absurdly long. The
216
+ cap matters: a sender that never sends a newline would otherwise
217
+ have this method buffer until the process died, and a size line is
218
+ a handful of bytes.
219
+ """
220
+ try:
221
+ line = self.rfile.readline(_MAX_FRAMING_LINE + 1)
222
+ except OSError:
223
+ return None
224
+ if not line or len(line) > _MAX_FRAMING_LINE or not line.endswith(b"\n"):
225
+ return None
226
+ return line.rstrip(b"\r\n")
227
+
228
+ def _read_exactly(self, count: int, *, keep: bool) -> bytes | None:
229
+ """``count`` bytes, or ``None`` if the sender stopped first.
230
+
231
+ ``keep=False`` counts them and throws them away, so an oversized
232
+ body costs flat memory however big it is — the same trade
233
+ :meth:`_refuse_oversized` makes.
234
+ """
235
+ out = bytearray() if keep else None
236
+ remaining = count
237
+ while remaining > 0:
238
+ try:
239
+ piece = self.rfile.read(min(remaining, 1 << 16))
240
+ except OSError:
241
+ return None
242
+ if not piece:
243
+ return None
244
+ if out is not None:
245
+ out += piece
246
+ remaining -= len(piece)
247
+ return bytes(out) if out is not None else b""
248
+
249
+ def _unframable(self, why: str) -> Any:
250
+ """400 and hang up: a body whose end we cannot find.
251
+
252
+ 400 rather than 413 or 500 because PROTOCOL.md's split is that a
253
+ 400 is a frame no relay could ever have accepted. Framing this
254
+ broken is exactly that, and it is a bug in the sender.
255
+
256
+ The connection closes because it has to. Every byte after the point
257
+ the framing stopped making sense is of unknown purpose, so there is
258
+ no position at which to start reading the next request, and a
259
+ keep-alive socket whose next request boundary is unknown can only
260
+ produce nonsense.
261
+ """
262
+ self.close_connection = True
263
+ self._respond(bad_request(400, f"request body framing: {why}"))
264
+ return _ANSWERED
265
+
266
+ def _refuse_oversized(self, length: int) -> None:
267
+ """Answer 413 — and make sure the sender can actually read it.
268
+
269
+ The obvious implementation answers at once without reading the
270
+ body, and it does not work. The sender is still writing when the
271
+ connection closes, so it takes ECONNRESET/EPIPE on its own socket
272
+ and never reads the response at all. A sender that cannot learn WHY
273
+ it failed retries byte for byte, which is the opposite of what a
274
+ limit is for.
275
+
276
+ So the body is read and thrown away first, counted rather than
277
+ buffered so memory stays flat however big it is, and the 413 goes
278
+ out after the last byte has arrived. Above `ABORT_BODY` that
279
+ politeness is the attack succeeding, so there the connection is
280
+ dropped and the sender is left to guess.
281
+
282
+ A test with a body just over the limit cannot tell these apart: it
283
+ fits in one socket write, so the sender is finished before the
284
+ response is written and reads it either way. The limit has to be
285
+ exceeded by megabytes for the difference to show up.
286
+ """
287
+ self.close_connection = True
288
+ if length > ABORT_BODY:
289
+ return
290
+ remaining = length
291
+ while remaining > 0:
292
+ try:
293
+ chunk = self.rfile.read(min(remaining, 1 << 16))
294
+ except OSError:
295
+ return
296
+ if not chunk:
297
+ # The sender gave up early. Nothing to answer to.
298
+ return
299
+ remaining -= len(chunk)
300
+ self._respond(too_large())
301
+
302
+ # PUT and DELETE exist only to be refused — `handle` answers 405 on
303
+ # every real route and 404 otherwise — but they still read the body
304
+ # first. A refusal that leaves the body in the socket corrupts the next
305
+ # request on it exactly as the chunked POST did, and "the route said no"
306
+ # is not a reason the connection has to die with it.
307
+ def do_PUT(self) -> None:
308
+ body = self._request_body()
309
+ if body is _ANSWERED:
310
+ return
311
+ self._serve(body)
312
+
313
+ def do_DELETE(self) -> None:
314
+ body = self._request_body()
315
+ if body is _ANSWERED:
316
+ return
317
+ self._serve(body)
318
+
319
+ def _serve(self, body: bytes | None) -> None:
320
+ split = urlsplit(self.path)
321
+ peer = self.client_address[0] if self.client_address else None
322
+ # `self.headers` is an `email.message.Message`, whose `.items()`
323
+ # yields every copy of a repeated header rather than collapsing
324
+ # them. That matters for `Cookie`, which is the one header that
325
+ # legitimately arrives more than once and the one the browser's
326
+ # credential rides in.
327
+ response = relay.handle(
328
+ self.command, split.path, split.query, body, peer, self.headers.items()
329
+ )
330
+ if response is None:
331
+ # Standalone, so an unknown path IS an error — unlike the
332
+ # embedded case, where `handle` returning None means "not mine,
333
+ # let the app answer".
334
+ self._respond(
335
+ bad_request(404, "this process serves /dk/* only", error="not-found")
336
+ )
337
+ return
338
+ self._respond(response)
339
+
340
+ def _respond(self, response: Response) -> None:
341
+ if response.stream is not None:
342
+ self._stream(response)
343
+ return
344
+ self.send_response(response.status)
345
+ for name, value in response.headers:
346
+ self.send_header(name, value)
347
+ self.send_header("Content-Length", str(len(response.body)))
348
+ self.end_headers()
349
+ self.wfile.write(response.body)
350
+
351
+ def _stream(self, response: Response) -> None:
352
+ stream = response.stream
353
+ assert stream is not None
354
+ self.send_response(response.status)
355
+ for name, value in response.headers:
356
+ # The Connection header from SSE_HEADERS is dropped here. An SSE
357
+ # body has no length known up front, and on HTTP/1.1 a body
358
+ # without a Content-Length is delimited by the connection
359
+ # closing — so this response cannot be a keep-alive one however
360
+ # much the generic header wants it to be. A client that waited
361
+ # for a length would hang forever.
362
+ if name.lower() == "connection":
363
+ continue
364
+ self.send_header(name, value)
365
+ self.send_header("Connection", "close")
366
+ self.end_headers()
367
+ self.close_connection = True
368
+
369
+ watcher = threading.Thread(
370
+ target=self._watch_for_hangup, args=(stream,), daemon=True
371
+ )
372
+ watcher.start()
373
+ try:
374
+ for chunk in stream.chunks():
375
+ self.wfile.write(chunk)
376
+ self.wfile.flush()
377
+ except (BrokenPipeError, ConnectionResetError, OSError, ValueError):
378
+ # The peer went away mid-write. That is the ordinary end of a
379
+ # stream, not an error: a person closed a tab.
380
+ pass
381
+ finally:
382
+ stream.close()
383
+
384
+ def _watch_for_hangup(self, stream: Any) -> None:
385
+ """Close the stream when the peer hangs up.
386
+
387
+ Needed because nothing else notices. The writer above only learns
388
+ of a dead peer when it next writes, and on an idle stream that is
389
+ one ping interval away — twenty seconds in which a closed tab is
390
+ still listed by ``/dk/tabs`` and a call to it waits out the whole
391
+ deadline instead of failing at once as ``tab-went-away``. So one
392
+ thread per stream sits in ``select`` on the socket: a readable
393
+ socket with nothing to read is EOF.
394
+
395
+ The 0.25s timeout is not a poll of the peer — ``select`` returns the
396
+ moment the socket becomes readable. It is only so this thread
397
+ notices that the stream ended on its own and exits rather than
398
+ holding a file descriptor open.
399
+ """
400
+ conn = self.connection
401
+ while not stream.closed:
402
+ try:
403
+ readable, _, _ = select.select([conn], [], [], 0.25)
404
+ except (OSError, ValueError):
405
+ break
406
+ if not readable:
407
+ continue
408
+ try:
409
+ peeked = conn.recv(1, socket.MSG_PEEK)
410
+ except (OSError, ValueError):
411
+ peeked = b""
412
+ if not peeked:
413
+ stream.close()
414
+ # Bytes we did not ask for: a pipelined request on a connection
415
+ # that is now a one-way stream. Nothing useful to do with it,
416
+ # and it is not a hangup, so stop watching rather than read it.
417
+ break
418
+
419
+ return RelayHTTPRequestHandler
420
+
421
+
422
+ class RelayServer:
423
+ """A running standalone relay. ``serve()`` returns one of these."""
424
+
425
+ def __init__(self, server: ThreadingHTTPServer, relay: Relay) -> None:
426
+ self.server = server
427
+ self.relay = relay
428
+ self._thread: threading.Thread | None = None
429
+
430
+ @property
431
+ def port(self) -> int:
432
+ return int(self.server.server_address[1])
433
+
434
+ @property
435
+ def url(self) -> str:
436
+ host = self.server.server_address[0]
437
+ if ":" in str(host):
438
+ host = f"[{host}]"
439
+ return f"http://{host}:{self.port}"
440
+
441
+ def start(self) -> "RelayServer":
442
+ """Serve in a background thread and return at once."""
443
+ if self._thread is None:
444
+ self._thread = threading.Thread(
445
+ target=self.server.serve_forever,
446
+ kwargs={"poll_interval": 0.02},
447
+ daemon=True,
448
+ )
449
+ self._thread.start()
450
+ return self
451
+
452
+ def serve_forever(self) -> None:
453
+ self.server.serve_forever(poll_interval=0.2)
454
+
455
+ def stop(self) -> None:
456
+ """Hang up every stream, then stop listening. Idempotent.
457
+
458
+ The relay is closed first on purpose: ``shutdown()`` waits for the
459
+ serving loop, and a thread writing an endless SSE body is not going to
460
+ return until somebody ends that body.
461
+ """
462
+ self.relay.close()
463
+ if self._thread is not None:
464
+ # Only when it is actually serving: `shutdown()` waits for the
465
+ # serving loop to acknowledge, and a loop that never started never
466
+ # will — it would hang here rather than report a misconfiguration.
467
+ self.server.shutdown()
468
+ self._thread.join(timeout=5)
469
+ self._thread = None
470
+ self.server.server_close()
471
+
472
+
473
+ def serve(
474
+ port: int = 7777,
475
+ host: str = "127.0.0.1",
476
+ *,
477
+ timeout_s: float = 60.0,
478
+ ping_s: float = 20.0,
479
+ allow_remote: bool = False,
480
+ auth: TabAuth | None = None,
481
+ resolve_principal: Any = None,
482
+ on_error: Any = None,
483
+ on_audit: Any = None,
484
+ start: bool = True,
485
+ ) -> RelayServer:
486
+ """Bind a relay to ``host:port``. ``port=0`` takes an ephemeral one.
487
+
488
+ Loopback by default, and changing it takes TWO deliberate acts: a host here
489
+ and ``allow_remote`` as well. That is not redundancy. Binding ``0.0.0.0`` is
490
+ something people do by reflex to reach a dev server from a phone; here it
491
+ would publish the ability to drive the logged-in session of whoever has a
492
+ tab open. Requiring the second flag means nobody arrives at a remotely
493
+ drivable browser by muscle memory.
494
+
495
+ Raised, not returned, and raised before any socket exists: a
496
+ misconfiguration that surfaced later would be one somebody forgot to check,
497
+ and the failure mode of forgetting is a listening public port.
498
+ """
499
+ # `auth` and `resolve_principal` are passed straight through; `Relay`
500
+ # itself refuses `allow_remote` without one of them, so there is no second
501
+ # copy of that rule to fall out of step with the first.
502
+ if host not in LOOPBACK_HOSTS and not allow_remote:
503
+ raise ValueError(
504
+ f"driverkit: refusing to bind {host} without allow_remote. A reachable relay is "
505
+ "someone else driving your logged-in browser session. Read "
506
+ '"Who is allowed to do this" in PROTOCOL.md, put your app\'s own auth in front of '
507
+ "the relay, then pass allow_remote=True."
508
+ )
509
+
510
+ relay = Relay(
511
+ timeout_s=timeout_s,
512
+ ping_s=ping_s,
513
+ allow_remote=allow_remote,
514
+ on_error=on_error,
515
+ # Passed straight through, like `auth`: the relay owns the record's
516
+ # shape and this function owns the socket. See `Relay.__init__`.
517
+ on_audit=on_audit,
518
+ auth=auth,
519
+ resolve_principal=resolve_principal,
520
+ )
521
+ server = ThreadingHTTPServer((host, port), _handler_class(relay))
522
+ # Threads must not outlive the process: a dangling SSE writer would keep a
523
+ # `driverkit-relay` alive after Ctrl-C and look like a hang.
524
+ server.daemon_threads = True
525
+ running = RelayServer(server, relay)
526
+ return running.start() if start else running
527
+
528
+
529
+ def _env_float(name: str, fallback: float) -> float:
530
+ raw = os.environ.get(name)
531
+ if not raw:
532
+ return fallback
533
+ try:
534
+ return float(raw)
535
+ except ValueError:
536
+ raise SystemExit(f"driverkit-relay: {name}={raw!r} is not a number") from None
537
+
538
+
539
+ def main(argv: list[str] | None = None) -> int:
540
+ """The ``driverkit-relay`` console script."""
541
+ parser = argparse.ArgumentParser(
542
+ prog="driverkit-relay",
543
+ description="The driverkit relay: the one place a browser tab and an agent can both reach.",
544
+ epilog="Prefer mounting driverkit.asgi.relay_asgi into a server you already run.",
545
+ )
546
+ parser.add_argument(
547
+ "--host",
548
+ default=os.environ.get("DK_HOST", "127.0.0.1"),
549
+ help="interface to bind (env DK_HOST, default 127.0.0.1). Anything but loopback "
550
+ "also needs --allow-remote.",
551
+ )
552
+ parser.add_argument(
553
+ "--port",
554
+ type=int,
555
+ default=int(os.environ.get("DK_PORT", "7777")),
556
+ help="port to bind (env DK_PORT, default 7777). 0 takes an ephemeral one.",
557
+ )
558
+ parser.add_argument(
559
+ "--timeout",
560
+ type=float,
561
+ default=_env_float("DK_TIMEOUT_S", 60.0),
562
+ help="seconds a call waits for the tab's result (env DK_TIMEOUT_S, default 60)",
563
+ )
564
+ parser.add_argument(
565
+ "--ping",
566
+ type=float,
567
+ default=_env_float("DK_PING_S", 20.0),
568
+ help="seconds between keep-alive comments on an idle stream (env DK_PING_S, default 20)",
569
+ )
570
+ parser.add_argument(
571
+ "--allow-remote",
572
+ action="store_true",
573
+ default=os.environ.get("DK_ALLOW_REMOTE") == "1",
574
+ help="serve callers that are not on loopback (env DK_ALLOW_REMOTE=1). Needs --secret "
575
+ "and --audience: a relay that serves strangers and cannot tell them apart offers "
576
+ "every connected tab to every one of them, so this refuses to start without them.",
577
+ )
578
+ parser.add_argument(
579
+ "--secret",
580
+ default=os.environ.get("DK_SECRET"),
581
+ help="the HMAC key the app's backend mints tab tokens with (env DK_SECRET). "
582
+ "At least 32 bytes. Required with --allow-remote. Prefer the env var: an "
583
+ "argument is visible in `ps` to every user on the box.",
584
+ )
585
+ parser.add_argument(
586
+ "--audience",
587
+ default=os.environ.get("DK_AUDIENCE"),
588
+ help="the audience this relay accepts tokens for (env DK_AUDIENCE). Name it after "
589
+ "the deployment, so a staging token is not a production token.",
590
+ )
591
+ parser.add_argument(
592
+ "--no-anonymous",
593
+ action="store_true",
594
+ default=os.environ.get("DK_NO_ANONYMOUS") == "1",
595
+ help="refuse anonymous credentials (env DK_NO_ANONYMOUS=1). Right for an app where "
596
+ "every user is logged in: an anonymous credential there can only be somebody probing.",
597
+ )
598
+ parser.add_argument(
599
+ "--require-tab-binding",
600
+ action="store_true",
601
+ default=os.environ.get("DK_REQUIRE_TAB_BINDING") == "1",
602
+ help="refuse a tab token that does not name the tab it is for "
603
+ "(env DK_REQUIRE_TAB_BINDING=1).",
604
+ )
605
+ args = parser.parse_args(argv)
606
+
607
+ auth: TabAuth | None = None
608
+ if args.secret or args.audience:
609
+ if not args.secret or not args.audience:
610
+ print(
611
+ "driverkit-relay: --secret and --audience go together. The secret verifies a "
612
+ "token; the audience says which relay it was minted for.",
613
+ file=sys.stderr,
614
+ )
615
+ return 2
616
+ try:
617
+ auth = TabAuth(
618
+ secret=args.secret,
619
+ audience=args.audience,
620
+ anonymous=not args.no_anonymous,
621
+ require_tab_binding=args.require_tab_binding,
622
+ )
623
+ except ValueError as err:
624
+ print(str(err), file=sys.stderr)
625
+ return 2
626
+
627
+ try:
628
+ running = serve(
629
+ auth=auth,
630
+ port=args.port,
631
+ host=args.host,
632
+ timeout_s=args.timeout,
633
+ ping_s=args.ping,
634
+ allow_remote=args.allow_remote,
635
+ on_error=lambda err: print(f"driverkit relay: {err}", file=sys.stderr),
636
+ start=False,
637
+ )
638
+ except ValueError as err:
639
+ print(str(err), file=sys.stderr)
640
+ return 2
641
+ except OSError as err:
642
+ print(f"driverkit-relay: cannot bind {args.host}:{args.port}: {err}", file=sys.stderr)
643
+ return 2
644
+
645
+ # stderr, so stdout stays free for anything a caller wants to pipe.
646
+ print(f"driverkit relay on {running.url} (tabs: {running.url}/dk/tabs)", file=sys.stderr)
647
+ if args.allow_remote:
648
+ print(
649
+ "driverkit relay: allow_remote is ON. Callers are identified by tab token "
650
+ f"(audience {args.audience!r})"
651
+ + ("; anonymous credentials refused." if args.no_anonymous else "; anonymous allowed.")
652
+ + " Each caller sees only its own tabs.",
653
+ file=sys.stderr,
654
+ )
655
+ elif auth is not None:
656
+ print(
657
+ "driverkit relay: tab tokens required, loopback only.",
658
+ file=sys.stderr,
659
+ )
660
+ try:
661
+ running.serve_forever()
662
+ except KeyboardInterrupt:
663
+ pass
664
+ finally:
665
+ running.stop()
666
+ return 0
667
+
668
+
669
+ if __name__ == "__main__": # pragma: no cover
670
+ raise SystemExit(main())