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/config.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Persistent configuration helpers compatible with Rust `~/.config/neruton/config.toml`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Optional, Tuple, Union
|
|
10
|
+
|
|
11
|
+
from ._version import DEFAULT_SERVER_URL
|
|
12
|
+
from .errors import NerutonError
|
|
13
|
+
|
|
14
|
+
if sys.version_info >= (3, 11):
|
|
15
|
+
import tomllib
|
|
16
|
+
else: # pragma: no cover
|
|
17
|
+
import tomli as tomllib # type: ignore[import-not-found]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Config:
|
|
22
|
+
"""Neruton CLI/SDK configuration stored in `config.toml`."""
|
|
23
|
+
|
|
24
|
+
server: Optional[str] = None
|
|
25
|
+
token: Optional[str] = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def config_path(explicit: Optional[Union[str, Path]] = None) -> Path:
|
|
29
|
+
"""Return the resolved path to `config.toml`.
|
|
30
|
+
|
|
31
|
+
Matches Rust `neruton-cli`:
|
|
32
|
+
- Explicit path if provided.
|
|
33
|
+
- On Unix (Linux/macOS): `~/.config/neruton/config.toml`.
|
|
34
|
+
- On Windows: `%APPDATA%\\neruton\\config.toml` (falling back to home dir).
|
|
35
|
+
"""
|
|
36
|
+
if explicit is not None:
|
|
37
|
+
return Path(explicit).expanduser()
|
|
38
|
+
|
|
39
|
+
if os.name != "nt":
|
|
40
|
+
return Path.home() / ".config" / "neruton" / "config.toml"
|
|
41
|
+
|
|
42
|
+
appdata = os.environ.get("APPDATA")
|
|
43
|
+
base = Path(appdata) if appdata else Path.home()
|
|
44
|
+
return base / "neruton" / "config.toml"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _clean_opt(value: Optional[str]) -> Optional[str]:
|
|
48
|
+
if value is None:
|
|
49
|
+
return None
|
|
50
|
+
trimmed = value.strip()
|
|
51
|
+
return trimmed if trimmed else None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_config(path: Optional[Union[str, Path]] = None) -> Config:
|
|
55
|
+
"""Load `Config` from `config.toml`, returning an empty `Config` if the file does not exist."""
|
|
56
|
+
target = config_path(path)
|
|
57
|
+
if not target.exists():
|
|
58
|
+
return Config()
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
raw_bytes = target.read_bytes()
|
|
62
|
+
except OSError as exc:
|
|
63
|
+
raise NerutonError(f"failed to read config file {target}: {exc}") from exc
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
data = tomllib.loads(raw_bytes.decode("utf-8"))
|
|
67
|
+
except (ValueError, UnicodeDecodeError) as exc:
|
|
68
|
+
raise NerutonError(f"failed to parse TOML config {target}: {exc}") from exc
|
|
69
|
+
|
|
70
|
+
server = data.get("server")
|
|
71
|
+
token = data.get("token")
|
|
72
|
+
if server is not None and not isinstance(server, str):
|
|
73
|
+
raise NerutonError(f"invalid 'server' field in {target}: expected string")
|
|
74
|
+
if token is not None and not isinstance(token, str):
|
|
75
|
+
raise NerutonError(f"invalid 'token' field in {target}: expected string")
|
|
76
|
+
|
|
77
|
+
return Config(server=server, token=token)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _escape_toml_string(value: str) -> str:
|
|
81
|
+
out = ['"']
|
|
82
|
+
for ch in value:
|
|
83
|
+
code = ord(ch)
|
|
84
|
+
if ch == "\\":
|
|
85
|
+
out.append("\\\\")
|
|
86
|
+
elif ch == '"':
|
|
87
|
+
out.append('\\"')
|
|
88
|
+
elif ch == "\b":
|
|
89
|
+
out.append("\\b")
|
|
90
|
+
elif ch == "\t":
|
|
91
|
+
out.append("\\t")
|
|
92
|
+
elif ch == "\n":
|
|
93
|
+
out.append("\\n")
|
|
94
|
+
elif ch == "\f":
|
|
95
|
+
out.append("\\f")
|
|
96
|
+
elif ch == "\r":
|
|
97
|
+
out.append("\\r")
|
|
98
|
+
elif code < 0x20 or code == 0x7F:
|
|
99
|
+
out.append(f"\\u{code:04x}")
|
|
100
|
+
else:
|
|
101
|
+
out.append(ch)
|
|
102
|
+
out.append('"')
|
|
103
|
+
return "".join(out)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _serialize_config_toml(cfg: Config) -> str:
|
|
107
|
+
lines = []
|
|
108
|
+
if cfg.server is not None:
|
|
109
|
+
lines.append(f"server = {_escape_toml_string(cfg.server)}")
|
|
110
|
+
if cfg.token is not None:
|
|
111
|
+
lines.append(f"token = {_escape_toml_string(cfg.token)}")
|
|
112
|
+
return ("\n".join(lines) + "\n") if lines else ""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def save_config(
|
|
116
|
+
config: Optional[Config] = None,
|
|
117
|
+
path: Optional[Union[str, Path]] = None,
|
|
118
|
+
*,
|
|
119
|
+
server: Optional[str] = None,
|
|
120
|
+
token: Optional[str] = None,
|
|
121
|
+
) -> Path:
|
|
122
|
+
"""Persist `Config` to `config.toml` with `0600` permissions on POSIX systems."""
|
|
123
|
+
if config is None:
|
|
124
|
+
cfg = Config(server=server, token=token)
|
|
125
|
+
else:
|
|
126
|
+
cfg = Config(
|
|
127
|
+
server=server if server is not None else config.server,
|
|
128
|
+
token=token if token is not None else config.token,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
target = config_path(path)
|
|
132
|
+
try:
|
|
133
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
134
|
+
except OSError as exc:
|
|
135
|
+
raise NerutonError(f"failed to create config directory {target.parent}: {exc}") from exc
|
|
136
|
+
|
|
137
|
+
content = _serialize_config_toml(cfg).encode("utf-8")
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
if os.name != "nt":
|
|
141
|
+
# Create/replace atomically with mode 0600 so secrets are never world-readable.
|
|
142
|
+
tmp_path = target.with_name(f".{target.name}.{os.getpid()}.tmp")
|
|
143
|
+
fd = os.open(
|
|
144
|
+
str(tmp_path),
|
|
145
|
+
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
|
|
146
|
+
0o600,
|
|
147
|
+
)
|
|
148
|
+
try:
|
|
149
|
+
os.write(fd, content)
|
|
150
|
+
finally:
|
|
151
|
+
os.close(fd)
|
|
152
|
+
os.chmod(tmp_path, 0o600)
|
|
153
|
+
os.replace(tmp_path, target)
|
|
154
|
+
os.chmod(target, 0o600)
|
|
155
|
+
else:
|
|
156
|
+
target.write_bytes(content)
|
|
157
|
+
except OSError as exc:
|
|
158
|
+
raise NerutonError(f"failed to write config file {target}: {exc}") from exc
|
|
159
|
+
|
|
160
|
+
return target
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def resolve_server_and_token(
|
|
164
|
+
*,
|
|
165
|
+
server: Optional[str] = None,
|
|
166
|
+
token: Optional[str] = None,
|
|
167
|
+
config_file: Optional[Union[str, Path]] = None,
|
|
168
|
+
) -> Tuple[str, Optional[str]]:
|
|
169
|
+
"""Resolve effective `(server, token)` following Rust CLI precedence.
|
|
170
|
+
|
|
171
|
+
- server: explicit arg > `NERUTON_SERVER` > `config.toml` > `https://neruton.moer.eu.org`
|
|
172
|
+
- token: explicit arg > `NERUTON_TOKEN` > `NERUTON_AUTH_TOKEN` > `config.toml` > `None`
|
|
173
|
+
"""
|
|
174
|
+
file_cfg = load_config(config_file)
|
|
175
|
+
|
|
176
|
+
resolved_server = (
|
|
177
|
+
_clean_opt(server)
|
|
178
|
+
or _clean_opt(os.environ.get("NERUTON_SERVER"))
|
|
179
|
+
or _clean_opt(file_cfg.server)
|
|
180
|
+
or DEFAULT_SERVER_URL
|
|
181
|
+
)
|
|
182
|
+
resolved_token = (
|
|
183
|
+
_clean_opt(token)
|
|
184
|
+
or _clean_opt(os.environ.get("NERUTON_TOKEN"))
|
|
185
|
+
or _clean_opt(os.environ.get("NERUTON_AUTH_TOKEN"))
|
|
186
|
+
or _clean_opt(file_cfg.token)
|
|
187
|
+
)
|
|
188
|
+
return resolved_server, resolved_token
|
neruton/errors.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Exception hierarchy for the Neruton Python SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NerutonError(Exception):
|
|
9
|
+
"""Base exception for all Neruton errors."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PrefixError(NerutonError, ValueError):
|
|
13
|
+
"""Raised when a subdomain prefix fails validation or is reserved."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, *, code: str = "invalid") -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.code = code
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AuthError(NerutonError):
|
|
21
|
+
"""Raised on HTTP 401 Unauthorized authentication failures (non-retryable)."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
message: str,
|
|
26
|
+
*,
|
|
27
|
+
status_code: int = 401,
|
|
28
|
+
server_message: Optional[str] = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
super().__init__(message)
|
|
31
|
+
self.status_code = status_code
|
|
32
|
+
self.server_message = server_message
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RegistrationError(NerutonError):
|
|
36
|
+
"""Raised when the Neruton server rejects tunnel registration."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, message: str, *, retryable: bool = False) -> None:
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.retryable = retryable
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class TunnelConnectionError(NerutonError, ConnectionError):
|
|
44
|
+
"""Raised when establishing or maintaining the tunnel WebSocket connection fails."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class TunnelClosedError(NerutonError):
|
|
48
|
+
"""Raised when operating on an already closed tunnel or session."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class YamuxError(NerutonError):
|
|
52
|
+
"""Base exception for Yamux multiplexing errors."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class YamuxProtocolError(YamuxError):
|
|
56
|
+
"""Raised on Yamux framing or flow-control protocol violations."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class YamuxClosedError(YamuxError):
|
|
60
|
+
"""Raised when reading/writing on a closed Yamux session or stream."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class YamuxStreamResetError(YamuxClosedError, ConnectionResetError):
|
|
64
|
+
"""Raised when a Yamux stream is reset (RST) by either peer."""
|