neruton 0.2.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.
- neruton/__init__.py +107 -0
- neruton/__main__.py +10 -0
- neruton/_version.py +11 -0
- neruton/cli.py +258 -0
- neruton/client.py +1017 -0
- neruton/config.py +188 -0
- neruton/errors.py +64 -0
- neruton/forwarder.py +810 -0
- neruton/protocol.py +358 -0
- neruton/py.typed +0 -0
- neruton/ui.py +127 -0
- neruton/yamux.py +974 -0
- neruton-0.2.0.dist-info/METADATA +136 -0
- neruton-0.2.0.dist-info/RECORD +18 -0
- neruton-0.2.0.dist-info/WHEEL +5 -0
- neruton-0.2.0.dist-info/entry_points.txt +2 -0
- neruton-0.2.0.dist-info/licenses/LICENSE +21 -0
- neruton-0.2.0.dist-info/top_level.txt +1 -0
neruton/protocol.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""Neruton wire-protocol helpers: prefix validation, URL normalization, and control frames."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import platform
|
|
7
|
+
import re
|
|
8
|
+
import uuid
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, Dict, Optional, Sequence, Tuple, Union
|
|
11
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
12
|
+
|
|
13
|
+
from ._version import TUNNEL_WS_PATH, __version__
|
|
14
|
+
from .errors import PrefixError
|
|
15
|
+
|
|
16
|
+
# Reserved subdomain labels matching `crates/neruton-proto/src/prefix.rs`.
|
|
17
|
+
RESERVED_PREFIXES: Tuple[str, ...] = (
|
|
18
|
+
"neruton",
|
|
19
|
+
"www",
|
|
20
|
+
"api",
|
|
21
|
+
"admin",
|
|
22
|
+
"_neruton",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
_DNS_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
|
|
26
|
+
|
|
27
|
+
_NON_RETRYABLE_PATTERNS: Tuple[str, ...] = (
|
|
28
|
+
"not permitted",
|
|
29
|
+
"restricted to specific prefixes",
|
|
30
|
+
"is reserved",
|
|
31
|
+
"must match dns label",
|
|
32
|
+
"tunnel limit reached",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def generate_uuid_prefix() -> str:
|
|
37
|
+
"""Generate a fresh lowercase UUID v4 string suitable as a DNS subdomain label."""
|
|
38
|
+
return str(uuid.uuid4())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def validate_prefix_format(raw: str) -> str:
|
|
42
|
+
"""Normalize (trim & ASCII lowercase) and validate DNS label syntax."""
|
|
43
|
+
normalized = raw.strip().lower()
|
|
44
|
+
if not normalized:
|
|
45
|
+
raise PrefixError("prefix cannot be empty", code="empty")
|
|
46
|
+
if len(normalized) > 63:
|
|
47
|
+
raise PrefixError(
|
|
48
|
+
f"prefix must be 1..=63 characters, got {len(normalized)}",
|
|
49
|
+
code="too_long",
|
|
50
|
+
)
|
|
51
|
+
if not normalized.isascii() or not _DNS_LABEL_RE.match(normalized):
|
|
52
|
+
raise PrefixError(
|
|
53
|
+
f"prefix '{normalized}' must match DNS label ^[a-z0-9]([a-z0-9-]{{0,61}}[a-z0-9])?$",
|
|
54
|
+
code="invalid_format",
|
|
55
|
+
)
|
|
56
|
+
return normalized
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def validate_prefix(
|
|
60
|
+
raw: str,
|
|
61
|
+
*,
|
|
62
|
+
extra_reserved: Sequence[str] = (),
|
|
63
|
+
) -> str:
|
|
64
|
+
"""Normalize and validate a subdomain prefix against built-in and extra reserved lists."""
|
|
65
|
+
normalized = raw.strip().lower()
|
|
66
|
+
if not normalized:
|
|
67
|
+
raise PrefixError("prefix cannot be empty", code="empty")
|
|
68
|
+
|
|
69
|
+
# Check reserved names before DNS character checks so e.g. "_neruton" reports reserved.
|
|
70
|
+
if normalized in RESERVED_PREFIXES:
|
|
71
|
+
raise PrefixError(f"prefix '{normalized}' is reserved", code="reserved")
|
|
72
|
+
for extra in extra_reserved:
|
|
73
|
+
if normalized == extra.strip().lower():
|
|
74
|
+
raise PrefixError(f"prefix '{normalized}' is reserved", code="reserved")
|
|
75
|
+
|
|
76
|
+
return validate_prefix_format(normalized)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _format_netloc(
|
|
80
|
+
hostname: str,
|
|
81
|
+
port: Optional[int],
|
|
82
|
+
default_port: int,
|
|
83
|
+
userinfo: Optional[str] = None,
|
|
84
|
+
) -> str:
|
|
85
|
+
host_part = f"[{hostname}]" if ":" in hostname and not hostname.startswith("[") else hostname
|
|
86
|
+
if port is not None and port != default_port:
|
|
87
|
+
host_port = f"{host_part}:{port}"
|
|
88
|
+
else:
|
|
89
|
+
host_port = host_part
|
|
90
|
+
if userinfo:
|
|
91
|
+
return f"{userinfo}@{host_port}"
|
|
92
|
+
return host_port
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def build_tunnel_ws_url(server: str) -> str:
|
|
96
|
+
"""Convert a server URL (`https://...`, `http://...`, `wss://...`, `ws://...`, or bare
|
|
97
|
+
`host[:port]`) into the Neruton tunnel WebSocket URL (`wss://<host>/_neruton/tunnel`).
|
|
98
|
+
"""
|
|
99
|
+
trimmed = server.strip()
|
|
100
|
+
if not trimmed:
|
|
101
|
+
raise ValueError("server URL cannot be empty")
|
|
102
|
+
|
|
103
|
+
with_scheme = trimmed if "://" in trimmed else f"https://{trimmed}"
|
|
104
|
+
parsed = urlsplit(with_scheme)
|
|
105
|
+
|
|
106
|
+
scheme_map = {
|
|
107
|
+
"https": "wss",
|
|
108
|
+
"http": "ws",
|
|
109
|
+
"wss": "wss",
|
|
110
|
+
"ws": "ws",
|
|
111
|
+
}
|
|
112
|
+
raw_scheme = parsed.scheme.lower()
|
|
113
|
+
if raw_scheme not in scheme_map:
|
|
114
|
+
raise ValueError(
|
|
115
|
+
f"unsupported server scheme '{parsed.scheme}' (expected http, https, ws, or wss)"
|
|
116
|
+
)
|
|
117
|
+
ws_scheme = scheme_map[raw_scheme]
|
|
118
|
+
|
|
119
|
+
hostname = parsed.hostname
|
|
120
|
+
if not hostname:
|
|
121
|
+
raise ValueError(f"server URL '{server}' is missing a host")
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
port = parsed.port
|
|
125
|
+
except ValueError as exc:
|
|
126
|
+
raise ValueError(f"invalid port in server URL '{server}': {exc}") from exc
|
|
127
|
+
|
|
128
|
+
default_port = 443 if ws_scheme == "wss" else 80
|
|
129
|
+
userinfo: Optional[str] = None
|
|
130
|
+
if parsed.username is not None:
|
|
131
|
+
userinfo = (
|
|
132
|
+
f"{parsed.username}:{parsed.password}"
|
|
133
|
+
if parsed.password is not None
|
|
134
|
+
else parsed.username
|
|
135
|
+
)
|
|
136
|
+
netloc = _format_netloc(hostname, port, default_port, userinfo)
|
|
137
|
+
|
|
138
|
+
clean_path = parsed.path.rstrip("/")
|
|
139
|
+
if not clean_path:
|
|
140
|
+
ws_path = TUNNEL_WS_PATH
|
|
141
|
+
elif clean_path.endswith(TUNNEL_WS_PATH):
|
|
142
|
+
ws_path = clean_path
|
|
143
|
+
else:
|
|
144
|
+
ws_path = f"{clean_path}{TUNNEL_WS_PATH}"
|
|
145
|
+
|
|
146
|
+
return urlunsplit((ws_scheme, netloc, ws_path, parsed.query, ""))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def normalize_target_url(raw: Union[str, int]) -> str:
|
|
150
|
+
"""Normalize a local target spec like `3000`, `localhost:3000`, or `http://127.0.0.1:8080`."""
|
|
151
|
+
if isinstance(raw, bool):
|
|
152
|
+
raise ValueError("target URL cannot be a boolean")
|
|
153
|
+
if isinstance(raw, int):
|
|
154
|
+
if raw < 1 or raw > 65535:
|
|
155
|
+
raise ValueError(f"invalid port {raw} (expected 1..=65535)")
|
|
156
|
+
return f"http://127.0.0.1:{raw}/"
|
|
157
|
+
|
|
158
|
+
trimmed = raw.strip()
|
|
159
|
+
if not trimmed:
|
|
160
|
+
raise ValueError("target URL cannot be empty")
|
|
161
|
+
|
|
162
|
+
if trimmed.isdigit():
|
|
163
|
+
port_num = int(trimmed)
|
|
164
|
+
if 0 <= port_num <= 65535:
|
|
165
|
+
return f"http://127.0.0.1:{port_num}/"
|
|
166
|
+
raise ValueError(f"invalid port '{trimmed}' (expected 0..=65535)")
|
|
167
|
+
|
|
168
|
+
lower = trimmed.lower()
|
|
169
|
+
if lower.startswith("http://") or lower.startswith("https://"):
|
|
170
|
+
candidate = trimmed
|
|
171
|
+
elif "://" in trimmed:
|
|
172
|
+
raise ValueError(
|
|
173
|
+
f"unsupported target scheme in '{trimmed}' (expected http:// or https://)"
|
|
174
|
+
)
|
|
175
|
+
else:
|
|
176
|
+
candidate = f"http://{trimmed}"
|
|
177
|
+
|
|
178
|
+
parsed = urlsplit(candidate)
|
|
179
|
+
scheme = parsed.scheme.lower()
|
|
180
|
+
if scheme not in ("http", "https"):
|
|
181
|
+
raise ValueError(
|
|
182
|
+
f"unsupported target scheme in '{trimmed}' (expected http:// or https://)"
|
|
183
|
+
)
|
|
184
|
+
hostname = parsed.hostname
|
|
185
|
+
if not hostname:
|
|
186
|
+
raise ValueError(f"target URL '{raw}' is missing a host")
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
port = parsed.port
|
|
190
|
+
except ValueError as exc:
|
|
191
|
+
raise ValueError(f"invalid target URL '{raw}': {exc}") from exc
|
|
192
|
+
|
|
193
|
+
default_port = 443 if scheme == "https" else 80
|
|
194
|
+
netloc = _format_netloc(hostname, port, default_port)
|
|
195
|
+
path = parsed.path if parsed.path else "/"
|
|
196
|
+
return urlunsplit((scheme, netloc, path, parsed.query, parsed.fragment))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def detect_client_os() -> str:
|
|
200
|
+
"""Return client OS/arch string formatted like Rust (`linux/x86_64`, `macos/aarch64`)."""
|
|
201
|
+
sys_name = platform.system().lower()
|
|
202
|
+
if sys_name == "darwin":
|
|
203
|
+
os_part = "macos"
|
|
204
|
+
elif sys_name:
|
|
205
|
+
os_part = sys_name
|
|
206
|
+
else:
|
|
207
|
+
os_part = "unknown"
|
|
208
|
+
|
|
209
|
+
machine = platform.machine().lower()
|
|
210
|
+
arch_map = {
|
|
211
|
+
"amd64": "x86_64",
|
|
212
|
+
"x64": "x86_64",
|
|
213
|
+
"arm64": "aarch64",
|
|
214
|
+
"i386": "x86",
|
|
215
|
+
"i686": "x86",
|
|
216
|
+
}
|
|
217
|
+
arch_part = arch_map.get(machine, machine or "unknown")
|
|
218
|
+
return f"{os_part}/{arch_part}"
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def is_non_retryable_rejection(err_msg: str) -> bool:
|
|
222
|
+
"""Return True if a registration rejection error message should fail fast without retrying."""
|
|
223
|
+
lower = err_msg.lower()
|
|
224
|
+
return any(pat in lower for pat in _NON_RETRYABLE_PATTERNS)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def format_401_error(body: Optional[bytes], had_token: bool) -> Tuple[str, Optional[str]]:
|
|
228
|
+
"""Build a clear diagnostic message for HTTP 401 responses, matching `neruton` CLI."""
|
|
229
|
+
server_msg: Optional[str] = None
|
|
230
|
+
if body:
|
|
231
|
+
try:
|
|
232
|
+
parsed = json.loads(body.decode("utf-8", errors="replace"))
|
|
233
|
+
if isinstance(parsed, dict):
|
|
234
|
+
raw_err = parsed.get("error")
|
|
235
|
+
if isinstance(raw_err, str) and raw_err.strip():
|
|
236
|
+
server_msg = raw_err.strip()
|
|
237
|
+
except (ValueError, UnicodeDecodeError):
|
|
238
|
+
pass
|
|
239
|
+
|
|
240
|
+
if server_msg:
|
|
241
|
+
detail = server_msg
|
|
242
|
+
elif had_token:
|
|
243
|
+
detail = "Invalid, disabled, or revoked tunnel token."
|
|
244
|
+
else:
|
|
245
|
+
detail = "Authentication token required by this Neruton server."
|
|
246
|
+
|
|
247
|
+
if had_token:
|
|
248
|
+
msg = (
|
|
249
|
+
f"Authentication failed (401 Unauthorized): {detail}\n"
|
|
250
|
+
" Verify or regenerate your token in the Neruton web panel, then run:\n"
|
|
251
|
+
" neruton config set --token <TOKEN>"
|
|
252
|
+
)
|
|
253
|
+
else:
|
|
254
|
+
msg = (
|
|
255
|
+
f"Authentication failed (401 Unauthorized): {detail}\n"
|
|
256
|
+
" Create a token in the Neruton web panel, then run:\n"
|
|
257
|
+
" neruton config set --token <TOKEN>\n"
|
|
258
|
+
" Or pass --token <TOKEN> (or set NERUTON_TOKEN)."
|
|
259
|
+
)
|
|
260
|
+
return msg, server_msg
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
@dataclass(frozen=True)
|
|
264
|
+
class RegisterRequest:
|
|
265
|
+
"""Initial JSON handshake sent by the client over the WebSocket control channel."""
|
|
266
|
+
|
|
267
|
+
prefix: Optional[str]
|
|
268
|
+
target_url: str
|
|
269
|
+
client_version: str = __version__
|
|
270
|
+
client_os: str = ""
|
|
271
|
+
|
|
272
|
+
def __post_init__(self) -> None:
|
|
273
|
+
if not self.client_os:
|
|
274
|
+
object.__setattr__(self, "client_os", detect_client_os())
|
|
275
|
+
|
|
276
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
277
|
+
return {
|
|
278
|
+
"prefix": self.prefix,
|
|
279
|
+
"target_url": self.target_url,
|
|
280
|
+
"client_version": self.client_version,
|
|
281
|
+
"client_os": self.client_os,
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
def to_json(self) -> str:
|
|
285
|
+
return json.dumps(self.to_dict(), separators=(",", ":"))
|
|
286
|
+
|
|
287
|
+
@classmethod
|
|
288
|
+
def from_json(cls, raw: str) -> RegisterRequest:
|
|
289
|
+
data = json.loads(raw)
|
|
290
|
+
if not isinstance(data, dict):
|
|
291
|
+
raise ValueError("RegisterRequest JSON must be an object")
|
|
292
|
+
return cls(
|
|
293
|
+
prefix=data.get("prefix"),
|
|
294
|
+
target_url=str(data["target_url"]),
|
|
295
|
+
client_version=str(data.get("client_version", "")),
|
|
296
|
+
client_os=str(data.get("client_os", "")),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@dataclass(frozen=True)
|
|
301
|
+
class RegisterResponse:
|
|
302
|
+
"""Server reply to `RegisterRequest` before switching WebSocket to Yamux binary mode."""
|
|
303
|
+
|
|
304
|
+
ok: bool
|
|
305
|
+
tunnel_id: str = ""
|
|
306
|
+
prefix: str = ""
|
|
307
|
+
public_url: str = ""
|
|
308
|
+
path_url: str = ""
|
|
309
|
+
preview_url: str = ""
|
|
310
|
+
dashboard_url: str = ""
|
|
311
|
+
error: Optional[str] = None
|
|
312
|
+
owner_username: Optional[str] = None
|
|
313
|
+
token_name: Optional[str] = None
|
|
314
|
+
|
|
315
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
316
|
+
return {
|
|
317
|
+
"ok": self.ok,
|
|
318
|
+
"tunnel_id": self.tunnel_id,
|
|
319
|
+
"prefix": self.prefix,
|
|
320
|
+
"public_url": self.public_url,
|
|
321
|
+
"path_url": self.path_url,
|
|
322
|
+
"preview_url": self.preview_url,
|
|
323
|
+
"dashboard_url": self.dashboard_url,
|
|
324
|
+
"error": self.error,
|
|
325
|
+
"owner_username": self.owner_username,
|
|
326
|
+
"token_name": self.token_name,
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
def to_json(self) -> str:
|
|
330
|
+
return json.dumps(self.to_dict(), separators=(",", ":"))
|
|
331
|
+
|
|
332
|
+
@classmethod
|
|
333
|
+
def from_json(cls, raw: str) -> RegisterResponse:
|
|
334
|
+
data = json.loads(raw)
|
|
335
|
+
if not isinstance(data, dict):
|
|
336
|
+
raise ValueError("RegisterResponse JSON must be an object")
|
|
337
|
+
if "ok" not in data or not isinstance(data["ok"], bool):
|
|
338
|
+
raise ValueError("RegisterResponse missing boolean 'ok' field")
|
|
339
|
+
return cls(
|
|
340
|
+
ok=data["ok"],
|
|
341
|
+
tunnel_id=str(data.get("tunnel_id") or ""),
|
|
342
|
+
prefix=str(data.get("prefix") or ""),
|
|
343
|
+
public_url=str(data.get("public_url") or ""),
|
|
344
|
+
path_url=str(data.get("path_url") or ""),
|
|
345
|
+
preview_url=str(data.get("preview_url") or ""),
|
|
346
|
+
dashboard_url=str(data.get("dashboard_url") or ""),
|
|
347
|
+
error=data.get("error") if isinstance(data.get("error"), str) else None,
|
|
348
|
+
owner_username=(
|
|
349
|
+
data.get("owner_username")
|
|
350
|
+
if isinstance(data.get("owner_username"), str)
|
|
351
|
+
else None
|
|
352
|
+
),
|
|
353
|
+
token_name=(
|
|
354
|
+
data.get("token_name")
|
|
355
|
+
if isinstance(data.get("token_name"), str)
|
|
356
|
+
else None
|
|
357
|
+
),
|
|
358
|
+
)
|
neruton/py.typed
ADDED
|
File without changes
|
neruton/ui.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Terminal UI formatting mirroring `crates/neruton-cli/src/ui.rs`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from typing import TextIO
|
|
9
|
+
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
from .protocol import RegisterResponse
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _use_color() -> bool:
|
|
15
|
+
return "NO_COLOR" not in os.environ
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _c(code: str, text: str) -> str:
|
|
19
|
+
if _use_color():
|
|
20
|
+
return f"\x1b[{code}m{text}\x1b[0m"
|
|
21
|
+
return text
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _now_hms() -> str:
|
|
25
|
+
return datetime.now().strftime("%H:%M:%S")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def print_banner(
|
|
29
|
+
resp: RegisterResponse,
|
|
30
|
+
target_url: str,
|
|
31
|
+
*,
|
|
32
|
+
stream: TextIO = sys.stdout,
|
|
33
|
+
) -> None:
|
|
34
|
+
"""Print the online tunnel status box matching Rust `neruton` CLI."""
|
|
35
|
+
if resp.owner_username and resp.token_name:
|
|
36
|
+
auth_label = f"{resp.owner_username} ({resp.token_name})"
|
|
37
|
+
elif resp.owner_username:
|
|
38
|
+
auth_label = resp.owner_username
|
|
39
|
+
elif resp.token_name:
|
|
40
|
+
auth_label = resp.token_name
|
|
41
|
+
else:
|
|
42
|
+
auth_label = "anonymous (open mode)"
|
|
43
|
+
|
|
44
|
+
rows = [
|
|
45
|
+
("Wildcard URL", resp.public_url, "1;36"),
|
|
46
|
+
("Web Preview", resp.preview_url, "1;32"),
|
|
47
|
+
("Path URL", resp.path_url, "36"),
|
|
48
|
+
("Dashboard", resp.dashboard_url, "34"),
|
|
49
|
+
("Forwarding", target_url, "33"),
|
|
50
|
+
("Prefix", resp.prefix, "1;35"),
|
|
51
|
+
("Auth", auth_label, "37"),
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
label_width = max(len(label) for label, _, _ in rows)
|
|
55
|
+
val_width = max(len(value) for _, value, _ in rows)
|
|
56
|
+
title = f" Neruton Tunnel v{__version__} · Online "
|
|
57
|
+
inner_width = max(label_width + 3 + val_width, len(title)) + 2
|
|
58
|
+
|
|
59
|
+
top_fill = max(0, inner_width - len(title))
|
|
60
|
+
left_fill = min(2, top_fill)
|
|
61
|
+
right_fill = max(0, top_fill - left_fill)
|
|
62
|
+
|
|
63
|
+
print(file=stream)
|
|
64
|
+
print(
|
|
65
|
+
f"{_c('36', '╭' + '─' * left_fill)}"
|
|
66
|
+
f"{_c('1;32', title)}"
|
|
67
|
+
f"{_c('36', '─' * right_fill)}"
|
|
68
|
+
f"{_c('36', '╮')}",
|
|
69
|
+
file=stream,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
for label, value, color in rows:
|
|
73
|
+
pad_label = " " * max(0, label_width - len(label))
|
|
74
|
+
content_len = label_width + 3 + len(value)
|
|
75
|
+
pad_right = " " * max(0, inner_width - content_len - 2)
|
|
76
|
+
print(
|
|
77
|
+
f"{_c('36', '│')} "
|
|
78
|
+
f"{_c('2', label)}{pad_label} "
|
|
79
|
+
f"{_c('2', '→')} "
|
|
80
|
+
f"{_c(color, value)}{pad_right} "
|
|
81
|
+
f"{_c('36', '│')}",
|
|
82
|
+
file=stream,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
print(_c("36", f"╰{'─' * inner_width}╯"), file=stream)
|
|
86
|
+
print(_c("2", "Press Ctrl+C to close the tunnel.\n"), file=stream, flush=True)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def log_request(
|
|
90
|
+
method: str,
|
|
91
|
+
path: str,
|
|
92
|
+
status: int,
|
|
93
|
+
duration_ms: int,
|
|
94
|
+
*,
|
|
95
|
+
stream: TextIO = sys.stdout,
|
|
96
|
+
) -> None:
|
|
97
|
+
now = _now_hms()
|
|
98
|
+
if status == 101:
|
|
99
|
+
status_color = "1;35"
|
|
100
|
+
elif 200 <= status <= 299:
|
|
101
|
+
status_color = "1;32"
|
|
102
|
+
elif 300 <= status <= 399:
|
|
103
|
+
status_color = "1;36"
|
|
104
|
+
elif 400 <= status <= 499:
|
|
105
|
+
status_color = "1;33"
|
|
106
|
+
else:
|
|
107
|
+
status_color = "1;31"
|
|
108
|
+
status_text = f"{status:3d}"
|
|
109
|
+
method_text = f"{method:<7}"
|
|
110
|
+
print(
|
|
111
|
+
f"{_c('2', now)} {_c(status_color, status_text)} "
|
|
112
|
+
f"{_c('1', method_text)} {path} {_c('2', f'({duration_ms}ms)')}",
|
|
113
|
+
file=stream,
|
|
114
|
+
flush=True,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def log_info(msg: str, *, stream: TextIO = sys.stdout) -> None:
|
|
119
|
+
print(f"{_c('2', _now_hms())} {_c('1;36', 'INFO')} {msg}", file=stream, flush=True)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def log_warn(msg: str, *, stream: TextIO = sys.stderr) -> None:
|
|
123
|
+
print(f"{_c('2', _now_hms())} {_c('1;33', 'WARN')} {msg}", file=stream, flush=True)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def log_error(msg: str, *, stream: TextIO = sys.stderr) -> None:
|
|
127
|
+
print(f"{_c('2', _now_hms())} {_c('1;31', 'ERR ')} {msg}", file=stream, flush=True)
|