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.
- devdoor/__init__.py +6 -0
- devdoor/__main__.py +8 -0
- devdoor/cli/__init__.py +1 -0
- devdoor/cli/app.py +99 -0
- devdoor/cli/auth.py +178 -0
- devdoor/cli/domains.py +214 -0
- devdoor/cli/inspector.py +209 -0
- devdoor/cli/local.py +790 -0
- devdoor/cli/share.py +443 -0
- devdoor/cli/validators.py +40 -0
- devdoor/core/__init__.py +1 -0
- devdoor/core/config.py +482 -0
- devdoor/core/engine.py +495 -0
- devdoor/core/events.py +287 -0
- devdoor/core/protocol.py +462 -0
- devdoor/core/router.py +163 -0
- devdoor/inspector/__init__.py +14 -0
- devdoor/inspector/curl.py +68 -0
- devdoor/inspector/daemon_hook.py +147 -0
- devdoor/inspector/replay.py +122 -0
- devdoor/inspector/store.py +291 -0
- devdoor/platform/__init__.py +36 -0
- devdoor/platform/base.py +209 -0
- devdoor/platform/darwin.py +194 -0
- devdoor/platform/linux.py +185 -0
- devdoor/platform/windows.py +143 -0
- devdoor/proxy/__init__.py +7 -0
- devdoor/proxy/certs.py +311 -0
- devdoor/proxy/forwarder.py +457 -0
- devdoor/proxy/https_server.py +122 -0
- devdoor/tui/__init__.py +17 -0
- devdoor/tui/inspector_app.py +667 -0
- devdoor/tunnel/__init__.py +1 -0
- devdoor/tunnel/auth_client.py +287 -0
- devdoor/tunnel/client.py +309 -0
- devdoor/tunnel/httperr.py +168 -0
- devdoor/tunnel/mux.py +566 -0
- devdoor/tunnel/relay_api.py +245 -0
- devdoor-0.1.0.dist-info/METADATA +227 -0
- devdoor-0.1.0.dist-info/RECORD +43 -0
- devdoor-0.1.0.dist-info/WHEEL +4 -0
- devdoor-0.1.0.dist-info/entry_points.txt +3 -0
- devdoor-0.1.0.dist-info/licenses/LICENSE +21 -0
devdoor/core/protocol.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
"""Zero-dependency wire protocol shared by DevDoor and devdoor-relay."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import struct
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import IntEnum
|
|
9
|
+
from typing import Literal, cast
|
|
10
|
+
|
|
11
|
+
PROTOCOL_VERSION = 1
|
|
12
|
+
MAX_FRAME_PAYLOAD = 65_536
|
|
13
|
+
MAX_CONTROL_PAYLOAD = 1_048_576
|
|
14
|
+
INITIAL_STREAM_WINDOW = 1_048_576
|
|
15
|
+
WINDOW_UPDATE_THRESHOLD = 524_288
|
|
16
|
+
|
|
17
|
+
CLOSE_TTL_EXPIRED = 4000
|
|
18
|
+
CLOSE_TUNNEL_DROPPED = 4001
|
|
19
|
+
CLOSE_AUTH_REVOKED = 4002
|
|
20
|
+
CLOSE_PROTOCOL_ERROR = 4003
|
|
21
|
+
|
|
22
|
+
HEADER_STRUCT = struct.Struct("!IBI")
|
|
23
|
+
HEADER_SIZE = HEADER_STRUCT.size
|
|
24
|
+
_U32_STRUCT = struct.Struct("!I")
|
|
25
|
+
_U64_STRUCT = struct.Struct("!Q")
|
|
26
|
+
_MAX_U32 = 0xFFFF_FFFF
|
|
27
|
+
|
|
28
|
+
HeaderPair = tuple[str, str]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ProtocolError(ValueError):
|
|
32
|
+
"""Raised when a wire frame or handshake payload violates protocol invariants."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class FrameType(IntEnum):
|
|
36
|
+
"""Binary multiplexed frame opcodes."""
|
|
37
|
+
|
|
38
|
+
STREAM_OPEN = 0x01
|
|
39
|
+
DATA = 0x02
|
|
40
|
+
END = 0x03
|
|
41
|
+
RST = 0x04
|
|
42
|
+
WS_OPEN_OK = 0x05
|
|
43
|
+
WS_FRAME = 0x06
|
|
44
|
+
WINDOW_UPDATE = 0x07
|
|
45
|
+
HEARTBEAT = 0x08
|
|
46
|
+
HEARTBEAT_ACK = 0x09
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class WsOpcode(IntEnum):
|
|
50
|
+
"""WebSocket frame flags carried inside WS_FRAME."""
|
|
51
|
+
|
|
52
|
+
TEXT = 1
|
|
53
|
+
BINARY = 2
|
|
54
|
+
CLOSE = 8
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class RegistrationRequest:
|
|
59
|
+
"""Initial client-to-relay JSON handshake message."""
|
|
60
|
+
|
|
61
|
+
token: str
|
|
62
|
+
version: int = PROTOCOL_VERSION
|
|
63
|
+
subdomain: str = ""
|
|
64
|
+
domain: str = ""
|
|
65
|
+
password: str = ""
|
|
66
|
+
ttl_seconds: int | None = None
|
|
67
|
+
client_version: str = ""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True, slots=True)
|
|
71
|
+
class RegistrationResponse:
|
|
72
|
+
"""Relay-to-client JSON handshake reply."""
|
|
73
|
+
|
|
74
|
+
ok: bool
|
|
75
|
+
url: str = ""
|
|
76
|
+
subdomain: str = ""
|
|
77
|
+
domain: str = ""
|
|
78
|
+
expires_at: str | None = None
|
|
79
|
+
error_code: str = ""
|
|
80
|
+
error: str = ""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class BinaryFrame:
|
|
85
|
+
"""Decoded binary multiplexed tunnel frame."""
|
|
86
|
+
|
|
87
|
+
stream_id: int
|
|
88
|
+
frame_type: FrameType
|
|
89
|
+
flags: int = 0
|
|
90
|
+
payload: bytes = b""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True, slots=True)
|
|
94
|
+
class StreamOpenRequest:
|
|
95
|
+
"""Visitor request metadata carried in a relay-to-client STREAM_OPEN frame."""
|
|
96
|
+
|
|
97
|
+
kind: Literal["http", "ws"]
|
|
98
|
+
method: str
|
|
99
|
+
raw_path: str
|
|
100
|
+
headers: tuple[HeaderPair, ...] = ()
|
|
101
|
+
client_ip: str = ""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True, slots=True)
|
|
105
|
+
class StreamOpenResponse:
|
|
106
|
+
"""Upstream HTTP response metadata carried in a client-to-relay STREAM_OPEN frame."""
|
|
107
|
+
|
|
108
|
+
status: int
|
|
109
|
+
reason: str = ""
|
|
110
|
+
headers: tuple[HeaderPair, ...] = ()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True, slots=True)
|
|
114
|
+
class WsOpenOk:
|
|
115
|
+
"""Upstream WebSocket 101 acceptance metadata carried in WS_OPEN_OK."""
|
|
116
|
+
|
|
117
|
+
headers: tuple[HeaderPair, ...] = ()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _encode_json_bytes(payload: dict[str, object]) -> bytes:
|
|
121
|
+
return json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _encode_json_text(payload: dict[str, object]) -> str:
|
|
125
|
+
return json.dumps(payload, separators=(",", ":"), sort_keys=True)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _decode_json_object(raw: str | bytes) -> dict[str, object]:
|
|
129
|
+
try:
|
|
130
|
+
text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
|
|
131
|
+
parsed: object = json.loads(text)
|
|
132
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
133
|
+
raise ProtocolError(f"invalid JSON payload: {exc}") from exc
|
|
134
|
+
if not isinstance(parsed, dict):
|
|
135
|
+
raise ProtocolError("expected JSON object")
|
|
136
|
+
return cast(dict[str, object], parsed)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _as_str(obj: dict[str, object], key: str, default: str = "") -> str:
|
|
140
|
+
val = obj.get(key, default)
|
|
141
|
+
if not isinstance(val, str):
|
|
142
|
+
raise ProtocolError(f"field {key!r} must be a string")
|
|
143
|
+
return val
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _as_optional_str(obj: dict[str, object], key: str) -> str | None:
|
|
147
|
+
val = obj.get(key)
|
|
148
|
+
if val is not None and not isinstance(val, str):
|
|
149
|
+
raise ProtocolError(f"field {key!r} must be a string or null")
|
|
150
|
+
return val
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _as_int(obj: dict[str, object], key: str) -> int:
|
|
154
|
+
val = obj.get(key)
|
|
155
|
+
if isinstance(val, bool) or not isinstance(val, int):
|
|
156
|
+
raise ProtocolError(f"field {key!r} must be an integer")
|
|
157
|
+
return val
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _normalize_headers(raw_headers: object) -> tuple[HeaderPair, ...]:
|
|
161
|
+
if not isinstance(raw_headers, list):
|
|
162
|
+
raise ProtocolError("headers must be a list of [name, value] pairs")
|
|
163
|
+
pairs: list[HeaderPair] = []
|
|
164
|
+
for entry in cast(list[object], raw_headers):
|
|
165
|
+
if not isinstance(entry, (list, tuple)):
|
|
166
|
+
raise ProtocolError("each header entry must be a [name, value] pair")
|
|
167
|
+
seq = cast(list[object] | tuple[object, ...], entry)
|
|
168
|
+
if len(seq) != 2 or not isinstance(seq[0], str) or not isinstance(seq[1], str):
|
|
169
|
+
raise ProtocolError("each header entry must contain two strings")
|
|
170
|
+
pairs.append((seq[0], seq[1]))
|
|
171
|
+
return tuple(pairs)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _validate_registration_request(req: RegistrationRequest) -> None:
|
|
175
|
+
if req.version != PROTOCOL_VERSION:
|
|
176
|
+
raise ProtocolError(f"unsupported protocol version: {req.version}")
|
|
177
|
+
if req.ttl_seconds is not None and (isinstance(req.ttl_seconds, bool) or req.ttl_seconds < 0):
|
|
178
|
+
raise ProtocolError("ttl_seconds must be a non-negative integer or null")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _validate_registration_response(resp: RegistrationResponse) -> None:
|
|
182
|
+
if resp.ok and not resp.url:
|
|
183
|
+
raise ProtocolError("successful registration response must include url")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def encode_registration_request(req: RegistrationRequest) -> str:
|
|
187
|
+
"""Serialize and validate a client registration request as JSON."""
|
|
188
|
+
_validate_registration_request(req)
|
|
189
|
+
return _encode_json_text(
|
|
190
|
+
{
|
|
191
|
+
"version": req.version,
|
|
192
|
+
"token": req.token,
|
|
193
|
+
"subdomain": req.subdomain,
|
|
194
|
+
"domain": req.domain,
|
|
195
|
+
"password": req.password,
|
|
196
|
+
"ttl_seconds": req.ttl_seconds,
|
|
197
|
+
"client_version": req.client_version,
|
|
198
|
+
}
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def decode_registration_request(raw: str) -> RegistrationRequest:
|
|
203
|
+
"""Parse and validate a JSON registration request."""
|
|
204
|
+
obj = _decode_json_object(raw)
|
|
205
|
+
version = _as_int(obj, "version")
|
|
206
|
+
ttl_val = obj.get("ttl_seconds")
|
|
207
|
+
if ttl_val is not None and (isinstance(ttl_val, bool) or not isinstance(ttl_val, int)):
|
|
208
|
+
raise ProtocolError("field 'ttl_seconds' must be an integer or null")
|
|
209
|
+
req = RegistrationRequest(
|
|
210
|
+
version=version,
|
|
211
|
+
token=_as_str(obj, "token"),
|
|
212
|
+
subdomain=_as_str(obj, "subdomain"),
|
|
213
|
+
domain=_as_str(obj, "domain"),
|
|
214
|
+
password=_as_str(obj, "password"),
|
|
215
|
+
ttl_seconds=ttl_val,
|
|
216
|
+
client_version=_as_str(obj, "client_version"),
|
|
217
|
+
)
|
|
218
|
+
_validate_registration_request(req)
|
|
219
|
+
return req
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def encode_registration_response(resp: RegistrationResponse) -> str:
|
|
223
|
+
"""Serialize and validate a relay registration response as JSON."""
|
|
224
|
+
_validate_registration_response(resp)
|
|
225
|
+
return _encode_json_text(
|
|
226
|
+
{
|
|
227
|
+
"ok": resp.ok,
|
|
228
|
+
"url": resp.url,
|
|
229
|
+
"subdomain": resp.subdomain,
|
|
230
|
+
"domain": resp.domain,
|
|
231
|
+
"expires_at": resp.expires_at,
|
|
232
|
+
"error_code": resp.error_code,
|
|
233
|
+
"error": resp.error,
|
|
234
|
+
}
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def decode_registration_response(raw: str) -> RegistrationResponse:
|
|
239
|
+
"""Parse and validate a JSON registration response."""
|
|
240
|
+
obj = _decode_json_object(raw)
|
|
241
|
+
ok_val = obj.get("ok")
|
|
242
|
+
if not isinstance(ok_val, bool):
|
|
243
|
+
raise ProtocolError("field 'ok' must be a boolean")
|
|
244
|
+
resp = RegistrationResponse(
|
|
245
|
+
ok=ok_val,
|
|
246
|
+
url=_as_str(obj, "url"),
|
|
247
|
+
subdomain=_as_str(obj, "subdomain"),
|
|
248
|
+
domain=_as_str(obj, "domain"),
|
|
249
|
+
expires_at=_as_optional_str(obj, "expires_at"),
|
|
250
|
+
error_code=_as_str(obj, "error_code"),
|
|
251
|
+
error=_as_str(obj, "error"),
|
|
252
|
+
)
|
|
253
|
+
_validate_registration_response(resp)
|
|
254
|
+
return resp
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _validate_frame(frame: BinaryFrame) -> None:
|
|
258
|
+
if not (0 <= frame.stream_id <= _MAX_U32):
|
|
259
|
+
raise ProtocolError(f"stream_id out of uint32 range: {frame.stream_id}")
|
|
260
|
+
if not (0 <= frame.flags <= _MAX_U32):
|
|
261
|
+
raise ProtocolError(f"flags out of uint32 range: {frame.flags}")
|
|
262
|
+
|
|
263
|
+
ftype = frame.frame_type
|
|
264
|
+
payload_len = len(frame.payload)
|
|
265
|
+
|
|
266
|
+
if ftype in (FrameType.HEARTBEAT, FrameType.HEARTBEAT_ACK):
|
|
267
|
+
if frame.stream_id != 0:
|
|
268
|
+
raise ProtocolError(f"{ftype.name} requires stream_id == 0")
|
|
269
|
+
if payload_len not in (0, 8):
|
|
270
|
+
raise ProtocolError(f"{ftype.name} payload must be 0 or 8 bytes")
|
|
271
|
+
return
|
|
272
|
+
|
|
273
|
+
if frame.stream_id == 0:
|
|
274
|
+
raise ProtocolError(f"{ftype.name} requires stream_id > 0")
|
|
275
|
+
|
|
276
|
+
if ftype == FrameType.DATA:
|
|
277
|
+
if payload_len == 0 or payload_len > MAX_FRAME_PAYLOAD:
|
|
278
|
+
raise ProtocolError(f"DATA payload length must be 1..{MAX_FRAME_PAYLOAD}")
|
|
279
|
+
elif ftype == FrameType.END:
|
|
280
|
+
if payload_len != 0 or frame.flags != 0:
|
|
281
|
+
raise ProtocolError("END frame must have empty payload and flags == 0")
|
|
282
|
+
elif ftype in (FrameType.STREAM_OPEN, FrameType.WS_OPEN_OK):
|
|
283
|
+
if payload_len == 0 or payload_len > MAX_CONTROL_PAYLOAD:
|
|
284
|
+
raise ProtocolError(f"{ftype.name} payload length must be 1..{MAX_CONTROL_PAYLOAD}")
|
|
285
|
+
elif ftype == FrameType.RST:
|
|
286
|
+
if payload_len > MAX_CONTROL_PAYLOAD:
|
|
287
|
+
raise ProtocolError(f"RST payload exceeds {MAX_CONTROL_PAYLOAD}")
|
|
288
|
+
elif ftype == FrameType.WS_FRAME:
|
|
289
|
+
if frame.flags not in (WsOpcode.TEXT, WsOpcode.BINARY, WsOpcode.CLOSE):
|
|
290
|
+
raise ProtocolError(f"invalid WS_FRAME opcode: {frame.flags}")
|
|
291
|
+
if payload_len > MAX_FRAME_PAYLOAD:
|
|
292
|
+
raise ProtocolError(f"WS_FRAME payload exceeds {MAX_FRAME_PAYLOAD}")
|
|
293
|
+
if frame.flags == WsOpcode.CLOSE and payload_len == 1:
|
|
294
|
+
raise ProtocolError("WS_FRAME CLOSE payload cannot be 1 byte")
|
|
295
|
+
elif ftype == FrameType.WINDOW_UPDATE:
|
|
296
|
+
if payload_len != 4:
|
|
297
|
+
raise ProtocolError("WINDOW_UPDATE payload must be exact 4-byte uint32")
|
|
298
|
+
(credit,) = _U32_STRUCT.unpack(frame.payload)
|
|
299
|
+
if credit == 0:
|
|
300
|
+
raise ProtocolError("WINDOW_UPDATE credit must be > 0")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def encode_frame(frame: BinaryFrame) -> bytes:
|
|
304
|
+
"""Validate and encode a BinaryFrame into wire bytes."""
|
|
305
|
+
_validate_frame(frame)
|
|
306
|
+
return HEADER_STRUCT.pack(frame.stream_id, int(frame.frame_type), frame.flags) + frame.payload
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def decode_frame(raw: bytes) -> BinaryFrame:
|
|
310
|
+
"""Decode and validate wire bytes into a BinaryFrame."""
|
|
311
|
+
if len(raw) < HEADER_SIZE:
|
|
312
|
+
raise ProtocolError(f"frame too short: {len(raw)} bytes (minimum {HEADER_SIZE})")
|
|
313
|
+
stream_id, raw_type, flags = HEADER_STRUCT.unpack_from(raw, 0)
|
|
314
|
+
try:
|
|
315
|
+
frame_type = FrameType(raw_type)
|
|
316
|
+
except ValueError as exc:
|
|
317
|
+
raise ProtocolError(f"unknown frame type: {raw_type:#x}") from exc
|
|
318
|
+
frame = BinaryFrame(
|
|
319
|
+
stream_id=stream_id,
|
|
320
|
+
frame_type=frame_type,
|
|
321
|
+
flags=flags,
|
|
322
|
+
payload=raw[HEADER_SIZE:],
|
|
323
|
+
)
|
|
324
|
+
_validate_frame(frame)
|
|
325
|
+
return frame
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def encode_stream_open_request(stream_id: int, request: StreamOpenRequest) -> BinaryFrame:
|
|
329
|
+
"""Build a validated STREAM_OPEN frame for an incoming visitor request."""
|
|
330
|
+
payload = _encode_json_bytes(
|
|
331
|
+
{
|
|
332
|
+
"kind": request.kind,
|
|
333
|
+
"method": request.method,
|
|
334
|
+
"raw_path": request.raw_path,
|
|
335
|
+
"headers": [[k, v] for k, v in request.headers],
|
|
336
|
+
"client_ip": request.client_ip,
|
|
337
|
+
}
|
|
338
|
+
)
|
|
339
|
+
frame = BinaryFrame(stream_id=stream_id, frame_type=FrameType.STREAM_OPEN, payload=payload)
|
|
340
|
+
_validate_frame(frame)
|
|
341
|
+
return frame
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def encode_stream_open_response(stream_id: int, response: StreamOpenResponse) -> BinaryFrame:
|
|
345
|
+
"""Build a validated STREAM_OPEN frame for an upstream HTTP response."""
|
|
346
|
+
payload = _encode_json_bytes(
|
|
347
|
+
{
|
|
348
|
+
"kind": "http",
|
|
349
|
+
"status": response.status,
|
|
350
|
+
"reason": response.reason,
|
|
351
|
+
"headers": [[k, v] for k, v in response.headers],
|
|
352
|
+
}
|
|
353
|
+
)
|
|
354
|
+
frame = BinaryFrame(stream_id=stream_id, frame_type=FrameType.STREAM_OPEN, payload=payload)
|
|
355
|
+
_validate_frame(frame)
|
|
356
|
+
return frame
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def decode_stream_open(frame: BinaryFrame) -> StreamOpenRequest | StreamOpenResponse:
|
|
360
|
+
"""Decode a STREAM_OPEN frame into a request or response metadata object."""
|
|
361
|
+
if frame.frame_type != FrameType.STREAM_OPEN:
|
|
362
|
+
raise ProtocolError(f"expected STREAM_OPEN frame, got {frame.frame_type.name}")
|
|
363
|
+
obj = _decode_json_object(frame.payload)
|
|
364
|
+
headers = _normalize_headers(obj.get("headers", []))
|
|
365
|
+
if "status" in obj:
|
|
366
|
+
status = _as_int(obj, "status")
|
|
367
|
+
return StreamOpenResponse(
|
|
368
|
+
status=status,
|
|
369
|
+
reason=_as_str(obj, "reason"),
|
|
370
|
+
headers=headers,
|
|
371
|
+
)
|
|
372
|
+
kind = _as_str(obj, "kind")
|
|
373
|
+
if kind == "http":
|
|
374
|
+
stream_kind: Literal["http", "ws"] = "http"
|
|
375
|
+
elif kind == "ws":
|
|
376
|
+
stream_kind = "ws"
|
|
377
|
+
else:
|
|
378
|
+
raise ProtocolError(f"invalid stream kind: {kind!r}")
|
|
379
|
+
return StreamOpenRequest(
|
|
380
|
+
kind=stream_kind,
|
|
381
|
+
method=_as_str(obj, "method"),
|
|
382
|
+
raw_path=_as_str(obj, "raw_path"),
|
|
383
|
+
headers=headers,
|
|
384
|
+
client_ip=_as_str(obj, "client_ip"),
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def encode_ws_open_ok(stream_id: int, ws_ok: WsOpenOk) -> BinaryFrame:
|
|
389
|
+
"""Build a WS_OPEN_OK frame confirming WebSocket upgrade."""
|
|
390
|
+
payload = _encode_json_bytes({"headers": [[k, v] for k, v in ws_ok.headers]})
|
|
391
|
+
frame = BinaryFrame(stream_id=stream_id, frame_type=FrameType.WS_OPEN_OK, payload=payload)
|
|
392
|
+
_validate_frame(frame)
|
|
393
|
+
return frame
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def decode_ws_open_ok(frame: BinaryFrame) -> WsOpenOk:
|
|
397
|
+
"""Decode a WS_OPEN_OK frame."""
|
|
398
|
+
if frame.frame_type != FrameType.WS_OPEN_OK:
|
|
399
|
+
raise ProtocolError(f"expected WS_OPEN_OK frame, got {frame.frame_type.name}")
|
|
400
|
+
obj = _decode_json_object(frame.payload)
|
|
401
|
+
return WsOpenOk(headers=_normalize_headers(obj.get("headers", [])))
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def encode_rst(stream_id: int, code: str = "", message: str = "") -> BinaryFrame:
|
|
405
|
+
"""Build an RST abort frame."""
|
|
406
|
+
payload = _encode_json_bytes({"code": code, "message": message}) if (code or message) else b""
|
|
407
|
+
frame = BinaryFrame(stream_id=stream_id, frame_type=FrameType.RST, payload=payload)
|
|
408
|
+
_validate_frame(frame)
|
|
409
|
+
return frame
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def decode_rst(frame: BinaryFrame) -> tuple[str, str]:
|
|
413
|
+
"""Decode an RST frame into (code, message)."""
|
|
414
|
+
if frame.frame_type != FrameType.RST:
|
|
415
|
+
raise ProtocolError(f"expected RST frame, got {frame.frame_type.name}")
|
|
416
|
+
if not frame.payload:
|
|
417
|
+
return ("", "")
|
|
418
|
+
obj = _decode_json_object(frame.payload)
|
|
419
|
+
return (_as_str(obj, "code"), _as_str(obj, "message"))
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def encode_window_update(stream_id: int, credit_bytes: int) -> BinaryFrame:
|
|
423
|
+
"""Build a WINDOW_UPDATE flow-control frame."""
|
|
424
|
+
if credit_bytes <= 0 or credit_bytes > _MAX_U32:
|
|
425
|
+
raise ProtocolError(f"WINDOW_UPDATE credit out of range: {credit_bytes}")
|
|
426
|
+
frame = BinaryFrame(
|
|
427
|
+
stream_id=stream_id,
|
|
428
|
+
frame_type=FrameType.WINDOW_UPDATE,
|
|
429
|
+
payload=_U32_STRUCT.pack(credit_bytes),
|
|
430
|
+
)
|
|
431
|
+
_validate_frame(frame)
|
|
432
|
+
return frame
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def decode_window_update(frame: BinaryFrame) -> int:
|
|
436
|
+
"""Extract credit_bytes from a WINDOW_UPDATE frame."""
|
|
437
|
+
if frame.frame_type != FrameType.WINDOW_UPDATE:
|
|
438
|
+
raise ProtocolError(f"expected WINDOW_UPDATE frame, got {frame.frame_type.name}")
|
|
439
|
+
_validate_frame(frame)
|
|
440
|
+
(credit,) = _U32_STRUCT.unpack(frame.payload)
|
|
441
|
+
return credit
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def encode_heartbeat(nonce_ms: int, *, ack: bool = False) -> BinaryFrame:
|
|
445
|
+
"""Build a HEARTBEAT or HEARTBEAT_ACK frame carrying an 8-byte nonce."""
|
|
446
|
+
if nonce_ms < 0:
|
|
447
|
+
raise ProtocolError("heartbeat nonce must be non-negative")
|
|
448
|
+
ftype = FrameType.HEARTBEAT_ACK if ack else FrameType.HEARTBEAT
|
|
449
|
+
frame = BinaryFrame(stream_id=0, frame_type=ftype, payload=_U64_STRUCT.pack(nonce_ms))
|
|
450
|
+
_validate_frame(frame)
|
|
451
|
+
return frame
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def decode_heartbeat(frame: BinaryFrame) -> int:
|
|
455
|
+
"""Extract the uint64 nonce from a HEARTBEAT or HEARTBEAT_ACK frame."""
|
|
456
|
+
if frame.frame_type not in (FrameType.HEARTBEAT, FrameType.HEARTBEAT_ACK):
|
|
457
|
+
raise ProtocolError(f"expected HEARTBEAT/ACK frame, got {frame.frame_type.name}")
|
|
458
|
+
_validate_frame(frame)
|
|
459
|
+
if not frame.payload:
|
|
460
|
+
return 0
|
|
461
|
+
(nonce,) = _U64_STRUCT.unpack(frame.payload)
|
|
462
|
+
return nonce
|
devdoor/core/router.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Host normalization and longest-prefix segment-safe request routing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from devdoor.core.config import GlobalConfig, LogMode, ProjectConfig, RouteConfig, ServiceConfig
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class RouteMatch:
|
|
13
|
+
"""Resolved upstream target and forwarding policy for an incoming request."""
|
|
14
|
+
|
|
15
|
+
domain: str
|
|
16
|
+
port: int
|
|
17
|
+
matched_prefix: str | None
|
|
18
|
+
target_path: str
|
|
19
|
+
strip_prefix: bool
|
|
20
|
+
cors: bool
|
|
21
|
+
log_mode: LogMode
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class _CompiledService:
|
|
26
|
+
domain: str
|
|
27
|
+
default_port: int
|
|
28
|
+
routes: tuple[RouteConfig, ...]
|
|
29
|
+
cors: bool
|
|
30
|
+
log_mode: LogMode
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def normalize_host(host: str) -> str:
|
|
34
|
+
"""Normalize an incoming ``Host`` header value by stripping whitespace, dot, and port."""
|
|
35
|
+
cleaned = host.strip().lower()
|
|
36
|
+
if cleaned.startswith("["):
|
|
37
|
+
end_bracket = cleaned.find("]")
|
|
38
|
+
if end_bracket != -1:
|
|
39
|
+
cleaned = cleaned[1:end_bracket]
|
|
40
|
+
elif ":" in cleaned:
|
|
41
|
+
cleaned = cleaned.split(":", 1)[0]
|
|
42
|
+
return cleaned.rstrip(".")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _split_target(raw_target: str) -> tuple[str, str | None]:
|
|
46
|
+
if not raw_target:
|
|
47
|
+
return "/", None
|
|
48
|
+
path, has_query, query = raw_target.partition("?")
|
|
49
|
+
normalized_path = path if path.startswith("/") else f"/{path}"
|
|
50
|
+
return normalized_path, query if has_query else None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _matches_prefix(path: str, prefix: str) -> bool:
|
|
54
|
+
if path == prefix:
|
|
55
|
+
return True
|
|
56
|
+
if not path.startswith(prefix):
|
|
57
|
+
return False
|
|
58
|
+
return prefix == "/" or prefix.endswith("/") or path[len(prefix)] == "/"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _build_target_path(path: str, query: str | None, route: RouteConfig | None) -> str:
|
|
62
|
+
if route is None or not route.strip_prefix or route.path == "/":
|
|
63
|
+
base = path
|
|
64
|
+
else:
|
|
65
|
+
remainder = path[len(route.path) :]
|
|
66
|
+
base = remainder if remainder else "/"
|
|
67
|
+
return f"{base}?{query}" if query is not None else base
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _compile_table(
|
|
71
|
+
services: Iterable[ServiceConfig],
|
|
72
|
+
*,
|
|
73
|
+
default_cors: bool,
|
|
74
|
+
default_log_mode: LogMode,
|
|
75
|
+
) -> dict[str, _CompiledService]:
|
|
76
|
+
table: dict[str, _CompiledService] = {}
|
|
77
|
+
for service in services:
|
|
78
|
+
domain = normalize_host(service.domain)
|
|
79
|
+
sorted_routes = tuple(
|
|
80
|
+
sorted(service.routes, key=lambda route: len(route.path), reverse=True)
|
|
81
|
+
)
|
|
82
|
+
table[domain] = _CompiledService(
|
|
83
|
+
domain=domain,
|
|
84
|
+
default_port=service.port,
|
|
85
|
+
routes=sorted_routes,
|
|
86
|
+
cors=default_cors if service.cors is None else service.cors,
|
|
87
|
+
log_mode=default_log_mode if service.log_mode is None else service.log_mode,
|
|
88
|
+
)
|
|
89
|
+
return table
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Router:
|
|
93
|
+
"""Thread- and task-safe router supporting longest-prefix matching and atomic reload."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, table: dict[str, _CompiledService] | None = None) -> None:
|
|
96
|
+
self._table: dict[str, _CompiledService] = dict(table or {})
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_project(cls, project: ProjectConfig) -> Router:
|
|
100
|
+
"""Build a ``Router`` from a validated ``ProjectConfig``."""
|
|
101
|
+
table = _compile_table(
|
|
102
|
+
project.services,
|
|
103
|
+
default_cors=project.cors,
|
|
104
|
+
default_log_mode=project.log_mode,
|
|
105
|
+
)
|
|
106
|
+
return cls(table)
|
|
107
|
+
|
|
108
|
+
@classmethod
|
|
109
|
+
def from_global(cls, config: GlobalConfig) -> Router:
|
|
110
|
+
"""Build a ``Router`` from a ``GlobalConfig`` domain registry."""
|
|
111
|
+
table = _compile_table(
|
|
112
|
+
config.domains.values(),
|
|
113
|
+
default_cors=config.cors,
|
|
114
|
+
default_log_mode=config.log_mode,
|
|
115
|
+
)
|
|
116
|
+
return cls(table)
|
|
117
|
+
|
|
118
|
+
@property
|
|
119
|
+
def domains(self) -> tuple[str, ...]:
|
|
120
|
+
"""Return currently configured domain names."""
|
|
121
|
+
return tuple(self._table.keys())
|
|
122
|
+
|
|
123
|
+
def has_domain(self, host: str) -> bool:
|
|
124
|
+
"""Check whether ``host`` matches a configured domain."""
|
|
125
|
+
return normalize_host(host) in self._table
|
|
126
|
+
|
|
127
|
+
def reload_global(self, config: GlobalConfig) -> None:
|
|
128
|
+
"""Atomically swap routing entries from ``config``."""
|
|
129
|
+
self._table = _compile_table(
|
|
130
|
+
config.domains.values(),
|
|
131
|
+
default_cors=config.cors,
|
|
132
|
+
default_log_mode=config.log_mode,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
def match(self, host: str, raw_target: str) -> RouteMatch | None:
|
|
136
|
+
"""Resolve ``host`` and ``raw_target`` to a ``RouteMatch`` or ``None``."""
|
|
137
|
+
table = self._table
|
|
138
|
+
service = table.get(normalize_host(host))
|
|
139
|
+
if service is None:
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
path, query = _split_target(raw_target)
|
|
143
|
+
for route in service.routes:
|
|
144
|
+
if _matches_prefix(path, route.path):
|
|
145
|
+
return RouteMatch(
|
|
146
|
+
domain=service.domain,
|
|
147
|
+
port=route.port,
|
|
148
|
+
matched_prefix=route.path,
|
|
149
|
+
target_path=_build_target_path(path, query, route),
|
|
150
|
+
strip_prefix=route.strip_prefix,
|
|
151
|
+
cors=service.cors,
|
|
152
|
+
log_mode=service.log_mode,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
return RouteMatch(
|
|
156
|
+
domain=service.domain,
|
|
157
|
+
port=service.default_port,
|
|
158
|
+
matched_prefix=None,
|
|
159
|
+
target_path=_build_target_path(path, query, None),
|
|
160
|
+
strip_prefix=False,
|
|
161
|
+
cors=service.cors,
|
|
162
|
+
log_mode=service.log_mode,
|
|
163
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Persistent SQLite traffic capture, cURL export, and request replay."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from devdoor.inspector.replay import ExchangeNotFoundError, ReplayService, TruncatedBodyError
|
|
6
|
+
from devdoor.inspector.store import MAX_STORED_EXCHANGES, InspectorStore
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"MAX_STORED_EXCHANGES",
|
|
10
|
+
"ExchangeNotFoundError",
|
|
11
|
+
"InspectorStore",
|
|
12
|
+
"ReplayService",
|
|
13
|
+
"TruncatedBodyError",
|
|
14
|
+
]
|