devdoor 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,457 @@
1
+ """Streaming HTTP and bidirectional WebSocket upstream forwarder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import html
7
+ import json
8
+ import time
9
+ from collections.abc import AsyncIterator, Iterable
10
+ from contextlib import suppress
11
+
12
+ import aiohttp
13
+ from aiohttp import web
14
+ from multidict import CIMultiDict
15
+
16
+ from devdoor.core.events import BodyTapBuffer, TrafficEventBus, TrafficSource
17
+ from devdoor.core.router import RouteMatch
18
+
19
+ HOP_BY_HOP_HEADERS: frozenset[str] = frozenset(
20
+ {
21
+ "connection",
22
+ "keep-alive",
23
+ "proxy-authenticate",
24
+ "proxy-authorization",
25
+ "te",
26
+ "trailers",
27
+ "transfer-encoding",
28
+ "upgrade",
29
+ }
30
+ )
31
+
32
+ _WS_HANDSHAKE_HEADERS: frozenset[str] = frozenset(
33
+ {
34
+ "sec-websocket-key",
35
+ "sec-websocket-version",
36
+ "sec-websocket-extensions",
37
+ "sec-websocket-protocol",
38
+ }
39
+ )
40
+
41
+ DEFAULT_CONNECT_TIMEOUT_S = 5.0
42
+ _DEFAULT_CORS_ALLOW_HEADERS = "Accept, Authorization, Content-Type, X-Requested-With"
43
+
44
+
45
+ def _connection_tokens(headers: Iterable[tuple[str, str]]) -> set[str]:
46
+ tokens: set[str] = set()
47
+ for name, value in headers:
48
+ if name.lower() == "connection":
49
+ for item in value.split(","):
50
+ token = item.strip().lower()
51
+ if token:
52
+ tokens.add(token)
53
+ return tokens
54
+
55
+
56
+ def build_upstream_headers(
57
+ raw_headers: Iterable[tuple[str, str]],
58
+ *,
59
+ client_ip: str | None,
60
+ proto: str,
61
+ original_host: str,
62
+ host_override: str | None = None,
63
+ drop_content_length: bool = False,
64
+ for_websocket: bool = False,
65
+ ) -> CIMultiDict[str]:
66
+ """Filter hop-by-hop headers and set proxy forwarding metadata."""
67
+ header_list = list(raw_headers)
68
+ blocked = set(HOP_BY_HOP_HEADERS) | _connection_tokens(header_list)
69
+ if for_websocket:
70
+ blocked |= _WS_HANDSHAKE_HEADERS
71
+
72
+ out: CIMultiDict[str] = CIMultiDict()
73
+ prior_forwarded_for: list[str] = []
74
+
75
+ for name, value in header_list:
76
+ lower = name.lower()
77
+ if lower in blocked:
78
+ continue
79
+ if drop_content_length and lower == "content-length":
80
+ continue
81
+ if lower == "host":
82
+ continue
83
+ if lower == "x-forwarded-for":
84
+ prior_forwarded_for.append(value)
85
+ continue
86
+ out.add(name, value)
87
+
88
+ out["Host"] = host_override if host_override is not None else original_host
89
+ forwarded_for_parts = [*prior_forwarded_for]
90
+ if client_ip:
91
+ forwarded_for_parts.append(client_ip)
92
+ if forwarded_for_parts:
93
+ out["X-Forwarded-For"] = ", ".join(forwarded_for_parts)
94
+ out["X-Forwarded-Proto"] = proto
95
+ out["X-Forwarded-Host"] = original_host
96
+ return out
97
+
98
+
99
+ def build_downstream_headers(
100
+ raw_headers: Iterable[tuple[str, str]],
101
+ *,
102
+ cors_enabled: bool,
103
+ request_origin: str | None,
104
+ request_headers: str | None = None,
105
+ ) -> CIMultiDict[str]:
106
+ """Filter hop-by-hop response headers and optionally apply dev CORS headers."""
107
+ header_list = list(raw_headers)
108
+ blocked = set(HOP_BY_HOP_HEADERS) | _connection_tokens(header_list)
109
+ apply_cors = cors_enabled and bool(request_origin)
110
+
111
+ out: CIMultiDict[str] = CIMultiDict()
112
+ for name, value in header_list:
113
+ lower = name.lower()
114
+ if lower in blocked:
115
+ continue
116
+ if apply_cors and lower.startswith("access-control-"):
117
+ continue
118
+ out.add(name, value)
119
+
120
+ if apply_cors and request_origin is not None:
121
+ out["Access-Control-Allow-Origin"] = request_origin
122
+ out["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD"
123
+ out["Access-Control-Allow-Headers"] = request_headers or _DEFAULT_CORS_ALLOW_HEADERS
124
+ out["Access-Control-Allow-Credentials"] = "true"
125
+ out["Access-Control-Max-Age"] = "86400"
126
+ out["Vary"] = "Origin"
127
+ return out
128
+
129
+
130
+ def _upstream_down_response(request: web.Request, target_port: int) -> web.Response:
131
+ headers = {"X-DevDoor-Error": "upstream-down"}
132
+ accept = request.headers.get("Accept", "")
133
+ if "application/json" in accept:
134
+ payload = json.dumps(
135
+ {
136
+ "error": "upstream-down",
137
+ "message": f"Upstream service on 127.0.0.1:{target_port} is unreachable.",
138
+ }
139
+ )
140
+ return web.Response(
141
+ status=502,
142
+ text=payload,
143
+ content_type="application/json",
144
+ headers=headers,
145
+ )
146
+ escaped_host = html.escape(request.host)
147
+ body = (
148
+ "<!doctype html><html><body>"
149
+ f"<h1>502 Bad Gateway</h1><p>No upstream service responded on "
150
+ f"<code>127.0.0.1:{target_port}</code> for <code>{escaped_host}</code>.</p>"
151
+ "</body></html>"
152
+ )
153
+ return web.Response(
154
+ status=502,
155
+ text=body,
156
+ content_type="text/html",
157
+ headers=headers,
158
+ )
159
+
160
+
161
+ async def wait_for_upstream(
162
+ port: int,
163
+ timeout: float = 10.0,
164
+ *,
165
+ host: str = "127.0.0.1",
166
+ poll_interval: float = 0.05,
167
+ ) -> None:
168
+ """Wait until ``host:port`` accepts TCP connections or raise ``TimeoutError``."""
169
+ deadline = time.monotonic() + timeout
170
+ while True:
171
+ try:
172
+ _, writer = await asyncio.wait_for(
173
+ asyncio.open_connection(host, port),
174
+ timeout=min(1.0, max(0.05, deadline - time.monotonic())),
175
+ )
176
+ writer.close()
177
+ with suppress(OSError):
178
+ await writer.wait_closed()
179
+ return
180
+ except (OSError, TimeoutError) as exc:
181
+ remaining = deadline - time.monotonic()
182
+ if remaining <= 0:
183
+ raise TimeoutError(
184
+ f"Upstream {host}:{port} did not become ready within {timeout:.2f}s"
185
+ ) from exc
186
+ await asyncio.sleep(min(poll_interval, remaining))
187
+
188
+
189
+ async def _stream_request_body(
190
+ request: web.Request,
191
+ tap: BodyTapBuffer,
192
+ ) -> AsyncIterator[bytes]:
193
+ async for chunk in request.content.iter_chunked(65_536):
194
+ if chunk:
195
+ tap.write(chunk)
196
+ yield chunk
197
+
198
+
199
+ async def _pump_ws(
200
+ src: web.WebSocketResponse | aiohttp.ClientWebSocketResponse,
201
+ dst: web.WebSocketResponse | aiohttp.ClientWebSocketResponse,
202
+ ) -> None:
203
+ async for msg in src:
204
+ if msg.type == aiohttp.WSMsgType.TEXT:
205
+ await dst.send_str(msg.data)
206
+ elif msg.type == aiohttp.WSMsgType.BINARY:
207
+ await dst.send_bytes(msg.data)
208
+ elif msg.type == aiohttp.WSMsgType.CLOSE:
209
+ await dst.close(code=msg.data or aiohttp.WSCloseCode.OK)
210
+ return
211
+ if not dst.closed:
212
+ await dst.close()
213
+
214
+
215
+ class Forwarder:
216
+ """Streaming HTTP and WebSocket forwarder targeting ``127.0.0.1:<port>``."""
217
+
218
+ def __init__(
219
+ self,
220
+ event_bus: TrafficEventBus,
221
+ *,
222
+ connect_timeout: float = DEFAULT_CONNECT_TIMEOUT_S,
223
+ ) -> None:
224
+ self._event_bus = event_bus
225
+ self._connect_timeout = connect_timeout
226
+ self._session: aiohttp.ClientSession | None = None
227
+
228
+ def get_session(self) -> aiohttp.ClientSession:
229
+ """Lazily create and return the shared streaming ``aiohttp.ClientSession``."""
230
+ if self._session is None or self._session.closed:
231
+ timeout = aiohttp.ClientTimeout(
232
+ total=None,
233
+ connect=self._connect_timeout,
234
+ sock_connect=self._connect_timeout,
235
+ sock_read=None,
236
+ )
237
+ connector = aiohttp.TCPConnector(
238
+ limit=256,
239
+ limit_per_host=128,
240
+ keepalive_timeout=300.0,
241
+ )
242
+ self._session = aiohttp.ClientSession(
243
+ connector=connector,
244
+ auto_decompress=False,
245
+ cookie_jar=aiohttp.DummyCookieJar(),
246
+ timeout=timeout,
247
+ )
248
+ return self._session
249
+
250
+ async def close(self) -> None:
251
+ """Close the shared upstream HTTP client session."""
252
+ if self._session is not None and not self._session.closed:
253
+ await self._session.close()
254
+ self._session = None
255
+
256
+ async def handle_request(
257
+ self,
258
+ request: web.Request,
259
+ match: RouteMatch,
260
+ *,
261
+ source: TrafficSource = "local",
262
+ host_override: str | None = None,
263
+ ) -> web.StreamResponse:
264
+ """Forward an incoming HTTP or WebSocket request using ``match``."""
265
+ if request.headers.get("Upgrade", "").lower() == "websocket":
266
+ return await self._handle_websocket(
267
+ request,
268
+ match,
269
+ source=source,
270
+ host_override=host_override,
271
+ )
272
+
273
+ started = time.perf_counter()
274
+ req_tap = BodyTapBuffer()
275
+ resp_tap = BodyTapBuffer()
276
+ original_host = request.host or match.domain
277
+ origin = request.headers.get("Origin")
278
+
279
+ if request.method.upper() == "OPTIONS" and match.cors and origin:
280
+ cors_headers = build_downstream_headers(
281
+ (),
282
+ cors_enabled=True,
283
+ request_origin=origin,
284
+ request_headers=request.headers.get("Access-Control-Request-Headers"),
285
+ )
286
+ resp = web.Response(status=204, headers=cors_headers)
287
+ self._emit(
288
+ request=request,
289
+ match=match,
290
+ source=source,
291
+ status=204,
292
+ started=started,
293
+ resp_headers=tuple(resp.headers.items()),
294
+ req_tap=req_tap,
295
+ resp_tap=resp_tap,
296
+ )
297
+ return resp
298
+
299
+ has_body = request.can_read_body
300
+ upstream_headers = build_upstream_headers(
301
+ request.headers.items(),
302
+ client_ip=request.remote,
303
+ proto=request.scheme or "http",
304
+ original_host=original_host,
305
+ host_override=host_override,
306
+ drop_content_length=has_body,
307
+ )
308
+ upstream_url = f"http://127.0.0.1:{match.port}{match.target_path}"
309
+ request_data = _stream_request_body(request, req_tap) if has_body else None
310
+
311
+ try:
312
+ async with self.get_session().request(
313
+ request.method,
314
+ upstream_url,
315
+ headers=upstream_headers,
316
+ data=request_data,
317
+ allow_redirects=False,
318
+ ) as upstream_resp:
319
+ downstream_headers = build_downstream_headers(
320
+ upstream_resp.headers.items(),
321
+ cors_enabled=match.cors,
322
+ request_origin=origin,
323
+ request_headers=request.headers.get("Access-Control-Request-Headers"),
324
+ )
325
+ stream_resp = web.StreamResponse(
326
+ status=upstream_resp.status,
327
+ reason=upstream_resp.reason,
328
+ headers=downstream_headers,
329
+ )
330
+ await stream_resp.prepare(request)
331
+ async for chunk in upstream_resp.content.iter_any():
332
+ if chunk:
333
+ resp_tap.write(chunk)
334
+ await stream_resp.write(chunk)
335
+ await stream_resp.write_eof()
336
+
337
+ self._emit(
338
+ request=request,
339
+ match=match,
340
+ source=source,
341
+ status=upstream_resp.status,
342
+ started=started,
343
+ resp_headers=tuple(stream_resp.headers.items()),
344
+ req_tap=req_tap,
345
+ resp_tap=resp_tap,
346
+ )
347
+ return stream_resp
348
+ except aiohttp.ClientError, TimeoutError, OSError:
349
+ err_resp = _upstream_down_response(request, match.port)
350
+ self._emit(
351
+ request=request,
352
+ match=match,
353
+ source=source,
354
+ status=502,
355
+ started=started,
356
+ resp_headers=tuple(err_resp.headers.items()),
357
+ req_tap=req_tap,
358
+ resp_tap=resp_tap,
359
+ )
360
+ return err_resp
361
+
362
+ async def _handle_websocket(
363
+ self,
364
+ request: web.Request,
365
+ match: RouteMatch,
366
+ *,
367
+ source: TrafficSource,
368
+ host_override: str | None,
369
+ ) -> web.StreamResponse:
370
+ started = time.perf_counter()
371
+ req_tap = BodyTapBuffer()
372
+ resp_tap = BodyTapBuffer()
373
+ original_host = request.host or match.domain
374
+ upstream_headers = build_upstream_headers(
375
+ request.headers.items(),
376
+ client_ip=request.remote,
377
+ proto=request.scheme or "http",
378
+ original_host=original_host,
379
+ host_override=host_override,
380
+ for_websocket=True,
381
+ )
382
+ raw_protocols = request.headers.get("Sec-WebSocket-Protocol", "")
383
+ protocols = [item.strip() for item in raw_protocols.split(",") if item.strip()]
384
+ ws_url = f"ws://127.0.0.1:{match.port}{match.target_path}"
385
+
386
+ try:
387
+ async with self.get_session().ws_connect(
388
+ ws_url,
389
+ headers=upstream_headers,
390
+ protocols=protocols,
391
+ autoclose=False,
392
+ ) as upstream_ws:
393
+ downstream_protocols = (upstream_ws.protocol,) if upstream_ws.protocol else ()
394
+ downstream_ws = web.WebSocketResponse(
395
+ protocols=downstream_protocols,
396
+ autoclose=False,
397
+ )
398
+ await downstream_ws.prepare(request)
399
+ self._emit(
400
+ request=request,
401
+ match=match,
402
+ source=source,
403
+ status=101,
404
+ started=started,
405
+ resp_headers=tuple(downstream_ws.headers.items()),
406
+ req_tap=req_tap,
407
+ resp_tap=resp_tap,
408
+ )
409
+ async with asyncio.TaskGroup() as group:
410
+ group.create_task(_pump_ws(downstream_ws, upstream_ws))
411
+ group.create_task(_pump_ws(upstream_ws, downstream_ws))
412
+ return downstream_ws
413
+ except aiohttp.ClientError, TimeoutError, OSError:
414
+ err_resp = _upstream_down_response(request, match.port)
415
+ self._emit(
416
+ request=request,
417
+ match=match,
418
+ source=source,
419
+ status=502,
420
+ started=started,
421
+ resp_headers=tuple(err_resp.headers.items()),
422
+ req_tap=req_tap,
423
+ resp_tap=resp_tap,
424
+ )
425
+ return err_resp
426
+
427
+ def _emit(
428
+ self,
429
+ *,
430
+ request: web.Request,
431
+ match: RouteMatch,
432
+ source: TrafficSource,
433
+ status: int,
434
+ started: float,
435
+ resp_headers: tuple[tuple[str, str], ...],
436
+ req_tap: BodyTapBuffer,
437
+ resp_tap: BodyTapBuffer,
438
+ ) -> None:
439
+ req_preview, req_truncated = req_tap.snapshot()
440
+ resp_preview, resp_truncated = resp_tap.snapshot()
441
+ duration_ms = (time.perf_counter() - started) * 1000.0
442
+ self._event_bus.emit_exchange(
443
+ source=source,
444
+ host=match.domain,
445
+ method=request.method,
446
+ path=request.raw_path or "/",
447
+ target_port=match.port,
448
+ status=status,
449
+ duration_ms=duration_ms,
450
+ req_headers=tuple(request.headers.items()),
451
+ resp_headers=resp_headers,
452
+ req_body_preview=req_preview,
453
+ resp_body_preview=resp_preview,
454
+ req_body_truncated=req_truncated,
455
+ resp_body_truncated=resp_truncated,
456
+ log_mode=match.log_mode,
457
+ )
@@ -0,0 +1,122 @@
1
+ """Local HTTP->HTTPS redirector and SNI-aware HTTPS reverse proxy server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from aiohttp import web
6
+
7
+ from devdoor.core.config import DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT, GlobalConfig
8
+ from devdoor.core.router import Router, normalize_host
9
+ from devdoor.proxy.certs import CertManager
10
+ from devdoor.proxy.forwarder import Forwarder
11
+
12
+
13
+ class LocalProxyServer:
14
+ """Runs local HTTP redirect (``:10080``) and SNI TLS reverse proxy (``:10443``)."""
15
+
16
+ def __init__(
17
+ self,
18
+ *,
19
+ router: Router,
20
+ forwarder: Forwarder,
21
+ cert_manager: CertManager,
22
+ http_port: int = DEFAULT_HTTP_PORT,
23
+ https_port: int = DEFAULT_HTTPS_PORT,
24
+ redirect_include_port: bool = False,
25
+ bind_host: str = "127.0.0.1",
26
+ ) -> None:
27
+ self._router = router
28
+ self._forwarder = forwarder
29
+ self._cert_manager = cert_manager
30
+ self._http_port = http_port
31
+ self._https_port = https_port
32
+ self._redirect_include_port = redirect_include_port
33
+ self._bind_host = bind_host
34
+
35
+ self._http_runner: web.AppRunner | None = None
36
+ self._https_runner: web.AppRunner | None = None
37
+ self._bound_http_port = http_port
38
+ self._bound_https_port = https_port
39
+
40
+ @property
41
+ def bound_http_port(self) -> int:
42
+ return self._bound_http_port
43
+
44
+ @property
45
+ def bound_https_port(self) -> int:
46
+ return self._bound_https_port
47
+
48
+ def sync_certs(self) -> None:
49
+ """Pre-mint Root CA and leaf certificates for all currently configured domains."""
50
+ self._cert_manager.sync_domains(self._router.domains)
51
+
52
+ def handle_reload(self, _config: GlobalConfig) -> None:
53
+ """Pre-mint certificates for any newly added domains on config reload."""
54
+ self.sync_certs()
55
+
56
+ async def start(self) -> None:
57
+ """Start the local HTTP redirector and SNI HTTPS proxy listeners."""
58
+ if self._http_runner is not None or self._https_runner is not None:
59
+ return
60
+
61
+ self.sync_certs()
62
+ ssl_context = self._cert_manager.build_base_ssl_context(self._router.has_domain)
63
+
64
+ https_app = web.Application(client_max_size=0)
65
+ https_app.router.add_route("*", "/{tail:.*}", self._handle_https)
66
+ https_runner = web.AppRunner(https_app)
67
+ await https_runner.setup()
68
+
69
+ http_app = web.Application(client_max_size=0)
70
+ http_app.router.add_route("*", "/{tail:.*}", self._handle_http_redirect)
71
+ http_runner = web.AppRunner(http_app)
72
+ await http_runner.setup()
73
+
74
+ try:
75
+ https_site = web.TCPSite(
76
+ https_runner,
77
+ self._bind_host,
78
+ self._https_port,
79
+ ssl_context=ssl_context,
80
+ )
81
+ await https_site.start()
82
+ if https_runner.addresses:
83
+ self._bound_https_port = int(https_runner.addresses[0][1])
84
+
85
+ http_site = web.TCPSite(http_runner, self._bind_host, self._http_port)
86
+ await http_site.start()
87
+ if http_runner.addresses:
88
+ self._bound_http_port = int(http_runner.addresses[0][1])
89
+ except BaseException:
90
+ await http_runner.cleanup()
91
+ await https_runner.cleanup()
92
+ raise
93
+
94
+ self._https_runner = https_runner
95
+ self._http_runner = http_runner
96
+
97
+ async def stop(self) -> None:
98
+ """Stop both HTTP and HTTPS listeners cleanly."""
99
+ if self._http_runner is not None:
100
+ await self._http_runner.cleanup()
101
+ self._http_runner = None
102
+ if self._https_runner is not None:
103
+ await self._https_runner.cleanup()
104
+ self._https_runner = None
105
+
106
+ async def _handle_http_redirect(self, request: web.Request) -> web.StreamResponse:
107
+ host = normalize_host(request.host)
108
+ if not host or not self._router.has_domain(host):
109
+ return web.Response(status=404, text="Unknown local domain")
110
+
111
+ target = request.raw_path or "/"
112
+ if self._redirect_include_port and self._bound_https_port != 443:
113
+ location = f"https://{host}:{self._bound_https_port}{target}"
114
+ else:
115
+ location = f"https://{host}{target}"
116
+ return web.Response(status=301, headers={"Location": location})
117
+
118
+ async def _handle_https(self, request: web.Request) -> web.StreamResponse:
119
+ match = self._router.match(request.host, request.raw_path or "/")
120
+ if match is None:
121
+ return web.Response(status=404, text="Unknown local domain")
122
+ return await self._forwarder.handle_request(request, match, source="local")
@@ -0,0 +1,17 @@
1
+ """Interactive Textual terminal UI for live request inspection and replay."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from devdoor.tui.inspector_app import (
6
+ InspectorApp,
7
+ ShareTunnelStatus,
8
+ run_inspect_tui,
9
+ run_share_tui,
10
+ )
11
+
12
+ __all__ = [
13
+ "InspectorApp",
14
+ "ShareTunnelStatus",
15
+ "run_inspect_tui",
16
+ "run_share_tui",
17
+ ]