@simplexai/localmodels-win32-x64 0.1.0-dev.61 → 0.1.0-dev.63
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +66 -63
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/bifrost_checks.py +19 -13
- package/modules/localmodels/bifrost_clients.py +38 -36
- package/modules/localmodels/bifrost_config.py +19 -6
- package/modules/localmodels/bifrost_log.py +3 -3
- package/modules/localmodels/bifrost_models.py +9 -8
- package/modules/localmodels/bifrost_pi.py +27 -72
- package/modules/localmodels/catalog.json +51 -58
- package/modules/localmodels/custom_hub.py +10 -1
- package/modules/localmodels/custom_hub_http.py +41 -107
- package/modules/localmodels/debug_mode.py +3 -3
- package/modules/localmodels/gateway.py +56 -55
- package/modules/localmodels/gateway_bifrost.py +70 -83
- package/modules/localmodels/gateway_clients.py +33 -116
- package/modules/localmodels/gateway_home.py +5 -5
- package/modules/localmodels/gateway_keys.py +8 -6
- package/modules/localmodels/gateway_probe.py +4 -4
- package/modules/localmodels/gateway_server.py +4 -4
- package/modules/localmodels/gateway_speed.py +2 -2
- package/modules/localmodels/harness.py +185 -401
- package/modules/localmodels/harness_core.py +409 -0
- package/modules/localmodels/harness_gateway.py +75 -73
- package/modules/localmodels/harness_probe.py +19 -216
- package/modules/localmodels/library_custom.py +51 -16
- package/modules/localmodels/library_elastic.py +1 -1
- package/modules/localmodels/library_gateway.py +59 -176
- package/modules/localmodels/library_jobs.py +4 -0
- package/modules/localmodels/library_model.py +23 -0
- package/modules/localmodels/library_pricing.py +2 -2
- package/modules/localmodels/library_serve.py +5 -3
- package/modules/localmodels/library_smoke.py +33 -21
- package/modules/localmodels/library_status.py +330 -2
- package/modules/localmodels/llm_rank.py +14 -5
- package/modules/localmodels/magpie_setup.py +5 -4
- package/modules/localmodels/magpie_windows.py +1 -1
- package/modules/localmodels/memcalc_load.py +9 -4
- package/modules/localmodels/pi_profile.py +384 -0
- package/modules/localmodels/process_identity.py +3 -3
- package/modules/localmodels/remote_ops_common.py +31 -90
- package/modules/localmodels/remote_ops_download.py +2 -0
- package/modules/localmodels/remote_ops_mirrors.py +1 -1
- package/modules/localmodels/remote_ops_ranges.py +4 -1
- package/modules/localmodels/remote_ops_redirect.py +393 -0
- package/modules/localmodels/runtime_cli.py +32 -46
- package/modules/localmodels/runtime_pi.py +1 -1
- package/modules/localmodels/source_byok.py +9 -16
- package/modules/localmodels/source_cli.py +136 -23
- package/modules/localmodels/speech_jobs.py +4 -0
- package/modules/localmodels/stack_binding.py +9 -7
- package/modules/localmodels/stack_clients.py +137 -21
- package/modules/localmodels/stack_doctor.py +6 -3
- package/modules/localmodels/stack_hardware.py +18 -0
- package/modules/localmodels/stack_lifecycle.py +3 -2
- package/modules/localmodels/stack_remove.py +2 -1
- package/modules/localmodels/stack_verify.py +2 -2
- package/modules/localmodels/stack_view_events.py +2 -2
- package/modules/localmodels/transport.py +1 -0
- package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/RECORD +63 -60
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Unified Layer-0 HTTP redirect validation, SSRF defense, and credential stripping.
|
|
3
|
+
|
|
4
|
+
Part of the remote_ops bundle (transport.BUNDLES): standard library only, Python 3.8+, and a
|
|
5
|
+
pure leaf module (zero imports from sibling localmodels modules) so controller modules such as
|
|
6
|
+
``custom_hub_http`` and ``memcalc_load`` share the exact same policy as ``remote_ops_download``
|
|
7
|
+
without creating import cycles.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ipaddress
|
|
13
|
+
import socket
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
from typing import Any, Union
|
|
18
|
+
|
|
19
|
+
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
|
|
20
|
+
|
|
21
|
+
MAX_REDIRECTS = 5
|
|
22
|
+
SENSITIVE_REDIRECT_HEADERS = frozenset({"authorization", "cookie", "proxy-authorization"})
|
|
23
|
+
|
|
24
|
+
_NAT64_WELL_KNOWN = ipaddress.IPv6Network("64:ff9b::/96")
|
|
25
|
+
_LOOPBACK_V4 = ipaddress.IPv4Network("127.0.0.0/8")
|
|
26
|
+
_LOOPBACK_V6 = ipaddress.IPv6Network("::1/128")
|
|
27
|
+
|
|
28
|
+
# Explicit network sets (never rely on ipaddress.is_global / is_reserved, which reject Fake-IP
|
|
29
|
+
# TUN pools like 198.18.0.0/15 & fc00::/18 as well as RFC 6052 NAT64 64:ff9b::/96).
|
|
30
|
+
_ALWAYS_BLOCKED_V4: tuple[ipaddress.IPv4Network, ...] = (
|
|
31
|
+
_LOOPBACK_V4, # loopback
|
|
32
|
+
ipaddress.IPv4Network("0.0.0.0/8"), # unspecified
|
|
33
|
+
ipaddress.IPv4Network("169.254.0.0/16"), # link-local / cloud IMDS
|
|
34
|
+
ipaddress.IPv4Network("224.0.0.0/4"), # multicast
|
|
35
|
+
)
|
|
36
|
+
_ALWAYS_BLOCKED_V6: tuple[ipaddress.IPv6Network, ...] = (
|
|
37
|
+
_LOOPBACK_V6, # loopback
|
|
38
|
+
ipaddress.IPv6Network("::/128"), # unspecified
|
|
39
|
+
ipaddress.IPv6Network("fe80::/10"), # link-local
|
|
40
|
+
ipaddress.IPv6Network("ff00::/8"), # multicast
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
# Fake-IP TUN pools (always blocked as literal redirect targets, allowed when returned by local
|
|
44
|
+
# DNS for a non-local FQDN).
|
|
45
|
+
_FAKEIP_LITERAL_V4: tuple[ipaddress.IPv4Network, ...] = (
|
|
46
|
+
ipaddress.IPv4Network("198.18.0.0/15"), # RFC 2544: FlClash/Mihomo/Clash/sing-box/Surge/V2RayN
|
|
47
|
+
)
|
|
48
|
+
_FAKEIP_LITERAL_V6: tuple[ipaddress.IPv6Network, ...] = (
|
|
49
|
+
ipaddress.IPv6Network("fc00::/18"), # Mihomo / Clash / sing-box IPv6 fake-IP
|
|
50
|
+
ipaddress.IPv6Network("fdfe:dcba:9876::/48"), # Surge IPv6 fake-IP
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# CGNAT / Tailscale / custom TUN range (allowed on DNS for public FQDNs; allowed as literal only
|
|
54
|
+
# from private origins).
|
|
55
|
+
_CGNAT_V4 = ipaddress.IPv4Network("100.64.0.0/10")
|
|
56
|
+
|
|
57
|
+
_DNS_ALLOWED_TUN_V4: tuple[ipaddress.IPv4Network, ...] = (*_FAKEIP_LITERAL_V4, _CGNAT_V4)
|
|
58
|
+
_DNS_ALLOWED_TUN_V6: tuple[ipaddress.IPv6Network, ...] = _FAKEIP_LITERAL_V6
|
|
59
|
+
|
|
60
|
+
_LAN_PRIVATE_V4: tuple[ipaddress.IPv4Network, ...] = (
|
|
61
|
+
ipaddress.IPv4Network("10.0.0.0/8"),
|
|
62
|
+
ipaddress.IPv4Network("172.16.0.0/12"),
|
|
63
|
+
ipaddress.IPv4Network("192.168.0.0/16"),
|
|
64
|
+
)
|
|
65
|
+
_LAN_PRIVATE_V6: tuple[ipaddress.IPv6Network, ...] = (
|
|
66
|
+
ipaddress.IPv6Network("fc00::/7"), # RFC 4193 ULA (checked after Fake-IP IPv6 sets on DNS)
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
_ALWAYS_BLOCKED_HOSTNAMES = frozenset({"localhost", "metadata.google.internal", "metadata.goog"})
|
|
70
|
+
_PRIVATE_LOCAL_SUFFIXES = (".local", ".internal", ".home.arpa", ".localdomain")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class UnsafeRedirectError(urllib.error.URLError):
|
|
74
|
+
"""Deterministic redirect security/policy refusal (never used for transient DNS failures)."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def normalize_host(host: str | None) -> str:
|
|
78
|
+
"""Lowercase a hostname or IP literal, stripping whitespace, IPv6 brackets, and trailing dots."""
|
|
79
|
+
clean = (host or "").strip().lower()
|
|
80
|
+
if clean.startswith("[") and clean.endswith("]"):
|
|
81
|
+
clean = clean[1:-1]
|
|
82
|
+
return clean.rstrip(".")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_hf_mirror_host(host: str | None) -> bool:
|
|
86
|
+
"""True for ``hf-mirror.com`` and any subdomain or trailing-dot spelling."""
|
|
87
|
+
norm = normalize_host(host)
|
|
88
|
+
return norm == "hf-mirror.com" or norm.endswith(".hf-mirror.com")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _parse_port(parsed: urllib.parse.SplitResult) -> int | None:
|
|
92
|
+
try:
|
|
93
|
+
port = parsed.port
|
|
94
|
+
except ValueError as exc:
|
|
95
|
+
raise UnsafeRedirectError(f"redirect refused: invalid port: {exc}") from None
|
|
96
|
+
if port is not None and not 1 <= port <= 65535:
|
|
97
|
+
raise UnsafeRedirectError(f"redirect refused: invalid port {port}")
|
|
98
|
+
return port
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def url_origin(url: str) -> tuple[str, str, int]:
|
|
102
|
+
"""Return ``(scheme, normalized_host, effective_port)``, rejecting malformed ports."""
|
|
103
|
+
parsed = urllib.parse.urlsplit(url)
|
|
104
|
+
scheme = parsed.scheme.lower()
|
|
105
|
+
host = normalize_host(parsed.hostname)
|
|
106
|
+
port = _parse_port(parsed)
|
|
107
|
+
if port is None:
|
|
108
|
+
port = 443 if scheme == "https" else (80 if scheme == "http" else 0)
|
|
109
|
+
return (scheme, host, port)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _parse_ip(raw: str) -> IPAddr | None:
|
|
113
|
+
candidate = normalize_host(raw).split("%", 1)[0]
|
|
114
|
+
if not candidate:
|
|
115
|
+
return None
|
|
116
|
+
try:
|
|
117
|
+
return ipaddress.ip_address(candidate)
|
|
118
|
+
except ValueError:
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _unwrap_ip(addr: IPAddr) -> IPAddr:
|
|
123
|
+
if isinstance(addr, ipaddress.IPv6Address):
|
|
124
|
+
if addr.ipv4_mapped is not None:
|
|
125
|
+
return addr.ipv4_mapped
|
|
126
|
+
if addr in _NAT64_WELL_KNOWN:
|
|
127
|
+
return ipaddress.IPv4Address(int(addr) & 0xFFFFFFFF)
|
|
128
|
+
return addr
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _in_v4_or_v6(
|
|
132
|
+
addr: IPAddr,
|
|
133
|
+
v4_nets: tuple[ipaddress.IPv4Network, ...],
|
|
134
|
+
v6_nets: tuple[ipaddress.IPv6Network, ...],
|
|
135
|
+
) -> bool:
|
|
136
|
+
if isinstance(addr, ipaddress.IPv4Address):
|
|
137
|
+
return any(addr in net for net in v4_nets)
|
|
138
|
+
return any(addr in net for net in v6_nets)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _is_loopback_ip(addr: IPAddr) -> bool:
|
|
142
|
+
return (
|
|
143
|
+
(addr in _LOOPBACK_V4)
|
|
144
|
+
if isinstance(addr, ipaddress.IPv4Address)
|
|
145
|
+
else (addr in _LOOPBACK_V6)
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _is_always_blocked_ip(addr: IPAddr) -> bool:
|
|
150
|
+
return _in_v4_or_v6(addr, _ALWAYS_BLOCKED_V4, _ALWAYS_BLOCKED_V6)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _is_fakeip_literal(addr: IPAddr) -> bool:
|
|
154
|
+
return _in_v4_or_v6(addr, _FAKEIP_LITERAL_V4, _FAKEIP_LITERAL_V6)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _is_dns_allowed_tun(addr: IPAddr) -> bool:
|
|
158
|
+
return _in_v4_or_v6(addr, _DNS_ALLOWED_TUN_V4, _DNS_ALLOWED_TUN_V6)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _is_lan_private_ip(addr: IPAddr) -> bool:
|
|
162
|
+
return _in_v4_or_v6(addr, _LAN_PRIVATE_V4, _LAN_PRIVATE_V6)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _is_lan_private_or_cgnat(addr: IPAddr) -> bool:
|
|
166
|
+
if isinstance(addr, ipaddress.IPv4Address) and addr in _CGNAT_V4:
|
|
167
|
+
return True
|
|
168
|
+
return _is_lan_private_ip(addr)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _is_always_blocked_hostname(host: str) -> bool:
|
|
172
|
+
return host in _ALWAYS_BLOCKED_HOSTNAMES or host.endswith(".localhost")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _is_literal_loopback(host: str) -> bool:
|
|
176
|
+
if host == "localhost":
|
|
177
|
+
return True
|
|
178
|
+
parsed = _parse_ip(host)
|
|
179
|
+
return parsed is not None and _is_loopback_ip(_unwrap_ip(parsed))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _is_private_origin_syntactic(source_url: str | None) -> bool:
|
|
183
|
+
"""True when ``source_url`` explicitly names a LAN/corporate mirror host or private IP."""
|
|
184
|
+
if not source_url:
|
|
185
|
+
return False
|
|
186
|
+
host = normalize_host(urllib.parse.urlsplit(source_url).hostname)
|
|
187
|
+
if not host or _is_always_blocked_hostname(host):
|
|
188
|
+
return False
|
|
189
|
+
literal = _parse_ip(host)
|
|
190
|
+
if literal is not None:
|
|
191
|
+
unwrapped = _unwrap_ip(literal)
|
|
192
|
+
if _is_always_blocked_ip(unwrapped) or _is_fakeip_literal(unwrapped):
|
|
193
|
+
return False
|
|
194
|
+
return _is_lan_private_or_cgnat(unwrapped)
|
|
195
|
+
return host.endswith(_PRIVATE_LOCAL_SUFFIXES) or "." not in host
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _source_resolves_lan_private(source_url: str | None) -> bool:
|
|
199
|
+
"""Lazy check for custom RFC 1918 / ULA Fake-IP TUN pools or transparent corporate proxies."""
|
|
200
|
+
if not source_url or is_proxy_routed(source_url):
|
|
201
|
+
return False
|
|
202
|
+
try:
|
|
203
|
+
_, src_host, src_port = url_origin(source_url)
|
|
204
|
+
except UnsafeRedirectError:
|
|
205
|
+
return False
|
|
206
|
+
if not src_host or _is_always_blocked_hostname(src_host) or _parse_ip(src_host) is not None:
|
|
207
|
+
return False
|
|
208
|
+
try:
|
|
209
|
+
records = socket.getaddrinfo(src_host, src_port or 443, type=socket.SOCK_STREAM)
|
|
210
|
+
except OSError:
|
|
211
|
+
return False
|
|
212
|
+
resolved: list[IPAddr] = []
|
|
213
|
+
for entry in records:
|
|
214
|
+
ip = _parse_ip(str(entry[4][0]))
|
|
215
|
+
if ip is not None:
|
|
216
|
+
resolved.append(_unwrap_ip(ip))
|
|
217
|
+
return (
|
|
218
|
+
bool(resolved)
|
|
219
|
+
and not any(_is_always_blocked_ip(ip) for ip in resolved)
|
|
220
|
+
and any(_is_lan_private_ip(ip) for ip in resolved)
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def is_proxy_routed(url: str) -> bool:
|
|
225
|
+
"""True when urllib routes ``url`` via an explicit HTTP/HTTPS/SOCKS proxy (not bypassed)."""
|
|
226
|
+
parsed = urllib.parse.urlsplit(url)
|
|
227
|
+
scheme = parsed.scheme.lower()
|
|
228
|
+
host = normalize_host(parsed.hostname)
|
|
229
|
+
if not scheme or not host:
|
|
230
|
+
return False
|
|
231
|
+
proxies = {k.lower(): v for k, v in urllib.request.getproxies().items() if v}
|
|
232
|
+
if not proxies.get(scheme):
|
|
233
|
+
return False
|
|
234
|
+
try:
|
|
235
|
+
port = parsed.port
|
|
236
|
+
except ValueError:
|
|
237
|
+
return False
|
|
238
|
+
if port is not None:
|
|
239
|
+
host_with_port = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
|
|
240
|
+
else:
|
|
241
|
+
host_with_port = host
|
|
242
|
+
try:
|
|
243
|
+
if urllib.request.proxy_bypass(host_with_port):
|
|
244
|
+
return False
|
|
245
|
+
if host_with_port != host and urllib.request.proxy_bypass(host):
|
|
246
|
+
return False
|
|
247
|
+
except Exception: # noqa: BLE001 - platform proxy_bypass quirks must not crash
|
|
248
|
+
return False
|
|
249
|
+
return True
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _validate_literal_ip(
|
|
253
|
+
host: str,
|
|
254
|
+
literal: IPAddr,
|
|
255
|
+
*,
|
|
256
|
+
source_is_private: bool,
|
|
257
|
+
allow_insecure_loopback: bool,
|
|
258
|
+
) -> None:
|
|
259
|
+
unwrapped = _unwrap_ip(literal)
|
|
260
|
+
if _is_always_blocked_ip(unwrapped):
|
|
261
|
+
if allow_insecure_loopback and _is_loopback_ip(unwrapped):
|
|
262
|
+
return
|
|
263
|
+
raise UnsafeRedirectError(f"redirect refused: disallowed IP {host!r}")
|
|
264
|
+
if _is_fakeip_literal(unwrapped):
|
|
265
|
+
raise UnsafeRedirectError(f"redirect refused: non-public IP {host!r}")
|
|
266
|
+
if _is_lan_private_or_cgnat(unwrapped) and not source_is_private:
|
|
267
|
+
raise UnsafeRedirectError(f"redirect refused: non-public IP {host!r}")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _validate_resolved_ips(
|
|
271
|
+
host: str,
|
|
272
|
+
records: list[Any],
|
|
273
|
+
*,
|
|
274
|
+
source_url: str | None,
|
|
275
|
+
source_is_private: bool,
|
|
276
|
+
) -> None:
|
|
277
|
+
if not records:
|
|
278
|
+
raise urllib.error.URLError(f"DNS lookup returned no addresses for {host!r}")
|
|
279
|
+
source_lan_private: bool | None = None
|
|
280
|
+
for entry in records:
|
|
281
|
+
raw_ip = str(entry[4][0])
|
|
282
|
+
parsed_ip = _parse_ip(raw_ip)
|
|
283
|
+
if parsed_ip is None:
|
|
284
|
+
raise UnsafeRedirectError(f"redirect refused: invalid IP for {host!r}")
|
|
285
|
+
unwrapped = _unwrap_ip(parsed_ip)
|
|
286
|
+
if _is_always_blocked_ip(unwrapped):
|
|
287
|
+
raise UnsafeRedirectError(f"redirect refused: disallowed IP for {host!r}")
|
|
288
|
+
if _is_dns_allowed_tun(unwrapped):
|
|
289
|
+
continue
|
|
290
|
+
if _is_lan_private_ip(unwrapped):
|
|
291
|
+
if source_is_private:
|
|
292
|
+
continue
|
|
293
|
+
if source_lan_private is None:
|
|
294
|
+
source_lan_private = _source_resolves_lan_private(source_url)
|
|
295
|
+
if source_lan_private:
|
|
296
|
+
continue
|
|
297
|
+
raise UnsafeRedirectError(f"redirect refused: non-public IP for {host!r}")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def validate_redirect_url(
|
|
301
|
+
target_url: str,
|
|
302
|
+
*,
|
|
303
|
+
source_url: str | None = None,
|
|
304
|
+
allow_insecure_loopback: bool = False,
|
|
305
|
+
) -> None:
|
|
306
|
+
"""Enforce HTTPS, URL hygiene, and proxy/Fake-IP-aware SSRF defense on redirect targets."""
|
|
307
|
+
parsed = urllib.parse.urlsplit(target_url)
|
|
308
|
+
scheme = parsed.scheme.lower()
|
|
309
|
+
host = normalize_host(parsed.hostname)
|
|
310
|
+
port = _parse_port(parsed)
|
|
311
|
+
if parsed.username is not None or parsed.password is not None:
|
|
312
|
+
raise UnsafeRedirectError("redirect refused: credentials in redirect URL")
|
|
313
|
+
if not host:
|
|
314
|
+
raise UnsafeRedirectError("redirect refused: missing target host")
|
|
315
|
+
loopback_test_ok = allow_insecure_loopback and scheme == "http" and _is_literal_loopback(host)
|
|
316
|
+
if scheme != "https" and not loopback_test_ok:
|
|
317
|
+
raise UnsafeRedirectError(f"redirect refused: non-HTTPS scheme {scheme!r}")
|
|
318
|
+
if loopback_test_ok:
|
|
319
|
+
return
|
|
320
|
+
if _is_always_blocked_hostname(host):
|
|
321
|
+
if allow_insecure_loopback and host == "localhost":
|
|
322
|
+
return
|
|
323
|
+
raise UnsafeRedirectError(f"redirect refused: local hostname {host!r}")
|
|
324
|
+
source_is_private = _is_private_origin_syntactic(source_url)
|
|
325
|
+
literal = _parse_ip(host)
|
|
326
|
+
if literal is not None:
|
|
327
|
+
_validate_literal_ip(
|
|
328
|
+
host,
|
|
329
|
+
literal,
|
|
330
|
+
source_is_private=source_is_private,
|
|
331
|
+
allow_insecure_loopback=allow_insecure_loopback,
|
|
332
|
+
)
|
|
333
|
+
return
|
|
334
|
+
if host.endswith(_PRIVATE_LOCAL_SUFFIXES) and not source_is_private:
|
|
335
|
+
raise UnsafeRedirectError(f"redirect refused: local hostname {host!r}")
|
|
336
|
+
if is_proxy_routed(target_url):
|
|
337
|
+
return
|
|
338
|
+
try:
|
|
339
|
+
records = socket.getaddrinfo(host, port or 443, type=socket.SOCK_STREAM)
|
|
340
|
+
except OSError as exc:
|
|
341
|
+
# Preserve transient DNS failures as standard URLError (NOT UnsafeRedirectError) so
|
|
342
|
+
# callers keep retryability and classify genuine offline outages as NETWORK_UNAVAILABLE.
|
|
343
|
+
raise urllib.error.URLError(exc) from None
|
|
344
|
+
_validate_resolved_ips(
|
|
345
|
+
host, records, source_url=source_url, source_is_private=source_is_private
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
class SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
350
|
+
"""Enforce HTTPS + proxy/Fake-IP-aware anti-SSRF and strip credentials on origin change."""
|
|
351
|
+
|
|
352
|
+
max_redirections = MAX_REDIRECTS
|
|
353
|
+
|
|
354
|
+
def __init__(self, *, allow_insecure_loopback: bool = False) -> None:
|
|
355
|
+
self._allow_insecure_loopback = allow_insecure_loopback
|
|
356
|
+
|
|
357
|
+
def allow_loopback(self) -> bool:
|
|
358
|
+
"""Whether loopback HTTP redirects are permitted (internal unit-test hook only)."""
|
|
359
|
+
return self._allow_insecure_loopback
|
|
360
|
+
|
|
361
|
+
def redirect_request(
|
|
362
|
+
self,
|
|
363
|
+
req: urllib.request.Request,
|
|
364
|
+
fp: Any,
|
|
365
|
+
code: int,
|
|
366
|
+
msg: str,
|
|
367
|
+
headers: Any,
|
|
368
|
+
newurl: str,
|
|
369
|
+
) -> urllib.request.Request | None:
|
|
370
|
+
hops = int(getattr(req, "_safe_redirect_hops", 0))
|
|
371
|
+
if hops >= self.max_redirections:
|
|
372
|
+
raise UnsafeRedirectError("redirect refused: redirect limit exceeded")
|
|
373
|
+
if not newurl or not newurl.strip():
|
|
374
|
+
raise UnsafeRedirectError("redirect refused: missing redirect target")
|
|
375
|
+
raw_split = urllib.parse.urlsplit(newurl.strip())
|
|
376
|
+
if raw_split.scheme.lower() in ("http", "https") and not raw_split.hostname:
|
|
377
|
+
raise UnsafeRedirectError("redirect refused: missing target host")
|
|
378
|
+
resolved = urllib.parse.urljoin(req.full_url, newurl)
|
|
379
|
+
validate_redirect_url(
|
|
380
|
+
resolved,
|
|
381
|
+
source_url=req.full_url,
|
|
382
|
+
allow_insecure_loopback=self.allow_loopback(),
|
|
383
|
+
)
|
|
384
|
+
redirected = super().redirect_request(req, fp, code, msg, headers, resolved)
|
|
385
|
+
if redirected is None:
|
|
386
|
+
return None
|
|
387
|
+
redirected.__dict__["_safe_redirect_hops"] = hops + 1
|
|
388
|
+
if url_origin(req.full_url) != url_origin(resolved):
|
|
389
|
+
for bag in (redirected.headers, redirected.unredirected_hdrs):
|
|
390
|
+
for key in list(bag.keys()):
|
|
391
|
+
if key.lower() in SENSITIVE_REDIRECT_HEADERS:
|
|
392
|
+
del bag[key]
|
|
393
|
+
return redirected
|
|
@@ -15,13 +15,17 @@ from typing import Any
|
|
|
15
15
|
|
|
16
16
|
from localmodels import (
|
|
17
17
|
http_local,
|
|
18
|
+
pi_profile,
|
|
18
19
|
runtime_auth,
|
|
19
20
|
runtime_discovery,
|
|
20
21
|
runtime_install,
|
|
21
22
|
runtime_pi,
|
|
22
23
|
runtime_process,
|
|
23
24
|
)
|
|
24
|
-
from localmodels.
|
|
25
|
+
from localmodels.harness_core import load_lock
|
|
26
|
+
from localmodels.pi_profile import PROFILE_DIRS as PROFILE_DIRS
|
|
27
|
+
from localmodels.pi_profile import PROFILE_KEYS as PROFILE_KEYS
|
|
28
|
+
from localmodels.pi_profile import RUNTIMES as RUNTIMES
|
|
25
29
|
from localmodels.runtime_auth import check_config, owned_files, provider_accepted, save_config
|
|
26
30
|
from localmodels.runtime_auth import save_api_key as save_api_key
|
|
27
31
|
from localmodels.runtime_discovery import compatible_version as _compatible_version
|
|
@@ -43,27 +47,16 @@ from localmodels.runtime_releases import codex_release as _codex_release
|
|
|
43
47
|
from localmodels.runtime_releases import resolve as _external_release
|
|
44
48
|
from localmodels.runtime_releases import version_key as _stable_version
|
|
45
49
|
|
|
46
|
-
RUNTIMES = ("codex", "claude", "pi")
|
|
47
50
|
LOCK = Path(__file__).with_name("runtime-lock.json")
|
|
48
|
-
PROFILE_KEYS = {"codex": "CODEX_HOME", "claude": "CLAUDE_CONFIG_DIR", "pi": "PI_CODING_AGENT_DIR"}
|
|
49
|
-
PROFILE_DIRS = {"codex": ".codex", "claude": ".claude", "pi": ".pi/agent"}
|
|
50
51
|
platform = runtime_discovery.platform_tag
|
|
51
|
-
_platform = platform
|
|
52
52
|
|
|
53
53
|
|
|
54
54
|
def owned_profile(directory: Path) -> bool:
|
|
55
|
-
|
|
56
|
-
return bool(files) and all(_private_file(directory / name) for name in files)
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
_owned_profile = owned_profile
|
|
55
|
+
return pi_profile.owned_profile(directory)
|
|
60
56
|
|
|
61
57
|
|
|
62
58
|
def active_profile(runtime: str, env: dict[str, str]) -> Path:
|
|
63
|
-
return
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
_active_profile = active_profile
|
|
59
|
+
return pi_profile.active_profile(runtime, env)
|
|
67
60
|
|
|
68
61
|
|
|
69
62
|
def _probe(
|
|
@@ -142,7 +135,7 @@ def _managed_command(root: Path, runtime: str, node: str | None = None) -> list[
|
|
|
142
135
|
target = _target(root, runtime)
|
|
143
136
|
if runtime == "pi":
|
|
144
137
|
return [str(target / ("pi.exe" if os.name == "nt" else "pi"))]
|
|
145
|
-
artifacts = _lock()["artifacts"].get(f"{runtime}/{
|
|
138
|
+
artifacts = _lock()["artifacts"].get(f"{runtime}/{platform()}", [])
|
|
146
139
|
return [str(target / artifacts[0]["executable"])] if artifacts else []
|
|
147
140
|
|
|
148
141
|
|
|
@@ -155,9 +148,6 @@ def runtime_env(root: Path, runtime: str) -> dict[str, str]:
|
|
|
155
148
|
return env
|
|
156
149
|
|
|
157
150
|
|
|
158
|
-
_runtime_env = runtime_env
|
|
159
|
-
|
|
160
|
-
|
|
161
151
|
def _credential_ambiguous(
|
|
162
152
|
runtime: str, profile: Path, owned: dict[str, str], env: dict[str, str]
|
|
163
153
|
) -> bool:
|
|
@@ -201,16 +191,16 @@ def _auth(runtime: str, argv: list[str], env: dict[str, str]) -> tuple[bool, str
|
|
|
201
191
|
except (ValueError, AttributeError):
|
|
202
192
|
return False, mode
|
|
203
193
|
# Pi auth check is credential resolvability; provider acceptance is a separate descriptor.
|
|
204
|
-
|
|
205
|
-
|
|
194
|
+
store = pi_profile.PiProfileStore(active_profile("pi", env))
|
|
195
|
+
settings = store.read_regular_settings()
|
|
206
196
|
model: str | None = None
|
|
207
|
-
if
|
|
208
|
-
settings
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
197
|
+
if (
|
|
198
|
+
settings is not None
|
|
199
|
+
and settings.get("defaultProvider") == "localmodels"
|
|
200
|
+
and isinstance(settings.get("defaultModel"), str)
|
|
201
|
+
):
|
|
202
|
+
model = "localmodels/" + settings["defaultModel"]
|
|
203
|
+
mode = "api-key"
|
|
214
204
|
return _pi_native_auth(argv, env, model, mode)
|
|
215
205
|
|
|
216
206
|
|
|
@@ -218,12 +208,8 @@ def _pi_native_auth(
|
|
|
218
208
|
argv: list[str], env: dict[str, str], model: str | None, mode: str | None
|
|
219
209
|
) -> tuple[bool, str | None]:
|
|
220
210
|
selections: list[list[str]] = []
|
|
221
|
-
directory =
|
|
222
|
-
stored = (
|
|
223
|
-
json.loads((directory / "auth.json").read_text())
|
|
224
|
-
if _owned_profile(directory) and (directory / "auth.json").is_file()
|
|
225
|
-
else {}
|
|
226
|
-
)
|
|
211
|
+
directory = active_profile("pi", env)
|
|
212
|
+
stored = pi_profile.PiProfileStore(directory).read_owned_auth(owned=owned_profile(directory))
|
|
227
213
|
provider = next(
|
|
228
214
|
(name for name in ("openai", "anthropic") if stored.get(name, {}).get("type") == "api_key"),
|
|
229
215
|
None,
|
|
@@ -279,12 +265,12 @@ def inspect_runtimes(
|
|
|
279
265
|
hosts = (
|
|
280
266
|
[explicit]
|
|
281
267
|
if explicit is not None
|
|
282
|
-
else runtime_discovery.host_commands(runtime,
|
|
268
|
+
else runtime_discovery.host_commands(runtime, platform())
|
|
283
269
|
)
|
|
284
270
|
commands: list[tuple[str, list[str], str]] = [(host, [], "host") for host in hosts if host]
|
|
285
271
|
if explicit is None:
|
|
286
272
|
managed = _managed_command(root, runtime, node)
|
|
287
|
-
managed_commands = runtime_discovery.managed_commands(root, runtime,
|
|
273
|
+
managed_commands = runtime_discovery.managed_commands(root, runtime, platform())
|
|
288
274
|
if managed and managed not in managed_commands:
|
|
289
275
|
managed_commands.append(managed)
|
|
290
276
|
commands.extend((entry[0], entry[1:], "managed") for entry in managed_commands)
|
|
@@ -322,9 +308,9 @@ def inspect_runtimes(
|
|
|
322
308
|
)
|
|
323
309
|
break
|
|
324
310
|
continue
|
|
325
|
-
env =
|
|
326
|
-
profile =
|
|
327
|
-
managed_profile = profile == root / "runtime" / runtime and
|
|
311
|
+
env = runtime_env(root, runtime)
|
|
312
|
+
profile = active_profile(runtime, env)
|
|
313
|
+
managed_profile = profile == root / "runtime" / runtime and owned_profile(profile)
|
|
328
314
|
owned = owned_files(profile) if managed_profile else {}
|
|
329
315
|
row["providerVerified"] = (
|
|
330
316
|
managed_profile
|
|
@@ -422,7 +408,7 @@ def build_plan(
|
|
|
422
408
|
plan = native_plan(
|
|
423
409
|
runtime,
|
|
424
410
|
root,
|
|
425
|
-
|
|
411
|
+
platform(),
|
|
426
412
|
command=[status["executable"], *status["argvPrefix"]] if status["installed"] else [],
|
|
427
413
|
version=status["version"],
|
|
428
414
|
)
|
|
@@ -434,7 +420,7 @@ def build_plan(
|
|
|
434
420
|
plan["artifactSource"] = "codex-stable-npm"
|
|
435
421
|
if runtime == "pi" and plan["action"] == "install":
|
|
436
422
|
runtime_pi.plan_install(
|
|
437
|
-
plan, lock, node, launcher, before_version, platform=
|
|
423
|
+
plan, lock, node, launcher, before_version, platform=platform(), probe=_probe
|
|
438
424
|
)
|
|
439
425
|
if runtime == "claude" and plan["action"] == "install" and before_version is not None:
|
|
440
426
|
plan["version"], plan["artifacts"] = _external_release(
|
|
@@ -505,7 +491,7 @@ def _validate_plan_artifacts(plan: dict[str, Any]) -> None:
|
|
|
505
491
|
lock = _lock()
|
|
506
492
|
if (
|
|
507
493
|
plan["schema"] != "localmodels.harness-plan/v1"
|
|
508
|
-
or plan["platform"] !=
|
|
494
|
+
or plan["platform"] != platform()
|
|
509
495
|
or plan["lockDigest"] != _lock_digest()
|
|
510
496
|
):
|
|
511
497
|
raise ValueError("Runtime platform or artifact lock changed; create a new plan")
|
|
@@ -525,26 +511,26 @@ def _validate_plan_artifacts(plan: dict[str, Any]) -> None:
|
|
|
525
511
|
or not isinstance(plan["version"], str)
|
|
526
512
|
):
|
|
527
513
|
raise ValueError("Invalid Codex registry plan")
|
|
528
|
-
expected_version, expected_artifacts = _codex_release(
|
|
514
|
+
expected_version, expected_artifacts = _codex_release(platform(), plan["version"])
|
|
529
515
|
elif runtime == "claude" and plan.get("artifactSource") == "claude-stable":
|
|
530
516
|
if plan["action"] != "install" or not isinstance(plan["version"], str):
|
|
531
517
|
raise ValueError("Invalid stable runtime plan")
|
|
532
518
|
expected_version, expected_artifacts = _external_release(
|
|
533
|
-
runtime,
|
|
519
|
+
runtime, platform(), plan["version"]
|
|
534
520
|
)
|
|
535
521
|
elif "artifactSource" not in plan:
|
|
536
522
|
expected_version = lock["versions"].get(runtime)
|
|
537
|
-
expected_artifacts = lock["artifacts"].get(f"{runtime}/{
|
|
523
|
+
expected_artifacts = lock["artifacts"].get(f"{runtime}/{platform()}")
|
|
538
524
|
else:
|
|
539
525
|
raise ValueError("Unknown runtime artifact source")
|
|
540
526
|
if (plan["version"], plan["artifacts"]) != (expected_version, expected_artifacts):
|
|
541
527
|
raise ValueError("Runtime artifact changed; create a new plan")
|
|
542
528
|
if (
|
|
543
529
|
plan.get("nodeArtifact") is not None
|
|
544
|
-
and plan["nodeArtifact"] != lock["node"]["artifacts"].get(
|
|
530
|
+
and plan["nodeArtifact"] != lock["node"]["artifacts"].get(platform())
|
|
545
531
|
) or (
|
|
546
532
|
plan.get("launcherArtifact") is not None
|
|
547
|
-
and plan["launcherArtifact"] != lock["launchers"].get(
|
|
533
|
+
and plan["launcherArtifact"] != lock["launchers"].get(platform())
|
|
548
534
|
):
|
|
549
535
|
raise ValueError("Runtime bootstrap lock changed")
|
|
550
536
|
|
|
@@ -15,7 +15,7 @@ from pathlib import Path
|
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
17
|
from localmodels import runtime_process
|
|
18
|
-
from localmodels.
|
|
18
|
+
from localmodels.harness_core import load_lock
|
|
19
19
|
from localmodels.runtime_discovery import owned_marker as owned_marker
|
|
20
20
|
from localmodels.runtime_install import bootstrap
|
|
21
21
|
from localmodels.runtime_io import rename_with_retry
|
|
@@ -19,6 +19,7 @@ from localmodels import (
|
|
|
19
19
|
harness,
|
|
20
20
|
hosts,
|
|
21
21
|
library_gateway,
|
|
22
|
+
pi_profile,
|
|
22
23
|
runtime_io,
|
|
23
24
|
)
|
|
24
25
|
from localmodels.probe import HostFacts
|
|
@@ -443,22 +444,14 @@ def _write_claude_profile(root: Path, addr: str, context: int) -> str:
|
|
|
443
444
|
|
|
444
445
|
|
|
445
446
|
def _write_pi_profile(root: Path, addr: str, facts: bifrost_models.LlmFacts) -> str:
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
}
|
|
455
|
-
settings_doc = {
|
|
456
|
-
"defaultProvider": gateway_bifrost.PI_PROVIDER,
|
|
457
|
-
"defaultModel": BYOK_MODEL,
|
|
458
|
-
}
|
|
459
|
-
runtime_io.write_private_json(pi_dir / "models.json", models_doc)
|
|
460
|
-
runtime_io.write_private_json(pi_dir / "settings.json", settings_doc)
|
|
461
|
-
return str(pi_dir)
|
|
447
|
+
store = pi_profile.PiProfileStore(root / ".pi" / "agent")
|
|
448
|
+
return str(
|
|
449
|
+
store.write_isolated_profile(
|
|
450
|
+
gateway_bifrost.PI_PROVIDER,
|
|
451
|
+
bifrost_models.pi_provider(facts, BYOK_MODEL, f"http://{addr}"),
|
|
452
|
+
BYOK_MODEL,
|
|
453
|
+
)
|
|
454
|
+
)
|
|
462
455
|
|
|
463
456
|
|
|
464
457
|
def write_byok_profiles(addr: str, creds: ByokCredentials) -> dict[str, str]:
|