@simplexai/localmodels-darwin-arm64 0.1.0-dev.47 → 0.1.0-dev.49
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 +55 -51
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/budget.py +40 -14
- package/modules/localmodels/catalog.json +57 -34
- package/modules/localmodels/debug_mode.py +25 -0
- package/modules/localmodels/deploy.py +3 -0
- package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
- package/modules/localmodels/engines.py +31 -6
- package/modules/localmodels/library_jobs.py +22 -1
- package/modules/localmodels/library_model.py +38 -2
- package/modules/localmodels/library_pricing.py +261 -78
- package/modules/localmodels/library_serve.py +20 -4
- package/modules/localmodels/library_status.py +19 -11
- package/modules/localmodels/library_vram.py +123 -0
- package/modules/localmodels/llm_rank.py +28 -1
- package/modules/localmodels/probe.py +39 -37
- package/modules/localmodels/process_identity.py +26 -33
- package/modules/localmodels/process_identity_darwin.py +189 -0
- package/modules/localmodels/process_identity_linux.py +62 -30
- package/modules/localmodels/recommend.py +3 -1
- package/modules/localmodels/remote_ops_service.py +15 -46
- package/modules/localmodels/service_probe.py +1 -1
- package/modules/localmodels/setup_inspection.py +14 -1
- package/modules/localmodels/setup_text.py +15 -3
- package/modules/localmodels/setup_upgrade.py +145 -0
- package/modules/localmodels/stack_binding.py +59 -12
- package/modules/localmodels/stack_compose.py +5 -1
- package/modules/localmodels/stack_hardware.py +5 -2
- package/modules/localmodels/stack_route.py +5 -1
- package/modules/localmodels/stack_suite.py +1 -1
- package/modules/localmodels/stack_view_access.py +238 -58
- package/modules/localmodels/stack_view_hub.py +12 -7
- package/modules/localmodels/stack_view_serve.py +13 -6
- package/modules/localmodels/transport.py +3 -1
- package/modules/localmodels/tui.py +4 -1
- package/modules/localmodels/tui_dialogs.py +42 -9
- package/modules/localmodels/tui_modals.py +63 -16
- package/modules/localmodels/tui_screen.py +80 -53
- package/modules/localmodels/tui_views.py +36 -6
- package/modules/localmodels/web/index.html +996 -300
- package/modules/localmodels/web/sizecalc/app.js +616 -88
- package/modules/localmodels/web/sizecalc/page.html +239 -106
- package/modules/localmodels/web/view/fleet.js +25 -2
- package/modules/localmodels/web/view/nav.js +19 -3
- package/modules/localmodels/web/view/view.css +110 -22
- package/modules/localmodels/web/view/view.js +40 -22
- package/modules/localmodels/win_probe.py +187 -0
- package/modules/{simplex_localmodels-0.1.0.dev47.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev47.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/RECORD +52 -48
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev47.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev47.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev47.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev47.dist-info → simplex_localmodels-0.1.0.dev49.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -6,6 +6,7 @@ import hashlib
|
|
|
6
6
|
import json
|
|
7
7
|
import os
|
|
8
8
|
import stat
|
|
9
|
+
import sys
|
|
9
10
|
from pathlib import Path
|
|
10
11
|
from typing import TypedDict, cast
|
|
11
12
|
|
|
@@ -44,6 +45,22 @@ def _windows() -> bool:
|
|
|
44
45
|
return os.name == "nt"
|
|
45
46
|
|
|
46
47
|
|
|
48
|
+
def _same_path(left: str | Path, right: str | Path) -> bool:
|
|
49
|
+
return os.path.normcase(os.path.normpath(os.path.expanduser(str(left)))) == os.path.normcase(
|
|
50
|
+
os.path.normpath(os.path.expanduser(str(right)))
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _same_real_path(left: str | Path, right: str | Path) -> bool:
|
|
55
|
+
return os.path.normcase(os.path.realpath(left)) == os.path.normcase(os.path.realpath(right))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _with_path(env: dict[str, str], prefixes: list[str]) -> dict[str, str]:
|
|
59
|
+
merged = {key: value for key, value in env.items() if key.upper() != "PATH"}
|
|
60
|
+
merged["PATH"] = os.pathsep.join([*prefixes, os.environ.get("PATH", "")])
|
|
61
|
+
return merged
|
|
62
|
+
|
|
63
|
+
|
|
47
64
|
def _reparse_point(info: os.stat_result) -> bool:
|
|
48
65
|
return bool(getattr(info, "st_file_attributes", 0) & _REPARSE_POINT)
|
|
49
66
|
|
|
@@ -197,7 +214,7 @@ def _deployments_ready(
|
|
|
197
214
|
or entry["kind"] != service["kind"]
|
|
198
215
|
# The manifest records the expanded directory (hosts.own_deployment); a plan on
|
|
199
216
|
# the default base directory names it under "~".
|
|
200
|
-
or entry["deploy_dir"]
|
|
217
|
+
or not _same_path(entry["deploy_dir"], service["deploy_dir"])
|
|
201
218
|
or entry["port"] != service["port"]
|
|
202
219
|
):
|
|
203
220
|
return False
|
|
@@ -214,7 +231,7 @@ def _bifrost_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") ->
|
|
|
214
231
|
or record["addr"] != gateway["addr"]
|
|
215
232
|
# an instance still on an earlier pinned binary is not the approved plan until apply
|
|
216
233
|
# restarts it
|
|
217
|
-
or record["binary"]
|
|
234
|
+
or not _same_path(record["binary"], harness.tool_path(plan["harness"], "bifrost"))
|
|
218
235
|
or not owned["pi"]
|
|
219
236
|
or owned["pi"]["model"] != gateway["pi_model"]
|
|
220
237
|
):
|
|
@@ -269,9 +286,9 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
|
|
|
269
286
|
fingerprint = _profile_fingerprint(executable, profile)
|
|
270
287
|
magpie = harness.tool_path(plan["harness"], "magpie")
|
|
271
288
|
env = {
|
|
272
|
-
**
|
|
273
|
-
|
|
274
|
-
[str(executable.parent), str(Path(magpie).parent),
|
|
289
|
+
**_with_path(
|
|
290
|
+
harness.checked_gateway_environment(plan["harness"]),
|
|
291
|
+
[str(executable.parent), str(Path(magpie).parent)],
|
|
275
292
|
),
|
|
276
293
|
"MAGPIE_ADDR": gateway["addr"],
|
|
277
294
|
"PI_CODING_AGENT_DIR": str(profile),
|
|
@@ -287,8 +304,8 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
|
|
|
287
304
|
or state.get("gateway_other_user")
|
|
288
305
|
or not state["pi"]
|
|
289
306
|
or not state["magpie"]
|
|
290
|
-
or
|
|
291
|
-
or
|
|
307
|
+
or not _same_real_path(state["magpie"], magpie)
|
|
308
|
+
or not _same_real_path(state["pi"], executable)
|
|
292
309
|
or state["pi_model"] != gateway["pi_model"]
|
|
293
310
|
):
|
|
294
311
|
return _reason("gateway-unavailable", lang)
|
|
@@ -311,11 +328,14 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
|
|
|
311
328
|
def _stack_installed(plan: StackPlan, owned: hosts.Owned) -> bool:
|
|
312
329
|
"""The Node.js and pi the plan installed are still in the manifest: ``stack remove``
|
|
313
330
|
deletes them and drops them from it. A tool the plan reused is no anchor."""
|
|
314
|
-
paths = [
|
|
331
|
+
paths = [
|
|
332
|
+
Path(os.path.normcase(os.path.normpath(os.path.expanduser(t["path"]))))
|
|
333
|
+
for t in owned["tools"]
|
|
334
|
+
]
|
|
315
335
|
for tool in plan["harness"]["tools"]:
|
|
316
336
|
if tool["action"] != "install" or tool["tool"] not in ("node", "pi"):
|
|
317
337
|
continue
|
|
318
|
-
wanted = Path(os.path.expanduser(tool["path"]))
|
|
338
|
+
wanted = Path(os.path.normcase(os.path.normpath(os.path.expanduser(tool["path"]))))
|
|
319
339
|
if not any(wanted == path or path in wanted.parents for path in paths):
|
|
320
340
|
return False
|
|
321
341
|
return True
|
|
@@ -359,8 +379,10 @@ def _library_binding(
|
|
|
359
379
|
return _reason("gateway-ownership", lang)
|
|
360
380
|
magpie = harness.tool_path(plan["harness"], "magpie")
|
|
361
381
|
env = {
|
|
362
|
-
**
|
|
363
|
-
|
|
382
|
+
**_with_path(
|
|
383
|
+
harness.checked_gateway_environment(plan["harness"]),
|
|
384
|
+
[str(Path(magpie).parent)],
|
|
385
|
+
),
|
|
364
386
|
"MAGPIE_ADDR": gateway["addr"],
|
|
365
387
|
}
|
|
366
388
|
state = harness.inspect(
|
|
@@ -380,6 +402,23 @@ def _library_binding(
|
|
|
380
402
|
}
|
|
381
403
|
|
|
382
404
|
|
|
405
|
+
def _diagnose_unavailable(exc: Exception) -> None:
|
|
406
|
+
"""Emit one fixed-category stderr line without paths, secrets, or raw exception text."""
|
|
407
|
+
if isinstance(exc, harness.HarnessError):
|
|
408
|
+
cause = "harness-error"
|
|
409
|
+
elif isinstance(exc, FileNotFoundError):
|
|
410
|
+
cause = "profile-missing"
|
|
411
|
+
elif isinstance(exc, PermissionError):
|
|
412
|
+
cause = "profile-permission"
|
|
413
|
+
elif isinstance(exc, ValueError):
|
|
414
|
+
cause = "profile-invalid"
|
|
415
|
+
elif isinstance(exc, KeyError):
|
|
416
|
+
cause = "environment-missing"
|
|
417
|
+
else:
|
|
418
|
+
cause = type(exc).__name__.lower()
|
|
419
|
+
print(f"localmodels setup binding: unavailable cause={cause}", file=sys.stderr)
|
|
420
|
+
|
|
421
|
+
|
|
383
422
|
def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
|
|
384
423
|
report: BindingReport = {
|
|
385
424
|
"schema": "localmodels.stack-binding/v1",
|
|
@@ -421,6 +460,14 @@ def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
|
|
|
421
460
|
else:
|
|
422
461
|
report["ready"] = True
|
|
423
462
|
report["pi"] = binding
|
|
424
|
-
except (
|
|
463
|
+
except (
|
|
464
|
+
OSError,
|
|
465
|
+
ValueError,
|
|
466
|
+
KeyError,
|
|
467
|
+
StopIteration,
|
|
468
|
+
AttributeError,
|
|
469
|
+
harness.HarnessError,
|
|
470
|
+
) as exc:
|
|
471
|
+
_diagnose_unavailable(exc)
|
|
425
472
|
report["reasons"] = [_reason("binding-unavailable", lang)]
|
|
426
473
|
return report
|
|
@@ -382,7 +382,11 @@ def _no_fit_reason(
|
|
|
382
382
|
if mac or not gpus:
|
|
383
383
|
return ""
|
|
384
384
|
if not cards:
|
|
385
|
-
eligible = [
|
|
385
|
+
eligible = [
|
|
386
|
+
p
|
|
387
|
+
for p in placements(facts)
|
|
388
|
+
if not p.pooled and not p.budget.uma and len(p.gpu_indices) == 1
|
|
389
|
+
]
|
|
386
390
|
if not eligible:
|
|
387
391
|
return ": no supported single-card GPU placement"
|
|
388
392
|
if not all(p.conflicts for p in eligible):
|
|
@@ -140,8 +140,11 @@ def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False)
|
|
|
140
140
|
raise StackError(f"this computer has one Metal GPU (GPU 0), no GPU {gpu}")
|
|
141
141
|
return [0]
|
|
142
142
|
by_free = {g["index"]: g["free_bytes"] for g in facts.get("gpus") or []}
|
|
143
|
-
singles = [
|
|
144
|
-
|
|
143
|
+
singles = [
|
|
144
|
+
p
|
|
145
|
+
for p in placements(facts, planning=True)
|
|
146
|
+
if not p.pooled and not p.budget.uma and len(p.gpu_indices) == 1
|
|
147
|
+
]
|
|
145
148
|
if gpu is not None:
|
|
146
149
|
if not any(p.gpu_indices == (gpu,) for p in singles):
|
|
147
150
|
found = ", ".join(str(p.gpu_indices[0]) for p in singles) or "none"
|
|
@@ -191,7 +191,11 @@ def reads_images(part: Plan) -> bool:
|
|
|
191
191
|
|
|
192
192
|
|
|
193
193
|
def _target_vram(facts: HostFacts, placement: str, primary: Plan) -> int:
|
|
194
|
-
candidates = [
|
|
194
|
+
candidates = [
|
|
195
|
+
p
|
|
196
|
+
for p in placements(facts, planning=True)
|
|
197
|
+
if not p.pooled and not p.budget.uma and p.gpu_indices
|
|
198
|
+
]
|
|
195
199
|
if placement != "auto":
|
|
196
200
|
matched = [p for p in candidates if p.id == placement]
|
|
197
201
|
return max((p.budget.total_device_bytes for p in matched), default=0)
|
|
@@ -193,7 +193,7 @@ def auto_strata_candidates(facts: HostFacts, at_least: int) -> list[suite.SuiteR
|
|
|
193
193
|
and total >= r.get("min_ram_total_bytes", 0)
|
|
194
194
|
and built_for(r, facts["platform"])
|
|
195
195
|
]
|
|
196
|
-
return sorted(found, key=lambda r: -r["quality"]["score"])
|
|
196
|
+
return sorted(found, key=lambda r: (-r["quality"]["score"], -r.get("vram_bytes", 0)))
|
|
197
197
|
|
|
198
198
|
|
|
199
199
|
def strata_recipe(facts: HostFacts, requested: str) -> tuple[suite.SuiteRecipe | None, list[str]]:
|
|
@@ -20,13 +20,102 @@ import os
|
|
|
20
20
|
import re
|
|
21
21
|
import secrets
|
|
22
22
|
import socket
|
|
23
|
+
from collections.abc import Callable, Mapping
|
|
24
|
+
from http import HTTPStatus
|
|
23
25
|
from http.cookies import SimpleCookie
|
|
26
|
+
from http.server import BaseHTTPRequestHandler
|
|
27
|
+
from typing import Any
|
|
24
28
|
from urllib.parse import parse_qs, unquote, urlencode, urlsplit, urlunsplit
|
|
25
29
|
|
|
26
30
|
KEY_ENV = "LOCALMODELS_VIEW_KEY"
|
|
27
31
|
COOKIE = "lm_view_key"
|
|
28
32
|
KEY_SHAPE = re.compile(r"^[A-Za-z0-9._~-]{16,128}$")
|
|
29
33
|
LOOPBACK = ("127.0.0.1", "localhost", "::1")
|
|
34
|
+
GATE_POST_MAX = 4096
|
|
35
|
+
GATE_FAVICON_HREF = (
|
|
36
|
+
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E"
|
|
37
|
+
"%3Crect width='64' height='64' rx='14' fill='%231c1c21'/%3E"
|
|
38
|
+
"%3Cg fill='none' stroke-linejoin='round' stroke-width='3.6'%3E"
|
|
39
|
+
"%3Cpath d='M32 12 13 21.5 32 31l19-9.5L32 12Z' stroke='%238b85ff' fill='%238b85ff' "
|
|
40
|
+
"fill-opacity='.18'/%3E"
|
|
41
|
+
"%3Cpath d='m13 32 19 9.5L51 32' stroke='%232dd4bf'/%3E"
|
|
42
|
+
"%3Cpath d='m13 42 19 9.5L51 42' stroke='%23fb923c'/%3E%3C/g%3E%3C/svg%3E"
|
|
43
|
+
)
|
|
44
|
+
GATE_BRAND_SVG = (
|
|
45
|
+
'<svg class="brand-ic" width="24" height="24" viewBox="0 0 64 64" aria-hidden="true">'
|
|
46
|
+
'<rect width="64" height="64" rx="14" fill="#1c1c21"/>'
|
|
47
|
+
'<g fill="none" stroke-linejoin="round" stroke-width="3.6">'
|
|
48
|
+
'<path d="M32 12 13 21.5 32 31l19-9.5L32 12Z" stroke="#8b85ff" fill="#8b85ff" '
|
|
49
|
+
'fill-opacity=".18"/>'
|
|
50
|
+
'<path d="m13 32 19 9.5L51 32" stroke="#2dd4bf"/>'
|
|
51
|
+
'<path d="m13 42 19 9.5L51 42" stroke="#fb923c"/></g></svg>'
|
|
52
|
+
)
|
|
53
|
+
GATE_STYLE_BODY = """* { box-sizing: border-box; }
|
|
54
|
+
body {
|
|
55
|
+
margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 20px;
|
|
56
|
+
background: var(--bg); color: var(--fg);
|
|
57
|
+
font: 13px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui,
|
|
58
|
+
"PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
|
59
|
+
-webkit-font-smoothing: antialiased;
|
|
60
|
+
}
|
|
61
|
+
main {
|
|
62
|
+
width: 100%; max-width: 432px; padding: 22px; border-radius: 12px;
|
|
63
|
+
background: var(--card); border: 1px solid var(--line); box-shadow: var(--shadow);
|
|
64
|
+
}
|
|
65
|
+
.brand-head { display: flex; align-items: center; gap: 10px; margin: 0 0 10px; }
|
|
66
|
+
.brand-ic { width: 24px; height: 24px; flex: none; display: block; }
|
|
67
|
+
h1 { margin: 0; font-size: 16px; font-weight: 650; line-height: 1.3; }
|
|
68
|
+
p { margin: 0 0 16px; color: var(--fg-2); }
|
|
69
|
+
label { display: block; margin-bottom: 6px; font-weight: 600; color: var(--fg); }
|
|
70
|
+
.row { display: flex; gap: 8px; }
|
|
71
|
+
input[type="password"] {
|
|
72
|
+
flex: 1; min-width: 0; height: 38px; padding: 0 12px; border-radius: 8px;
|
|
73
|
+
border: 1px solid var(--line); background: var(--bg); color: var(--fg); font: inherit;
|
|
74
|
+
}
|
|
75
|
+
input[type="password"][aria-invalid="true"] {
|
|
76
|
+
border-color: color-mix(in srgb, var(--bad) 70%, var(--line));
|
|
77
|
+
}
|
|
78
|
+
input[type="password"]:focus-visible, button:focus-visible, a:focus-visible {
|
|
79
|
+
outline: 2px solid var(--accent); outline-offset: 2px;
|
|
80
|
+
}
|
|
81
|
+
button {
|
|
82
|
+
height: 38px; padding: 0 16px; border: 0; border-radius: 8px; cursor: pointer;
|
|
83
|
+
white-space: nowrap; flex-shrink: 0;
|
|
84
|
+
background: var(--accent); color: var(--accent-fg); font: inherit; font-weight: 600;
|
|
85
|
+
transition: background 0.15s ease, transform 0.08s ease;
|
|
86
|
+
}
|
|
87
|
+
button:hover { background: var(--accent-hover); }
|
|
88
|
+
button:active { transform: translateY(0.5px); }
|
|
89
|
+
.err {
|
|
90
|
+
margin: 0 0 14px; padding: 9px 11px; border-radius: 8px;
|
|
91
|
+
border: 1px solid color-mix(in srgb, var(--bad) 45%, var(--line));
|
|
92
|
+
background: color-mix(in srgb, var(--bad) 8%, var(--card)); color: var(--bad);
|
|
93
|
+
}
|
|
94
|
+
.reload-box {
|
|
95
|
+
margin: 18px 0 0; padding: 12px 14px; border-radius: 10px;
|
|
96
|
+
border: 1px solid var(--line); background: var(--bg);
|
|
97
|
+
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
|
98
|
+
flex-wrap: wrap;
|
|
99
|
+
}
|
|
100
|
+
.reload-copy {
|
|
101
|
+
flex: 1 1 200px; min-width: 0; display: grid; gap: 2px;
|
|
102
|
+
font-size: 12px; color: var(--fg-2);
|
|
103
|
+
}
|
|
104
|
+
.reload-copy strong { font-size: 12.5px; font-weight: 600; color: var(--fg); }
|
|
105
|
+
.reload-btn {
|
|
106
|
+
display: inline-flex; align-items: center; justify-content: center;
|
|
107
|
+
height: 32px; padding: 0 12px; border-radius: 7px; flex: none;
|
|
108
|
+
border: 1px solid var(--line); background: var(--card); color: var(--fg);
|
|
109
|
+
font-size: 12.5px; font-weight: 600; text-decoration: none; white-space: nowrap;
|
|
110
|
+
transition: border-color 0.15s ease, background 0.15s ease;
|
|
111
|
+
}
|
|
112
|
+
.reload-btn:hover {
|
|
113
|
+
border-color: var(--accent);
|
|
114
|
+
background: color-mix(in srgb, var(--accent) 8%, var(--card));
|
|
115
|
+
}
|
|
116
|
+
@media (prefers-reduced-motion: reduce) {
|
|
117
|
+
*, *::before, *::after { animation: none !important; transition: none !important; }
|
|
118
|
+
}"""
|
|
30
119
|
|
|
31
120
|
|
|
32
121
|
class ViewKeyError(ValueError):
|
|
@@ -69,8 +158,16 @@ class Gate:
|
|
|
69
158
|
return True
|
|
70
159
|
return self._matches(self.offered(path, cookie))
|
|
71
160
|
|
|
161
|
+
@staticmethod
|
|
162
|
+
def _strip_key(value: str) -> str:
|
|
163
|
+
return value.strip()
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _query_key(path: str) -> str:
|
|
167
|
+
return Gate._strip_key(parse_qs(urlsplit(path).query).get("k", [""])[0])
|
|
168
|
+
|
|
72
169
|
def offered(self, path: str, cookie: str | None) -> str:
|
|
73
|
-
query =
|
|
170
|
+
query = self._query_key(path)
|
|
74
171
|
if query:
|
|
75
172
|
return query
|
|
76
173
|
jar = SimpleCookie()
|
|
@@ -86,12 +183,17 @@ class Gate:
|
|
|
86
183
|
offered.encode(), str(self.key).encode()
|
|
87
184
|
)
|
|
88
185
|
|
|
89
|
-
def
|
|
90
|
-
"""The Set-Cookie value when
|
|
91
|
-
|
|
186
|
+
def set_cookie_for(self, offered: str) -> str | None:
|
|
187
|
+
"""The Set-Cookie value when ``offered`` matches this gate's key."""
|
|
188
|
+
cleaned = self._strip_key(offered)
|
|
189
|
+
if self.key is None or not self._matches(cleaned):
|
|
92
190
|
return None
|
|
93
191
|
return f"{COOKIE}={self.key}; Path=/; HttpOnly; SameSite=Strict; Max-Age=34560000"
|
|
94
192
|
|
|
193
|
+
def set_cookie(self, path: str) -> str | None:
|
|
194
|
+
"""The Set-Cookie value when this request brought the key in its query."""
|
|
195
|
+
return self.set_cookie_for(self._query_key(path))
|
|
196
|
+
|
|
95
197
|
@staticmethod
|
|
96
198
|
def clean_path(path: str) -> str:
|
|
97
199
|
"""The same address without ``k``, for the redirect that takes the key out of the bar."""
|
|
@@ -110,36 +212,130 @@ class Gate:
|
|
|
110
212
|
name, sep, tail = clean[3:].partition("/")
|
|
111
213
|
decoded = unquote(name)
|
|
112
214
|
return bool(
|
|
113
|
-
|
|
114
|
-
and name
|
|
215
|
+
name
|
|
115
216
|
and "/" not in decoded
|
|
116
217
|
and decoded not in (".", "..")
|
|
117
|
-
and tail in ("", "index.html")
|
|
218
|
+
and (not sep or tail in ("", "index.html"))
|
|
118
219
|
)
|
|
119
220
|
return False
|
|
120
221
|
|
|
121
222
|
|
|
122
|
-
def
|
|
223
|
+
def read_gate_post(headers: Any, stream: Any, path: str) -> tuple[str, str, bool]:
|
|
224
|
+
"""Read a bounded URL-encoded LAN gate POST body.
|
|
225
|
+
|
|
226
|
+
Returns ``(offered_key, clean_target_path, oversized)``. Non-``k`` query parameters on
|
|
227
|
+
``path`` and hidden form fields in the body are preserved on ``clean_target_path``.
|
|
228
|
+
"""
|
|
229
|
+
clean = Gate.clean_path(path)
|
|
230
|
+
raw_len = (headers.get("Content-Length") or "").strip()
|
|
231
|
+
try:
|
|
232
|
+
length = int(raw_len) if raw_len else 0
|
|
233
|
+
except ValueError:
|
|
234
|
+
return "", clean, False
|
|
235
|
+
if length < 0 or length > GATE_POST_MAX:
|
|
236
|
+
return "", clean, length > GATE_POST_MAX
|
|
237
|
+
content_type = (headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()
|
|
238
|
+
if length > 0 and content_type not in ("", "application/x-www-form-urlencoded"):
|
|
239
|
+
return "", clean, False
|
|
240
|
+
raw = stream.read(length) if length > 0 else b""
|
|
241
|
+
form = parse_qs(raw.decode("utf-8", errors="replace"), keep_blank_values=True)
|
|
242
|
+
offered = Gate._strip_key(form.get("k", [""])[0])
|
|
243
|
+
parts = urlsplit(path)
|
|
244
|
+
path_params = [
|
|
245
|
+
(k, v)
|
|
246
|
+
for k, vs in parse_qs(parts.query, keep_blank_values=True).items()
|
|
247
|
+
if k != "k"
|
|
248
|
+
for v in vs
|
|
249
|
+
]
|
|
250
|
+
seen_keys = {k for k, _ in path_params}
|
|
251
|
+
extra_params = [(k, v) for k, vs in form.items() if k != "k" and k not in seen_keys for v in vs]
|
|
252
|
+
target = (
|
|
253
|
+
urlunsplit(("", "", parts.path or "/", urlencode([*path_params, *extra_params]), "")) or "/"
|
|
254
|
+
)
|
|
255
|
+
return offered, target, False
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def send_method_not_allowed(
|
|
259
|
+
handler: BaseHTTPRequestHandler,
|
|
260
|
+
headers_out: Mapping[str, str],
|
|
261
|
+
allow: str = "GET",
|
|
262
|
+
) -> None:
|
|
263
|
+
"""Answer a disallowed HTTP method with 405 and an explicit Allow header."""
|
|
264
|
+
body = b"method not allowed\n"
|
|
265
|
+
handler.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
|
|
266
|
+
handler.send_header("Allow", allow)
|
|
267
|
+
handler.send_header("Content-Type", "text/plain; charset=utf-8")
|
|
268
|
+
handler.send_header("Content-Length", str(len(body)))
|
|
269
|
+
handler.send_header("Cache-Control", "no-store")
|
|
270
|
+
for name, value in headers_out.items():
|
|
271
|
+
handler.send_header(name, value)
|
|
272
|
+
handler.end_headers()
|
|
273
|
+
handler.wfile.write(body)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def send_cookie_redirect(
|
|
277
|
+
handler: BaseHTTPRequestHandler,
|
|
278
|
+
cookie: str,
|
|
279
|
+
location: str,
|
|
280
|
+
headers_out: Mapping[str, str],
|
|
281
|
+
) -> None:
|
|
282
|
+
"""Trade an offered key for an HttpOnly cookie and redirect to the clean path."""
|
|
283
|
+
handler.send_response(HTTPStatus.SEE_OTHER)
|
|
284
|
+
handler.send_header("Set-Cookie", cookie)
|
|
285
|
+
handler.send_header("Location", location)
|
|
286
|
+
handler.send_header("Cache-Control", "no-store")
|
|
287
|
+
handler.send_header("Content-Length", "0")
|
|
288
|
+
for name, value in headers_out.items():
|
|
289
|
+
handler.send_header(name, value)
|
|
290
|
+
handler.end_headers()
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def handle_gate_post(
|
|
294
|
+
handler: BaseHTTPRequestHandler,
|
|
295
|
+
gate: Gate,
|
|
296
|
+
title: str,
|
|
297
|
+
headers_out: Mapping[str, str],
|
|
298
|
+
*,
|
|
299
|
+
render_denied: Callable[[str], bytes] | None = None,
|
|
300
|
+
) -> None:
|
|
301
|
+
"""Accept POST key submission only on HTML gate paths; refuse all others with 405."""
|
|
302
|
+
if not gate.wants_html_gate(handler.path):
|
|
303
|
+
send_method_not_allowed(handler, headers_out)
|
|
304
|
+
return
|
|
305
|
+
offered, target, oversized = read_gate_post(handler.headers, handler.rfile, handler.path)
|
|
306
|
+
if oversized:
|
|
307
|
+
handler.close_connection = True
|
|
308
|
+
if cookie := gate.set_cookie_for(offered):
|
|
309
|
+
send_cookie_redirect(handler, cookie, target, headers_out)
|
|
310
|
+
return
|
|
311
|
+
body = render_denied(target) if render_denied else gate_page(title, target, wrong=True)
|
|
312
|
+
handler.send_response(HTTPStatus.FORBIDDEN)
|
|
313
|
+
handler.send_header("Content-Type", "text/html; charset=utf-8")
|
|
314
|
+
handler.send_header("Content-Length", str(len(body)))
|
|
315
|
+
handler.send_header("Cache-Control", "no-store")
|
|
316
|
+
for name, value in headers_out.items():
|
|
317
|
+
handler.send_header(name, value)
|
|
318
|
+
handler.end_headers()
|
|
319
|
+
handler.wfile.write(body)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def gate_page(title: str, path: str, *, wrong: bool = False) -> bytes:
|
|
123
323
|
"""A self-contained, script-free HTML form that exchanges the LAN view key for a cookie."""
|
|
124
324
|
parts = urlsplit(path)
|
|
125
325
|
query = parse_qs(parts.query, keep_blank_values=True)
|
|
126
326
|
clean = Gate.clean_path(path)
|
|
127
|
-
clean_parts = urlsplit(clean)
|
|
128
327
|
escaped_title = html.escape(title)
|
|
129
328
|
escaped_clean = html.escape(clean, quote=True)
|
|
130
|
-
|
|
131
|
-
f'<input type="hidden" name="{html.escape(k, quote=True)}" '
|
|
132
|
-
f'value="{html.escape(v, quote=True)}">'
|
|
133
|
-
for k, vs in parse_qs(clean_parts.query, keep_blank_values=True).items()
|
|
134
|
-
for v in vs
|
|
135
|
-
)
|
|
329
|
+
has_error = wrong or ("k" in query)
|
|
136
330
|
alert = (
|
|
137
|
-
'<p class="err" role="alert">'
|
|
138
|
-
"That view key was not accepted. Check the key printed in the server terminal
|
|
331
|
+
'<p id="gate-err" class="err" role="alert">'
|
|
332
|
+
"That view key was not accepted. Check the key printed in the server terminal "
|
|
333
|
+
"or configured for view hub, and try again."
|
|
139
334
|
"</p>\n"
|
|
140
|
-
if
|
|
335
|
+
if has_error
|
|
141
336
|
else ""
|
|
142
337
|
)
|
|
338
|
+
err_attrs = ' aria-invalid="true" aria-describedby="gate-err"' if has_error else ""
|
|
143
339
|
body = f"""<!doctype html>
|
|
144
340
|
<html lang="en">
|
|
145
341
|
<head>
|
|
@@ -147,64 +343,48 @@ def gate_page(title: str, path: str) -> bytes:
|
|
|
147
343
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
148
344
|
<meta name="color-scheme" content="light dark">
|
|
149
345
|
<title>{escaped_title}</title>
|
|
346
|
+
<link rel="icon" type="image/svg+xml" href="{GATE_FAVICON_HREF}">
|
|
150
347
|
<style>
|
|
151
348
|
:root {{
|
|
152
349
|
color-scheme: light dark;
|
|
153
350
|
--bg: #f4f4f6; --fg: #1c1c21; --fg-2: #4a4a53; --muted: #5e5e68;
|
|
154
|
-
--line: #e3e3e8; --card: #ffffff; --accent: #4f46e5; --accent-
|
|
351
|
+
--line: #e3e3e8; --card: #ffffff; --accent: #4f46e5; --accent-hover: #4338ca;
|
|
352
|
+
--accent-fg: #ffffff; --bad: #d70015;
|
|
353
|
+
--shadow: 0 16px 44px rgba(20, 22, 30, 0.14), 0 2px 8px rgba(20, 22, 30, 0.06),
|
|
354
|
+
0 0 0 0.5px rgba(20, 22, 30, 0.08);
|
|
155
355
|
}}
|
|
156
356
|
@media (prefers-color-scheme: dark) {{
|
|
157
357
|
:root {{
|
|
158
|
-
--bg: #
|
|
159
|
-
--line: #34343a; --card: #
|
|
358
|
+
--bg: #121215; --fg: #ececf0; --fg-2: #c2c2c9; --muted: #aaaab4;
|
|
359
|
+
--line: #34343a; --card: #1b1b1e; --accent: #9b95ff; --accent-hover: #b2adff;
|
|
360
|
+
--accent-fg: #121215; --bad: #fb7185;
|
|
361
|
+
--shadow: 0 16px 44px rgba(0, 0, 0, 0.5), 0 0 0 0.5px rgba(255, 255, 255, 0.08);
|
|
160
362
|
}}
|
|
161
363
|
}}
|
|
162
|
-
|
|
163
|
-
body {{
|
|
164
|
-
margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 20px;
|
|
165
|
-
background: var(--bg); color: var(--fg);
|
|
166
|
-
font: 13px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif;
|
|
167
|
-
}}
|
|
168
|
-
main {{
|
|
169
|
-
width: 100%; max-width: 420px; padding: 20px; border-radius: 12px;
|
|
170
|
-
background: var(--card); border: 1px solid var(--line);
|
|
171
|
-
}}
|
|
172
|
-
h1 {{ margin: 0 0 8px; font-size: 16px; font-weight: 650; }}
|
|
173
|
-
p {{ margin: 0 0 14px; color: var(--fg-2); }}
|
|
174
|
-
label {{ display: block; margin-bottom: 6px; font-weight: 600; color: var(--fg); }}
|
|
175
|
-
.row {{ display: flex; gap: 8px; }}
|
|
176
|
-
input[type="password"] {{
|
|
177
|
-
flex: 1; min-width: 0; height: 34px; padding: 0 10px; border-radius: 8px;
|
|
178
|
-
border: 1px solid var(--line); background: var(--bg); color: var(--fg); font: inherit;
|
|
179
|
-
}}
|
|
180
|
-
input[type="password"]:focus-visible, button:focus-visible, a:focus-visible {{
|
|
181
|
-
outline: 2px solid var(--accent); outline-offset: 2px;
|
|
182
|
-
}}
|
|
183
|
-
button {{
|
|
184
|
-
height: 34px; padding: 0 14px; border: 0; border-radius: 8px; cursor: pointer;
|
|
185
|
-
background: var(--accent); color: var(--accent-fg); font: inherit; font-weight: 600;
|
|
186
|
-
}}
|
|
187
|
-
.err {{
|
|
188
|
-
margin: 0 0 14px; padding: 8px 10px; border-radius: 8px;
|
|
189
|
-
border: 1px solid color-mix(in srgb, var(--bad) 45%, var(--line));
|
|
190
|
-
background: color-mix(in srgb, var(--bad) 8%, var(--card)); color: var(--bad);
|
|
191
|
-
}}
|
|
192
|
-
.hint {{ margin: 14px 0 0; font-size: 12px; color: var(--muted); }}
|
|
193
|
-
.hint a {{ color: var(--accent); }}
|
|
364
|
+
{GATE_STYLE_BODY}
|
|
194
365
|
</style>
|
|
195
366
|
</head>
|
|
196
367
|
<body>
|
|
197
368
|
<main>
|
|
369
|
+
<div class="brand-head">
|
|
370
|
+
{GATE_BRAND_SVG}
|
|
198
371
|
<h1>{escaped_title}</h1>
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
{
|
|
372
|
+
</div>
|
|
373
|
+
<p>Enter the view key for this server (printed with --lan or configured for view hub).</p>
|
|
374
|
+
{alert}<form method="post" action="{escaped_clean}">
|
|
375
|
+
<label for="view-key">View key</label>
|
|
202
376
|
<div class="row">
|
|
203
|
-
<input id="view-key" name="k" type="password" required autofocus autocomplete="
|
|
377
|
+
<input id="view-key" name="k" type="password" required autofocus spellcheck="false" autocapitalize="off" autocomplete="off"{err_attrs}>
|
|
204
378
|
<button type="submit">Open</button>
|
|
205
379
|
</div>
|
|
206
380
|
</form>
|
|
207
|
-
<
|
|
381
|
+
<div class="reload-box">
|
|
382
|
+
<div class="reload-copy">
|
|
383
|
+
<strong>Opened from another app?</strong>
|
|
384
|
+
<span>If this browser already saved the view key, reload once with your cookie instead of re-entering it.</span>
|
|
385
|
+
</div>
|
|
386
|
+
<a class="reload-btn" href="{escaped_clean}">Reload on this site</a>
|
|
387
|
+
</div>
|
|
208
388
|
</main>
|
|
209
389
|
</body>
|
|
210
390
|
</html>
|
|
@@ -40,7 +40,15 @@ from urllib.parse import urlsplit
|
|
|
40
40
|
|
|
41
41
|
from localmodels import hosts, http_local, stack_view_text
|
|
42
42
|
from localmodels.stack_view import SCHEMA, StackView
|
|
43
|
-
from localmodels.stack_view_access import
|
|
43
|
+
from localmodels.stack_view_access import (
|
|
44
|
+
KEY_ENV,
|
|
45
|
+
Gate,
|
|
46
|
+
gate_page,
|
|
47
|
+
handle_gate_post,
|
|
48
|
+
lan_addresses,
|
|
49
|
+
run_key,
|
|
50
|
+
send_cookie_redirect,
|
|
51
|
+
)
|
|
44
52
|
from localmodels.stack_view_serve import (
|
|
45
53
|
FILES,
|
|
46
54
|
FORBIDDEN,
|
|
@@ -446,7 +454,8 @@ class HubHandler(BaseHTTPRequestHandler):
|
|
|
446
454
|
|
|
447
455
|
def do_POST(self) -> None:
|
|
448
456
|
if urlsplit(self.path).path != "/api/push":
|
|
449
|
-
|
|
457
|
+
handle_gate_post(self, self.gate, "localmodels - view hub", self.headers_out)
|
|
458
|
+
return
|
|
450
459
|
scheme, _, token = (self.headers.get("Authorization") or "").partition(" ")
|
|
451
460
|
name = self.fleet.registry.who(token.strip()) if scheme == "Bearer" and token else None
|
|
452
461
|
if name is None:
|
|
@@ -470,11 +479,7 @@ class HubHandler(BaseHTTPRequestHandler):
|
|
|
470
479
|
)
|
|
471
480
|
return self._send(HTTPStatus.FORBIDDEN, FORBIDDEN, "text/plain; charset=utf-8")
|
|
472
481
|
if cookie := self.gate.set_cookie(self.path):
|
|
473
|
-
self.
|
|
474
|
-
self.send_header("Set-Cookie", cookie)
|
|
475
|
-
self.send_header("Location", self.gate.clean_path(self.path))
|
|
476
|
-
self.send_header("Content-Length", "0")
|
|
477
|
-
self.end_headers()
|
|
482
|
+
send_cookie_redirect(self, cookie, self.gate.clean_path(self.path), self.headers_out)
|
|
478
483
|
return
|
|
479
484
|
path = urlsplit(self.path).path
|
|
480
485
|
if path == "/h" or path.startswith("/h/"):
|
|
@@ -36,7 +36,15 @@ from urllib.parse import parse_qs, urlsplit
|
|
|
36
36
|
from localmodels import hosts, stack_view, stack_view_demo, stack_view_sandbox, stack_view_text
|
|
37
37
|
from localmodels.stack_plan import Hardware
|
|
38
38
|
from localmodels.stack_view import Reading
|
|
39
|
-
from localmodels.stack_view_access import
|
|
39
|
+
from localmodels.stack_view_access import (
|
|
40
|
+
KEY_ENV,
|
|
41
|
+
Gate,
|
|
42
|
+
gate_page,
|
|
43
|
+
handle_gate_post,
|
|
44
|
+
lan_addresses,
|
|
45
|
+
run_key,
|
|
46
|
+
send_cookie_redirect,
|
|
47
|
+
)
|
|
40
48
|
from localmodels.stack_view_events import Event
|
|
41
49
|
|
|
42
50
|
PAGE_DIR = Path(__file__).with_name("web") / "view"
|
|
@@ -260,6 +268,9 @@ def handler_for(
|
|
|
260
268
|
self.end_headers()
|
|
261
269
|
self.wfile.write(body)
|
|
262
270
|
|
|
271
|
+
def do_POST(self) -> None:
|
|
272
|
+
handle_gate_post(self, door, "localmodels - stack", headers)
|
|
273
|
+
|
|
263
274
|
def do_GET(self) -> None:
|
|
264
275
|
peer, host = self.client_address[0], self.headers.get("Host")
|
|
265
276
|
if not door.admit(peer, host, self.path, self.headers.get("Cookie")):
|
|
@@ -273,11 +284,7 @@ def handler_for(
|
|
|
273
284
|
if cookie := door.set_cookie(
|
|
274
285
|
self.path
|
|
275
286
|
): # a ?k= link: keep the key, drop it from the bar
|
|
276
|
-
self.
|
|
277
|
-
self.send_header("Set-Cookie", cookie)
|
|
278
|
-
self.send_header("Location", door.clean_path(self.path))
|
|
279
|
-
self.send_header("Content-Length", "0")
|
|
280
|
-
self.end_headers()
|
|
287
|
+
send_cookie_redirect(self, cookie, door.clean_path(self.path), headers)
|
|
281
288
|
return
|
|
282
289
|
path = urlsplit(self.path).path.strip("/")
|
|
283
290
|
routes: dict[str, Callable[[], None]] = {
|
|
@@ -35,15 +35,17 @@ SSH_OPTIONS = (
|
|
|
35
35
|
# one stdin payload, and an in-memory loader resolves each part as ``localmodels.<stem>`` on the
|
|
36
36
|
# target — the same name it imports as a member of this package.
|
|
37
37
|
BUNDLES = {
|
|
38
|
-
"probe.py": ("metal_probe.py",),
|
|
38
|
+
"probe.py": ("metal_probe.py", "win_probe.py"),
|
|
39
39
|
"service_probe.py": (
|
|
40
40
|
"process_identity.py",
|
|
41
|
+
"process_identity_darwin.py",
|
|
41
42
|
"process_identity_linux.py",
|
|
42
43
|
"process_windows.py",
|
|
43
44
|
"remote_ops_launchd.py",
|
|
44
45
|
),
|
|
45
46
|
"remote_ops.py": (
|
|
46
47
|
"process_identity.py",
|
|
48
|
+
"process_identity_darwin.py",
|
|
47
49
|
"process_identity_linux.py",
|
|
48
50
|
"remote_ops_download.py",
|
|
49
51
|
"remote_ops_prepare.py",
|