opencode-unlimited 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- opencode_unlimited/__init__.py +12 -0
- opencode_unlimited/__main__.py +6 -0
- opencode_unlimited/cli.py +921 -0
- opencode_unlimited/config.py +213 -0
- opencode_unlimited/constants.py +113 -0
- opencode_unlimited/daemon.py +223 -0
- opencode_unlimited/dashboard/__init__.py +1 -0
- opencode_unlimited/dashboard/server.py +503 -0
- opencode_unlimited/egress/__init__.py +0 -0
- opencode_unlimited/egress/clean_endpoint.py +182 -0
- opencode_unlimited/egress/tor_installer.py +379 -0
- opencode_unlimited/egress/tor_manager.py +372 -0
- opencode_unlimited/egress/warp_keeper.py +208 -0
- opencode_unlimited/guards/__init__.py +0 -0
- opencode_unlimited/guards/auto_resume.py +267 -0
- opencode_unlimited/guards/zen_guard.py +269 -0
- opencode_unlimited/launcher.py +379 -0
- opencode_unlimited/pool/__init__.py +1 -0
- opencode_unlimited/pool/account_pool.py +235 -0
- opencode_unlimited/proxy/__init__.py +1 -0
- opencode_unlimited/proxy/proxy_chain.py +344 -0
- opencode_unlimited/proxy/zen_proxy.py +701 -0
- opencode_unlimited-0.1.0.dist-info/METADATA +283 -0
- opencode_unlimited-0.1.0.dist-info/RECORD +27 -0
- opencode_unlimited-0.1.0.dist-info/WHEEL +4 -0
- opencode_unlimited-0.1.0.dist-info/entry_points.txt +2 -0
- opencode_unlimited-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""
|
|
2
|
+
tor_installer.py - Locate, install, and put Tor on PATH.
|
|
3
|
+
|
|
4
|
+
* :func:`find_tor_binary` looks on PATH, in ocu's own install directory, and
|
|
5
|
+
in common Tor Browser locations.
|
|
6
|
+
* :func:`install_tor_bundle` downloads the official Tor Expert Bundle from
|
|
7
|
+
dist.torproject.org, checks its SHA-256 against the published
|
|
8
|
+
``sha256sums-signed-build.txt``, and extracts it into ocu's data directory.
|
|
9
|
+
* :func:`add_to_user_path` appends a directory to the Windows *user* PATH
|
|
10
|
+
(HKCU\\Environment) without touching the system PATH.
|
|
11
|
+
* :func:`package_manager_options` lists native installs on macOS/Linux/Termux.
|
|
12
|
+
|
|
13
|
+
Note: the checksum file is fetched over HTTPS from the same server, so it
|
|
14
|
+
guards against corrupted or truncated downloads. It is not a substitute for
|
|
15
|
+
verifying the GPG signature (``.asc``) if you need protection against a
|
|
16
|
+
compromised mirror.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
import logging
|
|
23
|
+
import os
|
|
24
|
+
import platform
|
|
25
|
+
import re
|
|
26
|
+
import shutil
|
|
27
|
+
import subprocess
|
|
28
|
+
import sys
|
|
29
|
+
import tarfile
|
|
30
|
+
import tempfile
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
from typing import Callable, Optional
|
|
33
|
+
|
|
34
|
+
import httpx
|
|
35
|
+
|
|
36
|
+
log = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
TOR_DOWNLOAD_PAGE = "https://download.torproject.org/tor/"
|
|
39
|
+
TOR_DIST_BASE = "https://dist.torproject.org/torbrowser"
|
|
40
|
+
CHECKSUM_FILE = "sha256sums-signed-build.txt"
|
|
41
|
+
|
|
42
|
+
_BINARY = "tor.exe" if sys.platform == "win32" else "tor"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _data_dir() -> Path:
|
|
46
|
+
if sys.platform == "win32":
|
|
47
|
+
base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
|
|
48
|
+
elif sys.platform == "darwin":
|
|
49
|
+
base = Path.home() / "Library" / "Application Support"
|
|
50
|
+
else:
|
|
51
|
+
xdg = os.environ.get("XDG_DATA_HOME", "")
|
|
52
|
+
base = Path(xdg) if xdg else Path.home() / ".local" / "share"
|
|
53
|
+
return base / "opencode-unlimited"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
INSTALL_DIR: Path = _data_dir() / "tor"
|
|
57
|
+
"""Where :func:`install_tor_bundle` extracts the expert bundle."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---------------------------------------------------------------------------
|
|
61
|
+
# Discovery
|
|
62
|
+
# ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def bundled_binary(install_dir: Path = INSTALL_DIR) -> Path:
|
|
66
|
+
"""Path of tor inside an extracted expert bundle (``tor/tor.exe``)."""
|
|
67
|
+
return install_dir / "tor" / _BINARY
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _candidate_paths() -> list[Path]:
|
|
71
|
+
paths = [bundled_binary()]
|
|
72
|
+
if sys.platform == "win32":
|
|
73
|
+
home = Path.home()
|
|
74
|
+
tb = Path("Browser") / "TorBrowser" / "Tor" / "tor.exe"
|
|
75
|
+
for desktop in (home / "Desktop", home / "OneDrive" / "Desktop"):
|
|
76
|
+
paths.append(desktop / "Tor Browser" / tb)
|
|
77
|
+
local = Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local"))
|
|
78
|
+
paths.append(local / "Tor Browser" / tb)
|
|
79
|
+
elif sys.platform == "darwin":
|
|
80
|
+
paths += [Path("/opt/homebrew/bin/tor"), Path("/usr/local/bin/tor")]
|
|
81
|
+
else:
|
|
82
|
+
paths += [Path("/usr/bin/tor"), Path("/usr/local/bin/tor")]
|
|
83
|
+
return paths
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def find_tor_binary() -> Optional[str]:
|
|
87
|
+
"""Return the full path to a tor binary, or None if Tor isn't installed."""
|
|
88
|
+
found = shutil.which(_BINARY) or shutil.which("tor")
|
|
89
|
+
if found:
|
|
90
|
+
return found
|
|
91
|
+
for p in _candidate_paths():
|
|
92
|
+
if p.is_file():
|
|
93
|
+
return str(p)
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def tor_version(binary: str) -> Optional[str]:
|
|
98
|
+
"""First line of ``tor --version``, or None if it can't be run."""
|
|
99
|
+
try:
|
|
100
|
+
out = subprocess.run(
|
|
101
|
+
[binary, "--version"], capture_output=True, text=True, timeout=15
|
|
102
|
+
)
|
|
103
|
+
except (OSError, subprocess.SubprocessError):
|
|
104
|
+
return None
|
|
105
|
+
line = (out.stdout or out.stderr).strip().splitlines()
|
|
106
|
+
return line[0] if line else None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
# Official expert bundle download
|
|
111
|
+
# ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def bundle_platform() -> Optional[str]:
|
|
115
|
+
"""Expert-bundle platform tag for this machine, e.g. ``windows-x86_64``."""
|
|
116
|
+
machine = platform.machine().lower()
|
|
117
|
+
arch = {
|
|
118
|
+
"amd64": "x86_64",
|
|
119
|
+
"x86_64": "x86_64",
|
|
120
|
+
"x64": "x86_64",
|
|
121
|
+
"arm64": "aarch64",
|
|
122
|
+
"aarch64": "aarch64",
|
|
123
|
+
"x86": "i686",
|
|
124
|
+
"i386": "i686",
|
|
125
|
+
"i686": "i686",
|
|
126
|
+
}.get(machine)
|
|
127
|
+
if arch is None:
|
|
128
|
+
return None
|
|
129
|
+
if sys.platform == "win32":
|
|
130
|
+
return f"windows-{arch}" if arch in {"x86_64", "i686"} else None
|
|
131
|
+
if sys.platform == "darwin":
|
|
132
|
+
return f"macos-{arch}" if arch in {"x86_64", "aarch64"} else None
|
|
133
|
+
if sys.platform.startswith("linux"):
|
|
134
|
+
return f"linux-{arch}" if arch in {"x86_64", "aarch64", "i686"} else None
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _version_key(v: str) -> tuple[int, ...]:
|
|
139
|
+
return tuple(int(p) for p in v.split("."))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def parse_latest_stable(html: str, plat: str) -> Optional[tuple[str, str]]:
|
|
143
|
+
"""
|
|
144
|
+
Find the newest *stable* expert bundle for *plat* on the download page.
|
|
145
|
+
Alpha builds (e.g. ``16.0a14``) are skipped. Returns ``(version, url)``.
|
|
146
|
+
"""
|
|
147
|
+
pattern = re.compile(
|
|
148
|
+
r"https://dist\.torproject\.org/torbrowser/(?P<v>[0-9][0-9a-z.]*)/"
|
|
149
|
+
r"tor-expert-bundle-" + re.escape(plat) + r"-(?P=v)\.tar\.gz(?![.\w])"
|
|
150
|
+
)
|
|
151
|
+
stable = {
|
|
152
|
+
m.group("v"): m.group(0)
|
|
153
|
+
for m in pattern.finditer(html)
|
|
154
|
+
if re.fullmatch(r"\d+(\.\d+)+", m.group("v"))
|
|
155
|
+
}
|
|
156
|
+
if not stable:
|
|
157
|
+
return None
|
|
158
|
+
version = max(stable, key=_version_key)
|
|
159
|
+
return version, stable[version]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def parse_checksum(sums_text: str, filename: str) -> Optional[str]:
|
|
163
|
+
"""Return the SHA-256 for *filename* from a ``sha256sum``-style listing."""
|
|
164
|
+
for line in sums_text.splitlines():
|
|
165
|
+
parts = line.split()
|
|
166
|
+
if len(parts) == 2 and parts[1].lstrip("*") == filename:
|
|
167
|
+
digest = parts[0].lower()
|
|
168
|
+
if re.fullmatch(r"[0-9a-f]{64}", digest):
|
|
169
|
+
return digest
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _safe_extract(archive: Path, dest: Path) -> None:
|
|
174
|
+
with tarfile.open(archive, "r:gz") as tar:
|
|
175
|
+
if hasattr(tarfile, "data_filter"):
|
|
176
|
+
tar.extractall(dest, filter="data")
|
|
177
|
+
return
|
|
178
|
+
# Python without extraction filters: reject anything escaping dest.
|
|
179
|
+
root = dest.resolve()
|
|
180
|
+
for member in tar.getmembers():
|
|
181
|
+
target = (dest / member.name).resolve()
|
|
182
|
+
if root not in target.parents and target != root:
|
|
183
|
+
raise RuntimeError(f"Unsafe path in archive: {member.name}")
|
|
184
|
+
if member.issym() or member.islnk():
|
|
185
|
+
raise RuntimeError(f"Links are not allowed in archive: {member.name}")
|
|
186
|
+
tar.extractall(dest) # noqa: S202 - members validated above
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def install_tor_bundle(
|
|
190
|
+
install_dir: Path = INSTALL_DIR,
|
|
191
|
+
*,
|
|
192
|
+
progress: Optional[Callable[[int, Optional[int]], None]] = None,
|
|
193
|
+
client: Optional[httpx.Client] = None,
|
|
194
|
+
) -> Path:
|
|
195
|
+
"""
|
|
196
|
+
Download, verify, and extract the latest stable Tor Expert Bundle.
|
|
197
|
+
|
|
198
|
+
Returns the path to the tor binary. Raises ``RuntimeError`` on any
|
|
199
|
+
failure (unsupported platform, page format change, checksum mismatch).
|
|
200
|
+
"""
|
|
201
|
+
plat = bundle_platform()
|
|
202
|
+
if plat is None:
|
|
203
|
+
raise RuntimeError(
|
|
204
|
+
f"No official Tor Expert Bundle for {sys.platform}/{platform.machine()}."
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
own_client = client is None
|
|
208
|
+
http = client or httpx.Client(timeout=60.0, follow_redirects=True, trust_env=True)
|
|
209
|
+
try:
|
|
210
|
+
page = http.get(TOR_DOWNLOAD_PAGE)
|
|
211
|
+
page.raise_for_status()
|
|
212
|
+
found = parse_latest_stable(page.text, plat)
|
|
213
|
+
if found is None:
|
|
214
|
+
raise RuntimeError(
|
|
215
|
+
f"Could not find a stable expert bundle for {plat} on {TOR_DOWNLOAD_PAGE}."
|
|
216
|
+
)
|
|
217
|
+
version, url = found
|
|
218
|
+
filename = url.rsplit("/", 1)[1]
|
|
219
|
+
|
|
220
|
+
sums = http.get(f"{TOR_DIST_BASE}/{version}/{CHECKSUM_FILE}")
|
|
221
|
+
sums.raise_for_status()
|
|
222
|
+
expected = parse_checksum(sums.text, filename)
|
|
223
|
+
if expected is None:
|
|
224
|
+
raise RuntimeError(f"{filename} is not listed in {CHECKSUM_FILE}.")
|
|
225
|
+
|
|
226
|
+
log.info("Downloading Tor %s from %s", version, url)
|
|
227
|
+
with tempfile.TemporaryDirectory(prefix="ocu_tor_dl_") as tmp:
|
|
228
|
+
archive = Path(tmp) / filename
|
|
229
|
+
digest = hashlib.sha256()
|
|
230
|
+
with http.stream("GET", url) as resp:
|
|
231
|
+
resp.raise_for_status()
|
|
232
|
+
total = int(resp.headers.get("content-length", 0)) or None
|
|
233
|
+
done = 0
|
|
234
|
+
with archive.open("wb") as fh:
|
|
235
|
+
for chunk in resp.iter_bytes():
|
|
236
|
+
fh.write(chunk)
|
|
237
|
+
digest.update(chunk)
|
|
238
|
+
done += len(chunk)
|
|
239
|
+
if progress:
|
|
240
|
+
progress(done, total)
|
|
241
|
+
|
|
242
|
+
actual = digest.hexdigest()
|
|
243
|
+
if actual != expected:
|
|
244
|
+
raise RuntimeError(
|
|
245
|
+
f"Checksum mismatch for {filename}: expected {expected}, got {actual}."
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
install_dir.mkdir(parents=True, exist_ok=True)
|
|
249
|
+
try:
|
|
250
|
+
_safe_extract(archive, install_dir)
|
|
251
|
+
except PermissionError as exc:
|
|
252
|
+
raise RuntimeError(
|
|
253
|
+
f"Could not write to {install_dir} ({exc}). Is Tor still running? Run `ocu stop` first."
|
|
254
|
+
) from exc
|
|
255
|
+
finally:
|
|
256
|
+
if own_client:
|
|
257
|
+
http.close()
|
|
258
|
+
|
|
259
|
+
binary = bundled_binary(install_dir)
|
|
260
|
+
if not binary.is_file():
|
|
261
|
+
raise RuntimeError(f"Bundle extracted, but {binary} is missing.")
|
|
262
|
+
if sys.platform != "win32":
|
|
263
|
+
binary.chmod(binary.stat().st_mode | 0o111)
|
|
264
|
+
(install_dir / "VERSION").write_text(version, encoding="utf-8")
|
|
265
|
+
return binary
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
# ---------------------------------------------------------------------------
|
|
269
|
+
# Native package managers (macOS / Linux / Termux)
|
|
270
|
+
# ---------------------------------------------------------------------------
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def package_manager_options() -> list[tuple[str, list[str]]]:
|
|
274
|
+
"""Native install commands available on this machine, best first."""
|
|
275
|
+
options: list[tuple[str, list[str]]] = []
|
|
276
|
+
if sys.platform == "win32":
|
|
277
|
+
return options
|
|
278
|
+
if "com.termux" in os.environ.get("PREFIX", "") and shutil.which("pkg"):
|
|
279
|
+
options.append(("Termux: pkg install tor", ["pkg", "install", "-y", "tor"]))
|
|
280
|
+
if shutil.which("brew"):
|
|
281
|
+
options.append(("Homebrew: brew install tor", ["brew", "install", "tor"]))
|
|
282
|
+
sudo = ["sudo"] if shutil.which("sudo") and os.geteuid() != 0 else [] # type: ignore[attr-defined]
|
|
283
|
+
if shutil.which("apt-get"):
|
|
284
|
+
options.append(("APT: sudo apt-get install tor", [*sudo, "apt-get", "install", "-y", "tor"]))
|
|
285
|
+
if shutil.which("dnf"):
|
|
286
|
+
options.append(("DNF: sudo dnf install tor", [*sudo, "dnf", "install", "-y", "tor"]))
|
|
287
|
+
if shutil.which("pacman"):
|
|
288
|
+
options.append(("pacman: sudo pacman -S tor", [*sudo, "pacman", "-S", "--noconfirm", "tor"]))
|
|
289
|
+
return options
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
# ---------------------------------------------------------------------------
|
|
293
|
+
# Windows user PATH
|
|
294
|
+
# ---------------------------------------------------------------------------
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _norm(p: str) -> str:
|
|
298
|
+
return os.path.normcase(os.path.expandvars(p).rstrip("\\/"))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def path_contains(path_value: str, directory: str) -> bool:
|
|
302
|
+
"""True if *directory* is one of the ``;``-separated entries of *path_value*."""
|
|
303
|
+
target = _norm(directory)
|
|
304
|
+
return any(_norm(entry) == target for entry in path_value.split(os.pathsep) if entry)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _broadcast_environment_change() -> None:
|
|
308
|
+
"""Tell Explorer and new terminals that the environment changed."""
|
|
309
|
+
import ctypes
|
|
310
|
+
from ctypes import wintypes
|
|
311
|
+
|
|
312
|
+
result = wintypes.DWORD()
|
|
313
|
+
ctypes.windll.user32.SendMessageTimeoutW( # type: ignore[attr-defined]
|
|
314
|
+
0xFFFF, # HWND_BROADCAST
|
|
315
|
+
0x001A, # WM_SETTINGCHANGE
|
|
316
|
+
0,
|
|
317
|
+
"Environment",
|
|
318
|
+
0x0002, # SMTO_ABORTIFHUNG
|
|
319
|
+
5000,
|
|
320
|
+
ctypes.byref(result),
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def add_to_user_path(directory: str | Path) -> bool:
|
|
325
|
+
"""
|
|
326
|
+
Append *directory* to the current user's PATH. Returns True if PATH was
|
|
327
|
+
changed, False if it was already there.
|
|
328
|
+
|
|
329
|
+
On Windows this edits ``HKCU\\Environment\\Path`` (keeping its registry
|
|
330
|
+
type) and broadcasts ``WM_SETTINGCHANGE``. It does not use ``setx``,
|
|
331
|
+
which truncates PATH at 1024 characters. The running process's PATH is
|
|
332
|
+
updated too. On other platforms it raises ``NotImplementedError``.
|
|
333
|
+
"""
|
|
334
|
+
directory = str(Path(directory))
|
|
335
|
+
if sys.platform != "win32":
|
|
336
|
+
raise NotImplementedError("Automatic PATH editing is only implemented for Windows.")
|
|
337
|
+
|
|
338
|
+
import winreg
|
|
339
|
+
|
|
340
|
+
with winreg.OpenKey(
|
|
341
|
+
winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE
|
|
342
|
+
) as key:
|
|
343
|
+
try:
|
|
344
|
+
current, kind = winreg.QueryValueEx(key, "Path")
|
|
345
|
+
except FileNotFoundError:
|
|
346
|
+
current, kind = "", winreg.REG_EXPAND_SZ
|
|
347
|
+
if kind not in (winreg.REG_SZ, winreg.REG_EXPAND_SZ):
|
|
348
|
+
raise RuntimeError("User PATH has an unexpected registry type; not modifying it.")
|
|
349
|
+
|
|
350
|
+
changed = not path_contains(current, directory)
|
|
351
|
+
if changed:
|
|
352
|
+
new_value = f"{current.rstrip(os.pathsep)}{os.pathsep}{directory}" if current else directory
|
|
353
|
+
winreg.SetValueEx(key, "Path", 0, kind, new_value)
|
|
354
|
+
|
|
355
|
+
if changed:
|
|
356
|
+
try:
|
|
357
|
+
_broadcast_environment_change()
|
|
358
|
+
except Exception as exc: # noqa: BLE001
|
|
359
|
+
log.debug("WM_SETTINGCHANGE broadcast failed: %s", exc)
|
|
360
|
+
|
|
361
|
+
if not path_contains(os.environ.get("PATH", ""), directory):
|
|
362
|
+
os.environ["PATH"] = os.environ.get("PATH", "") + os.pathsep + directory
|
|
363
|
+
return changed
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def user_path_has(directory: str | Path) -> bool:
|
|
367
|
+
"""True if *directory* is on the persisted user PATH (Windows) or current PATH."""
|
|
368
|
+
directory = str(Path(directory))
|
|
369
|
+
if sys.platform == "win32":
|
|
370
|
+
import winreg
|
|
371
|
+
|
|
372
|
+
try:
|
|
373
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key:
|
|
374
|
+
value, _ = winreg.QueryValueEx(key, "Path")
|
|
375
|
+
if path_contains(value, directory):
|
|
376
|
+
return True
|
|
377
|
+
except FileNotFoundError:
|
|
378
|
+
pass
|
|
379
|
+
return path_contains(os.environ.get("PATH", ""), directory)
|