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/cli/local.py
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
"""Local HTTPS lifecycle CLI commands: start, stop, up, down, list, doctor, uninstall."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import importlib
|
|
8
|
+
import json
|
|
9
|
+
import shutil
|
|
10
|
+
import signal
|
|
11
|
+
import socket
|
|
12
|
+
import sys
|
|
13
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Annotated, cast
|
|
17
|
+
|
|
18
|
+
import aiohttp
|
|
19
|
+
import typer
|
|
20
|
+
from rich.console import Console
|
|
21
|
+
from rich.table import Table
|
|
22
|
+
|
|
23
|
+
from devdoor.cli.validators import parse_cli_log_mode, parse_cli_port, resolve_wait_timeout
|
|
24
|
+
from devdoor.core.config import (
|
|
25
|
+
ConfigError,
|
|
26
|
+
DevDoorPaths,
|
|
27
|
+
GlobalConfig,
|
|
28
|
+
RegisteredService,
|
|
29
|
+
RouteConfig,
|
|
30
|
+
load_global_config,
|
|
31
|
+
load_project_config,
|
|
32
|
+
mutate_global_config,
|
|
33
|
+
resolve_paths,
|
|
34
|
+
validate_domain,
|
|
35
|
+
)
|
|
36
|
+
from devdoor.core.engine import (
|
|
37
|
+
ControlExtender,
|
|
38
|
+
DaemonState,
|
|
39
|
+
DevDoorEngine,
|
|
40
|
+
check_upstream_tcp,
|
|
41
|
+
is_process_alive,
|
|
42
|
+
launch_detached_process,
|
|
43
|
+
load_daemon_state,
|
|
44
|
+
)
|
|
45
|
+
from devdoor.core.events import TrafficEventBus
|
|
46
|
+
from devdoor.core.router import Router
|
|
47
|
+
from devdoor.platform import OSPlatformAdapter, PlatformAdapterError, get_platform_adapter
|
|
48
|
+
from devdoor.proxy.certs import RENEWAL_WINDOW_DAYS, CertManager, read_cert_metadata
|
|
49
|
+
from devdoor.proxy.forwarder import Forwarder, wait_for_upstream
|
|
50
|
+
from devdoor.proxy.https_server import LocalProxyServer
|
|
51
|
+
from devdoor.tunnel.auth_client import resolve_auth_token, resolve_relay_url
|
|
52
|
+
from devdoor.tunnel.httperr import RelayRequestError
|
|
53
|
+
from devdoor.tunnel.relay_api import RelayApiClient
|
|
54
|
+
|
|
55
|
+
DaemonLauncher = Callable[["LocalRuntime"], Awaitable[DaemonState]]
|
|
56
|
+
IngressProbe = Callable[[int, int], Awaitable[bool]]
|
|
57
|
+
PortAvailabilityProbe = Callable[[int, int], Awaitable[None]]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_route_spec(raw: str) -> RouteConfig:
|
|
61
|
+
"""Parse ``/prefix=port`` CLI route argument into a validated ``RouteConfig``."""
|
|
62
|
+
prefix, sep, port_str = raw.partition("=")
|
|
63
|
+
if not sep or not prefix.strip() or not port_str.strip():
|
|
64
|
+
raise typer.BadParameter(f"Expected route format '/prefix=port', got {raw!r}")
|
|
65
|
+
return RouteConfig(path=prefix.strip(), port=parse_cli_port(port_str))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def _default_daemon_launcher(runtime: LocalRuntime) -> DaemonState:
|
|
69
|
+
return await launch_detached_process(
|
|
70
|
+
[sys.executable, "-m", "devdoor.cli.local"],
|
|
71
|
+
paths=runtime.paths,
|
|
72
|
+
log_filename="daemon.log",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
async def _default_ingress_probe(_http_port: int, _https_port: int) -> bool:
|
|
77
|
+
return await check_upstream_tcp(443, timeout=0.3) and await check_upstream_tcp(80, timeout=0.3)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def _default_port_availability_probe(http_port: int, https_port: int) -> None:
|
|
81
|
+
for port in (http_port, https_port):
|
|
82
|
+
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
|
|
83
|
+
try:
|
|
84
|
+
sock.bind(("127.0.0.1", port))
|
|
85
|
+
except OSError as exc:
|
|
86
|
+
raise PlatformAdapterError(
|
|
87
|
+
f"Proxy listener port {port} is already in use ({exc})."
|
|
88
|
+
) from exc
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(slots=True)
|
|
92
|
+
class LocalRuntime:
|
|
93
|
+
"""Injectable runtime dependencies for local HTTPS lifecycle commands."""
|
|
94
|
+
|
|
95
|
+
paths: DevDoorPaths
|
|
96
|
+
adapter: OSPlatformAdapter
|
|
97
|
+
daemon_launcher: DaemonLauncher = _default_daemon_launcher
|
|
98
|
+
ingress_probe: IngressProbe = _default_ingress_probe
|
|
99
|
+
port_availability_probe: PortAvailabilityProbe = _default_port_availability_probe
|
|
100
|
+
cert_manager: CertManager = field(init=False)
|
|
101
|
+
|
|
102
|
+
def __post_init__(self) -> None:
|
|
103
|
+
self.cert_manager = CertManager(paths=self.paths)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def build_local_runtime(*, elevated_windows: bool = False) -> LocalRuntime:
|
|
107
|
+
"""Construct the active ``LocalRuntime`` using the detected host OS adapter."""
|
|
108
|
+
return LocalRuntime(
|
|
109
|
+
paths=resolve_paths(),
|
|
110
|
+
adapter=get_platform_adapter(elevated_windows=elevated_windows),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
async def _control_request(
|
|
115
|
+
state: DaemonState,
|
|
116
|
+
method: str,
|
|
117
|
+
path: str,
|
|
118
|
+
) -> tuple[int, dict[str, object]]:
|
|
119
|
+
timeout = aiohttp.ClientTimeout(total=3.0)
|
|
120
|
+
headers = {"Authorization": f"Bearer {state.token}"}
|
|
121
|
+
async with (
|
|
122
|
+
aiohttp.ClientSession(timeout=timeout) as session,
|
|
123
|
+
session.request(method, f"{state.control_url}{path}", headers=headers) as resp,
|
|
124
|
+
):
|
|
125
|
+
text = await resp.text()
|
|
126
|
+
parsed: object = json.loads(text) if text.strip() else {}
|
|
127
|
+
mapping = cast(dict[object, object], parsed) if isinstance(parsed, dict) else {}
|
|
128
|
+
return resp.status, {str(k): v for k, v in mapping.items()}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
async def _probe_live_daemon(
|
|
132
|
+
paths: DevDoorPaths,
|
|
133
|
+
) -> tuple[DaemonState | None, dict[str, object] | None]:
|
|
134
|
+
state = load_daemon_state(paths)
|
|
135
|
+
if state is None or not is_process_alive(state.pid):
|
|
136
|
+
return None, None
|
|
137
|
+
try:
|
|
138
|
+
status, payload = await _control_request(state, "GET", "/_control/status")
|
|
139
|
+
if status == 200:
|
|
140
|
+
return state, payload
|
|
141
|
+
except aiohttp.ClientError, TimeoutError, OSError:
|
|
142
|
+
return None, None
|
|
143
|
+
return None, None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
async def _request_daemon_shutdown(
|
|
147
|
+
state: DaemonState,
|
|
148
|
+
paths: DevDoorPaths,
|
|
149
|
+
*,
|
|
150
|
+
timeout: float = 2.0,
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Ask the daemon to shut down and wait briefly until its control socket closes."""
|
|
153
|
+
await _control_request(state, "POST", "/_control/shutdown")
|
|
154
|
+
deadline = asyncio.get_running_loop().time() + timeout
|
|
155
|
+
while asyncio.get_running_loop().time() < deadline:
|
|
156
|
+
current = load_daemon_state(paths)
|
|
157
|
+
state_gone = current is None or current.pid != state.pid or current.token != state.token
|
|
158
|
+
try:
|
|
159
|
+
await _control_request(state, "GET", "/_control/status")
|
|
160
|
+
except aiohttp.ClientError, TimeoutError, OSError:
|
|
161
|
+
if state_gone:
|
|
162
|
+
return
|
|
163
|
+
await asyncio.sleep(0.02)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
async def run_local_daemon(*, paths: DevDoorPaths | None = None) -> None:
|
|
167
|
+
"""Run the unprivileged local HTTPS reverse proxy and loopback control plane."""
|
|
168
|
+
resolved = paths or resolve_paths()
|
|
169
|
+
config = load_global_config(resolved)
|
|
170
|
+
router = Router.from_global(config)
|
|
171
|
+
event_bus = TrafficEventBus()
|
|
172
|
+
forwarder = Forwarder(event_bus)
|
|
173
|
+
cert_manager = CertManager(paths=resolved)
|
|
174
|
+
|
|
175
|
+
adapter = get_platform_adapter()
|
|
176
|
+
redirect_with_port = (
|
|
177
|
+
config.default_tld == ".localhost"
|
|
178
|
+
or adapter.default_tld == ".localhost"
|
|
179
|
+
or not adapter.is_port_forwarding_active()
|
|
180
|
+
)
|
|
181
|
+
proxy_server = LocalProxyServer(
|
|
182
|
+
router=router,
|
|
183
|
+
forwarder=forwarder,
|
|
184
|
+
cert_manager=cert_manager,
|
|
185
|
+
http_port=config.http_port,
|
|
186
|
+
https_port=config.https_port,
|
|
187
|
+
redirect_include_port=redirect_with_port,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
extender: ControlExtender | None = None
|
|
191
|
+
inspector_cleanup: Callable[[], Awaitable[None]] | None = None
|
|
192
|
+
try:
|
|
193
|
+
bridge = importlib.import_module("devdoor.inspector.daemon_hook")
|
|
194
|
+
attach_fn = getattr(bridge, "attach_inspector_to_engine", None)
|
|
195
|
+
if callable(attach_fn):
|
|
196
|
+
extender, inspector_cleanup = cast(
|
|
197
|
+
tuple[ControlExtender, Callable[[], Awaitable[None]]],
|
|
198
|
+
attach_fn(resolved, event_bus, router, forwarder),
|
|
199
|
+
)
|
|
200
|
+
except ModuleNotFoundError:
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
async def _shutdown_hook() -> None:
|
|
204
|
+
await proxy_server.stop()
|
|
205
|
+
if inspector_cleanup is not None:
|
|
206
|
+
await inspector_cleanup()
|
|
207
|
+
|
|
208
|
+
await proxy_server.start()
|
|
209
|
+
engine = DevDoorEngine(
|
|
210
|
+
paths=resolved,
|
|
211
|
+
router=router,
|
|
212
|
+
event_bus=event_bus,
|
|
213
|
+
forwarder=forwarder,
|
|
214
|
+
reload_callback=proxy_server.handle_reload,
|
|
215
|
+
shutdown_callback=_shutdown_hook,
|
|
216
|
+
control_app_extender=extender,
|
|
217
|
+
)
|
|
218
|
+
loop = asyncio.get_running_loop()
|
|
219
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
220
|
+
with contextlib.suppress(NotImplementedError, RuntimeError):
|
|
221
|
+
loop.add_signal_handler(sig, lambda: asyncio.create_task(engine.stop()))
|
|
222
|
+
|
|
223
|
+
try:
|
|
224
|
+
await engine.start()
|
|
225
|
+
await engine.wait_closed()
|
|
226
|
+
finally:
|
|
227
|
+
await engine.stop()
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _effective_tld(cfg: GlobalConfig, adapter: OSPlatformAdapter) -> str:
|
|
231
|
+
return cfg.default_tld or adapter.default_tld
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _ensure_os_environment(runtime: LocalRuntime, cfg: GlobalConfig) -> None:
|
|
235
|
+
ca_cert_path, _ = runtime.cert_manager.ensure_root_ca()
|
|
236
|
+
if not runtime.adapter.is_ca_trusted(str(ca_cert_path)):
|
|
237
|
+
runtime.adapter.trust_ca(str(ca_cert_path))
|
|
238
|
+
if (
|
|
239
|
+
_effective_tld(cfg, runtime.adapter) != ".localhost"
|
|
240
|
+
and not runtime.adapter.is_port_forwarding_active()
|
|
241
|
+
):
|
|
242
|
+
runtime.adapter.enable_port_forwarding(cfg.http_port, cfg.https_port)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _all_service_ports(entries: Iterable[RegisteredService]) -> list[int]:
|
|
246
|
+
ports: set[int] = set()
|
|
247
|
+
for entry in entries:
|
|
248
|
+
ports.add(entry.port)
|
|
249
|
+
for route in entry.routes:
|
|
250
|
+
ports.add(route.port)
|
|
251
|
+
return sorted(ports)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
async def _ensure_port_forwarding_healthy(runtime: LocalRuntime, cfg: GlobalConfig) -> bool:
|
|
255
|
+
if _effective_tld(cfg, runtime.adapter) == ".localhost":
|
|
256
|
+
return True
|
|
257
|
+
fwd_active = runtime.adapter.is_port_forwarding_active()
|
|
258
|
+
probe_ok = await runtime.ingress_probe(cfg.http_port, cfg.https_port)
|
|
259
|
+
if fwd_active and probe_ok:
|
|
260
|
+
return True
|
|
261
|
+
with contextlib.suppress(PlatformAdapterError):
|
|
262
|
+
runtime.adapter.enable_port_forwarding(cfg.http_port, cfg.https_port)
|
|
263
|
+
return runtime.adapter.is_port_forwarding_active() and (
|
|
264
|
+
await runtime.ingress_probe(cfg.http_port, cfg.https_port)
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
async def _rollback_entries(
|
|
269
|
+
runtime: LocalRuntime,
|
|
270
|
+
*,
|
|
271
|
+
previous_domains: dict[str, RegisteredService],
|
|
272
|
+
applied_domains: tuple[str, ...],
|
|
273
|
+
had_live_daemon: bool,
|
|
274
|
+
) -> None:
|
|
275
|
+
def _restore(cfg: GlobalConfig) -> GlobalConfig:
|
|
276
|
+
restored = dict(cfg.domains)
|
|
277
|
+
for domain in applied_domains:
|
|
278
|
+
if domain in previous_domains:
|
|
279
|
+
restored[domain] = previous_domains[domain]
|
|
280
|
+
else:
|
|
281
|
+
restored.pop(domain, None)
|
|
282
|
+
return cfg.model_copy(update={"domains": restored})
|
|
283
|
+
|
|
284
|
+
updated = mutate_global_config(_restore, paths=runtime.paths)
|
|
285
|
+
for domain in applied_domains:
|
|
286
|
+
if domain not in previous_domains and not domain.endswith(".localhost"):
|
|
287
|
+
with contextlib.suppress(PlatformAdapterError):
|
|
288
|
+
runtime.adapter.remove_host(domain)
|
|
289
|
+
|
|
290
|
+
live_state, _ = await _probe_live_daemon(runtime.paths)
|
|
291
|
+
if live_state is None:
|
|
292
|
+
return
|
|
293
|
+
with contextlib.suppress(aiohttp.ClientError, TimeoutError, OSError):
|
|
294
|
+
if not had_live_daemon and not updated.domains:
|
|
295
|
+
await _request_daemon_shutdown(live_state, runtime.paths)
|
|
296
|
+
else:
|
|
297
|
+
await _control_request(live_state, "POST", "/_control/reload")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
async def _register_and_apply_services(
|
|
301
|
+
runtime: LocalRuntime,
|
|
302
|
+
entries: list[RegisteredService],
|
|
303
|
+
*,
|
|
304
|
+
wait: bool,
|
|
305
|
+
wait_timeout: float,
|
|
306
|
+
) -> tuple[DaemonState, GlobalConfig]:
|
|
307
|
+
initial_cfg = load_global_config(runtime.paths)
|
|
308
|
+
live_state, _ = await _probe_live_daemon(runtime.paths)
|
|
309
|
+
had_live_daemon = live_state is not None
|
|
310
|
+
if not had_live_daemon:
|
|
311
|
+
await runtime.port_availability_probe(initial_cfg.http_port, initial_cfg.https_port)
|
|
312
|
+
|
|
313
|
+
_ensure_os_environment(runtime, initial_cfg)
|
|
314
|
+
|
|
315
|
+
previous_domains = dict(initial_cfg.domains)
|
|
316
|
+
applied_domains = tuple(entry.domain for entry in entries)
|
|
317
|
+
|
|
318
|
+
def _apply(cfg: GlobalConfig) -> GlobalConfig:
|
|
319
|
+
updated_domains = dict(cfg.domains)
|
|
320
|
+
for entry in entries:
|
|
321
|
+
updated_domains[entry.domain] = entry
|
|
322
|
+
return cfg.model_copy(update={"domains": updated_domains})
|
|
323
|
+
|
|
324
|
+
updated_cfg = mutate_global_config(_apply, paths=runtime.paths)
|
|
325
|
+
for entry in entries:
|
|
326
|
+
runtime.cert_manager.ensure_leaf_cert(entry.domain)
|
|
327
|
+
if not entry.domain.endswith(".localhost"):
|
|
328
|
+
runtime.adapter.add_host(entry.domain)
|
|
329
|
+
|
|
330
|
+
if live_state is not None:
|
|
331
|
+
await _control_request(live_state, "POST", "/_control/reload")
|
|
332
|
+
state = live_state
|
|
333
|
+
else:
|
|
334
|
+
state = await runtime.daemon_launcher(runtime)
|
|
335
|
+
|
|
336
|
+
if _effective_tld(updated_cfg, runtime.adapter) != ".localhost":
|
|
337
|
+
await _ensure_port_forwarding_healthy(runtime, updated_cfg)
|
|
338
|
+
|
|
339
|
+
if wait:
|
|
340
|
+
ports = _all_service_ports(entries)
|
|
341
|
+
try:
|
|
342
|
+
await asyncio.gather(*(wait_for_upstream(port, timeout=wait_timeout) for port in ports))
|
|
343
|
+
except BaseException:
|
|
344
|
+
await _rollback_entries(
|
|
345
|
+
runtime,
|
|
346
|
+
previous_domains=previous_domains,
|
|
347
|
+
applied_domains=applied_domains,
|
|
348
|
+
had_live_daemon=had_live_daemon,
|
|
349
|
+
)
|
|
350
|
+
raise
|
|
351
|
+
|
|
352
|
+
return state, updated_cfg
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
async def _unregister_domains(runtime: LocalRuntime, domains: Iterable[str]) -> bool:
|
|
356
|
+
to_remove = set(domains)
|
|
357
|
+
|
|
358
|
+
def _apply(cfg: GlobalConfig) -> GlobalConfig:
|
|
359
|
+
remaining = {k: v for k, v in cfg.domains.items() if k not in to_remove}
|
|
360
|
+
return cfg.model_copy(update={"domains": remaining})
|
|
361
|
+
|
|
362
|
+
updated = mutate_global_config(_apply, paths=runtime.paths)
|
|
363
|
+
for domain in sorted(to_remove):
|
|
364
|
+
if not domain.endswith(".localhost"):
|
|
365
|
+
runtime.adapter.remove_host(domain)
|
|
366
|
+
|
|
367
|
+
live_state, _ = await _probe_live_daemon(runtime.paths)
|
|
368
|
+
if live_state is None:
|
|
369
|
+
return False
|
|
370
|
+
|
|
371
|
+
if updated.domains:
|
|
372
|
+
await _control_request(live_state, "POST", "/_control/reload")
|
|
373
|
+
return True
|
|
374
|
+
|
|
375
|
+
await _request_daemon_shutdown(live_state, runtime.paths)
|
|
376
|
+
return False
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _domain_url(domain: str, cfg: GlobalConfig, adapter: OSPlatformAdapter) -> str:
|
|
380
|
+
needs_port = domain.endswith(".localhost") or (
|
|
381
|
+
adapter.default_tld == ".localhost" and not adapter.is_port_forwarding_active()
|
|
382
|
+
)
|
|
383
|
+
return f"https://{domain}:{cfg.https_port}" if needs_port else f"https://{domain}"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def start_command(
|
|
387
|
+
name: Annotated[
|
|
388
|
+
str, typer.Argument(help="Domain name or bare label (e.g. myapp or myapp.test).")
|
|
389
|
+
],
|
|
390
|
+
port: Annotated[int, typer.Option("--port", "-p", help="Local upstream TCP port.")],
|
|
391
|
+
route: Annotated[
|
|
392
|
+
list[str] | None,
|
|
393
|
+
typer.Option("--route", "-r", help="Additional path route '/api=8080'."),
|
|
394
|
+
] = None,
|
|
395
|
+
cors: Annotated[
|
|
396
|
+
bool, typer.Option("--cors", help="Inject permissive dev CORS headers.")
|
|
397
|
+
] = False,
|
|
398
|
+
log_mode: Annotated[
|
|
399
|
+
str | None,
|
|
400
|
+
typer.Option("--log-mode", help="Logging detail (full, minimal, off)."),
|
|
401
|
+
] = None,
|
|
402
|
+
wait: Annotated[
|
|
403
|
+
bool,
|
|
404
|
+
typer.Option("--wait", "-w", help="Wait for upstream ports before completing."),
|
|
405
|
+
] = False,
|
|
406
|
+
timeout: Annotated[
|
|
407
|
+
str | None,
|
|
408
|
+
typer.Option("--timeout", help="Upstream wait timeout (requires --wait), e.g. 30s."),
|
|
409
|
+
] = None,
|
|
410
|
+
) -> None:
|
|
411
|
+
"""Expose a local port on a trusted local HTTPS domain."""
|
|
412
|
+
wait_seconds = resolve_wait_timeout(wait, timeout)
|
|
413
|
+
if not (1 <= port <= 65535):
|
|
414
|
+
typer.secho(f"Port must be 1..65535, got {port}.", fg=typer.colors.RED, err=True)
|
|
415
|
+
raise typer.Exit(code=1)
|
|
416
|
+
|
|
417
|
+
parsed_routes = [parse_route_spec(item) for item in (route or ())]
|
|
418
|
+
parsed_log = parse_cli_log_mode(log_mode) if log_mode is not None else None
|
|
419
|
+
|
|
420
|
+
runtime = build_local_runtime()
|
|
421
|
+
cfg = load_global_config(runtime.paths)
|
|
422
|
+
default_tld = _effective_tld(cfg, runtime.adapter)
|
|
423
|
+
|
|
424
|
+
try:
|
|
425
|
+
validated = validate_domain(name, default_tld=default_tld)
|
|
426
|
+
for warning in validated.warnings:
|
|
427
|
+
typer.secho(f"Warning: {warning}", fg=typer.colors.YELLOW, err=True)
|
|
428
|
+
entry = RegisteredService(
|
|
429
|
+
domain=validated.domain,
|
|
430
|
+
port=port,
|
|
431
|
+
routes=parsed_routes,
|
|
432
|
+
cors=cors or None,
|
|
433
|
+
log_mode=parsed_log,
|
|
434
|
+
)
|
|
435
|
+
_, updated_cfg = asyncio.run(
|
|
436
|
+
_register_and_apply_services(
|
|
437
|
+
runtime,
|
|
438
|
+
[entry],
|
|
439
|
+
wait=wait,
|
|
440
|
+
wait_timeout=wait_seconds,
|
|
441
|
+
)
|
|
442
|
+
)
|
|
443
|
+
except (
|
|
444
|
+
ConfigError,
|
|
445
|
+
PlatformAdapterError,
|
|
446
|
+
TimeoutError,
|
|
447
|
+
aiohttp.ClientError,
|
|
448
|
+
ValueError,
|
|
449
|
+
) as exc:
|
|
450
|
+
typer.secho(f"Failed to start {name}: {exc}", fg=typer.colors.RED, err=True)
|
|
451
|
+
raise typer.Exit(code=1) from exc
|
|
452
|
+
|
|
453
|
+
serving_url = _domain_url(entry.domain, updated_cfg, runtime.adapter)
|
|
454
|
+
typer.echo(f"Serving {serving_url} -> 127.0.0.1:{entry.port}")
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def stop_command(
|
|
458
|
+
name: Annotated[
|
|
459
|
+
str | None,
|
|
460
|
+
typer.Argument(help="Domain name to stop (omit to stop all local domains and daemon)."),
|
|
461
|
+
] = None,
|
|
462
|
+
) -> None:
|
|
463
|
+
"""Stop one local HTTPS domain or all local domains and shut down the proxy daemon."""
|
|
464
|
+
runtime = build_local_runtime()
|
|
465
|
+
cfg = load_global_config(runtime.paths)
|
|
466
|
+
if name is None:
|
|
467
|
+
all_domains = tuple(cfg.domains.keys())
|
|
468
|
+
asyncio.run(_unregister_domains(runtime, all_domains))
|
|
469
|
+
typer.echo("Stopped all local domains and shut down DevDoor proxy.")
|
|
470
|
+
return
|
|
471
|
+
|
|
472
|
+
default_tld = _effective_tld(cfg, runtime.adapter)
|
|
473
|
+
try:
|
|
474
|
+
target = validate_domain(name, default_tld=default_tld).domain
|
|
475
|
+
except ConfigError as exc:
|
|
476
|
+
typer.secho(f"Invalid domain: {exc}", fg=typer.colors.RED, err=True)
|
|
477
|
+
raise typer.Exit(code=1) from exc
|
|
478
|
+
|
|
479
|
+
if target not in cfg.domains:
|
|
480
|
+
typer.secho(f"Domain {target!r} is not currently registered.", fg=typer.colors.YELLOW)
|
|
481
|
+
return
|
|
482
|
+
|
|
483
|
+
asyncio.run(_unregister_domains(runtime, (target,)))
|
|
484
|
+
typer.echo(f"Stopped {target}.")
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def up_command(
|
|
488
|
+
config: Annotated[
|
|
489
|
+
Path | None,
|
|
490
|
+
typer.Option("--config", "-c", help="Path to devdoor.yaml / .devdoor.yaml."),
|
|
491
|
+
] = None,
|
|
492
|
+
wait: Annotated[
|
|
493
|
+
bool,
|
|
494
|
+
typer.Option("--wait", "-w", help="Wait for all configured upstream ports."),
|
|
495
|
+
] = False,
|
|
496
|
+
timeout: Annotated[
|
|
497
|
+
str | None,
|
|
498
|
+
typer.Option("--timeout", help="Upstream wait timeout (requires --wait), e.g. 30s."),
|
|
499
|
+
] = None,
|
|
500
|
+
) -> None:
|
|
501
|
+
"""Start all local HTTPS services defined in ``devdoor.yaml``."""
|
|
502
|
+
wait_seconds = resolve_wait_timeout(wait, timeout)
|
|
503
|
+
|
|
504
|
+
runtime = build_local_runtime()
|
|
505
|
+
cfg = load_global_config(runtime.paths)
|
|
506
|
+
default_tld = _effective_tld(cfg, runtime.adapter)
|
|
507
|
+
|
|
508
|
+
try:
|
|
509
|
+
loaded = load_project_config(config_path=config, default_tld=default_tld)
|
|
510
|
+
for warning in loaded.warnings:
|
|
511
|
+
typer.secho(f"Warning: {warning}", fg=typer.colors.YELLOW, err=True)
|
|
512
|
+
|
|
513
|
+
entries = [
|
|
514
|
+
RegisteredService(
|
|
515
|
+
name=svc.name,
|
|
516
|
+
domain=svc.domain,
|
|
517
|
+
port=svc.port,
|
|
518
|
+
routes=svc.routes,
|
|
519
|
+
cors=svc.cors if svc.cors is not None else loaded.project.cors,
|
|
520
|
+
log_mode=svc.log_mode or loaded.project.log_mode,
|
|
521
|
+
project_dir=str(loaded.config_path.parent),
|
|
522
|
+
)
|
|
523
|
+
for svc in loaded.project.services
|
|
524
|
+
]
|
|
525
|
+
_, updated_cfg = asyncio.run(
|
|
526
|
+
_register_and_apply_services(
|
|
527
|
+
runtime,
|
|
528
|
+
entries,
|
|
529
|
+
wait=wait,
|
|
530
|
+
wait_timeout=wait_seconds,
|
|
531
|
+
)
|
|
532
|
+
)
|
|
533
|
+
except (ConfigError, PlatformAdapterError, TimeoutError, aiohttp.ClientError) as exc:
|
|
534
|
+
typer.secho(f"Failed to start project services: {exc}", fg=typer.colors.RED, err=True)
|
|
535
|
+
raise typer.Exit(code=1) from exc
|
|
536
|
+
|
|
537
|
+
for entry in entries:
|
|
538
|
+
typer.echo(
|
|
539
|
+
f"Serving {_domain_url(entry.domain, updated_cfg, runtime.adapter)} "
|
|
540
|
+
f"-> 127.0.0.1:{entry.port}"
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def down_command(
|
|
545
|
+
config: Annotated[
|
|
546
|
+
Path | None,
|
|
547
|
+
typer.Option("--config", "-c", help="Path to devdoor.yaml / .devdoor.yaml."),
|
|
548
|
+
] = None,
|
|
549
|
+
) -> None:
|
|
550
|
+
"""Stop only the services declared in the current project's ``devdoor.yaml``."""
|
|
551
|
+
runtime = build_local_runtime()
|
|
552
|
+
cfg = load_global_config(runtime.paths)
|
|
553
|
+
default_tld = _effective_tld(cfg, runtime.adapter)
|
|
554
|
+
try:
|
|
555
|
+
loaded = load_project_config(config_path=config, default_tld=default_tld)
|
|
556
|
+
except ConfigError as exc:
|
|
557
|
+
typer.secho(f"Failed to read project config: {exc}", fg=typer.colors.RED, err=True)
|
|
558
|
+
raise typer.Exit(code=1) from exc
|
|
559
|
+
|
|
560
|
+
domains = [svc.domain for svc in loaded.project.services]
|
|
561
|
+
asyncio.run(_unregister_domains(runtime, domains))
|
|
562
|
+
typer.echo(f"Stopped project domains: {', '.join(domains)}")
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def list_command(
|
|
566
|
+
json_output: Annotated[
|
|
567
|
+
bool,
|
|
568
|
+
typer.Option("--json", help="Print active local domains and public tunnels as JSON."),
|
|
569
|
+
] = False,
|
|
570
|
+
) -> None:
|
|
571
|
+
"""List local HTTPS domains and active public tunnels."""
|
|
572
|
+
runtime = build_local_runtime()
|
|
573
|
+
cfg = load_global_config(runtime.paths)
|
|
574
|
+
|
|
575
|
+
async def _collect() -> dict[str, object]:
|
|
576
|
+
live_state, status_payload = await _probe_live_daemon(runtime.paths)
|
|
577
|
+
daemon_running = live_state is not None
|
|
578
|
+
|
|
579
|
+
ingress_healthy = True
|
|
580
|
+
if daemon_running:
|
|
581
|
+
ingress_healthy = await _ensure_port_forwarding_healthy(runtime, cfg)
|
|
582
|
+
|
|
583
|
+
health_by_domain: dict[str, bool] = {}
|
|
584
|
+
if status_payload and isinstance(status_payload.get("domains"), list):
|
|
585
|
+
for raw_item in cast(list[object], status_payload["domains"]):
|
|
586
|
+
if isinstance(raw_item, dict):
|
|
587
|
+
item = cast(dict[object, object], raw_item)
|
|
588
|
+
dom = item.get("domain")
|
|
589
|
+
healthy = item.get("healthy")
|
|
590
|
+
if isinstance(dom, str) and isinstance(healthy, bool):
|
|
591
|
+
health_by_domain[dom] = healthy
|
|
592
|
+
|
|
593
|
+
local_items: list[dict[str, object]] = []
|
|
594
|
+
for dom, entry in sorted(cfg.domains.items()):
|
|
595
|
+
url = _domain_url(dom, cfg, runtime.adapter)
|
|
596
|
+
if not daemon_running:
|
|
597
|
+
status_text = "daemon stopped"
|
|
598
|
+
elif not ingress_healthy:
|
|
599
|
+
status_text = "● ingress down"
|
|
600
|
+
elif health_by_domain.get(dom, False):
|
|
601
|
+
status_text = "● healthy"
|
|
602
|
+
else:
|
|
603
|
+
status_text = "○ upstream unreachable"
|
|
604
|
+
local_items.append(
|
|
605
|
+
{
|
|
606
|
+
"domain": dom,
|
|
607
|
+
"url": url,
|
|
608
|
+
"port": entry.port,
|
|
609
|
+
"routes": [r.model_dump() for r in entry.routes],
|
|
610
|
+
"status": status_text,
|
|
611
|
+
}
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
tunnels: list[dict[str, object]] = []
|
|
615
|
+
token = resolve_auth_token(paths=runtime.paths)
|
|
616
|
+
if token:
|
|
617
|
+
relay_url = resolve_relay_url(paths=runtime.paths)
|
|
618
|
+
with contextlib.suppress(RelayRequestError, ValueError):
|
|
619
|
+
async with RelayApiClient(relay_url=relay_url, token=token) as api:
|
|
620
|
+
tunnels = [t.model_dump() for t in await api.list_active_tunnels()]
|
|
621
|
+
|
|
622
|
+
return {
|
|
623
|
+
"daemon_running": daemon_running,
|
|
624
|
+
"ingress_healthy": ingress_healthy,
|
|
625
|
+
"local": local_items,
|
|
626
|
+
"tunnels": tunnels,
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
result = asyncio.run(_collect())
|
|
630
|
+
if json_output:
|
|
631
|
+
typer.echo(json.dumps(result, indent=2))
|
|
632
|
+
return
|
|
633
|
+
|
|
634
|
+
local_rows = cast(list[dict[str, object]], result["local"])
|
|
635
|
+
tunnel_rows = cast(list[dict[str, object]], result["tunnels"])
|
|
636
|
+
|
|
637
|
+
local_table = Table(title="Local Domains")
|
|
638
|
+
local_table.add_column("Domain", style="cyan")
|
|
639
|
+
local_table.add_column("Target")
|
|
640
|
+
local_table.add_column("Status")
|
|
641
|
+
for item in local_rows:
|
|
642
|
+
local_table.add_row(str(item["url"]), f"127.0.0.1:{item['port']}", str(item["status"]))
|
|
643
|
+
|
|
644
|
+
console = Console()
|
|
645
|
+
console.print(local_table)
|
|
646
|
+
|
|
647
|
+
if tunnel_rows:
|
|
648
|
+
tun_table = Table(title="Active Public Tunnels")
|
|
649
|
+
tun_table.add_column("Subdomain", style="green")
|
|
650
|
+
tun_table.add_column("URL")
|
|
651
|
+
for tun in tunnel_rows:
|
|
652
|
+
tun_table.add_row(str(tun["subdomain"]), str(tun["url"]))
|
|
653
|
+
console.print(tun_table)
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def doctor_command(
|
|
657
|
+
json_output: Annotated[
|
|
658
|
+
bool,
|
|
659
|
+
typer.Option("--json", help="Print diagnostic checks as JSON."),
|
|
660
|
+
] = False,
|
|
661
|
+
) -> None:
|
|
662
|
+
"""Inspect Root CA health, OS trust, port forwarding, hosts entries, and daemon state."""
|
|
663
|
+
runtime = build_local_runtime()
|
|
664
|
+
cfg = load_global_config(runtime.paths)
|
|
665
|
+
checks: list[dict[str, str]] = []
|
|
666
|
+
|
|
667
|
+
def _add(name: str, status: str, detail: str) -> None:
|
|
668
|
+
checks.append({"name": name, "status": status, "detail": detail})
|
|
669
|
+
|
|
670
|
+
# 1. Root CA health + <30d expiry
|
|
671
|
+
ca_cert = runtime.cert_manager.root_ca_cert_path
|
|
672
|
+
if not ca_cert.is_file():
|
|
673
|
+
_add("root-ca", "fail", f"Missing Root CA at {ca_cert}")
|
|
674
|
+
trusted = False
|
|
675
|
+
else:
|
|
676
|
+
meta = read_cert_metadata(ca_cert)
|
|
677
|
+
if meta.remaining_days <= 0:
|
|
678
|
+
_add("root-ca", "fail", "Root CA has expired.")
|
|
679
|
+
elif meta.remaining_days < RENEWAL_WINDOW_DAYS:
|
|
680
|
+
_add("root-ca", "warn", f"Root CA expires in {meta.remaining_days:.0f} days.")
|
|
681
|
+
else:
|
|
682
|
+
_add("root-ca", "ok", f"Valid ({meta.remaining_days:.0f} days left)")
|
|
683
|
+
trusted = runtime.adapter.is_ca_trusted(str(ca_cert))
|
|
684
|
+
|
|
685
|
+
_add(
|
|
686
|
+
"ca-trust",
|
|
687
|
+
"ok" if trusted else "fail",
|
|
688
|
+
"Trusted by OS store" if trusted else "Root CA is not trusted in OS store",
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
# 2. Port forwarding
|
|
692
|
+
if _effective_tld(cfg, runtime.adapter) == ".localhost":
|
|
693
|
+
_add("port-forwarding", "ok", "Zero-admin .localhost mode active")
|
|
694
|
+
else:
|
|
695
|
+
pf_ok = runtime.adapter.is_port_forwarding_active()
|
|
696
|
+
_add(
|
|
697
|
+
"port-forwarding",
|
|
698
|
+
"ok" if pf_ok else "fail",
|
|
699
|
+
"Ports 80/443 redirected cleanly" if pf_ok else "Port forwarding rules inactive",
|
|
700
|
+
)
|
|
701
|
+
|
|
702
|
+
# 3. Hosts entries
|
|
703
|
+
managed_hosts = set(runtime.adapter.list_hosts())
|
|
704
|
+
missing_hosts = [
|
|
705
|
+
d for d in sorted(cfg.domains) if not d.endswith(".localhost") and d not in managed_hosts
|
|
706
|
+
]
|
|
707
|
+
if missing_hosts:
|
|
708
|
+
_add("hosts", "fail", f"Missing hosts entries: {', '.join(missing_hosts)}")
|
|
709
|
+
else:
|
|
710
|
+
_add("hosts", "ok", f"{len(managed_hosts)} managed host entry/entries")
|
|
711
|
+
|
|
712
|
+
# 4. Daemon status
|
|
713
|
+
live_state, _ = asyncio.run(_probe_live_daemon(runtime.paths))
|
|
714
|
+
_add(
|
|
715
|
+
"daemon",
|
|
716
|
+
"ok" if live_state is not None else "warn",
|
|
717
|
+
f"Running (pid {live_state.pid})" if live_state is not None else "Proxy daemon not running",
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
# 5. Per-domain leaf cert expiry
|
|
721
|
+
for domain in sorted(cfg.domains):
|
|
722
|
+
leaf_path = runtime.cert_manager.leaf_cert_path(domain)
|
|
723
|
+
if not leaf_path.is_file():
|
|
724
|
+
_add(f"leaf:{domain}", "fail", "Leaf certificate missing")
|
|
725
|
+
continue
|
|
726
|
+
leaf_meta = read_cert_metadata(leaf_path)
|
|
727
|
+
if leaf_meta.remaining_days <= 0:
|
|
728
|
+
_add(f"leaf:{domain}", "fail", "Leaf certificate expired")
|
|
729
|
+
elif leaf_meta.remaining_days < RENEWAL_WINDOW_DAYS:
|
|
730
|
+
_add(
|
|
731
|
+
f"leaf:{domain}",
|
|
732
|
+
"warn",
|
|
733
|
+
f"Leaf certificate expires in {leaf_meta.remaining_days:.0f} days",
|
|
734
|
+
)
|
|
735
|
+
else:
|
|
736
|
+
_add(f"leaf:{domain}", "ok", f"Valid ({leaf_meta.remaining_days:.0f} days left)")
|
|
737
|
+
|
|
738
|
+
has_failures = any(item["status"] == "fail" for item in checks)
|
|
739
|
+
if json_output:
|
|
740
|
+
typer.echo(json.dumps({"ok": not has_failures, "checks": checks}, indent=2))
|
|
741
|
+
else:
|
|
742
|
+
table = Table(title="DevDoor Doctor")
|
|
743
|
+
table.add_column("Check", style="cyan")
|
|
744
|
+
table.add_column("Status")
|
|
745
|
+
table.add_column("Details")
|
|
746
|
+
for item in checks:
|
|
747
|
+
table.add_row(item["name"], item["status"].upper(), item["detail"])
|
|
748
|
+
Console().print(table)
|
|
749
|
+
|
|
750
|
+
if has_failures:
|
|
751
|
+
raise typer.Exit(code=1)
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def uninstall_command(
|
|
755
|
+
yes: Annotated[
|
|
756
|
+
bool,
|
|
757
|
+
typer.Option("--yes", "-y", help="Skip confirmation prompt."),
|
|
758
|
+
] = False,
|
|
759
|
+
) -> None:
|
|
760
|
+
"""Shut down daemon, remove OS trust/hosts/port rules, and delete ``~/.devdoor`` state."""
|
|
761
|
+
if not yes and not typer.confirm(
|
|
762
|
+
"Remove DevDoor Root CA trust, hosts entries, firewall rules, and ~/.devdoor runtime files?"
|
|
763
|
+
):
|
|
764
|
+
raise typer.Exit(code=1)
|
|
765
|
+
|
|
766
|
+
runtime = build_local_runtime()
|
|
767
|
+
|
|
768
|
+
async def _stop_daemon() -> None:
|
|
769
|
+
live_state, _ = await _probe_live_daemon(runtime.paths)
|
|
770
|
+
if live_state is not None:
|
|
771
|
+
with contextlib.suppress(aiohttp.ClientError, TimeoutError, OSError):
|
|
772
|
+
await _request_daemon_shutdown(live_state, runtime.paths)
|
|
773
|
+
|
|
774
|
+
asyncio.run(_stop_daemon())
|
|
775
|
+
runtime.adapter.disable_port_forwarding()
|
|
776
|
+
runtime.adapter.remove_all_hosts()
|
|
777
|
+
runtime.adapter.untrust_ca(str(runtime.cert_manager.root_ca_cert_path))
|
|
778
|
+
|
|
779
|
+
if runtime.paths.home.exists():
|
|
780
|
+
shutil.rmtree(runtime.paths.home)
|
|
781
|
+
typer.echo("Uninstalled DevDoor OS configuration and removed runtime directory.")
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def daemon_entrypoint() -> None:
|
|
785
|
+
"""Entrypoint executed by background daemon child processes."""
|
|
786
|
+
asyncio.run(run_local_daemon())
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
if __name__ == "__main__":
|
|
790
|
+
daemon_entrypoint()
|