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
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
"""Interactive Textual terminal UI for live request inspection and replay."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from typing import ClassVar, Literal, cast
|
|
12
|
+
|
|
13
|
+
import aiohttp
|
|
14
|
+
from textual import on, work
|
|
15
|
+
from textual.app import App, ComposeResult
|
|
16
|
+
from textual.binding import Binding, BindingType
|
|
17
|
+
from textual.containers import Horizontal, Vertical
|
|
18
|
+
from textual.screen import ModalScreen
|
|
19
|
+
from textual.widgets import (
|
|
20
|
+
Button,
|
|
21
|
+
DataTable,
|
|
22
|
+
Footer,
|
|
23
|
+
Header,
|
|
24
|
+
Input,
|
|
25
|
+
Static,
|
|
26
|
+
TabbedContent,
|
|
27
|
+
TabPane,
|
|
28
|
+
TextArea,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from devdoor.core.config import DevDoorPaths, load_global_config, resolve_paths
|
|
32
|
+
from devdoor.core.engine import is_process_alive, load_daemon_state
|
|
33
|
+
from devdoor.core.events import CapturedExchange, TrafficEventBus, redact_headers
|
|
34
|
+
from devdoor.core.router import Router, normalize_host
|
|
35
|
+
from devdoor.inspector.curl import build_curl_command
|
|
36
|
+
from devdoor.inspector.replay import (
|
|
37
|
+
ExchangeNotFoundError,
|
|
38
|
+
ReplayService,
|
|
39
|
+
TruncatedBodyError,
|
|
40
|
+
)
|
|
41
|
+
from devdoor.inspector.store import InspectorStore
|
|
42
|
+
from devdoor.proxy.forwarder import Forwarder
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(slots=True)
|
|
46
|
+
class ShareTunnelStatus:
|
|
47
|
+
"""Mutable tunnel status displayed in ``devdoor share --tui`` header banner."""
|
|
48
|
+
|
|
49
|
+
url: str = "connecting..."
|
|
50
|
+
target: str = ""
|
|
51
|
+
status: str = "connecting"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _format_body_preview(raw: bytes) -> str:
|
|
55
|
+
if not raw:
|
|
56
|
+
return "(empty body)"
|
|
57
|
+
try:
|
|
58
|
+
text = raw.decode("utf-8")
|
|
59
|
+
except UnicodeDecodeError:
|
|
60
|
+
return f"<binary {len(raw)} bytes>"
|
|
61
|
+
stripped = text.strip()
|
|
62
|
+
if stripped.startswith("{") or stripped.startswith("["):
|
|
63
|
+
try:
|
|
64
|
+
parsed: object = json.loads(stripped)
|
|
65
|
+
return json.dumps(parsed, indent=2)
|
|
66
|
+
except ValueError:
|
|
67
|
+
pass
|
|
68
|
+
return text
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def format_exchange_detail(
|
|
72
|
+
exchange: CapturedExchange,
|
|
73
|
+
*,
|
|
74
|
+
side: Literal["request", "response"],
|
|
75
|
+
reveal_secrets: bool,
|
|
76
|
+
) -> str:
|
|
77
|
+
"""Format request or response headers + body preview for Textual detail pane."""
|
|
78
|
+
lines: list[str] = []
|
|
79
|
+
if side == "request":
|
|
80
|
+
lines.append(f"{exchange.method} https://{exchange.host}{exchange.path}")
|
|
81
|
+
lines.append(f"Target: 127.0.0.1:{exchange.target_port} (source={exchange.source})")
|
|
82
|
+
headers = redact_headers(exchange.req_headers, include_secrets=reveal_secrets)
|
|
83
|
+
truncated = exchange.req_body_truncated
|
|
84
|
+
body = exchange.req_body_preview
|
|
85
|
+
else:
|
|
86
|
+
lines.append(f"HTTP {exchange.status} ({exchange.duration_ms:.1f}ms)")
|
|
87
|
+
headers = redact_headers(exchange.resp_headers, include_secrets=reveal_secrets)
|
|
88
|
+
truncated = exchange.resp_body_truncated
|
|
89
|
+
body = exchange.resp_body_preview
|
|
90
|
+
|
|
91
|
+
if exchange.replayed_from_id:
|
|
92
|
+
lines.append(f"Replayed from: {exchange.replayed_from_id}")
|
|
93
|
+
lines.append("")
|
|
94
|
+
lines.append("--- Headers ---")
|
|
95
|
+
if headers:
|
|
96
|
+
for name, value in headers:
|
|
97
|
+
lines.append(f"{name}: {value}")
|
|
98
|
+
else:
|
|
99
|
+
lines.append("(none)")
|
|
100
|
+
|
|
101
|
+
lines.append("")
|
|
102
|
+
badge = " [TRUNCATED AT 1 MiB]" if truncated else ""
|
|
103
|
+
lines.append(f"--- Body{badge} ---")
|
|
104
|
+
lines.append(_format_body_preview(body))
|
|
105
|
+
return "\n".join(lines)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def matches_exchange_filter(
|
|
109
|
+
exchange: CapturedExchange,
|
|
110
|
+
query: str,
|
|
111
|
+
*,
|
|
112
|
+
domain_filter: str | None = None,
|
|
113
|
+
) -> bool:
|
|
114
|
+
"""Return whether ``exchange`` satisfies optional domain scope and text filter."""
|
|
115
|
+
if domain_filter and normalize_host(exchange.host) != domain_filter:
|
|
116
|
+
return False
|
|
117
|
+
needle = query.strip().lower()
|
|
118
|
+
if not needle:
|
|
119
|
+
return True
|
|
120
|
+
haystack = " ".join(
|
|
121
|
+
(
|
|
122
|
+
exchange.path.lower(),
|
|
123
|
+
exchange.method.lower(),
|
|
124
|
+
exchange.host.lower(),
|
|
125
|
+
exchange.source.lower(),
|
|
126
|
+
str(exchange.status),
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
return needle in haystack
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class EditReplayModal(ModalScreen[tuple[tuple[tuple[str, str], ...], bytes] | None]):
|
|
133
|
+
"""Modal editor allowing header/body edits prior to local replay."""
|
|
134
|
+
|
|
135
|
+
DEFAULT_CSS = """
|
|
136
|
+
EditReplayModal {
|
|
137
|
+
align: center middle;
|
|
138
|
+
}
|
|
139
|
+
#edit-modal-box {
|
|
140
|
+
width: 80;
|
|
141
|
+
height: 30;
|
|
142
|
+
border: round $accent;
|
|
143
|
+
background: $surface;
|
|
144
|
+
padding: 1 2;
|
|
145
|
+
}
|
|
146
|
+
#edit-headers, #edit-body {
|
|
147
|
+
height: 1fr;
|
|
148
|
+
margin-bottom: 1;
|
|
149
|
+
}
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
def __init__(self, exchange: CapturedExchange) -> None:
|
|
153
|
+
super().__init__()
|
|
154
|
+
self._exchange = exchange
|
|
155
|
+
|
|
156
|
+
def compose(self) -> ComposeResult:
|
|
157
|
+
headers_text = "\n".join(f"{k}: {v}" for k, v in self._exchange.req_headers)
|
|
158
|
+
try:
|
|
159
|
+
body_text = self._exchange.req_body_preview.decode("utf-8")
|
|
160
|
+
except UnicodeDecodeError:
|
|
161
|
+
body_text = ""
|
|
162
|
+
|
|
163
|
+
with Vertical(id="edit-modal-box"):
|
|
164
|
+
yield Static(
|
|
165
|
+
f"Edit & Replay {self._exchange.method} {self._exchange.path}",
|
|
166
|
+
markup=False,
|
|
167
|
+
)
|
|
168
|
+
yield Static("Headers (Name: Value per line):", markup=False)
|
|
169
|
+
yield TextArea(headers_text, id="edit-headers")
|
|
170
|
+
yield Static("Body:", markup=False)
|
|
171
|
+
yield TextArea(body_text, id="edit-body")
|
|
172
|
+
with Horizontal():
|
|
173
|
+
yield Button("Send Replay", variant="primary", id="btn-send")
|
|
174
|
+
yield Button("Cancel", id="btn-cancel")
|
|
175
|
+
|
|
176
|
+
@on(Button.Pressed, "#btn-cancel")
|
|
177
|
+
def _cancel(self) -> None:
|
|
178
|
+
self.dismiss(None)
|
|
179
|
+
|
|
180
|
+
@on(Button.Pressed, "#btn-send")
|
|
181
|
+
def _submit(self) -> None:
|
|
182
|
+
raw_headers = self.query_one("#edit-headers", TextArea).text
|
|
183
|
+
raw_body = self.query_one("#edit-body", TextArea).text
|
|
184
|
+
parsed_headers: list[tuple[str, str]] = []
|
|
185
|
+
for line in raw_headers.splitlines():
|
|
186
|
+
if ":" not in line:
|
|
187
|
+
continue
|
|
188
|
+
name, _, val = line.partition(":")
|
|
189
|
+
if name.strip():
|
|
190
|
+
parsed_headers.append((name.strip(), val.strip()))
|
|
191
|
+
self.dismiss((tuple(parsed_headers), raw_body.encode("utf-8")))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class ConfirmClearModal(ModalScreen[bool]):
|
|
195
|
+
"""Confirmation dialog before clearing captured traffic history."""
|
|
196
|
+
|
|
197
|
+
DEFAULT_CSS = """
|
|
198
|
+
ConfirmClearModal {
|
|
199
|
+
align: center middle;
|
|
200
|
+
}
|
|
201
|
+
#confirm-box {
|
|
202
|
+
width: 54;
|
|
203
|
+
height: 9;
|
|
204
|
+
border: round $warning;
|
|
205
|
+
background: $surface;
|
|
206
|
+
padding: 1 2;
|
|
207
|
+
}
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
def compose(self) -> ComposeResult:
|
|
211
|
+
with Vertical(id="confirm-box"):
|
|
212
|
+
yield Static("Clear all captured exchanges from inspector.db?", markup=False)
|
|
213
|
+
with Horizontal():
|
|
214
|
+
yield Button("Clear History", variant="error", id="btn-confirm-clear")
|
|
215
|
+
yield Button("Cancel", id="btn-cancel-clear")
|
|
216
|
+
|
|
217
|
+
@on(Button.Pressed, "#btn-cancel-clear")
|
|
218
|
+
def _cancel(self) -> None:
|
|
219
|
+
self.dismiss(False)
|
|
220
|
+
|
|
221
|
+
@on(Button.Pressed, "#btn-confirm-clear")
|
|
222
|
+
def _confirm(self) -> None:
|
|
223
|
+
self.dismiss(True)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class InspectorApp(App[None]):
|
|
227
|
+
"""Split-pane Textual TUI displaying live HTTP traffic, headers/bodies, cURL, and replay."""
|
|
228
|
+
|
|
229
|
+
TITLE = "DevDoor Inspector"
|
|
230
|
+
|
|
231
|
+
CSS = """
|
|
232
|
+
Screen {
|
|
233
|
+
layout: vertical;
|
|
234
|
+
}
|
|
235
|
+
#tunnel-banner {
|
|
236
|
+
height: 1;
|
|
237
|
+
background: $boost;
|
|
238
|
+
color: $text;
|
|
239
|
+
padding: 0 1;
|
|
240
|
+
}
|
|
241
|
+
#main-split {
|
|
242
|
+
height: 1fr;
|
|
243
|
+
}
|
|
244
|
+
#list-pane {
|
|
245
|
+
width: 1fr;
|
|
246
|
+
border-right: solid $primary-darken-2;
|
|
247
|
+
}
|
|
248
|
+
#detail-pane {
|
|
249
|
+
width: 2fr;
|
|
250
|
+
padding: 0 1;
|
|
251
|
+
}
|
|
252
|
+
#filter-input {
|
|
253
|
+
margin: 0 0 1 0;
|
|
254
|
+
}
|
|
255
|
+
#exchange-table {
|
|
256
|
+
height: 1fr;
|
|
257
|
+
}
|
|
258
|
+
"""
|
|
259
|
+
|
|
260
|
+
BINDINGS: ClassVar[list[BindingType]] = [
|
|
261
|
+
Binding("/", "focus_filter", "Filter"),
|
|
262
|
+
Binding("r", "replay_selected", "Replay"),
|
|
263
|
+
Binding("e", "edit_replay", "Edit"),
|
|
264
|
+
Binding("c", "copy_curl", "cURL"),
|
|
265
|
+
Binding("s", "toggle_secrets", "Secrets"),
|
|
266
|
+
Binding("x", "clear_history", "Clear"),
|
|
267
|
+
Binding("q", "quit", "Quit"),
|
|
268
|
+
Binding("escape", "focus_table", "Table", show=False),
|
|
269
|
+
]
|
|
270
|
+
|
|
271
|
+
def __init__(
|
|
272
|
+
self,
|
|
273
|
+
*,
|
|
274
|
+
store: InspectorStore,
|
|
275
|
+
event_bus: TrafficEventBus | None = None,
|
|
276
|
+
replay_service: ReplayService | None = None,
|
|
277
|
+
paths: DevDoorPaths | None = None,
|
|
278
|
+
domain_filter: str | None = None,
|
|
279
|
+
limit: int = 200,
|
|
280
|
+
tunnel_status: ShareTunnelStatus | None = None,
|
|
281
|
+
) -> None:
|
|
282
|
+
super().__init__()
|
|
283
|
+
self._store = store
|
|
284
|
+
self._event_bus = event_bus
|
|
285
|
+
self._replay_service = replay_service
|
|
286
|
+
self._paths = paths or resolve_paths()
|
|
287
|
+
self._domain_filter = normalize_host(domain_filter) if domain_filter else None
|
|
288
|
+
self._limit = limit
|
|
289
|
+
self._tunnel_status = tunnel_status
|
|
290
|
+
|
|
291
|
+
self._all_exchanges: list[CapturedExchange] = []
|
|
292
|
+
self._visible_exchanges: list[CapturedExchange] = []
|
|
293
|
+
self._selected_id: str | None = None
|
|
294
|
+
self._filter_query = ""
|
|
295
|
+
self._reveal_secrets = False
|
|
296
|
+
self._bus_queue: asyncio.Queue[CapturedExchange] | None = None
|
|
297
|
+
|
|
298
|
+
@property
|
|
299
|
+
def all_exchanges(self) -> tuple[CapturedExchange, ...]:
|
|
300
|
+
return tuple(self._all_exchanges)
|
|
301
|
+
|
|
302
|
+
@property
|
|
303
|
+
def visible_exchanges(self) -> tuple[CapturedExchange, ...]:
|
|
304
|
+
return tuple(self._visible_exchanges)
|
|
305
|
+
|
|
306
|
+
def compose(self) -> ComposeResult:
|
|
307
|
+
yield Header()
|
|
308
|
+
if self._tunnel_status is not None:
|
|
309
|
+
yield Static(self._format_banner_text(), id="tunnel-banner", markup=False)
|
|
310
|
+
with Horizontal(id="main-split"):
|
|
311
|
+
with Vertical(id="list-pane"):
|
|
312
|
+
yield Input(
|
|
313
|
+
placeholder="Filter path, method, host, status (/ to focus)...",
|
|
314
|
+
id="filter-input",
|
|
315
|
+
)
|
|
316
|
+
yield DataTable(id="exchange-table", cursor_type="row")
|
|
317
|
+
with Vertical(id="detail-pane"), TabbedContent(id="detail-tabs"):
|
|
318
|
+
with TabPane("Request", id="tab-request"):
|
|
319
|
+
yield Static("Select a request to inspect.", id="req-view", markup=False)
|
|
320
|
+
with TabPane("Response", id="tab-response"):
|
|
321
|
+
yield Static("Select a request to inspect.", id="resp-view", markup=False)
|
|
322
|
+
with TabPane("cURL", id="tab-curl"):
|
|
323
|
+
yield Static("Select a request to export cURL.", id="curl-view", markup=False)
|
|
324
|
+
yield Footer()
|
|
325
|
+
|
|
326
|
+
def _format_banner_text(self) -> str:
|
|
327
|
+
if self._tunnel_status is None:
|
|
328
|
+
return ""
|
|
329
|
+
target_part = f" -> {self._tunnel_status.target}" if self._tunnel_status.target else ""
|
|
330
|
+
return f"Tunnel [{self._tunnel_status.status}] {self._tunnel_status.url}{target_part}"
|
|
331
|
+
|
|
332
|
+
def refresh_tunnel_banner(self) -> None:
|
|
333
|
+
"""Refresh the top share-tunnel status banner safely from async callbacks."""
|
|
334
|
+
if self._tunnel_status is None:
|
|
335
|
+
return
|
|
336
|
+
with contextlib.suppress(LookupError):
|
|
337
|
+
self.query_one("#tunnel-banner", Static).update(self._format_banner_text())
|
|
338
|
+
|
|
339
|
+
def _exchange_table(self) -> DataTable[str]:
|
|
340
|
+
return cast(DataTable[str], self.query_one("#exchange-table", DataTable))
|
|
341
|
+
|
|
342
|
+
async def on_mount(self) -> None:
|
|
343
|
+
table = self._exchange_table()
|
|
344
|
+
table.add_columns("TIME", "SRC", "METHOD", "PATH", "STATUS", "LATENCY")
|
|
345
|
+
table.focus()
|
|
346
|
+
await self._load_initial_history()
|
|
347
|
+
self._listen_for_events()
|
|
348
|
+
|
|
349
|
+
async def on_unmount(self) -> None:
|
|
350
|
+
if self._event_bus is not None and self._bus_queue is not None:
|
|
351
|
+
self._event_bus.unsubscribe(self._bus_queue)
|
|
352
|
+
self._bus_queue = None
|
|
353
|
+
|
|
354
|
+
async def _load_initial_history(self) -> None:
|
|
355
|
+
rows = await self._store.list_exchanges(
|
|
356
|
+
limit=self._limit,
|
|
357
|
+
host=self._domain_filter,
|
|
358
|
+
)
|
|
359
|
+
self._all_exchanges = rows
|
|
360
|
+
self._rebuild_table()
|
|
361
|
+
|
|
362
|
+
def _selected_exchange(self) -> CapturedExchange | None:
|
|
363
|
+
if self._selected_id is not None:
|
|
364
|
+
for item in self._visible_exchanges:
|
|
365
|
+
if item.id == self._selected_id:
|
|
366
|
+
return item
|
|
367
|
+
return self._visible_exchanges[0] if self._visible_exchanges else None
|
|
368
|
+
|
|
369
|
+
def _rebuild_table(self) -> None:
|
|
370
|
+
table = self._exchange_table()
|
|
371
|
+
prev_id = self._selected_id
|
|
372
|
+
self._visible_exchanges = [
|
|
373
|
+
item
|
|
374
|
+
for item in self._all_exchanges
|
|
375
|
+
if matches_exchange_filter(
|
|
376
|
+
item,
|
|
377
|
+
self._filter_query,
|
|
378
|
+
domain_filter=self._domain_filter,
|
|
379
|
+
)
|
|
380
|
+
]
|
|
381
|
+
|
|
382
|
+
table.clear()
|
|
383
|
+
for item in self._visible_exchanges:
|
|
384
|
+
stamp = datetime.fromtimestamp(item.created_at_ms / 1000.0).strftime("%H:%M:%S")
|
|
385
|
+
table.add_row(
|
|
386
|
+
stamp,
|
|
387
|
+
item.source,
|
|
388
|
+
item.method,
|
|
389
|
+
item.path,
|
|
390
|
+
str(item.status),
|
|
391
|
+
f"{item.duration_ms:.0f}ms",
|
|
392
|
+
key=item.id,
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
if self._visible_exchanges:
|
|
396
|
+
target_idx = 0
|
|
397
|
+
if prev_id is not None:
|
|
398
|
+
for idx, item in enumerate(self._visible_exchanges):
|
|
399
|
+
if item.id == prev_id:
|
|
400
|
+
target_idx = idx
|
|
401
|
+
break
|
|
402
|
+
self._selected_id = self._visible_exchanges[target_idx].id
|
|
403
|
+
table.move_cursor(row=target_idx)
|
|
404
|
+
else:
|
|
405
|
+
self._selected_id = None
|
|
406
|
+
self._render_detail_panes()
|
|
407
|
+
|
|
408
|
+
def _render_detail_panes(self) -> None:
|
|
409
|
+
selected = self._selected_exchange()
|
|
410
|
+
req_widget = self.query_one("#req-view", Static)
|
|
411
|
+
resp_widget = self.query_one("#resp-view", Static)
|
|
412
|
+
curl_widget = self.query_one("#curl-view", Static)
|
|
413
|
+
if selected is None:
|
|
414
|
+
req_widget.update("No matching requests captured.")
|
|
415
|
+
resp_widget.update("No matching requests captured.")
|
|
416
|
+
curl_widget.update("")
|
|
417
|
+
return
|
|
418
|
+
req_widget.update(
|
|
419
|
+
format_exchange_detail(selected, side="request", reveal_secrets=self._reveal_secrets)
|
|
420
|
+
)
|
|
421
|
+
resp_widget.update(
|
|
422
|
+
format_exchange_detail(selected, side="response", reveal_secrets=self._reveal_secrets)
|
|
423
|
+
)
|
|
424
|
+
curl_widget.update(build_curl_command(selected, reveal_secrets=self._reveal_secrets))
|
|
425
|
+
|
|
426
|
+
def _ingest_live_exchange(self, exchange: CapturedExchange) -> None:
|
|
427
|
+
self._all_exchanges = [
|
|
428
|
+
exchange,
|
|
429
|
+
*(item for item in self._all_exchanges if item.id != exchange.id),
|
|
430
|
+
][: self._limit]
|
|
431
|
+
self._rebuild_table()
|
|
432
|
+
|
|
433
|
+
@work(exclusive=True)
|
|
434
|
+
async def _listen_for_events(self) -> None:
|
|
435
|
+
if self._event_bus is not None:
|
|
436
|
+
queue = self._event_bus.subscribe()
|
|
437
|
+
self._bus_queue = queue
|
|
438
|
+
try:
|
|
439
|
+
while True:
|
|
440
|
+
exchange = await queue.get()
|
|
441
|
+
self._ingest_live_exchange(exchange)
|
|
442
|
+
except asyncio.CancelledError:
|
|
443
|
+
return
|
|
444
|
+
finally:
|
|
445
|
+
self._event_bus.unsubscribe(queue)
|
|
446
|
+
if self._bus_queue is queue:
|
|
447
|
+
self._bus_queue = None
|
|
448
|
+
|
|
449
|
+
state = load_daemon_state(self._paths)
|
|
450
|
+
if state is None or not is_process_alive(state.pid):
|
|
451
|
+
return
|
|
452
|
+
ws_url = state.control_url.replace("http://", "ws://") + "/_control/events"
|
|
453
|
+
with contextlib.suppress(
|
|
454
|
+
aiohttp.ClientError, TimeoutError, OSError, asyncio.CancelledError
|
|
455
|
+
):
|
|
456
|
+
async with (
|
|
457
|
+
aiohttp.ClientSession() as session,
|
|
458
|
+
session.ws_connect(
|
|
459
|
+
ws_url,
|
|
460
|
+
headers={"Authorization": f"Bearer {state.token}"},
|
|
461
|
+
) as ws,
|
|
462
|
+
):
|
|
463
|
+
async for msg in ws:
|
|
464
|
+
if msg.type == aiohttp.WSMsgType.TEXT:
|
|
465
|
+
raw: object = json.loads(msg.data)
|
|
466
|
+
if isinstance(raw, dict):
|
|
467
|
+
mapping = {
|
|
468
|
+
str(k): v for k, v in cast(dict[object, object], raw).items()
|
|
469
|
+
}
|
|
470
|
+
self._ingest_live_exchange(CapturedExchange.from_event_dict(mapping))
|
|
471
|
+
|
|
472
|
+
@on(DataTable.RowHighlighted, "#exchange-table")
|
|
473
|
+
def _on_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
|
|
474
|
+
if event.row_key.value is not None:
|
|
475
|
+
self._selected_id = str(event.row_key.value)
|
|
476
|
+
self._render_detail_panes()
|
|
477
|
+
|
|
478
|
+
@on(Input.Changed, "#filter-input")
|
|
479
|
+
def _on_filter_changed(self, event: Input.Changed) -> None:
|
|
480
|
+
self._filter_query = event.value
|
|
481
|
+
self._rebuild_table()
|
|
482
|
+
|
|
483
|
+
def action_focus_filter(self) -> None:
|
|
484
|
+
self.query_one("#filter-input", Input).focus()
|
|
485
|
+
|
|
486
|
+
def action_focus_table(self) -> None:
|
|
487
|
+
self.query_one("#exchange-table", DataTable).focus()
|
|
488
|
+
|
|
489
|
+
def action_toggle_secrets(self) -> None:
|
|
490
|
+
self._reveal_secrets = not self._reveal_secrets
|
|
491
|
+
self._render_detail_panes()
|
|
492
|
+
|
|
493
|
+
def action_copy_curl(self) -> None:
|
|
494
|
+
selected = self._selected_exchange()
|
|
495
|
+
if selected is None:
|
|
496
|
+
self.notify("No exchange selected.", severity="warning")
|
|
497
|
+
return
|
|
498
|
+
cmd = build_curl_command(selected, reveal_secrets=self._reveal_secrets)
|
|
499
|
+
self.copy_to_clipboard(cmd)
|
|
500
|
+
self.notify("Copied cURL command.")
|
|
501
|
+
|
|
502
|
+
def action_replay_selected(self) -> None:
|
|
503
|
+
selected = self._selected_exchange()
|
|
504
|
+
if selected is None:
|
|
505
|
+
return
|
|
506
|
+
self._dispatch_replay(selected.id, headers_override=None, body_override=None)
|
|
507
|
+
|
|
508
|
+
def action_edit_replay(self) -> None:
|
|
509
|
+
selected = self._selected_exchange()
|
|
510
|
+
if selected is None:
|
|
511
|
+
return
|
|
512
|
+
|
|
513
|
+
def _after_edit(
|
|
514
|
+
result: tuple[tuple[tuple[str, str], ...], bytes] | None,
|
|
515
|
+
) -> None:
|
|
516
|
+
if result is None:
|
|
517
|
+
return
|
|
518
|
+
headers_override, body_override = result
|
|
519
|
+
self._dispatch_replay(
|
|
520
|
+
selected.id,
|
|
521
|
+
headers_override=headers_override,
|
|
522
|
+
body_override=body_override,
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
self.push_screen(EditReplayModal(selected), _after_edit)
|
|
526
|
+
|
|
527
|
+
def action_clear_history(self) -> None:
|
|
528
|
+
def _after_confirm(confirmed: bool | None) -> None:
|
|
529
|
+
if confirmed:
|
|
530
|
+
self._clear_all()
|
|
531
|
+
|
|
532
|
+
self.push_screen(ConfirmClearModal(), _after_confirm)
|
|
533
|
+
|
|
534
|
+
@work(exclusive=True)
|
|
535
|
+
async def _clear_all(self) -> None:
|
|
536
|
+
await self._store.clear_exchanges()
|
|
537
|
+
self._all_exchanges = []
|
|
538
|
+
self._rebuild_table()
|
|
539
|
+
|
|
540
|
+
@work(exclusive=False)
|
|
541
|
+
async def _dispatch_replay(
|
|
542
|
+
self,
|
|
543
|
+
exchange_id: str,
|
|
544
|
+
*,
|
|
545
|
+
headers_override: tuple[tuple[str, str], ...] | None,
|
|
546
|
+
body_override: bytes | None,
|
|
547
|
+
) -> None:
|
|
548
|
+
if self._replay_service is not None:
|
|
549
|
+
try:
|
|
550
|
+
child = await self._replay_service.replay(
|
|
551
|
+
exchange_id,
|
|
552
|
+
headers_override=headers_override,
|
|
553
|
+
body_override=body_override,
|
|
554
|
+
)
|
|
555
|
+
except TruncatedBodyError as exc:
|
|
556
|
+
self.notify(str(exc), severity="warning")
|
|
557
|
+
return
|
|
558
|
+
except (ExchangeNotFoundError, aiohttp.ClientError, TimeoutError, OSError) as exc:
|
|
559
|
+
self.notify(f"Replay failed: {exc}", severity="error")
|
|
560
|
+
return
|
|
561
|
+
self._ingest_live_exchange(child)
|
|
562
|
+
self.notify(f"Replayed -> {child.status}")
|
|
563
|
+
return
|
|
564
|
+
|
|
565
|
+
state = load_daemon_state(self._paths)
|
|
566
|
+
if state is None or not is_process_alive(state.pid):
|
|
567
|
+
self.notify("Daemon not running; cannot replay via control API.", severity="error")
|
|
568
|
+
return
|
|
569
|
+
|
|
570
|
+
payload: dict[str, object] = {}
|
|
571
|
+
if headers_override is not None:
|
|
572
|
+
payload["headers"] = [[k, v] for k, v in headers_override]
|
|
573
|
+
if body_override is not None:
|
|
574
|
+
payload["body"] = body_override.decode("utf-8", errors="replace")
|
|
575
|
+
|
|
576
|
+
try:
|
|
577
|
+
async with (
|
|
578
|
+
aiohttp.ClientSession() as session,
|
|
579
|
+
session.post(
|
|
580
|
+
f"{state.control_url}/_control/replay/{exchange_id}",
|
|
581
|
+
headers={"Authorization": f"Bearer {state.token}"},
|
|
582
|
+
json=payload or None,
|
|
583
|
+
) as resp,
|
|
584
|
+
):
|
|
585
|
+
data: object = await resp.json()
|
|
586
|
+
if resp.status >= 400:
|
|
587
|
+
msg = (
|
|
588
|
+
str(cast(dict[object, object], data).get("message", f"HTTP {resp.status}"))
|
|
589
|
+
if isinstance(data, dict)
|
|
590
|
+
else f"HTTP {resp.status}"
|
|
591
|
+
)
|
|
592
|
+
self.notify(msg, severity="warning")
|
|
593
|
+
return
|
|
594
|
+
if isinstance(data, dict):
|
|
595
|
+
mapping = {str(k): v for k, v in cast(dict[object, object], data).items()}
|
|
596
|
+
child = CapturedExchange.from_event_dict(mapping)
|
|
597
|
+
self._ingest_live_exchange(child)
|
|
598
|
+
self.notify(f"Replayed -> {child.status}")
|
|
599
|
+
except (aiohttp.ClientError, TimeoutError, OSError) as exc:
|
|
600
|
+
self.notify(f"Replay error: {exc}", severity="error")
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
async def run_inspect_tui(
|
|
604
|
+
*,
|
|
605
|
+
domain: str | None = None,
|
|
606
|
+
limit: int = 200,
|
|
607
|
+
paths: DevDoorPaths | None = None,
|
|
608
|
+
) -> None:
|
|
609
|
+
"""Launch standalone ``devdoor inspect`` TUI backed by WAL SQLite and loopback daemon."""
|
|
610
|
+
resolved = paths or resolve_paths()
|
|
611
|
+
bus = TrafficEventBus()
|
|
612
|
+
forwarder = Forwarder(bus)
|
|
613
|
+
router = Router.from_global(load_global_config(resolved))
|
|
614
|
+
async with InspectorStore(paths=resolved) as store:
|
|
615
|
+
replay = ReplayService(store=store, forwarder=forwarder, event_bus=bus, router=router)
|
|
616
|
+
tui = InspectorApp(
|
|
617
|
+
store=store,
|
|
618
|
+
event_bus=None,
|
|
619
|
+
replay_service=replay,
|
|
620
|
+
paths=resolved,
|
|
621
|
+
domain_filter=domain,
|
|
622
|
+
limit=limit,
|
|
623
|
+
)
|
|
624
|
+
try:
|
|
625
|
+
await tui.run_async()
|
|
626
|
+
finally:
|
|
627
|
+
await forwarder.close()
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
async def run_share_tui(
|
|
631
|
+
event_bus: TrafficEventBus,
|
|
632
|
+
stop_callback: Callable[[], None],
|
|
633
|
+
*,
|
|
634
|
+
router: Router | None = None,
|
|
635
|
+
forwarder: Forwarder | None = None,
|
|
636
|
+
paths: DevDoorPaths | None = None,
|
|
637
|
+
tunnel_status: ShareTunnelStatus | None = None,
|
|
638
|
+
on_app_ready: Callable[[InspectorApp], None] | None = None,
|
|
639
|
+
) -> None:
|
|
640
|
+
"""Run ``InspectorApp`` live alongside ``devdoor share --tui``."""
|
|
641
|
+
resolved = paths or resolve_paths()
|
|
642
|
+
owned_forwarder = forwarder is None
|
|
643
|
+
active_forwarder = forwarder or Forwarder(event_bus)
|
|
644
|
+
async with InspectorStore(paths=resolved) as store:
|
|
645
|
+
stop_writer = store.start_bus_writer(event_bus)
|
|
646
|
+
replay = ReplayService(
|
|
647
|
+
store=store,
|
|
648
|
+
forwarder=active_forwarder,
|
|
649
|
+
event_bus=event_bus,
|
|
650
|
+
router=router,
|
|
651
|
+
)
|
|
652
|
+
tui = InspectorApp(
|
|
653
|
+
store=store,
|
|
654
|
+
event_bus=event_bus,
|
|
655
|
+
replay_service=replay,
|
|
656
|
+
paths=resolved,
|
|
657
|
+
tunnel_status=tunnel_status or ShareTunnelStatus(),
|
|
658
|
+
)
|
|
659
|
+
if on_app_ready is not None:
|
|
660
|
+
on_app_ready(tui)
|
|
661
|
+
try:
|
|
662
|
+
await tui.run_async()
|
|
663
|
+
finally:
|
|
664
|
+
await stop_writer()
|
|
665
|
+
if owned_forwarder:
|
|
666
|
+
await active_forwarder.close()
|
|
667
|
+
stop_callback()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Tunnel client authentication, REST API, stream multiplexing, and reconnection."""
|