-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvortex_node.py
More file actions
5238 lines (4461 loc) · 192 KB
/
vortex_node.py
File metadata and controls
5238 lines (4461 loc) · 192 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Vortex Network
Single file self hosted node for Vortex OS.
Modes:
python vortex_node.py install
python vortex_node.py run
python vortex_node.py service-install
python vortex_node.py doctor
python vortex_node.py print-nginx
This script keeps everything in one file:
- interactive installer / config wizard
- FastAPI web server
- auth + rate limiting
- remote browser sessions via Playwright
- translated local-render pages + asset proxy
- fallback screenshot stream mode
- Tor / proxy / system-VPN aware routing
- tmux helpers / service-install helper
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import contextlib
import dataclasses
import hashlib
import hmac
import html as html_lib
import io
import json
import select
import pty
import pwd
import fcntl
import termios
import struct
import signal
import mimetypes
import os
import pathlib
import re
import secrets
import shutil
import socket
import subprocess
import sys
import tempfile
import tarfile
import textwrap
import time
import traceback
import typing as t
import urllib.parse
import uuid
from collections import defaultdict, deque
from datetime import datetime, timezone, timedelta
import ssl
# Third-party runtime deps
try:
import httpx
except ImportError: # pragma: no cover
httpx = None
try:
from bs4 import BeautifulSoup
except ImportError: # pragma: no cover
BeautifulSoup = None
try:
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
except ImportError: # pragma: no cover
FastAPI = None
try:
import uvicorn
except ImportError: # pragma: no cover
uvicorn = None
try:
from playwright.async_api import async_playwright, Browser, BrowserContext, Page, Playwright
except ImportError: # pragma: no cover
async_playwright = None
Browser = BrowserContext = Page = Playwright = t.Any
try:
import pyotp
except ImportError: # pragma: no cover
pyotp = None
try:
import qrcode
except ImportError: # pragma: no cover
qrcode = None
try:
import av
from aiortc import RTCPeerConnection, RTCConfiguration, RTCIceServer, RTCSessionDescription
from aiortc.contrib.media import MediaPlayer
except ImportError: # pragma: no cover
av = None
RTCPeerConnection = RTCConfiguration = RTCIceServer = RTCSessionDescription = None
MediaPlayer = None
APP_NAME = "Vortex Node"
APP_VERSION = "0.3.0"
SCRIPT_PATH = pathlib.Path(__file__).resolve()
SCRIPT_DIR = SCRIPT_PATH.parent
DEFAULT_DATA_DIR = pathlib.Path(
os.environ.get("VORTEX_NETWORK_DIR") or str(SCRIPT_DIR / "vortex_network_state")
).expanduser().resolve()
CONFIG_PATH = DEFAULT_DATA_DIR / "config.json"
BROWSER_STATE_DIR = DEFAULT_DATA_DIR / "browser"
LOG_DIR = DEFAULT_DATA_DIR / "logs"
SESSION_DIR = DEFAULT_DATA_DIR / "sessions"
RUNTIME_DIR = DEFAULT_DATA_DIR / "runtime"
WRAPPER_DIR = RUNTIME_DIR / "wrappers"
WIREGUARD_DIR = DEFAULT_DATA_DIR / "wireguard"
VENDOR_DIR = DEFAULT_DATA_DIR / "vendor"
TERMINAL_VENDOR_DIR = VENDOR_DIR / "xterm"
MAX_BODY_PREVIEW = 1024 * 1024
DEFAULT_UI_HTML_CANDIDATES = [
SCRIPT_DIR / "vortex_os.html",
SCRIPT_DIR / "vortexos.html",
]
DEFAULT_UI_HTML = next((p for p in DEFAULT_UI_HTML_CANDIDATES if p.exists()), DEFAULT_UI_HTML_CANDIDATES[0])
DEFAULT_UPDATE_OWNER = os.environ.get("REPO_OWNER", "MagnetosphereLabs")
DEFAULT_UPDATE_REPO = os.environ.get("REPO_NAME", "VortexOS")
DEFAULT_UPDATE_BRANCH = os.environ.get("REPO_BRANCH", "main")
DEFAULT_REMOTE_BACKEND_PATH = SCRIPT_PATH.name
DEFAULT_REMOTE_FRONTEND_PATH = "vortex_os.html"
DEFAULT_WG_INTERFACE = "vortexwg0"
DEFAULT_WG_NAMESPACE = "vortexnode-worker"
DEFAULT_TOR_SOCKS = "socks5://127.0.0.1:9050"
def github_raw_url(owner: str, repo: str, branch: str, remote_path: str) -> str:
return (
"https://raw.githubusercontent.com/"
f"{urllib.parse.quote(owner, safe='')}/"
f"{urllib.parse.quote(repo, safe='')}/"
f"{urllib.parse.quote(branch, safe='')}/"
f"{urllib.parse.quote(remote_path, safe='/')}"
)
PAIR_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 180 # 180 days
SYNCED_BLOB_DIR = DEFAULT_DATA_DIR / "synced_os_profiles"
TERMINAL_STATE_DIR = DEFAULT_DATA_DIR / "terminal"
MAX_TABS_PER_SESSION = 10
DEFAULT_REMOTE_WIDTH_CAP = 1280
DEFAULT_REMOTE_HEIGHT_CAP = 720
MAX_REMOTE_FPS = 60
DEFAULT_XVFB_START_DISPLAY = 110
DEFAULT_REMOTE_STUN_SERVERS = ["stun:stun.l.google.com:19302"]
TERMINAL_VENDOR_ASSETS = {
"xterm.css": {
"repo_file": "vendor_xterm-5.5.0.tgz",
"member": "package/css/xterm.css",
},
"xterm.js": {
"repo_file": "vendor_xterm-5.5.0.tgz",
"member": "package/lib/xterm.js",
},
"xterm-addon-fit.js": {
"repo_file": "vendor_xterm-addon-fit-0.10.0.tgz",
"member": "package/lib/addon-fit.js",
},
}
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def ensure_dirs() -> None:
DEFAULT_DATA_DIR.mkdir(parents=True, exist_ok=True)
BROWSER_STATE_DIR.mkdir(parents=True, exist_ok=True)
LOG_DIR.mkdir(parents=True, exist_ok=True)
SESSION_DIR.mkdir(parents=True, exist_ok=True)
RUNTIME_DIR.mkdir(parents=True, exist_ok=True)
WRAPPER_DIR.mkdir(parents=True, exist_ok=True)
WIREGUARD_DIR.mkdir(parents=True, exist_ok=True)
VENDOR_DIR.mkdir(parents=True, exist_ok=True)
TERMINAL_VENDOR_DIR.mkdir(parents=True, exist_ok=True)
SYNCED_BLOB_DIR.mkdir(parents=True, exist_ok=True)
TERMINAL_STATE_DIR.mkdir(parents=True, exist_ok=True)
def read_json(path: pathlib.Path, default: t.Any) -> t.Any:
try:
return json.loads(path.read_text("utf-8"))
except Exception:
return default
def write_json(path: pathlib.Path, payload: t.Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(payload, indent=2, sort_keys=False), "utf-8")
tmp.replace(path)
def prompt(text: str, default: t.Optional[str] = None, secret: bool = False) -> str:
suffix = f" [{default}]" if default else ""
label = f"{text}{suffix}: "
if secret:
import getpass
while True:
value = getpass.getpass(label)
if value:
return value
if default is not None:
return default
while True:
value = input(label).strip()
if value:
return value
if default is not None:
return default
def prompt_yes_no(text: str, default: bool = True) -> bool:
suffix = "Y/n" if default else "y/N"
while True:
value = input(f"{text} [{suffix}]: ").strip().lower()
if not value:
return default
if value in {"y", "yes"}:
return True
if value in {"n", "no"}:
return False
print("Please answer yes or no.")
def prompt_choice(text: str, choices: list[tuple[str, str]], default_key: str) -> str:
print(text)
for key, label in choices:
marker = "*" if key == default_key else " "
print(f" {marker} {key}: {label}")
valid = {k for k, _ in choices}
while True:
value = input(f"Choose [{default_key}]: ").strip().lower()
if not value:
return default_key
if value in valid:
return value
print(f"Choose one of: {', '.join(sorted(valid))}")
def prompt_int(text: str, default: int, minimum: int | None = None, maximum: int | None = None) -> int:
while True:
value = prompt(text, default=str(default))
try:
number = int(value)
except ValueError:
print("Please enter a whole number.")
continue
if minimum is not None and number < minimum:
print(f"Please enter a value >= {minimum}.")
continue
if maximum is not None and number > maximum:
print(f"Please enter a value <= {maximum}.")
continue
return number
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
def b64url_decode(data: str) -> bytes:
padding = "=" * (-len(data) % 4)
return base64.urlsafe_b64decode(data + padding)
def hash_password(
password: str,
*,
n: int = 2**15,
r: int = 8,
p: int = 1,
maxmem: int = 256 * 1024 * 1024,
) -> str:
salt = secrets.token_bytes(16)
dk = hashlib.scrypt(
password.encode("utf-8"),
salt=salt,
n=n,
r=r,
p=p,
dklen=64,
maxmem=maxmem,
)
return f"scrypt${n}${r}${p}${b64url(salt)}${b64url(dk)}"
def verify_password(password: str, stored: str) -> bool:
try:
algo, n, r, p, salt_b64, dk_b64 = stored.split("$", 5)
if algo != "scrypt":
return False
salt = b64url_decode(salt_b64)
expected = b64url_decode(dk_b64)
actual = hashlib.scrypt(
password.encode("utf-8"),
salt=salt,
n=int(n),
r=int(r),
p=int(p),
dklen=len(expected),
maxmem=256 * 1024 * 1024,
)
return hmac.compare_digest(actual, expected)
except Exception:
return False
def sign_token(secret_key: str, payload: dict[str, t.Any]) -> str:
body = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
body_b64 = b64url(body)
sig = hmac.new(secret_key.encode("utf-8"), body_b64.encode("utf-8"), hashlib.sha256).digest()
return f"{body_b64}.{b64url(sig)}"
def verify_token(secret_key: str, token: str) -> dict[str, t.Any]:
try:
body_b64, sig_b64 = token.split(".", 1)
expected_sig = hmac.new(secret_key.encode("utf-8"), body_b64.encode("utf-8"), hashlib.sha256).digest()
if not hmac.compare_digest(expected_sig, b64url_decode(sig_b64)):
raise ValueError("bad signature")
payload = json.loads(b64url_decode(body_b64).decode("utf-8"))
exp = int(payload.get("exp", 0))
if exp and time.time() > exp:
raise ValueError("expired")
return payload
except Exception as exc:
raise ValueError("invalid token") from exc
def shell_join(cmd: list[str]) -> str:
return " ".join(shlex_quote(x) for x in cmd)
def shlex_quote(value: str) -> str:
import shlex
return shlex.quote(value)
def which(name: str) -> str | None:
return shutil.which(name)
def local_ip_guess() -> str:
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect(("8.8.8.8", 80))
return sock.getsockname()[0]
except Exception:
return "127.0.0.1"
def parse_origin_list(raw: str) -> list[str]:
values = [x.strip() for x in raw.split(",") if x.strip()]
clean: list[str] = []
for value in values:
parsed = urllib.parse.urlparse(value)
if parsed.scheme in {"http", "https"} and parsed.netloc:
clean.append(f"{parsed.scheme}://{parsed.netloc}")
return sorted(set(clean))
@dataclasses.dataclass
class SimpleUpstreamResponse:
status_code: int
content: bytes
headers: dict[str, str]
def prompt_multiline(text: str, end_marker: str = "EOF") -> str:
print(f"{text} (finish with a line containing only {end_marker})")
lines: list[str] = []
while True:
line = input()
if line.strip() == end_marker:
break
lines.append(line)
return "\n".join(lines).strip() + "\n"
def run_command(
cmd: list[str],
*,
check: bool = True,
capture_output: bool = True,
text: bool = True,
input_data: str | bytes | None = None,
env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess:
return subprocess.run(
cmd,
check=check,
capture_output=capture_output,
text=text,
input=input_data,
env=env,
)
def write_private_text(path: pathlib.Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, "utf-8")
os.chmod(path, 0o600)
def apt_install(packages: list[str]) -> None:
if sys.platform != "linux":
raise RuntimeError("Automatic package installation in this script is only implemented for Linux.")
if os.geteuid() != 0:
raise RuntimeError("Run the installer with sudo/root so packages can be installed automatically.")
run_command(["apt-get", "update"], check=False)
run_command(["apt-get", "install", "-y", *packages], check=True)
def restart_current_process(reason: str) -> None:
print(reason)
os.execv(sys.executable, [sys.executable, str(SCRIPT_PATH), *sys.argv[1:]])
def read_text_if_exists(path: pathlib.Path) -> str:
try:
return path.read_text("utf-8")
except Exception:
return ""
def write_text_atomic(path: pathlib.Path, content: str, *, mode: int = 0o644) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(content, "utf-8")
os.chmod(tmp, mode)
tmp.replace(path)
def migrate_config(raw: dict[str, t.Any]) -> dict[str, t.Any]:
raw = dict(raw or {})
if not raw:
return raw
raw.setdefault("version", 4)
raw.setdefault("frontend", {})
raw["frontend"].setdefault("serve_ui", False)
raw["frontend"].setdefault("ui_html_path", str(DEFAULT_UI_HTML))
raw.setdefault("auth", {})
raw["auth"].setdefault(
"system_username",
str(
raw["auth"].get("system_username")
or os.environ.get("SUDO_USER")
or os.environ.get("USER")
or raw["auth"].get("username")
or "root"
),
)
raw.setdefault("files", {})
raw["files"].setdefault("default_path", "")
raw["files"].setdefault("allow_hidden", True)
raw.setdefault("ops", {})
legacy_updates = raw["ops"].get("updates")
if isinstance(legacy_updates, dict):
raw.setdefault("updates", {})
for key, value in legacy_updates.items():
raw["updates"].setdefault(key, value)
raw["ops"].pop("updates", None)
raw.setdefault("updates", {})
raw["updates"].setdefault("enabled", True)
raw["updates"].setdefault("owner", DEFAULT_UPDATE_OWNER)
raw["updates"].setdefault("repo", DEFAULT_UPDATE_REPO)
raw["updates"].setdefault("branch", DEFAULT_UPDATE_BRANCH)
raw["updates"].setdefault("backend_path", DEFAULT_REMOTE_BACKEND_PATH)
raw["updates"].setdefault("frontend_path", DEFAULT_REMOTE_FRONTEND_PATH)
raw.setdefault("server", {})
raw["server"].setdefault("host", "127.0.0.1")
raw["server"].setdefault("port", 8787)
raw["server"].setdefault("public_base_url", "https://node.example.com")
raw["server"].setdefault("allowed_origins", [])
raw["server"].setdefault("frame_ancestors", [])
raw["server"].setdefault("max_clients", 12)
raw["server"].setdefault("exposure_mode", "lan")
raw.setdefault("browser", {})
raw["browser"].setdefault("mode", "stream")
if str(raw["browser"].get("mode") or "").lower() != "stream":
raw["browser"]["mode"] = "stream"
raw["browser"].setdefault("max_sessions", 4)
raw["browser"].setdefault("max_tabs_per_session", MAX_TABS_PER_SESSION)
raw["browser"].setdefault("viewport", {"width": 1366, "height": 900})
raw["browser"].setdefault("user_agent", "")
raw["browser"].setdefault("block_aggressive_popups", True)
raw["browser"].setdefault("strip_common_junk", True)
raw["browser"].setdefault("allow_media_proxy", True)
raw["browser"].setdefault("screenshot_quality", 80)
raw["browser"].setdefault("screenshot_fps", 60)
raw["browser"].setdefault("remote_width_cap", DEFAULT_REMOTE_WIDTH_CAP)
raw["browser"].setdefault("remote_height_cap", DEFAULT_REMOTE_HEIGHT_CAP)
raw["browser"].setdefault("detection", {})
raw["browser"]["detection"].setdefault("heavy_dom_threshold", 5000)
raw["browser"]["detection"].setdefault("heavy_script_threshold", 32)
raw["browser"]["detection"].setdefault("canvas_threshold", 2)
raw["ops"].setdefault("use_tmux", True)
raw["ops"].setdefault("run_on_boot", True)
raw["ops"].setdefault("auto_https", False)
raw["ops"].setdefault("certbot_email", "")
return raw
def ensure_system_packages() -> None:
missing: list[str] = []
if which("curl") is None:
missing.append("curl")
if which("tmux") is None:
missing.append("tmux")
if which("ip") is None:
missing.append("iproute2")
if which("wg") is None:
missing.extend(["wireguard", "wireguard-tools"])
if which("tor") is None:
missing.append("tor")
if which("ffmpeg") is None:
missing.append("ffmpeg")
if which("Xvfb") is None:
missing.append("xvfb")
if which("xrandr") is None:
missing.append("x11-xserver-utils")
if which("pulseaudio") is None:
missing.append("pulseaudio")
if which("pactl") is None:
missing.append("pulseaudio-utils")
if which("dbus-launch") is None:
missing.append("dbus-x11")
missing = sorted(set(missing))
if missing:
print(f"Installing Ubuntu packages: {', '.join(missing)}")
apt_install(missing)
def ensure_python_packages() -> bool:
missing: list[str] = []
if FastAPI is None:
missing.append("fastapi")
if uvicorn is None:
missing.append("uvicorn[standard]")
if httpx is None:
missing.append("httpx[socks]")
if BeautifulSoup is None:
missing.extend(["beautifulsoup4", "lxml"])
if async_playwright is None:
missing.append("playwright")
if pyotp is None:
missing.append("pyotp")
if qrcode is None:
missing.append("qrcode[pil]")
if RTCPeerConnection is None:
missing.append("aiortc")
if av is None:
missing.append("av")
missing = sorted(set(missing))
if not missing:
return False
print(f"Installing Python packages: {', '.join(missing)}")
run_command([sys.executable, "-m", "pip", "install", "--upgrade", "pip"], check=False)
run_command([sys.executable, "-m", "pip", "install", *missing], check=True)
return True
def playwright_browser_ready() -> bool:
try:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
return pathlib.Path(p.chromium.executable_path).exists()
except Exception:
return False
def ensure_playwright_browser() -> None:
if playwright_browser_ready():
return
print("Installing Playwright Chromium...")
run_command([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
if sys.platform == "linux" and os.geteuid() == 0:
run_command([sys.executable, "-m", "playwright", "install-deps", "chromium"], check=True)
def bootstrap_runtime(cfg_raw: dict[str, t.Any] | None = None) -> None:
ensure_dirs()
ensure_system_packages()
if ensure_python_packages():
restart_current_process("Python dependencies installed. Restarting Vortex Node...")
ensure_playwright_browser()
ensure_terminal_vendor_assets(cfg_raw=cfg_raw)
def current_frontend_path(cfg_raw: dict[str, t.Any] | None = None) -> pathlib.Path:
cfg_raw = cfg_raw or {}
ui_path = str((cfg_raw.get("frontend") or {}).get("ui_html_path") or DEFAULT_UI_HTML)
return pathlib.Path(ui_path).expanduser().resolve()
def _download_url_bytes(url: str) -> bytes:
import urllib.request
request = urllib.request.Request(
url,
headers={"User-Agent": f"{APP_NAME}/{APP_VERSION}"}
)
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
def _download_first_available_bytes(urls: list[str]) -> tuple[bytes, str]:
errors: list[str] = []
for url in urls:
try:
return _download_url_bytes(url), url
except Exception as exc:
errors.append(f"{url}: {exc}")
raise RuntimeError(
"Unable to download vendor asset from any source:\n" + "\n".join(errors)
)
def github_raw_url(owner: str, repo: str, branch: str, remote_path: str) -> str:
return (
f"https://raw.githubusercontent.com/"
f"{urllib.parse.quote(owner, safe='')}/"
f"{urllib.parse.quote(repo, safe='')}/"
f"{urllib.parse.quote(branch, safe='')}/"
f"{urllib.parse.quote(remote_path, safe='/')}"
)
def configured_update_refs(cfg_raw: dict[str, t.Any] | None = None) -> tuple[str, str, str]:
cfg_raw = migrate_config(cfg_raw or {})
updates = cfg_raw.get("updates") or {}
owner = str(
updates.get("owner")
or os.environ.get("REPO_OWNER")
or DEFAULT_UPDATE_OWNER
).strip() or DEFAULT_UPDATE_OWNER
repo = str(
updates.get("repo")
or os.environ.get("REPO_NAME")
or DEFAULT_UPDATE_REPO
).strip() or DEFAULT_UPDATE_REPO
branch = str(
updates.get("branch")
or os.environ.get("REPO_BRANCH")
or DEFAULT_UPDATE_BRANCH
).strip() or DEFAULT_UPDATE_BRANCH
return owner, repo, branch
def ensure_terminal_vendor_assets(
force: bool = False,
cfg_raw: dict[str, t.Any] | None = None,
) -> None:
ensure_dirs()
owner, repo, branch = configured_update_refs(cfg_raw)
tarball_cache: dict[str, bytes] = {}
for filename, spec in TERMINAL_VENDOR_ASSETS.items():
dest = TERMINAL_VENDOR_DIR / filename
if dest.exists() and dest.stat().st_size > 0 and not force:
continue
repo_file = str(spec["repo_file"])
tarball_url = github_raw_url(owner, repo, branch, repo_file)
tarball_bytes = tarball_cache.get(repo_file)
if tarball_bytes is None:
tarball_bytes = _download_url_bytes(tarball_url)
tarball_cache[repo_file] = tarball_bytes
print(f"Fetched terminal vendor asset for {filename} from {tarball_url}")
with tarfile.open(fileobj=io.BytesIO(tarball_bytes), mode="r:gz") as tar:
try:
member = tar.extractfile(spec["member"])
except KeyError as exc:
available = ", ".join(
m.name for m in tar.getmembers()[:40]
)
raise RuntimeError(
f"Unable to locate vendor asset {spec['member']} in {repo_file} "
f"from repo {owner}/{repo}@{branch}. "
f"Available archive entries include: {available}"
) from exc
if member is None:
raise RuntimeError(
f"Unable to open vendor asset {spec['member']} in {repo_file} "
f"from repo {owner}/{repo}@{branch}"
)
content = member.read()
tmp = dest.with_suffix(dest.suffix + ".tmp")
tmp.write_bytes(content)
os.chmod(tmp, 0o644)
tmp.replace(dest)
def github_fetch_text(owner: str, repo: str, branch: str, remote_path: str) -> str:
import urllib.request
raw_url = github_raw_url(owner, repo, branch, remote_path)
request = urllib.request.Request(
raw_url,
headers={"User-Agent": f"{APP_NAME}/{APP_VERSION}"}
)
with urllib.request.urlopen(request, timeout=30) as response:
return response.read().decode("utf-8")
def apply_startup_updates(
cfg_raw: dict[str, t.Any] | None = None,
*,
restart_after_backend_update: bool = True,
) -> dict[str, t.Any]:
cfg_raw = migrate_config(cfg_raw or {})
updates = cfg_raw.get("updates") or {}
if not updates.get("enabled", True):
return {"checked": False, "updated": []}
owner = str(updates.get("owner") or DEFAULT_UPDATE_OWNER)
repo = str(updates.get("repo") or DEFAULT_UPDATE_REPO)
branch = str(updates.get("branch") or DEFAULT_UPDATE_BRANCH)
backend_remote = str(updates.get("backend_path") or DEFAULT_REMOTE_BACKEND_PATH)
frontend_remote = str(updates.get("frontend_path") or DEFAULT_REMOTE_FRONTEND_PATH)
changed: list[str] = []
try:
remote_backend = github_fetch_text(owner, repo, branch, backend_remote)
if remote_backend != read_text_if_exists(SCRIPT_PATH):
print(f"Update detected for {SCRIPT_PATH.name}. Applying...")
write_text_atomic(SCRIPT_PATH, remote_backend, mode=0o755)
changed.append("backend")
frontend_path = current_frontend_path(cfg_raw)
remote_frontend = github_fetch_text(owner, repo, branch, frontend_remote)
if remote_frontend != read_text_if_exists(frontend_path):
print(f"Update detected for {frontend_path.name}. Applying...")
write_text_atomic(frontend_path, remote_frontend, mode=0o644)
changed.append("frontend")
except Exception as exc:
print(f"Startup update check skipped: {exc}")
return {"checked": False, "updated": [], "error": str(exc)}
if "backend" in changed and restart_after_backend_update:
restart_current_process("Backend update applied. Restarting Vortex Node...")
return {"checked": True, "updated": changed}
def factory_reset_flow(*, reinstall: bool = False) -> int:
print(f"{APP_NAME} factory reset\n")
if not prompt_yes_no("Erase ALL node state, config, pairings, logs, and runtime files?", default=False):
print("Cancelled.")
return 1
shutil.rmtree(DEFAULT_DATA_DIR, ignore_errors=True)
ensure_dirs()
print(f"Wiped {DEFAULT_DATA_DIR}")
if reinstall:
return install_flow()
print(f"Node state erased. Run `python {SCRIPT_PATH.name} install` to configure it again.")
return 0
def free_display_number(start: int = DEFAULT_XVFB_START_DISPLAY, stop: int = DEFAULT_XVFB_START_DISPLAY + 60) -> int:
for number in range(start, stop):
if not pathlib.Path(f"/tmp/.X11-unix/X{number}").exists():
return number
raise RuntimeError("No free Xvfb display numbers were found.")
def ensure_xvfb(display_number: int, width: int, height: int) -> subprocess.Popen:
proc = subprocess.Popen(
["Xvfb", f":{display_number}", "-screen", "0", f"{width}x{height}x24", "-ac", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
deadline = time.time() + 5
socket_path = pathlib.Path(f"/tmp/.X11-unix/X{display_number}")
while time.time() < deadline:
if socket_path.exists():
return proc
time.sleep(0.1)
with contextlib.suppress(Exception):
proc.terminate()
raise RuntimeError(f"Xvfb did not start on :{display_number}")
def ensure_pulse_server() -> dict[str, str]:
runtime_dir = (RUNTIME_DIR / "pulse-runtime").resolve()
runtime_dir.mkdir(parents=True, exist_ok=True)
os.chmod(runtime_dir, 0o700)
socket_path = runtime_dir / "native"
env = os.environ.copy()
env["XDG_RUNTIME_DIR"] = str(runtime_dir)
env["PULSE_SERVER"] = f"unix:{socket_path}"
if not socket_path.exists():
subprocess.run(
[
"pulseaudio",
"--daemonize=yes",
"--exit-idle-time=-1",
"--disable-shm=yes",
"--log-target=stderr",
"--load", f"module-native-protocol-unix auth-anonymous=1 socket={socket_path}",
],
env=env,
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
deadline = time.time() + 5
while time.time() < deadline:
if socket_path.exists():
break
time.sleep(0.1)
if not socket_path.exists():
raise RuntimeError("PulseAudio did not start correctly.")
return env
def pulse_load_module(pulse_env: dict[str, str], *args: str) -> str:
result = run_command(["pactl", "load-module", *args], env=pulse_env, check=True)
return (result.stdout or "").strip()
def pulse_unload_module(pulse_env: dict[str, str], module_id: str | None) -> None:
if not module_id:
return
with contextlib.suppress(Exception):
run_command(["pactl", "unload-module", module_id], env=pulse_env, check=False)
def create_session_audio_devices(session_id: str, pulse_env: dict[str, str]) -> dict[str, t.Any]:
safe_id = re.sub(r"[^a-zA-Z0-9]", "", session_id)[:12]
sink_name = f"vortex_{safe_id}_sink"
sink_module_id = pulse_load_module(
pulse_env,
"module-null-sink",
f"sink_name={sink_name}",
f"sink_properties=device.description=Vortex-{safe_id}",
)
mic_fifo = RUNTIME_DIR / f"{safe_id}.mic.pcm"
with contextlib.suppress(FileNotFoundError):
mic_fifo.unlink()
os.mkfifo(mic_fifo, 0o600)
mic_source_name = f"vortex_{safe_id}_mic"
mic_module_id = pulse_load_module(
pulse_env,
"module-pipe-source",
f"file={mic_fifo}",
f"source_name={mic_source_name}",
"format=s16le",
"rate=48000",
"channels=2",
)
return {
"sink_name": sink_name,
"sink_module_id": sink_module_id,
"mic_source_name": mic_source_name,
"mic_module_id": mic_module_id,
"mic_fifo": mic_fifo,
}
def parse_wireguard_config(raw: str) -> dict[str, t.Any]:
section = ""
addresses: list[str] = []
dns_servers: list[str] = []
mtu: int | None = None
stripped_lines: list[str] = []
for raw_line in raw.splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
stripped_lines.append(raw_line)
continue
section_match = re.match(r"^\[(.+?)\]\s*$", line)
if section_match:
section = section_match.group(1).strip().lower()
stripped_lines.append(raw_line)
continue
if "=" not in raw_line:
stripped_lines.append(raw_line)
continue
key, value = [x.strip() for x in raw_line.split("=", 1)]
key_lower = key.lower()
if section == "interface":
if key_lower == "address":
addresses.extend([x.strip() for x in value.split(",") if x.strip()])
continue
if key_lower == "dns":
dns_servers.extend([x.strip() for x in value.split(",") if x.strip()])
continue
if key_lower == "mtu":
try:
mtu = int(value)
except Exception:
mtu = None
continue
if key_lower in {"table", "preup", "postup", "predown", "postdown", "saveconfig"}:
continue
stripped_lines.append(raw_line)
stripped = "\n".join(stripped_lines).strip() + "\n"
return {
"addresses": addresses,
"dns_servers": dns_servers,
"mtu": mtu,
"stripped_config": stripped,
}
def ensure_tor_service_running(cfg: "NodeConfig") -> None:
tor_cfg = cfg.egress.get("tor", {})
socks_url = tor_cfg.get("socks_url", DEFAULT_TOR_SOCKS)
parsed = urllib.parse.urlparse(socks_url)
host = parsed.hostname or "127.0.0.1"
port = parsed.port or 9050
if which("tor") is None and tor_cfg.get("install_if_missing", True):
apt_install(["tor"])
if sys.platform == "linux" and which("systemctl"):
run_command(["systemctl", "enable", "--now", "tor"], check=False)
run_command(["systemctl", "enable", "--now", "tor@default"], check=False)
try:
with socket.create_connection((host, port), timeout=2):
return
except Exception as exc:
raise RuntimeError(f"Tor SOCKS endpoint is not reachable at {host}:{port}") from exc
def ensure_wireguard_namespace(cfg: "NodeConfig") -> None:
if sys.platform != "linux":
raise RuntimeError("WireGuard namespace mode in this implementation is Linux-only.")
if os.geteuid() != 0:
raise RuntimeError("WireGuard namespace setup requires sudo/root.")
if which("ip") is None or which("wg") is None or which("curl") is None: