stealthmaven 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.
- stealthmaven/__init__.py +16 -0
- stealthmaven/__main__.py +5 -0
- stealthmaven/assets/nodemaven-mark.svg +19 -0
- stealthmaven/brand.py +95 -0
- stealthmaven/browser.py +462 -0
- stealthmaven/check.py +465 -0
- stealthmaven/cli.py +284 -0
- stealthmaven/geo.py +110 -0
- stealthmaven/identity.py +109 -0
- stealthmaven/mcp.py +391 -0
- stealthmaven/mcp_http.py +227 -0
- stealthmaven/profiles.py +107 -0
- stealthmaven/proxy.py +153 -0
- stealthmaven/relay.py +393 -0
- stealthmaven/screen.py +108 -0
- stealthmaven/useragent.py +182 -0
- stealthmaven-0.1.0.dist-info/METADATA +229 -0
- stealthmaven-0.1.0.dist-info/RECORD +22 -0
- stealthmaven-0.1.0.dist-info/WHEEL +5 -0
- stealthmaven-0.1.0.dist-info/entry_points.txt +2 -0
- stealthmaven-0.1.0.dist-info/licenses/LICENSE +21 -0
- stealthmaven-0.1.0.dist-info/top_level.txt +1 -0
stealthmaven/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""stealthmaven: a real Chromium whose timezone, languages and WebRTC match its proxy exit."""
|
|
2
|
+
|
|
3
|
+
from .browser import Browser, NoProxyWarning, launch
|
|
4
|
+
from .geo import Exit, LookupFailed
|
|
5
|
+
from .identity import Identity
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Browser",
|
|
10
|
+
"Exit",
|
|
11
|
+
"Identity",
|
|
12
|
+
"LookupFailed",
|
|
13
|
+
"NoProxyWarning",
|
|
14
|
+
"launch",
|
|
15
|
+
"__version__",
|
|
16
|
+
]
|
stealthmaven/__main__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
<svg viewBox="0 0 133 160" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
+
<path fill-rule="evenodd" clip-rule="evenodd" d="M45.0258 90.8567V144.727L0 118.193V42.6147L65.1265 4.8252L70.7549 16.0816L45.8298 30.5542L87.6394 69.9519V16.0816L132.665 42.6147V118.193L68.3427 155.179L61.9104 144.727L86.0314 130.254L45.0258 90.8567ZM12.8645 110.957V49.8511L34.5733 36.9864L106.936 105.329V88.4445L99.6997 81.2081V37.7904L119.8 49.8511V110.957L97.2876 123.822L25.729 55.479V73.168L32.9653 79.6V123.018L12.8645 110.957Z" fill="url(#nm0)"/>
|
|
3
|
+
<path d="M77.9895 11.2564C77.9895 17.4732 72.9498 22.5129 66.7332 22.5129C60.5166 22.5129 55.4766 17.4732 55.4766 11.2564C55.4766 5.03967 60.5166 0 66.7332 0C72.9498 0 77.9895 5.03967 77.9895 11.2564Z" fill="url(#nm1)"/>
|
|
4
|
+
<path d="M77.9895 148.744C77.9895 154.96 72.9498 160 66.7332 160C60.5166 160 55.4766 154.96 55.4766 148.744C55.4766 142.527 60.5166 137.487 66.7332 137.487C72.9498 137.487 77.9895 142.527 77.9895 148.744Z" fill="url(#nm2)"/>
|
|
5
|
+
<defs>
|
|
6
|
+
<linearGradient id="nm0" x1="66.3324" y1="0.00100541" x2="66.3324" y2="160.003" gradientUnits="userSpaceOnUse">
|
|
7
|
+
<stop stop-color="#4783F2"/>
|
|
8
|
+
<stop offset="1" stop-color="#23E6A8"/>
|
|
9
|
+
</linearGradient>
|
|
10
|
+
<linearGradient id="nm1" x1="66.331" y1="0" x2="66.331" y2="160.002" gradientUnits="userSpaceOnUse">
|
|
11
|
+
<stop stop-color="#4783F2"/>
|
|
12
|
+
<stop offset="1" stop-color="#23E6A8"/>
|
|
13
|
+
</linearGradient>
|
|
14
|
+
<linearGradient id="nm2" x1="66.331" y1="-0.00220857" x2="66.331" y2="160" gradientUnits="userSpaceOnUse">
|
|
15
|
+
<stop stop-color="#4783F2"/>
|
|
16
|
+
<stop offset="1" stop-color="#23E6A8"/>
|
|
17
|
+
</linearGradient>
|
|
18
|
+
</defs>
|
|
19
|
+
</svg>
|
stealthmaven/brand.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""What carries the NodeMaven name: links, the mark, the start page of `open`, the CLI
|
|
2
|
+
banner. Nothing here reaches a page the browser visits - the start page is shown only
|
|
3
|
+
in `stealthmaven open` without a URL, as local content with no requests and no
|
|
4
|
+
scripts bound to the page.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from html import escape
|
|
10
|
+
from importlib.resources import files
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
|
|
14
|
+
NAME = "stealthmaven"
|
|
15
|
+
BY = "by NodeMaven"
|
|
16
|
+
REPO = "https://github.com/nodemaven/stealthmaven"
|
|
17
|
+
SITE = (
|
|
18
|
+
"https://nodemaven.com/?utm_source=stealthmaven&utm_medium={medium}&utm_campaign=stealthmaven"
|
|
19
|
+
)
|
|
20
|
+
SIGNUP = (
|
|
21
|
+
"https://dashboard.nodemaven.com/accounts/signup/"
|
|
22
|
+
"?utm_source=stealthmaven&utm_medium={medium}&utm_campaign=stealthmaven"
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
#: NodeMaven's mark, as in the organisation's GitHub assets.
|
|
26
|
+
MARK_SVG = files(__package__).joinpath("assets/nodemaven-mark.svg").read_text(encoding="utf-8")
|
|
27
|
+
|
|
28
|
+
#: The pages `stealthmaven check` reads, offered on the start page as plain links.
|
|
29
|
+
DETECTORS = (
|
|
30
|
+
("deviceandbrowserinfo.com", "https://deviceandbrowserinfo.com/are_you_a_bot"),
|
|
31
|
+
("BrowserScan", "https://www.browserscan.net/bot-detection"),
|
|
32
|
+
("CreepJS", "https://abrahamjuliot.github.io/creepjs/"),
|
|
33
|
+
("bot.sannysoft.com", "https://bot.sannysoft.com/"),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def banner() -> str:
|
|
38
|
+
return f"{NAME} {__version__} {BY}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def signup(medium: str = "cli") -> str:
|
|
42
|
+
return SIGNUP.format(medium=medium)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def start_page(ident, proxy: str, screen=None) -> str:
|
|
46
|
+
"""The page `stealthmaven open` shows when no URL is given: who this browser is."""
|
|
47
|
+
where = "not looked up"
|
|
48
|
+
if ident.exit:
|
|
49
|
+
where = ident.exit.country + (f", {ident.exit.city}" if ident.exit.city else "")
|
|
50
|
+
rows = [
|
|
51
|
+
("Exit", where),
|
|
52
|
+
("Timezone", ident.timezone or "this machine's"),
|
|
53
|
+
("Languages", ", ".join(ident.languages)),
|
|
54
|
+
("Proxy", proxy),
|
|
55
|
+
]
|
|
56
|
+
if screen:
|
|
57
|
+
rows.append(("Screen", f"{screen[0]}x{screen[1]}, headless"))
|
|
58
|
+
table = "".join(f"<tr><th>{escape(k)}</th><td>{escape(v)}</td></tr>" for k, v in rows)
|
|
59
|
+
links = "".join(f'<a href="{escape(u)}">{escape(n)}</a>' for n, u in DETECTORS)
|
|
60
|
+
site = escape(SITE.format(medium="start_page"))
|
|
61
|
+
return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
|
|
62
|
+
<title>{NAME}</title><style>
|
|
63
|
+
:root {{ --fg:#0b1220; --muted:#5b6475; --card:#f5f7fb; --line:#e2e7f0; --bg:#ffffff;
|
|
64
|
+
--accent:#1153FC; }}
|
|
65
|
+
@media (prefers-color-scheme: dark) {{ :root {{ --fg:#e8edf7; --muted:#97a1b5;
|
|
66
|
+
--card:#141b2b; --line:#24304a; --bg:#0b1020; --accent:#6f9bff; }} }}
|
|
67
|
+
* {{ box-sizing:border-box }}
|
|
68
|
+
body {{ margin:0; min-height:100vh; display:grid; place-items:center; background:var(--bg);
|
|
69
|
+
color:var(--fg); font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif }}
|
|
70
|
+
main {{ width:min(560px,92vw) }}
|
|
71
|
+
header {{ display:flex; align-items:center; gap:14px; margin-bottom:22px }}
|
|
72
|
+
header svg {{ width:40px; height:48px }}
|
|
73
|
+
h1 {{ margin:0; font-size:26px; letter-spacing:-.01em }}
|
|
74
|
+
.by {{ color:var(--muted); font-size:14px }}
|
|
75
|
+
.by a {{ color:inherit }}
|
|
76
|
+
table {{ width:100%; border-collapse:collapse; background:var(--card); border:1px solid var(--line);
|
|
77
|
+
border-radius:12px; overflow:hidden }}
|
|
78
|
+
th, td {{ text-align:left; padding:10px 14px; border-bottom:1px solid var(--line) }}
|
|
79
|
+
tr:last-child th, tr:last-child td {{ border-bottom:0 }}
|
|
80
|
+
th {{ width:32%; color:var(--muted); font-weight:500 }}
|
|
81
|
+
h2 {{ font-size:14px; color:var(--muted); font-weight:500; margin:26px 0 10px }}
|
|
82
|
+
nav {{ display:flex; flex-wrap:wrap; gap:8px }}
|
|
83
|
+
nav a {{ padding:7px 12px; border:1px solid var(--line); border-radius:8px; color:var(--accent);
|
|
84
|
+
text-decoration:none }}
|
|
85
|
+
nav a:hover {{ border-color:var(--accent) }}
|
|
86
|
+
footer {{ margin-top:26px; color:var(--muted); font-size:13px }}
|
|
87
|
+
footer a {{ color:inherit }}
|
|
88
|
+
</style></head><body><main>
|
|
89
|
+
<header>{MARK_SVG}<div><h1>{NAME}</h1>
|
|
90
|
+
<div class="by">{BY} · <a href="{site}">nodemaven.com</a></div></div></header>
|
|
91
|
+
<table>{table}</table>
|
|
92
|
+
<h2>Check this identity</h2><nav>{links}</nav>
|
|
93
|
+
<footer>{NAME} {__version__} · <a href="{REPO}">{REPO.removeprefix("https://")}</a>
|
|
94
|
+
· or run <code>stealthmaven check</code></footer>
|
|
95
|
+
</main></body></html>"""
|
stealthmaven/browser.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
"""Start Chromium through patchright with an identity that matches its exit.
|
|
2
|
+
|
|
3
|
+
from stealthmaven import launch
|
|
4
|
+
|
|
5
|
+
with launch(country="us") as browser: # NodeMaven login from the environment
|
|
6
|
+
page = browser.new_page() # an ordinary Playwright page
|
|
7
|
+
page.goto("https://example.com")
|
|
8
|
+
|
|
9
|
+
`launch()` returns a `Browser`: the patchright `BrowserContext` underneath, with
|
|
10
|
+
the identity it was given and the traffic it used. Anything a `BrowserContext`
|
|
11
|
+
has, a `Browser` has too.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import shutil
|
|
18
|
+
import tempfile
|
|
19
|
+
import warnings
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from urllib.parse import urlsplit
|
|
22
|
+
|
|
23
|
+
from . import geo, identity, profiles, useragent
|
|
24
|
+
from . import screen as screens
|
|
25
|
+
from .proxy import ProxySource, new_session_id, pick_source
|
|
26
|
+
from .relay import Relay
|
|
27
|
+
|
|
28
|
+
#: Switches the identity sets itself, or that replace the browser's own list
|
|
29
|
+
#: rather than add to it (Chromium honours only the last `--disable-features`).
|
|
30
|
+
_RESERVED = (
|
|
31
|
+
"--disable-features",
|
|
32
|
+
"--enable-features",
|
|
33
|
+
"--lang=",
|
|
34
|
+
"--accept-lang",
|
|
35
|
+
"--force-webrtc-ip-handling-policy",
|
|
36
|
+
"--proxy-server",
|
|
37
|
+
"--proxy-bypass-list",
|
|
38
|
+
"--no-proxy-server",
|
|
39
|
+
"--proxy-pac-url",
|
|
40
|
+
"--proxy-auto-detect",
|
|
41
|
+
"--screen-info",
|
|
42
|
+
"--user-agent",
|
|
43
|
+
"--remote-debugging-port",
|
|
44
|
+
"--remote-debugging-address",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Browser:
|
|
49
|
+
"""A running browser: `context` is the patchright `BrowserContext`. `screen`
|
|
50
|
+
is the (width, height) stealthmaven gave it, or None for the machine's own."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, context, playwright, relay, ident, temp_dir, describe, screen=None) -> None:
|
|
53
|
+
self.context = context
|
|
54
|
+
self.identity = ident
|
|
55
|
+
self.proxy = describe
|
|
56
|
+
self.screen = screen
|
|
57
|
+
#: With `cdp_port`, where other tools connect: http://127.0.0.1:<port>, and the
|
|
58
|
+
#: browser's WebSocket URL. None otherwise.
|
|
59
|
+
self.cdp_endpoint: str | None = None
|
|
60
|
+
self.cdp_websocket: str | None = None
|
|
61
|
+
self._pw = playwright
|
|
62
|
+
self._relay = relay
|
|
63
|
+
self._temp = temp_dir
|
|
64
|
+
self._override = None
|
|
65
|
+
|
|
66
|
+
def __getattr__(self, name):
|
|
67
|
+
return getattr(self.context, name)
|
|
68
|
+
|
|
69
|
+
def new_page(self):
|
|
70
|
+
page = self.context.new_page()
|
|
71
|
+
if self._override is not None:
|
|
72
|
+
self._override.install(page)
|
|
73
|
+
return page
|
|
74
|
+
|
|
75
|
+
def _use_override(self, override: dict) -> None:
|
|
76
|
+
"""Client hints for every page: the ones open now, the ones `new_page` makes,
|
|
77
|
+
and the ones the browser opens itself (popups, target=_blank)."""
|
|
78
|
+
self._override = useragent.PageOverride(self.context, override)
|
|
79
|
+
for page in self.context.pages:
|
|
80
|
+
self._override.install(page)
|
|
81
|
+
self.context.on("page", self._override.on_page)
|
|
82
|
+
|
|
83
|
+
def traffic(self) -> dict:
|
|
84
|
+
"""Bytes through the proxy so far, both ways, and per target host."""
|
|
85
|
+
if self._relay is None:
|
|
86
|
+
return {}
|
|
87
|
+
return {
|
|
88
|
+
"bytes_up": self._relay.bytes_up,
|
|
89
|
+
"bytes_down": self._relay.bytes_down,
|
|
90
|
+
"blocked": self._relay.blocked,
|
|
91
|
+
"hosts": self._relay.hosts(),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
def close(self) -> None:
|
|
95
|
+
try:
|
|
96
|
+
if self.context is not None:
|
|
97
|
+
self.context.close()
|
|
98
|
+
finally:
|
|
99
|
+
self.context = None
|
|
100
|
+
try:
|
|
101
|
+
if self._pw is not None:
|
|
102
|
+
self._pw.stop()
|
|
103
|
+
finally:
|
|
104
|
+
self._pw = None
|
|
105
|
+
if self._relay is not None:
|
|
106
|
+
self._relay.stop()
|
|
107
|
+
if self._temp:
|
|
108
|
+
shutil.rmtree(self._temp, ignore_errors=True)
|
|
109
|
+
self._temp = None
|
|
110
|
+
|
|
111
|
+
def __enter__(self) -> Browser:
|
|
112
|
+
return self
|
|
113
|
+
|
|
114
|
+
def __exit__(self, *exc) -> None:
|
|
115
|
+
self.close()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def check_args(args) -> list[str]:
|
|
119
|
+
for arg in args:
|
|
120
|
+
if arg.startswith(_RESERVED):
|
|
121
|
+
raise ValueError(
|
|
122
|
+
f"{arg.split('=', 1)[0]} is set by stealthmaven or would replace the "
|
|
123
|
+
"browser's own list; not accepted"
|
|
124
|
+
)
|
|
125
|
+
return list(args)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _merge(base: dict, extra: dict) -> dict:
|
|
129
|
+
for key, value in extra.items():
|
|
130
|
+
if isinstance(value, dict) and isinstance(base.get(key), dict):
|
|
131
|
+
_merge(base[key], value)
|
|
132
|
+
else:
|
|
133
|
+
base[key] = value
|
|
134
|
+
return base
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
#: NodeMaven blue for the browser's own frame and toolbar (Chrome's "user colour").
|
|
138
|
+
#: Only the person at the window sees it: pages cannot read the browser theme, and
|
|
139
|
+
#: the colour scheme pages see (light/dark) is left to the system.
|
|
140
|
+
THEME_COLOR = 0xFF1153FC
|
|
141
|
+
THEME_VARIANT = 3 # vibrant: the tint still shows on a dark system theme
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def theme_prefs() -> dict:
|
|
145
|
+
signed = THEME_COLOR - (1 << 32) if THEME_COLOR >= 1 << 31 else THEME_COLOR
|
|
146
|
+
return {"browser": {"theme": {"user_color": signed, "color_variant": THEME_VARIANT}}}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def seed_prefs(user_data: str, prefs: dict) -> None:
|
|
150
|
+
"""Merge `prefs` into the profile's `Default/Preferences` before Chromium starts."""
|
|
151
|
+
path = Path(user_data) / "Default" / "Preferences"
|
|
152
|
+
current = {}
|
|
153
|
+
if path.exists():
|
|
154
|
+
try:
|
|
155
|
+
current = json.loads(path.read_text(encoding="utf-8"))
|
|
156
|
+
except ValueError:
|
|
157
|
+
current = {}
|
|
158
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
159
|
+
path.write_text(json.dumps(_merge(current, prefs)), encoding="utf-8")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _upstream(source: ProxySource | None, session_id: str) -> dict[str, str] | None:
|
|
163
|
+
return source.for_session(session_id) if source else None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def launch(
|
|
167
|
+
*,
|
|
168
|
+
proxy: str | None = None,
|
|
169
|
+
country: str | None = None,
|
|
170
|
+
profile: str | None = None,
|
|
171
|
+
timezone: str | None = None,
|
|
172
|
+
locale: str | None = None,
|
|
173
|
+
lookup: bool = True,
|
|
174
|
+
headless: bool = False,
|
|
175
|
+
channel: str | None = None,
|
|
176
|
+
executable_path: str | None = None,
|
|
177
|
+
args=(),
|
|
178
|
+
engine: str = "patchright",
|
|
179
|
+
screen="auto",
|
|
180
|
+
cdp_port: int | None = None,
|
|
181
|
+
) -> Browser:
|
|
182
|
+
"""Start a browser.
|
|
183
|
+
|
|
184
|
+
proxy: a proxy URL, `{session}` where the provider's session id goes. Without
|
|
185
|
+
it, STEALTHMAVEN_PROXY, then NODEMAVEN_LOGIN / NODEMAVEN_PASSWORD; with
|
|
186
|
+
none of them, the machine's own address.
|
|
187
|
+
country: NodeMaven only; another provider takes its country in the URL.
|
|
188
|
+
profile: keep the browser's profile under this name; without it the profile
|
|
189
|
+
is temporary and removed on close.
|
|
190
|
+
timezone, locale: override what the exit says.
|
|
191
|
+
lookup: ask the exit where it is (on by default). Off, nothing is aligned
|
|
192
|
+
unless `timezone` and `locale` are given.
|
|
193
|
+
headless: off by default. A headless browser gets the screen below.
|
|
194
|
+
engine: "patchright" (Chromium, the default) or "camoufox" (Firefox with its own
|
|
195
|
+
fingerprint; needs `pip install "stealthmaven[camoufox]"` and
|
|
196
|
+
`python -m camoufox fetch`). The proxy, the exit lookup and the identity's
|
|
197
|
+
timezone, languages and place are the same for both.
|
|
198
|
+
screen: Chromium only. "auto" (default): where a window has no desktop to land
|
|
199
|
+
on - a server, a Windows service, or `headless=True` - the browser runs
|
|
200
|
+
headless with a 1920x1080 screen and a taskbar-sized work area, set by
|
|
201
|
+
Chrome itself; on a desktop the real screen is left alone. `(w, h)` or
|
|
202
|
+
"WxH" gives that screen always; None never.
|
|
203
|
+
cdp_port: Chromium only. Also listen for the Chrome DevTools Protocol on
|
|
204
|
+
127.0.0.1 at this port (0 picks a free one), so another tool can drive the
|
|
205
|
+
same browser; `browser.cdp_endpoint` says where. Its client decides how
|
|
206
|
+
visible the automation is: patchright's `connect_over_cdp` keeps it hidden,
|
|
207
|
+
a stock CDP client may not.
|
|
208
|
+
"""
|
|
209
|
+
extra = _check_engine(engine, channel, args)
|
|
210
|
+
size, port, extra = _chromium_options(engine, screen, headless, cdp_port, extra)
|
|
211
|
+
source = pick_source(proxy, country)
|
|
212
|
+
if source is None:
|
|
213
|
+
warnings.warn(DIRECT_WARNING, NoProxyWarning, stacklevel=2)
|
|
214
|
+
temp_dir = None
|
|
215
|
+
if profile:
|
|
216
|
+
prof = profiles.open_or_create(profile, new_session_id, engine)
|
|
217
|
+
session_id, user_data = prof.session_id, str(prof.user_data)
|
|
218
|
+
else:
|
|
219
|
+
session_id = new_session_id()
|
|
220
|
+
temp_dir = user_data = tempfile.mkdtemp(prefix="stealthmaven-")
|
|
221
|
+
relay = None
|
|
222
|
+
try:
|
|
223
|
+
# A temporary profile with a sticky source may take another exit when the
|
|
224
|
+
# first one does not answer; a named profile keeps the exit it was made on.
|
|
225
|
+
retries = LOOKUP_ATTEMPTS if (lookup and not profile and source and source.sticky) else 1
|
|
226
|
+
relay, browser_proxy, found = _open_exit(source, session_id, lookup, retries)
|
|
227
|
+
ident = identity.build(found, timezone=timezone, locale=locale)
|
|
228
|
+
if engine == "camoufox":
|
|
229
|
+
context, pw = _start_camoufox(
|
|
230
|
+
user_data, browser_proxy, ident, headless, executable_path
|
|
231
|
+
)
|
|
232
|
+
else:
|
|
233
|
+
seed_prefs(user_data, _merge(ident.prefs(), theme_prefs()))
|
|
234
|
+
context, pw, override = _start(
|
|
235
|
+
user_data, browser_proxy, ident, extra, headless, channel, executable_path, size
|
|
236
|
+
)
|
|
237
|
+
except BaseException:
|
|
238
|
+
if relay is not None:
|
|
239
|
+
relay.stop()
|
|
240
|
+
if temp_dir:
|
|
241
|
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
|
242
|
+
raise
|
|
243
|
+
describe = source.describe() if source else "direct"
|
|
244
|
+
browser = Browser(context, pw, relay, ident, temp_dir, describe, size)
|
|
245
|
+
if engine != "camoufox" and override:
|
|
246
|
+
browser._use_override(override)
|
|
247
|
+
if port:
|
|
248
|
+
_attach_cdp(browser, port)
|
|
249
|
+
return browser
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _chromium_options(engine, screen, headless, cdp_port, extra):
|
|
253
|
+
"""The screen, the DevTools port and the switches they add; refused for Camoufox."""
|
|
254
|
+
if engine == "camoufox":
|
|
255
|
+
if screen not in ("auto", None):
|
|
256
|
+
raise ValueError("screen applies to the patchright engine only")
|
|
257
|
+
if cdp_port is not None:
|
|
258
|
+
raise ValueError("cdp_port applies to the patchright engine only")
|
|
259
|
+
return None, None, extra
|
|
260
|
+
size = screens.resolve(screen, headless)
|
|
261
|
+
if size and any(a.startswith("--window-size") for a in extra):
|
|
262
|
+
raise ValueError("--window-size is set from screen; pass screen=None to set it")
|
|
263
|
+
port = None
|
|
264
|
+
if cdp_port is not None:
|
|
265
|
+
port = cdp_port or _free_port()
|
|
266
|
+
extra = extra + [f"--remote-debugging-port={port}"]
|
|
267
|
+
return size, port, extra
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _attach_cdp(browser, port):
|
|
271
|
+
try:
|
|
272
|
+
browser.cdp_websocket = _cdp_websocket(port)
|
|
273
|
+
except BaseException:
|
|
274
|
+
browser.close()
|
|
275
|
+
raise
|
|
276
|
+
browser.cdp_endpoint = f"http://127.0.0.1:{port}"
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _free_port() -> int:
|
|
280
|
+
import socket
|
|
281
|
+
|
|
282
|
+
with socket.socket() as sock:
|
|
283
|
+
sock.bind(("127.0.0.1", 0))
|
|
284
|
+
return sock.getsockname()[1]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _cdp_websocket(port: int, attempts: int = 50) -> str:
|
|
288
|
+
"""The browser's DevTools WebSocket URL, asked of Chrome itself on loopback
|
|
289
|
+
(http.client, so no system proxy setting can send it elsewhere)."""
|
|
290
|
+
import http.client
|
|
291
|
+
import time
|
|
292
|
+
|
|
293
|
+
last = None
|
|
294
|
+
for _ in range(attempts):
|
|
295
|
+
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
|
|
296
|
+
try:
|
|
297
|
+
conn.request("GET", "/json/version")
|
|
298
|
+
return json.loads(conn.getresponse().read())["webSocketDebuggerUrl"]
|
|
299
|
+
except (OSError, ValueError, KeyError) as exc:
|
|
300
|
+
last = exc
|
|
301
|
+
time.sleep(0.1)
|
|
302
|
+
finally:
|
|
303
|
+
conn.close()
|
|
304
|
+
raise RuntimeError(f"Chrome did not open its DevTools port {port}: {last}")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
ENGINES = ("patchright", "camoufox")
|
|
308
|
+
DIRECT_WARNING = (
|
|
309
|
+
"no proxy configured (no proxy=, STEALTHMAVEN_PROXY or NODEMAVEN_LOGIN): the browser "
|
|
310
|
+
"uses this machine's own address"
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class NoProxyWarning(UserWarning):
|
|
315
|
+
"""launch() found no proxy and connects from this machine's own address."""
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
#: Exits tried for a temporary profile before launch() gives up on the lookup.
|
|
319
|
+
LOOKUP_ATTEMPTS = 3
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _open_exit(source, session_id, lookup, attempts):
|
|
323
|
+
"""The relay, the browser's proxy and the exit's location. An exit the gateway
|
|
324
|
+
cannot reach fails its lookup; with `attempts` > 1 a new session is tried."""
|
|
325
|
+
for attempt in range(attempts):
|
|
326
|
+
upstream = _upstream(source, session_id if attempt == 0 else new_session_id())
|
|
327
|
+
relay = None
|
|
328
|
+
if upstream is None or urlsplit(upstream["server"]).scheme == "http":
|
|
329
|
+
relay = Relay(upstream)
|
|
330
|
+
browser_proxy = {"server": relay.start()}
|
|
331
|
+
else:
|
|
332
|
+
# The relay speaks HTTP to the upstream; anything else goes straight in.
|
|
333
|
+
browser_proxy = upstream
|
|
334
|
+
try:
|
|
335
|
+
return relay, browser_proxy, (_lookup(browser_proxy, relay) if lookup else None)
|
|
336
|
+
except geo.LookupFailed as exc:
|
|
337
|
+
refusal = relay.refusal if relay is not None else None
|
|
338
|
+
if relay is not None:
|
|
339
|
+
relay.stop()
|
|
340
|
+
if attempt == attempts - 1:
|
|
341
|
+
if refusal: # the gateway's own status line: 407 wrong password, 402 no traffic
|
|
342
|
+
raise geo.LookupFailed(f"{exc}; the proxy answered: {refusal}") from None
|
|
343
|
+
raise
|
|
344
|
+
except BaseException: # Ctrl+C during the lookup: do not leave the relay running
|
|
345
|
+
if relay is not None:
|
|
346
|
+
relay.stop()
|
|
347
|
+
raise
|
|
348
|
+
raise AssertionError("unreachable")
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _check_engine(engine, channel, args) -> list[str]:
|
|
352
|
+
if engine not in ENGINES:
|
|
353
|
+
raise ValueError(f"engine must be one of {', '.join(ENGINES)}, got {engine!r}")
|
|
354
|
+
if engine == "camoufox" and (channel or args):
|
|
355
|
+
raise ValueError("channel and args apply to the patchright engine only")
|
|
356
|
+
return check_args(args)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _lookup(browser_proxy, relay):
|
|
360
|
+
if relay is None:
|
|
361
|
+
raise RuntimeError(
|
|
362
|
+
"the exit can be looked up only through an HTTP proxy; pass "
|
|
363
|
+
"timezone= and locale= with lookup=False for this one"
|
|
364
|
+
)
|
|
365
|
+
return geo.lookup(browser_proxy["server"])
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def camoufox_config(ident) -> dict:
|
|
369
|
+
"""Camoufox properties for an identity: the same timezone and place as the
|
|
370
|
+
Chromium engine, and WebRTC candidates that carry the exit's address. Camoufox
|
|
371
|
+
builds the rest of the fingerprint itself."""
|
|
372
|
+
config = {}
|
|
373
|
+
if ident.timezone:
|
|
374
|
+
config["timezone"] = ident.timezone
|
|
375
|
+
if ident.geolocation:
|
|
376
|
+
config["geolocation:latitude"] = ident.geolocation["latitude"]
|
|
377
|
+
config["geolocation:longitude"] = ident.geolocation["longitude"]
|
|
378
|
+
config["geolocation:accuracy"] = ident.geolocation["accuracy"]
|
|
379
|
+
if ident.exit and ident.exit.ip.count(".") == 3:
|
|
380
|
+
config["webrtc:ipv4"] = ident.exit.ip
|
|
381
|
+
return config
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
#: Firefox preferences for the Camoufox engine.
|
|
385
|
+
FIREFOX_PREFS = {
|
|
386
|
+
# Camoufox rewrites the address in a STUN candidate, but the STUN request itself
|
|
387
|
+
# still leaves this machine directly, where a site's own STUN server sees the real
|
|
388
|
+
# address. Proxied traffic only, as on Chromium.
|
|
389
|
+
"media.peerconnection.ice.proxy_only": True,
|
|
390
|
+
"media.peerconnection.ice.proxy_only_if_behind_proxy": True,
|
|
391
|
+
# A fresh Firefox profile downloads its media plugins (Widevine from Google's
|
|
392
|
+
# servers, OpenH264 from Cisco's): 35-50 MiB of proxy traffic per new profile.
|
|
393
|
+
"media.gmp-manager.updateEnabled": False,
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _start_camoufox(user_data, browser_proxy, ident, headless, executable_path):
|
|
398
|
+
try:
|
|
399
|
+
from camoufox.sync_api import NewBrowser
|
|
400
|
+
from playwright.sync_api import sync_playwright
|
|
401
|
+
except ImportError as exc:
|
|
402
|
+
raise RuntimeError(
|
|
403
|
+
'the camoufox engine needs: pip install "stealthmaven[camoufox]", '
|
|
404
|
+
"then python -m camoufox fetch"
|
|
405
|
+
) from exc
|
|
406
|
+
pw = sync_playwright().start()
|
|
407
|
+
try:
|
|
408
|
+
with warnings.catch_warnings():
|
|
409
|
+
# The place and timezone come from a lookup through this exit, which is
|
|
410
|
+
# what Camoufox's geoip would do, so its advice to pass geoip does not apply.
|
|
411
|
+
warnings.filterwarnings("ignore", message=".*geoip.*")
|
|
412
|
+
context = NewBrowser(
|
|
413
|
+
pw,
|
|
414
|
+
persistent_context=True,
|
|
415
|
+
user_data_dir=user_data,
|
|
416
|
+
headless=headless,
|
|
417
|
+
proxy=browser_proxy,
|
|
418
|
+
config=camoufox_config(ident),
|
|
419
|
+
locale=ident.languages,
|
|
420
|
+
executable_path=executable_path,
|
|
421
|
+
firefox_user_prefs=FIREFOX_PREFS,
|
|
422
|
+
i_know_what_im_doing=True,
|
|
423
|
+
)
|
|
424
|
+
except BaseException:
|
|
425
|
+
pw.stop()
|
|
426
|
+
raise
|
|
427
|
+
return context, pw
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _start(user_data, browser_proxy, ident, extra, headless, channel, executable_path, size=None):
|
|
431
|
+
from patchright.sync_api import sync_playwright
|
|
432
|
+
|
|
433
|
+
pw = sync_playwright().start()
|
|
434
|
+
try:
|
|
435
|
+
override = None
|
|
436
|
+
if size:
|
|
437
|
+
headless = True
|
|
438
|
+
if headless and not channel and not executable_path:
|
|
439
|
+
# New headless in the full Chrome binary rather than the separate
|
|
440
|
+
# headless shell, which is a different, smaller build.
|
|
441
|
+
executable_path = pw.chromium.executable_path
|
|
442
|
+
if size:
|
|
443
|
+
# The switch names the browser without "Headless" everywhere, service
|
|
444
|
+
# workers included; the browser then puts the real client hints back
|
|
445
|
+
# on each page (useragent.py says why both).
|
|
446
|
+
override = useragent.override_for(pw, channel, executable_path, browser_proxy)
|
|
447
|
+
extra = extra + screens.switches(size) + [f"--user-agent={override['userAgent']}"]
|
|
448
|
+
context = pw.chromium.launch_persistent_context(
|
|
449
|
+
user_data_dir=user_data,
|
|
450
|
+
headless=headless,
|
|
451
|
+
channel=channel,
|
|
452
|
+
executable_path=executable_path,
|
|
453
|
+
proxy=browser_proxy,
|
|
454
|
+
no_viewport=True,
|
|
455
|
+
timezone_id=ident.timezone,
|
|
456
|
+
geolocation=ident.geolocation,
|
|
457
|
+
args=ident.launch_args() + extra,
|
|
458
|
+
)
|
|
459
|
+
except BaseException:
|
|
460
|
+
pw.stop()
|
|
461
|
+
raise
|
|
462
|
+
return context, pw, override
|