Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: stealth runtime v2 — structured bundle architecture (#380)

luigiagentda0e0a2ce6df
diff --git a/.gitignore b/.gitignore
index c6e46c9b..81157de8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,7 @@
# npm package
# package-lock.json is committed for reproducible installs via npm ci
*.js
+!tests/e2e/fixtures/stealth-service-worker.js
!dashboard/eslint.config.js
!dashboard/vite.config.ts
!internal/assets/*.js
diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.go
index 45347373..38008d4f 100644
--- a/cmd/pinchtab/cmd_config_test.go
+++ b/cmd/pinchtab/cmd_config_test.go
@@ -82,13 +82,13 @@ func TestConfigSetAllowsDashPrefixedValue(t *testing.T) {
})
output := captureStdout(t, func() {
- rootCmd.SetArgs([]string{"config", "set", "browser.extraFlags", "--no-sandbox --disable-gpu"})
+ rootCmd.SetArgs([]string{"config", "set", "browser.extraFlags", "--disable-gpu --ash-no-nudges"})
if err := rootCmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v", err)
}
})
- if !strings.Contains(output, "Set browser.extraFlags = --no-sandbox --disable-gpu") {
+ if !strings.Contains(output, "Set browser.extraFlags = --disable-gpu --ash-no-nudges") {
t.Fatalf("expected success output, got %q", output)
}
@@ -96,8 +96,41 @@ func TestConfigSetAllowsDashPrefixedValue(t *testing.T) {
if err != nil {
t.Fatalf("LoadFileConfig() error = %v", err)
}
- if saved.Browser.ChromeExtraFlags != "--no-sandbox --disable-gpu" {
- t.Fatalf("ChromeExtraFlags = %q, want %q", saved.Browser.ChromeExtraFlags, "--no-sandbox --disable-gpu")
+ if saved.Browser.ChromeExtraFlags != "--disable-gpu --ash-no-nudges" {
+ t.Fatalf("ChromeExtraFlags = %q, want %q", saved.Browser.ChromeExtraFlags, "--disable-gpu --ash-no-nudges")
+ }
+}
+
+func TestConfigSetRejectsUnsafeChromeExtraFlags(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ t.Cleanup(func() {
+ rootCmd.SetArgs(nil)
+ })
+
+ output := captureStdout(t, func() {
+ rootCmd.SetArgs([]string{"config", "set", "browser.extraFlags", "--no-sandbox --disable-gpu"})
+ if err := rootCmd.Execute(); err != nil {
+ t.Fatalf("Execute() error = %v", err)
+ }
+ })
+
+ if !strings.Contains(output, "browser.extraFlags") || !strings.Contains(output, "PINCHTAB_CHROME_NO_SANDBOX") {
+ t.Fatalf("expected unsafe flag warning, got %q", output)
+ }
+
+ saved, _, err := config.LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+ if saved.Browser.ChromeExtraFlags != "" {
+ t.Fatalf("ChromeExtraFlags = %q, want empty string after declining unsafe save", saved.Browser.ChromeExtraFlags)
}
}
diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsx
index bfeabfde..06352c3f 100644
--- a/dashboard/src/pages/SettingsPage.tsx
+++ b/dashboard/src/pages/SettingsPage.tsx
@@ -744,16 +744,15 @@ export default function SettingsPage() {
<strong className="text-text-secondary">
Light:
</strong>{" "}
- Safe baseline stealth. Hides navigator.webdriver,
- removes CDP markers, spoofs
- plugins/languages/hardware.
+ Default baseline stealth. Keeps the lowest-risk
+ launch and JS contract while hiding basic
+ automation markers.
</div>
<div className="text-success/80">
- ✓ No functional side effects
+ ✓ Default product security baseline
</div>
<div className="text-success/80">
- ✓ No security implications — standard automation
- hiding only
+ ✓ No intentional API realism or security tradeoff
</div>
</div>
)}
@@ -762,22 +761,25 @@ export default function SettingsPage() {
<div className="space-y-2">
<div>
<strong className="text-warning">Medium:</strong>{" "}
- Adds Client Hints API, chrome.runtime.connect (for
- Cloudflare Turnstile), chrome.csi/loadTimes,
- enhanced permissions, video codec spoofing.
+ Non-default risk mode. Adds Client Hints,
+ `chrome.runtime` shims, iframe propagation, stack
+ filtering, and native-looking function masking to
+ improve anti-bot compatibility.
</div>
<div className="text-warning/80">
- ⚠ May interfere with error monitoring (Sentry,
- LogRocket) — Error.prepareStackTrace is blocked
+ ⚠ Alters browser-visible APIs and error/stack
+ behavior. Monitoring and debugging tools may see
+ different results.
</div>
<div className="text-warning/80">
- ⚠ Permissions API returns fake states — code
- relying on accurate permission checks may
- misbehave
+ ⚠ Permissions and compatibility shims can return
+ intentionally altered values. Do not use this as
+ the default safety baseline.
</div>
<div className="text-warning/80">
- ⚠ chrome.runtime.connect returns dummy objects —
- real extension messaging won't work
+ ⚠ Reports that require explicitly enabling Medium
+ should be treated as opt-in risk acceptance, not
+ default-path behavior.
</div>
</div>
)}
@@ -788,25 +790,28 @@ export default function SettingsPage() {
<strong className="text-destructive">
Full:
</strong>{" "}
- Maximum stealth. Adds WebGL/canvas fingerprint
- noise, WebRTC IP leak prevention, AudioContext
- protection.
+ Highest-risk non-default mode. Adds graphics,
+ canvas, audio, system-color, and WebRTC
+ alterations on top of Medium.
</div>
<div className="text-destructive/80">
- ⚠ WebRTC forced to relay mode — direct P2P
- connections disabled, video calls may fail
+ ⚠ Browser output is intentionally less native and
+ less stable. Rendering, media, and networking
+ behavior may break or drift from real Chrome.
</div>
<div className="text-destructive/80">
- ⚠ Canvas operations have subtle pixel noise — may
- affect pixel-precise rendering or image comparison
+ ⚠ This mode is not an acceptable default security
+ posture. Only enable it when you explicitly accept
+ the tradeoff surface.
</div>
<div className="text-destructive/80">
- ⚠ WebGL reports spoofed GPU — applications
- detecting GPU capabilities may behave unexpectedly
+ ⚠ Reports that depend on enabling Full should be
+ triaged as non-default operator risk unless a
+ default-path bypass is shown.
</div>
<div className="text-destructive/80">
- ⚠ AudioContext has frequency noise — may affect
- audio fingerprinting detection or processing apps
+ ⚠ WebRTC, WebGL, canvas, and audio behavior can
+ all diverge from baseline Chrome.
</div>
</div>
)}
diff --git a/docker-entrypoint-release.sh b/docker-entrypoint-release.sh
deleted file mode 100644
index de43906b..00000000
--- a/docker-entrypoint-release.sh
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/bin/sh
-set -eu
-
-home_dir="${HOME:-/data}"
-xdg_config_home="${XDG_CONFIG_HOME:-$home_dir/.config}"
-default_config_path="$xdg_config_home/pinchtab/config.json"
-
-mkdir -p "$home_dir" "$xdg_config_home" "$(dirname "$default_config_path")"
-
-# Generate a persisted config on first boot.
-# The PINCHTAB_TOKEN env var can be used to set an auth token via Docker secrets
-# or environment variables. Prefer Docker secrets for sensitive data:
-# docker run -e PINCHTAB_TOKEN_FILE=/run/secrets/pinchtab_token
-if [ -z "${PINCHTAB_CONFIG:-}" ] && [ ! -f "$default_config_path" ]; then
- /usr/local/bin/pinchtab config init >/dev/null
- # Docker containers need to bind to 0.0.0.0 for port publishing to work
- /usr/local/bin/pinchtab config set server.bind "0.0.0.0" >/dev/null
- if [ -n "${PINCHTAB_TOKEN:-}" ]; then
- /usr/local/bin/pinchtab config set server.token "$PINCHTAB_TOKEN" >/dev/null
- fi
-fi
-
-# CHROME SANDBOX DISABLED IN CONTAINERS
-#
-# Chrome requires --no-sandbox inside containers because:
-# - Containers don't have user namespaces (sandboxing requires this)
-# - Container security (cgroups, capabilities, seccomp) provides isolation
-# - The Dockerfile already drops capabilities and uses read-only filesystem
-#
-# This is standard for headless Chrome in containerized environments.
-# Backfill the flag into managed config if not already set.
-if [ -z "${PINCHTAB_CONFIG:-}" ] && [ -f "$default_config_path" ]; then
- current_flags="$(/usr/local/bin/pinchtab config get browser.extraFlags 2>/dev/null || true)"
- if [ -z "$current_flags" ]; then
- /usr/local/bin/pinchtab config set browser.extraFlags "--no-sandbox --disable-gpu" >/dev/null
- fi
-fi
-
-exec "$@"
diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh
index de43906b..dfdc242c 100644
--- a/docker-entrypoint.sh
+++ b/docker-entrypoint.sh
@@ -20,20 +20,4 @@ if [ -z "${PINCHTAB_CONFIG:-}" ] && [ ! -f "$default_config_path" ]; then
fi
fi
-# CHROME SANDBOX DISABLED IN CONTAINERS
-#
-# Chrome requires --no-sandbox inside containers because:
-# - Containers don't have user namespaces (sandboxing requires this)
-# - Container security (cgroups, capabilities, seccomp) provides isolation
-# - The Dockerfile already drops capabilities and uses read-only filesystem
-#
-# This is standard for headless Chrome in containerized environments.
-# Backfill the flag into managed config if not already set.
-if [ -z "${PINCHTAB_CONFIG:-}" ] && [ -f "$default_config_path" ]; then
- current_flags="$(/usr/local/bin/pinchtab config get browser.extraFlags 2>/dev/null || true)"
- if [ -z "$current_flags" ]; then
- /usr/local/bin/pinchtab config set browser.extraFlags "--no-sandbox --disable-gpu" >/dev/null
- fi
-fi
-
exec "$@"
diff --git a/docs/guides/docker.md b/docs/guides/docker.md
index f7cd136d..94e94bb2 100644
--- a/docs/guides/docker.md
+++ b/docs/guides/docker.md
@@ -243,6 +243,8 @@ PinchTab runs Chrome with `--no-sandbox` in containers. This is standard practic
This configuration is used by major headless browser services (Puppeteer, Playwright, Browserless).
+PinchTab manages this compatibility at runtime. Do not put `--no-sandbox` in `browser.extraFlags`.
+
## Resource Notes
Chrome in containers usually needs:
diff --git a/docs/guides/identifying-instances.md b/docs/guides/identifying-instances.md
index e9799686..0451a376 100644
--- a/docs/guides/identifying-instances.md
+++ b/docs/guides/identifying-instances.md
@@ -24,12 +24,15 @@ Now a process listing such as `ps -axo pid,command | rg pinchtab-chrome` gives y
## 2. Add Recognizable Chrome Flags
-Extra Chrome flags are configured through `browser.extraFlags` in `config.json`:
+Use `instanceDefaults.userAgent` for a visible process marker, and reserve `browser.extraFlags` for safe non-security-reducing flags:
```json
{
+ "instanceDefaults": {
+ "userAgent": "PinchTab-Automation/1.0"
+ },
"browser": {
- "extraFlags": "--user-agent=PinchTab-Automation/1.0 --disable-dev-shm-usage"
+ "extraFlags": "--ash-no-nudges --disable-focus-on-load"
}
}
```
@@ -42,6 +45,8 @@ ps -axo pid,command | rg 'PinchTab-Automation|user-data-dir'
Use this when you want to differentiate roles such as “scraper”, “monitor”, or “debug”.
+Do not put security-reducing or PinchTab-owned flags in `browser.extraFlags`. For example, `--user-agent=...`, `--no-sandbox`, and stealth/runtime-owned flags are rejected.
+
## 3. Use Profile Paths As An Identifier
Each managed profile lives under the configured profile base directory. By default that is the OS-specific PinchTab config directory under `profiles/`.
@@ -74,7 +79,7 @@ curl http://localhost:9867/instances
For most setups, this combination is enough:
1. point PinchTab to a renamed Chrome binary via `browser.binary` in config
-2. add a recognizable `browser.extraFlags` marker in config
+2. add a recognizable `instanceDefaults.userAgent` marker or a safe `browser.extraFlags` marker in config
3. verify the profile path or instance ID in the dashboard
## Docker
@@ -82,5 +87,5 @@ For most setups, this combination is enough:
The same approach works in containers:
- set `browser.binary` in config if you need to override the bundled browser path
-- put identifying flags in `browser.extraFlags`
+- put only safe identifying flags in `browser.extraFlags`
- inspect the instance list from the API or dashboard rather than relying only on process names inside the container
diff --git a/docs/implementations/docker-local-testing.md b/docs/implementations/docker-local-testing.md
index aa6a7a47..cd1c804e 100644
--- a/docs/implementations/docker-local-testing.md
+++ b/docs/implementations/docker-local-testing.md
@@ -55,9 +55,6 @@ Create a local config file, for example `./tmp/config.json`:
"bind": "0.0.0.0",
"port": "9867",
"token": "local-test-token"
- },
- "browser": {
- "extraFlags": "--no-sandbox --disable-gpu"
}
}
```
@@ -113,16 +110,12 @@ docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'
## Current Caveat
-The development Docker path may still need explicit Chrome flags on some hosts.
+The Docker runtime path owns `--no-sandbox` compatibility now. Do not put it in `browser.extraFlags`.
-If Chromium fails to launch in the local development image, add:
+If Chromium still fails to launch in an unusual Linux container environment, set:
-```json
-{
- "browser": {
- "extraFlags": "--no-sandbox --disable-gpu"
- }
-}
+```bash
+PINCHTAB_CHROME_NO_SANDBOX=1
```
-The release image path backfills those flags into the managed config automatically.
+Use that environment variable instead of saving `--no-sandbox` into config.
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 9a203418..8b7bd024 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -233,6 +233,27 @@ Current nested file-config shape:
}
```
+`browser.extraFlags` is validated and sanitized. It is only for user-safe Chrome flags that do not weaken browser security and do not override PinchTab-owned launch behavior.
+
+Rejected examples include:
+
+- `--no-sandbox`
+- `--disable-web-security`
+- `--ignore-certificate-errors`
+- `--user-agent=...`
+- `--enable-automation=...`
+- `--disable-blink-features=...`
+
+Use the dedicated config fields instead:
+
+- `instanceDefaults.userAgent` for UA overrides
+- `instanceDefaults.mode` for headed/headless
+- `instanceDefaults.timezone` for timezone
+- `browser.extensionPaths` for extension loading
+- `browser.remoteDebuggingPort` for the remote debugging port
+
+For Linux container compatibility, use the runtime-managed path instead of `browser.extraFlags`. PinchTab enables `--no-sandbox` automatically when needed, and you can force that compatibility mode with `PINCHTAB_CHROME_NO_SANDBOX=1`.
+
## Sections
| Section | Purpose |
diff --git a/internal/assets/stealth.js b/internal/assets/stealth.js
index d6d49398..96f8013a 100644
--- a/internal/assets/stealth.js
+++ b/internal/assets/stealth.js
@@ -11,6 +11,48 @@
const sessionSeed = (typeof __pinchtab_seed !== 'undefined') ? __pinchtab_seed : 42;
const stealthLevel = (typeof __pinchtab_stealth_level !== 'undefined') ? __pinchtab_stealth_level : 'light';
+const headlessMode = (typeof __pinchtab_headless !== 'undefined') ? !!__pinchtab_headless : true;
+const stealthProfile = (typeof __pinchtab_profile !== 'undefined' && __pinchtab_profile && typeof __pinchtab_profile === 'object') ? __pinchtab_profile : {};
+const navigatorProto = Object.getPrototypeOf(navigator) || Navigator.prototype;
+
+function deriveNavigatorPlatformFromUA(ua) {
+ if (ua.includes('Macintosh') || ua.includes('Mac OS X')) return 'MacIntel';
+ if (ua.includes('Windows')) return 'Win32';
+ if (ua.includes('Linux')) return ua.includes('x86_64') ? 'Linux x86_64' : 'Linux';
+ return navigator.platform || 'Win32';
+}
+
+const profileUserAgent = (typeof stealthProfile.userAgent === 'string' && stealthProfile.userAgent) ? stealthProfile.userAgent : (navigator.userAgent || '');
+const profileLanguage = (typeof stealthProfile.language === 'string' && stealthProfile.language) ? stealthProfile.language : (navigator.language || 'en-US');
+const profileLanguages = (Array.isArray(stealthProfile.languages) && stealthProfile.languages.length) ? stealthProfile.languages.slice() : [profileLanguage, 'en'].filter((value, index, list) => !!value && list.indexOf(value) === index);
+const frozenProfileLanguages = Object.freeze(profileLanguages.slice());
+const profileNavigatorPlatform = (typeof stealthProfile.navigatorPlatform === 'string' && stealthProfile.navigatorPlatform) ? stealthProfile.navigatorPlatform : deriveNavigatorPlatformFromUA(profileUserAgent);
+const profileUserAgentData = (stealthProfile.userAgentData && typeof stealthProfile.userAgentData === 'object') ? stealthProfile.userAgentData : null;
+
+function definePrototypeGetter(target, name, getter) {
+ if (!target || typeof getter !== 'function') return;
+ const existing = Object.getOwnPropertyDescriptor(target, name);
+ try {
+ Object.defineProperty(target, name, {
+ get: getter,
+ configurable: true,
+ enumerable: existing ? existing.enumerable : true
+ });
+ } catch (e) {}
+}
+
+function arraysEqual(a, b) {
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
+ return a.every((value, index) => value === b[index]);
+}
+
+function brandListsEqual(a, b) {
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
+ return a.every((value, index) => {
+ const other = b[index];
+ return !!other && value.brand === other.brand && value.version === other.version;
+ });
+}
const seededRandom = (function() {
const cache = {};
@@ -25,14 +67,75 @@ const seededRandom = (function() {
};
})();
+function maskFunctionAsNative(fn, name) {
+ return fn;
+}
+
+function wrapCallableAsNative(fn, applyHandler) {
+ if (typeof fn !== 'function' || typeof applyHandler !== 'function' || typeof Proxy !== 'function') {
+ return fn;
+ }
+ try {
+ return new Proxy(fn, {
+ apply(target, thisArg, args) {
+ return applyHandler(target, thisArg, args || []);
+ }
+ });
+ } catch (e) {
+ return fn;
+ }
+}
+
+function wrapConstructableAsNative(fn, constructHandler) {
+ if (typeof fn !== 'function' || typeof constructHandler !== 'function' || typeof Proxy !== 'function') {
+ return fn;
+ }
+ try {
+ return new Proxy(fn, {
+ apply(target, thisArg, args) {
+ return constructHandler(target, args || [], target);
+ },
+ construct(target, args, newTarget) {
+ return constructHandler(target, args || [], newTarget || target);
+ }
+ });
+ } catch (e) {
+ return fn;
+ }
+}
+
+function sanitizeStackString(stack) {
+ if (typeof stack !== 'string') return stack;
+ const lines = stack.split('\n');
+ if (lines.length <= 1) return stack;
+ const firstLine = lines[0];
+ const filtered = lines.slice(1).filter(line => !stackSanitizerPatterns.some(pattern => pattern.test(line)));
+ return [firstLine].concat(filtered).join('\n');
+}
+
+function sanitizeErrorStack(error) {
+ if (!error || (typeof error !== 'object' && typeof error !== 'function')) return error;
+ try {
+ if (typeof error.stack === 'string') {
+ Object.defineProperty(error, 'stack', {
+ value: sanitizeStackString(error.stack),
+ configurable: true,
+ writable: true,
+ enumerable: false
+ });
+ }
+ } catch (e) {}
+ return error;
+}
+
// ═══════════════════════════════════════════════════════════════════════════
// LIGHT LEVEL - Safe, no functional impact
// ═══════════════════════════════════════════════════════════════════════════
-// - Hides navigator.webdriver
+// - Relies on launch-layer webdriver behavior instead of JS navigator proxying
// - Removes CDP markers (cdc_*, __webdriver, etc.)
// - Spoofs plugins array
-// - Sets navigator.languages, platform, hardwareConcurrency, deviceMemory
-// - Basic chrome.runtime object
+// - Sets navigator.languages, platform
+// - Basic chrome.runtime object (light/medium only)
// ═══════════════════════════════════════════════════════════════════════════
// CDP MARKER CLEANUP - Remove automation traces
@@ -53,121 +156,152 @@ const seededRandom = (function() {
}
})();
-// WEBDRIVER EVASION - Hide the property
-(function() {
- const realNavigator = window.navigator;
- const proxyNavigator = new Proxy(realNavigator, {
- get(target, prop) {
- if (prop === 'webdriver') return undefined;
- return Reflect.get(target, prop, target);
- },
- has(target, prop) {
- if (prop === 'webdriver') return false;
- return Reflect.has(target, prop);
- },
- getOwnPropertyDescriptor(target, prop) {
- if (prop === 'webdriver') return undefined;
- return Reflect.getOwnPropertyDescriptor(target, prop);
- }
- });
-
- try {
- Object.defineProperty(window, 'navigator', {
- get: () => proxyNavigator,
- configurable: true
- });
- } catch(e) {}
-
- const proto = Object.getPrototypeOf(realNavigator);
- try { delete realNavigator.webdriver; } catch(e) {}
- try { delete proto.webdriver; } catch(e) {}
-})();
-
// BASIC CHROME OBJECT
if (!window.chrome) { window.chrome = {}; }
if (!window.chrome.runtime) {
window.chrome.runtime = { onConnect: undefined, onMessage: undefined };
}
-// PLUGINS ARRAY - Proper PluginArray that passes instanceof checks
+// PLUGINS / MIMETYPES - prefer native values when available; only synthesize
+// a modern PDF surface if Chrome exposes an empty array.
(function() {
+ try {
+ if (navigator.plugins && navigator.plugins.length > 0 && navigator.mimeTypes && navigator.mimeTypes.length > 0) {
+ return;
+ }
+ } catch (e) {}
+
const fakePlugins = [
- { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format', length: 1 },
- { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai', description: '', length: 1 },
- { name: 'Native Client', filename: 'internal-nacl-plugin', description: '', length: 1 }
+ {
+ name: 'PDF Viewer',
+ filename: 'internal-pdf-viewer',
+ description: 'Portable Document Format',
+ mimeTypes: [{ type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format' }]
+ },
+ {
+ name: 'Chrome PDF Viewer',
+ filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai',
+ description: 'Portable Document Format',
+ mimeTypes: [{ type: 'application/x-google-chrome-pdf', suffixes: 'pdf', description: 'Portable Document Format' }]
+ },
+ {
+ name: 'Chromium PDF Viewer',
+ filename: 'internal-pdf-viewer',
+ description: 'Portable Document Format',
+ mimeTypes: [{ type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format' }]
+ }
];
-
- const realPluginsProto = Object.getPrototypeOf(navigator.plugins);
- const pluginArray = Object.create(realPluginsProto, {
- length: { value: fakePlugins.length, writable: false, enumerable: true },
+
+ const realPluginsProto = Object.getPrototypeOf(navigator.plugins) || PluginArray.prototype;
+ const realMimeTypesProto = Object.getPrototypeOf(navigator.mimeTypes) || MimeTypeArray.prototype;
+ const pluginArray = Object.create(realPluginsProto);
+ const mimeTypeArray = Object.create(realMimeTypesProto);
+
+ Object.defineProperties(pluginArray, {
item: { value: function(i) { return this[i] || null; }, writable: false },
- namedItem: { value: function(name) {
- for (let i = 0; i < this.length; i++) {
- if (this[i] && this[i].name === name) return this[i];
- }
- return null;
- }, writable: false },
+ namedItem: { value: function(name) { return this[name] || null; }, writable: false },
refresh: { value: function() {}, writable: false }
});
-
- fakePlugins.forEach((p, i) => {
- const plugin = Object.create(Plugin.prototype, {
- name: { value: p.name, writable: false, enumerable: true },
- filename: { value: p.filename, writable: false, enumerable: true },
- description: { value: p.description, writable: false, enumerable: true },
- length: { value: p.length, writable: false, enumerable: true },
- item: { value: function() { return null; }, writable: false },
- namedItem: { value: function() { return null; }, writable: false }
+
+ Object.defineProperties(mimeTypeArray, {
+ item: { value: function(i) { return this[i] || null; }, writable: false },
+ namedItem: { value: function(name) { return this[name] || null; }, writable: false }
+ });
+
+ const mimeTypeEntries = [];
+ fakePlugins.forEach((pluginDef, pluginIndex) => {
+ const plugin = Object.create(Plugin.prototype);
+ const pluginMimeTypes = [];
+
+ pluginDef.mimeTypes.forEach((mimeDef) => {
+ let mimeType = mimeTypeEntries.find((entry) => entry.type === mimeDef.type);
+ if (!mimeType) {
+ mimeType = Object.create(MimeType.prototype, {
+ type: { value: mimeDef.type, writable: false, enumerable: true },
+ suffixes: { value: mimeDef.suffixes, writable: false, enumerable: true },
+ description: { value: mimeDef.description, writable: false, enumerable: true }
+ });
+ mimeTypeEntries.push(mimeType);
+ }
+ pluginMimeTypes.push(mimeType);
});
- Object.defineProperty(pluginArray, i, { value: plugin, writable: false, enumerable: true });
- Object.defineProperty(pluginArray, p.name, { value: plugin, writable: false, enumerable: false });
+
+ Object.defineProperties(plugin, {
+ name: { value: pluginDef.name, writable: false, enumerable: true },
+ filename: { value: pluginDef.filename, writable: false, enumerable: true },
+ description: { value: pluginDef.description, writable: false, enumerable: true },
+ length: { value: pluginMimeTypes.length, writable: false, enumerable: true },
+ item: { value: function(i) { return this[i] || null; }, writable: false },
+ namedItem: { value: function(name) { return this[name] || null; }, writable: false }
+ });
+
+ pluginMimeTypes.forEach((mimeType, mimeIndex) => {
+ try {
+ Object.defineProperty(mimeType, 'enabledPlugin', { get: () => plugin, configurable: true });
+ } catch (e) {}
+ Object.defineProperty(plugin, mimeIndex, { value: mimeType, writable: false, enumerable: true });
+ Object.defineProperty(plugin, mimeType.type, { value: mimeType, writable: false, enumerable: false });
+ });
+
+ Object.defineProperty(pluginArray, pluginIndex, { value: plugin, writable: false, enumerable: true });
+ Object.defineProperty(pluginArray, pluginDef.name, { value: plugin, writable: false, enumerable: false });
});
-
- Object.defineProperty(navigator, 'plugins', { get: () => pluginArray, configurable: true });
+
+ mimeTypeEntries.forEach((mimeType, mimeIndex) => {
+ Object.defineProperty(mimeTypeArray, mimeIndex, { value: mimeType, writable: false, enumerable: true });
+ Object.defineProperty(mimeTypeArray, mimeType.type, { value: mimeType, writable: false, enumerable: false });
+ });
+
+ Object.defineProperty(pluginArray, 'length', { value: fakePlugins.length, writable: false, enumerable: true });
+ Object.defineProperty(mimeTypeArray, 'length', { value: mimeTypeEntries.length, writable: false, enumerable: true });
+
+ definePrototypeGetter(navigatorProto, 'plugins', () => pluginArray);
+ definePrototypeGetter(navigatorProto, 'mimeTypes', () => mimeTypeArray);
})();
// NAVIGATOR PROPERTIES
-Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'], configurable: true });
-
(function() {
- const ua = navigator.userAgent || '';
- let platform = 'Win32';
- if (ua.includes('Macintosh') || ua.includes('Mac OS X')) platform = 'MacIntel';
- else if (ua.includes('Linux')) platform = ua.includes('x86_64') ? 'Linux x86_64' : 'Linux';
- Object.defineProperty(navigator, 'platform', { get: () => platform, configurable: true });
+ if (navigator.language !== profileLanguage) {
+ definePrototypeGetter(navigatorProto, 'language', () => profileLanguage);
+ }
+ if (!arraysEqual(navigator.languages || [], frozenProfileLanguages)) {
+ definePrototypeGetter(navigatorProto, 'languages', () => frozenProfileLanguages);
+ }
+ if (navigator.platform !== profileNavigatorPlatform) {
+ definePrototypeGetter(navigatorProto, 'platform', () => profileNavigatorPlatform);
+ }
})();
-const hardwareCore = 2 + Math.floor(seededRandom(sessionSeed) * 6) * 2;
-const deviceMem = [2, 4, 8, 16][Math.floor(seededRandom(sessionSeed * 2) * 4)];
-
-Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => hardwareCore, configurable: true });
-Object.defineProperty(navigator, 'deviceMemory', { get: () => deviceMem, configurable: true });
-
Object.defineProperty(navigator.connection || {}, 'rtt', {
get: () => 50 + Math.floor(seededRandom(sessionSeed * 3) * 100),
configurable: true
});
-// TIMEZONE OVERRIDE
-const __pinchtab_origGetTimezoneOffset = Date.prototype.getTimezoneOffset;
-Object.defineProperty(Date.prototype, 'getTimezoneOffset', {
- value: function() { return window.__pinchtab_timezone || __pinchtab_origGetTimezoneOffset.call(this); },
- configurable: true
-});
-
-// BASIC PERMISSIONS (notifications only)
-const originalQuery = navigator.permissions.query.bind(navigator.permissions);
-navigator.permissions.query = (parameters) => (
- parameters.name === 'notifications' ?
- Promise.resolve({ state: Notification.permission === 'default' ? 'prompt' : Notification.permission, onchange: null }) :
- originalQuery(parameters)
-);
+// NETWORK INFORMATION - downlinkMax is often missing in headless.
+// Define it on the prototype so page checks see a normal API surface without
+// creating an own-property mismatch on navigator.connection instances.
+if (navigator.connection) {
+ try {
+ const connectionProto = Object.getPrototypeOf(navigator.connection);
+ if (connectionProto && !Object.prototype.hasOwnProperty.call(connectionProto, 'downlinkMax')) {
+ Object.defineProperty(connectionProto, 'downlinkMax', {
+ get: () => Infinity,
+ configurable: true,
+ enumerable: true
+ });
+ }
+ } catch (e) {}
+}
// SCREEN DIMENSIONS - Headless often has weird/small values
(function() {
- const screenWidth = 1920;
- const screenHeight = 1080;
- const availHeight = 1055; // Account for taskbar
+ if (!headlessMode) return;
+ const outerWidth = Math.max(window.outerWidth || 0, window.innerWidth || 0, 1280);
+ const outerHeight = Math.max(window.outerHeight || 0, window.innerHeight || 0, 720);
+ const screenWidth = Math.max(outerWidth + 120, 1366);
+ const screenHeight = Math.max(outerHeight + 80, 768);
+ const chromeHeight = Math.max(screenHeight - outerHeight, 32);
+ const availHeight = Math.max(outerHeight, screenHeight - chromeHeight);
Object.defineProperty(screen, 'width', { get: () => screenWidth, configurable: true });
Object.defineProperty(screen, 'height', { get: () => screenHeight, configurable: true });
@@ -177,9 +311,15 @@ navigator.permissions.query = (parameters) => (
Object.defineProperty(screen, 'pixelDepth', { get: () => 24, configurable: true });
})();
+if (!(window.devicePixelRatio > 0)) {
+ try {
+ Object.defineProperty(window, 'devicePixelRatio', { get: () => 1, configurable: true });
+ } catch (e) {}
+}
+
// BATTERY API - Headless often lacks this
if (!navigator.getBattery) {
- navigator.getBattery = function() {
+ navigator.getBattery = wrapCallableAsNative(function getBattery() {
return Promise.resolve({
charging: true,
chargingTime: 0,
@@ -188,7 +328,7 @@ if (!navigator.getBattery) {
addEventListener: function() {},
removeEventListener: function() {}
});
- };
+ }, (target, thisArg, args) => Reflect.apply(target, thisArg, args));
}
// ═══════════════════════════════════════════════════════════════════════════
@@ -197,29 +337,13 @@ if (!navigator.getBattery) {
// Adds:
// - navigator.userAgentData (Client Hints API)
// - chrome.runtime.connect/sendMessage (required by Cloudflare Turnstile)
-// - chrome.csi, chrome.loadTimes, chrome.app
-// - Error.prepareStackTrace protection
-// - Enhanced permissions API
-// - Video codec spoofing
// - maxTouchPoints
//
-// ⚠️ May interfere with: Error monitoring (Sentry), extension messaging
+// ⚠️ May interfere with: extension messaging
// ═══════════════════════════════════════════════════════════════════════════
if (stealthLevel === 'medium' || stealthLevel === 'full') {
-// ERROR.PREPARESTACKTRACE PROTECTION
-// ⚠️ May interfere with error monitoring tools (Sentry, LogRocket, etc.)
-(function() {
- const originalPrepareStackTrace = Error.prepareStackTrace;
- Object.defineProperty(Error, 'prepareStackTrace', {
- get() { return originalPrepareStackTrace; },
- set(fn) { /* block modifications to prevent CDP detection */ },
- configurable: true,
- enumerable: false
- });
-})();
-
// ENHANCED CDP MARKER CLEANUP (includes puppeteer/playwright)
(function() {
const patterns = [/^__puppeteer/, /^__playwright/, /^\$chrome_/];
@@ -232,10 +356,11 @@ if (stealthLevel === 'medium' || stealthLevel === 'full') {
// CHROME EXTENDED APIS
(function() {
+ if (stealthLevel !== 'medium') return;
// chrome.runtime.connect - required by Cloudflare Turnstile
// ⚠️ Returns dummy Port object - real extension messaging won't work
if (!window.chrome.runtime.connect) {
- window.chrome.runtime.connect = function(extensionId, connectInfo) {
+ const connect = function connect(extensionId, connectInfo) {
return {
name: connectInfo?.name || '',
sender: undefined,
@@ -245,124 +370,157 @@ if (stealthLevel === 'medium' || stealthLevel === 'full') {
disconnect: function() {}
};
};
+ window.chrome.runtime.connect = wrapCallableAsNative(connect, (target, thisArg, args) => Reflect.apply(target, thisArg, args));
}
if (!window.chrome.runtime.sendMessage) {
- window.chrome.runtime.sendMessage = function(extensionId, message, options, callback) {
+ const sendMessage = function sendMessage(extensionId, message, options, callback) {
if (typeof callback === 'function') setTimeout(callback, 0);
};
+ window.chrome.runtime.sendMessage = wrapCallableAsNative(sendMessage, (target, thisArg, args) => Reflect.apply(target, thisArg, args));
}
window.chrome.runtime.onConnect = window.chrome.runtime.onConnect || { addListener: function() {}, removeListener: function() {}, hasListener: function() { return false; } };
window.chrome.runtime.onMessage = window.chrome.runtime.onMessage || { addListener: function() {}, removeListener: function() {}, hasListener: function() { return false; } };
- // chrome.csi - Chrome Speed Index
- if (!window.chrome.csi) {
- window.chrome.csi = function() {
- const now = Date.now();
- return { startE: now - 500, onloadT: now - 100, pageT: now, tran: 15 };
- };
- }
-
- // chrome.loadTimes - deprecated but still checked
- if (!window.chrome.loadTimes) {
- window.chrome.loadTimes = function() {
- const now = Date.now() / 1000;
- return {
- requestTime: now - 0.5, startLoadTime: now - 0.4, commitLoadTime: now - 0.3,
- finishDocumentLoadTime: now - 0.1, finishLoadTime: now, firstPaintTime: now - 0.2,
- firstPaintAfterLoadTime: 0, navigationType: "Other", wasFetchedViaSpdy: false,
- wasNpnNegotiated: true, npnNegotiatedProtocol: "h2", wasAlternateProtocolAvailable: false, connectionInfo: "h2"
- };
- };
- }
-
- // chrome.app
- if (!window.chrome.app) {
- window.chrome.app = {
- isInstalled: false,
- InstallState: { DISABLED: 'disabled', INSTALLED: 'installed', NOT_INSTALLED: 'not_installed' },
- RunningState: { CANNOT_RUN: 'cannot_run', READY_TO_RUN: 'ready_to_run', RUNNING: 'running' },
- getDetails: function() { return null; },
- getIsInstalled: function() { return false; }
- };
- }
})();
// NAVIGATOR.USERAGENTDATA - Client Hints API (required by Turnstile/CF)
(function() {
- const ua = navigator.userAgent || '';
- const chromeMatch = ua.match(/Chrome\/(\d+)/);
- const chromeVersion = chromeMatch ? chromeMatch[1] : '129';
-
- let platform = 'Windows', platformVersion = '15.0.0';
- if (ua.includes('Macintosh') || ua.includes('Mac OS X')) { platform = 'macOS'; platformVersion = '14.0.0'; }
- else if (ua.includes('Linux')) { platform = 'Linux'; platformVersion = '6.5.0'; }
-
- const brands = [
- { brand: 'Chromium', version: chromeVersion },
- { brand: 'Google Chrome', version: chromeVersion },
- { brand: 'Not=A?Brand', version: '24' }
- ];
-
+ if (!profileUserAgentData) return;
+
+ const nativeUAData = navigator.userAgentData;
+ if (nativeUAData) {
+ return;
+ }
+
+ const brands = Array.isArray(profileUserAgentData.brands) ? profileUserAgentData.brands.map((brand) => ({ brand: brand.brand, version: brand.version })) : [];
+ const fullVersionList = Array.isArray(profileUserAgentData.fullVersionList) ? profileUserAgentData.fullVersionList.map((brand) => ({ brand: brand.brand, version: brand.version })) : [];
const userAgentData = {
brands: brands,
- mobile: false,
- platform: platform,
- getHighEntropyValues: async function(hints) {
- const values = { brands: brands, mobile: false, platform: platform };
+ mobile: !!profileUserAgentData.mobile,
+ platform: profileUserAgentData.platform,
+ getHighEntropyValues: async function getHighEntropyValues(hints) {
+ const values = { brands: brands, mobile: !!profileUserAgentData.mobile, platform: profileUserAgentData.platform };
for (const hint of hints) {
- if (hint === 'platformVersion') values.platformVersion = platformVersion;
- else if (hint === 'architecture') values.architecture = 'x86';
- else if (hint === 'model') values.model = '';
- else if (hint === 'bitness') values.bitness = '64';
- else if (hint === 'uaFullVersion') values.uaFullVersion = chromeVersion + '.0.0.0';
- else if (hint === 'fullVersionList') values.fullVersionList = brands.map(b => ({ ...b, version: b.version + '.0.0.0' }));
- else if (hint === 'wow64') values.wow64 = false;
+ if (hint === 'platformVersion') values.platformVersion = profileUserAgentData.platformVersion;
+ else if (hint === 'architecture') values.architecture = profileUserAgentData.architecture;
+ else if (hint === 'model') values.model = profileUserAgentData.model || '';
+ else if (hint === 'bitness') values.bitness = profileUserAgentData.bitness || '64';
+ else if (hint === 'uaFullVersion') values.uaFullVersion = (fullVersionList[1] && fullVersionList[1].version) || '';
+ else if (hint === 'fullVersionList') values.fullVersionList = fullVersionList;
+ else if (hint === 'wow64') values.wow64 = !!profileUserAgentData.wow64;
}
return values;
},
- toJSON: function() { return { brands: this.brands, mobile: this.mobile, platform: this.platform }; }
+ toJSON: function toJSON() { return { brands: this.brands, mobile: this.mobile, platform: this.platform }; }
};
-
- Object.defineProperty(Navigator.prototype, 'userAgentData', { get: () => userAgentData, configurable: true, enumerable: true });
+
+ userAgentData.getHighEntropyValues = wrapCallableAsNative(userAgentData.getHighEntropyValues, (target, thisArg, args) => Reflect.apply(target, thisArg, args));
+ userAgentData.toJSON = wrapCallableAsNative(userAgentData.toJSON, (target, thisArg, args) => Reflect.apply(target, thisArg, args));
+ definePrototypeGetter(navigatorProto, 'userAgentData', () => userAgentData);
})();
-// ENHANCED PERMISSIONS API
-// ⚠️ Returns fake permission states - may affect permission-dependent logic
+// maxTouchPoints
+if (navigator.maxTouchPoints !== 0) {
+ definePrototypeGetter(navigatorProto, 'maxTouchPoints', () => 0);
+}
+
+// IFRAME ISOLATION - ensure same-origin iframe contexts receive the same
+// medium-tier compatibility surface even for dynamic about:blank/srcdoc frames.
(function() {
- const origQuery = navigator.permissions.query.bind(navigator.permissions);
- navigator.permissions.query = async function(desc) {
- const handlers = {
- 'notifications': () => Notification.permission === 'default' ? 'prompt' : Notification.permission,
- 'geolocation': () => 'prompt',
- 'camera': () => 'prompt',
- 'microphone': () => 'prompt',
- 'background-sync': () => 'granted',
- 'accelerometer': () => 'granted',
- 'gyroscope': () => 'granted'
+ const patchIframeWindow = (frameWindow) => {
+ try {
+ if (!frameWindow || frameWindow === window || frameWindow.__pinchtabIframePatched) return;
+ Object.defineProperty(frameWindow, '__pinchtabIframePatched', { value: true, configurable: true });
+
+ if (window.chrome && !frameWindow.chrome) {
+ frameWindow.chrome = {};
+ }
+ if (window.chrome && frameWindow.chrome && !frameWindow.chrome.runtime) {
+ frameWindow.chrome.runtime = window.chrome.runtime;
+ }
+ if (window.chrome && frameWindow.chrome && !frameWindow.chrome.app && window.chrome.app) {
+ frameWindow.chrome.app = window.chrome.app;
+ }
+
+ const childNavigator = frameWindow.navigator;
+ if (!childNavigator) return;
+ const childNavigatorProto = Object.getPrototypeOf(childNavigator);
+
+ if (navigator.userAgentData && childNavigatorProto && !('userAgentData' in childNavigator)) {
+ try {
+ Object.defineProperty(childNavigatorProto, 'userAgentData', {
+ get: () => navigator.userAgentData,
+ configurable: true,
+ enumerable: true
+ });
+ } catch (e) {}
+ }
+
+ if (childNavigator.permissions && typeof navigator.permissions.query === 'function') {
+ try {
+ childNavigator.permissions.query = wrapCallableAsNative(navigator.permissions.query, (target, thisArg, args) => {
+ return Reflect.apply(target, navigator.permissions, args);
+ });
+ maskFunctionAsNative(childNavigator.permissions.query, 'query');
+ } catch (e) {}
+ }
+
+ if (typeof navigator.maxTouchPoints !== 'undefined') {
+ try {
+ Object.defineProperty(childNavigator, 'maxTouchPoints', {
+ get: () => navigator.maxTouchPoints,
+ configurable: true
+ });
+ } catch (e) {}
+ }
+ } catch (e) {}
+ };
+
+ const patchIframeElement = (iframe) => {
+ if (!iframe || iframe.__pinchtabIframeObserved) return;
+ try {
+ Object.defineProperty(iframe, '__pinchtabIframeObserved', { value: true, configurable: true });
+ } catch (e) {}
+
+ const apply = () => {
+ try {
+ const frameWindow = iframe.contentWindow;
+ if (!frameWindow) return;
+ const href = frameWindow.location && frameWindow.location.href ? frameWindow.location.href : '';
+ if (href && href !== 'about:blank' && href !== 'about:srcdoc' && frameWindow.location.origin !== window.location.origin) {
+ return;
+ }
+ patchIframeWindow(frameWindow);
+ } catch (e) {}
};
- if (desc.name in handlers) return { state: handlers[desc.name](), onchange: null };
- return origQuery(desc);
+
+ iframe.addEventListener('load', apply, true);
+ setTimeout(apply, 0);
};
-})();
-// VIDEO CODEC SPOOFING
-// ⚠️ Returns "probably" for common codecs - may affect codec selection logic
-(function() {
- const originalCanPlayType = HTMLMediaElement.prototype.canPlayType;
- HTMLMediaElement.prototype.canPlayType = function(type) {
- if (type.includes('avc1') || type.includes('h264')) return 'probably';
- if (type.includes('mp4a.40') || type.includes('aac')) return 'probably';
- if (type === 'video/mp4' || type === 'audio/mp4') return 'probably';
- if (type.includes('vp8') || type.includes('vp9') || type.includes('opus')) return 'probably';
- if (type === 'video/webm' || type === 'audio/webm') return 'probably';
- return originalCanPlayType.apply(this, arguments);
+ const registerNode = (node) => {
+ if (!node || node.nodeType !== 1) return;
+ if (node.tagName === 'IFRAME') {
+ patchIframeElement(node);
+ }
+ if (typeof node.querySelectorAll === 'function') {
+ node.querySelectorAll('iframe').forEach(patchIframeElement);
+ }
};
-})();
-// maxTouchPoints
-Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 0, configurable: true });
+ if (document.documentElement) {
+ const observer = new MutationObserver((mutations) => {
+ mutations.forEach((mutation) => {
+ mutation.addedNodes.forEach(registerNode);
+ });
+ });
+ observer.observe(document.documentElement, { childList: true, subtree: true });
+ }
+
+ document.querySelectorAll('iframe').forEach(patchIframeElement);
+})();
} // end medium level
@@ -370,20 +528,46 @@ Object.defineProperty(navigator, 'maxTouchPoints', { get: () => 0, configurable:
// FULL LEVEL - Maximum stealth (may break functionality)
// ═══════════════════════════════════════════════════════════════════════════
// Adds:
-// - WebGL vendor/renderer spoofing
-// - Canvas fingerprint noise
-// - WebRTC IP leak prevention
-// - AudioContext fingerprint protection
-// - Font measurement noise
+// - screen/window realism adjustments
+// - headless-only WebGL vendor/renderer spoofing
//
-// ⚠️ May break: WebRTC video calls, canvas-dependent apps, audio processing
+// ⚠️ May break: graphics-dependent sites in headless mode
// ═══════════════════════════════════════════════════════════════════════════
if (stealthLevel === 'full') {
+(function() {
+ if (!headlessMode) return;
+ const numericWindowValue = (value) => {
+ return Number.isFinite(value) ? value : 0;
+ };
+ const defineWindowMetric = (name, value) => {
+ try {
+ Object.defineProperty(window, name, { get: () => value, configurable: true });
+ } catch (e) {}
+ };
+
+ const screenX = Math.max(numericWindowValue(window.screenX), numericWindowValue(window.screenLeft));
+ const screenY = Math.max(numericWindowValue(window.screenY), numericWindowValue(window.screenTop));
+ const innerWidth = Math.max(numericWindowValue(window.innerWidth), 1280);
+ const innerHeight = Math.max(numericWindowValue(window.innerHeight), 720);
+ const widthDelta = Math.max(numericWindowValue(window.outerWidth) - innerWidth, 0);
+ const heightDelta = Math.max(numericWindowValue(window.outerHeight) - innerHeight, 0);
+ const outerWidth = widthDelta > 120 ? innerWidth : Math.max(numericWindowValue(window.outerWidth), innerWidth);
+ const outerHeight = heightDelta > 96 ? innerHeight + 80 : Math.max(numericWindowValue(window.outerHeight), innerHeight + Math.min(heightDelta, 96));
+
+ defineWindowMetric('screenX', screenX);
+ defineWindowMetric('screenLeft', screenX);
+ defineWindowMetric('screenY', screenY);
+ defineWindowMetric('screenTop', screenY);
+ defineWindowMetric('outerWidth', outerWidth);
+ defineWindowMetric('outerHeight', outerHeight);
+})();
+
// WebGL SPOOFING
// ⚠️ Changes reported GPU - may affect WebGL-dependent applications
(function() {
+ if (!headlessMode) return;
const ua = navigator.userAgent || '';
let vendor = 'Google Inc. (Intel)';
let renderer = 'ANGLE (Intel, Intel(R) UHD Graphics 630 Direct3D11 vs_5_0 ps_5_0)';
@@ -398,105 +582,19 @@ if (stealthLevel === 'full') {
const spoofWebGL = (proto) => {
const getParameter = proto.getParameter;
- proto.getParameter = function(parameter) {
+ proto.getParameter = wrapCallableAsNative(getParameter, (target, thisArg, args) => {
+ const parameter = args[0];
if (parameter === 37445) return vendor; // UNMASKED_VENDOR
if (parameter === 37446) return renderer; // UNMASKED_RENDERER
- return getParameter.apply(this, arguments);
- };
+ return Reflect.apply(target, thisArg, args);
+ });
};
spoofWebGL(WebGLRenderingContext.prototype);
if (typeof WebGL2RenderingContext !== 'undefined') spoofWebGL(WebGL2RenderingContext.prototype);
})();
-// CANVAS FINGERPRINT NOISE
-// ⚠️ Adds subtle pixel noise - may affect pixel-precise canvas operations
-const originalToDataURL = HTMLCanvasElement.prototype.toDataURL;
-const originalGetImageData = CanvasRenderingContext2D.prototype.getImageData;
-
-HTMLCanvasElement.prototype.toDataURL = function(...args) {
- const context = this.getContext('2d');
- if (context && this.width > 0 && this.height > 0) {
- const tempCanvas = document.createElement('canvas');
- tempCanvas.width = this.width;
- tempCanvas.height = this.height;
- const tempCtx = tempCanvas.getContext('2d');
- tempCtx.drawImage(this, 0, 0);
- const imageData = tempCtx.getImageData(0, 0, this.width, this.height);
- const pixelCount = Math.min(10, Math.floor(imageData.data.length / 400));
- for (let i = 0; i < pixelCount; i++) {
- const idx = Math.floor(seededRandom(sessionSeed + i) * (imageData.data.length / 4)) * 4;
- if (imageData.data[idx] < 255) imageData.data[idx] += 1;
- if (imageData.data[idx + 1] < 255) imageData.data[idx + 1] += 1;
- }
- tempCtx.putImageData(imageData, 0, 0);
- return originalToDataURL.apply(tempCanvas, args);
- }
- return originalToDataURL.apply(this, args);
-};
-
-HTMLCanvasElement.prototype.toBlob = function(callback, type, quality) {
- const dataURL = this.toDataURL(type, quality);
- const arr = dataURL.split(',');
- const mime = arr[0].match(/:(.*?);/)[1];
- const bstr = atob(arr[1]);
- let n = bstr.length;
- const u8arr = new Uint8Array(n);
- while(n--){ u8arr[n] = bstr.charCodeAt(n); }
- setTimeout(() => callback(new Blob([u8arr], {type: mime})), 5 + seededRandom(sessionSeed + 1000) * 10);
-};
-
-CanvasRenderingContext2D.prototype.getImageData = function(...args) {
- const imageData = originalGetImageData.apply(this, args);
- const pixelCount = imageData.data.length / 4;
- const noisyPixels = Math.min(10, pixelCount * 0.0001);
- for (let i = 0; i < noisyPixels; i++) {
- const pixelIndex = Math.floor(seededRandom(sessionSeed + 2000 + i) * pixelCount) * 4;
- imageData.data[pixelIndex] = Math.min(255, Math.max(0, imageData.data[pixelIndex] + (seededRandom(sessionSeed + 3000 + i) > 0.5 ? 1 : -1)));
- }
- return imageData;
-};
-
-// FONT MEASUREMENT NOISE
-const originalMeasureText = CanvasRenderingContext2D.prototype.measureText;
-CanvasRenderingContext2D.prototype.measureText = function(text) {
- const metrics = originalMeasureText.apply(this, arguments);
- const noise = 0.0001 + (seededRandom(sessionSeed + text.length) * 0.0002);
- return new Proxy(metrics, {
- get(target, prop) {
- if (prop === 'width') return target.width * (1 + noise);
- return target[prop];
- }
- });
-};
-
-// WEBRTC IP LEAK PREVENTION
-// ⚠️ Forces relay mode - direct P2P connections won't work
-if (window.RTCPeerConnection) {
- const originalRTCPeerConnection = window.RTCPeerConnection;
- window.RTCPeerConnection = function(config, constraints) {
- if (config && config.iceServers) config.iceTransportPolicy = 'relay';
- return new originalRTCPeerConnection(config, constraints);
- };
- window.RTCPeerConnection.prototype = originalRTCPeerConnection.prototype;
-}
-
-// AUDIOCONTEXT FINGERPRINT PROTECTION
-// ⚠️ Adds subtle frequency noise - may affect audio processing applications
-if (window.AudioContext || window.webkitAudioContext) {
- const AudioContextClass = window.AudioContext || window.webkitAudioContext;
- const originalCreateOscillator = AudioContextClass.prototype.createOscillator;
-
- AudioContextClass.prototype.createOscillator = function() {
- const oscillator = originalCreateOscillator.apply(this, arguments);
- const originalConnect = oscillator.connect.bind(oscillator);
- oscillator.connect = function(dest) {
- if (dest instanceof AnalyserNode) {
- oscillator.frequency.value += seededRandom(sessionSeed + 4000) * 0.0001;
- }
- return originalConnect(dest);
- };
- return oscillator;
- };
-}
+// Keep canvas/audio/webrtc/font primitives native in full mode. Public anti-bot
+// sites classify these wrappers more aggressively than they reward the extra
+// fingerprint noise, so the current contract favors native behavior here.
} // end full level
diff --git a/internal/authn/cookie.go b/internal/authn/cookie.go
index 0cfab314..f557c26d 100644
--- a/internal/authn/cookie.go
+++ b/internal/authn/cookie.go
@@ -1,6 +1,7 @@
package authn
import (
+ "net"
"net/http"
"net/url"
"strings"
@@ -10,7 +11,7 @@ import (
// SetSessionCookie stores the opaque dashboard session id in an HttpOnly
// same-site cookie so browser APIs can authenticate without exposing the
// underlying bearer token to JavaScript.
-func SetSessionCookie(w http.ResponseWriter, _ *http.Request, sessionID string, maxLifetime time.Duration) {
+func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string, maxLifetime time.Duration, trustProxy bool) {
if maxLifetime <= 0 {
maxLifetime = DefaultSessionMaxLifetime
}
@@ -19,7 +20,7 @@ func SetSessionCookie(w http.ResponseWriter, _ *http.Request, sessionID string,
Value: url.QueryEscape(strings.TrimSpace(sessionID)),
Path: "/",
HttpOnly: true,
- Secure: true,
+ Secure: sessionCookieSecure(r, trustProxy),
SameSite: http.SameSiteStrictMode,
MaxAge: int(maxLifetime.Seconds()),
Expires: time.Now().Add(maxLifetime),
@@ -27,15 +28,98 @@ func SetSessionCookie(w http.ResponseWriter, _ *http.Request, sessionID string,
}
// ClearSessionCookie expires the dashboard auth cookie.
-func ClearSessionCookie(w http.ResponseWriter, _ *http.Request) {
+func ClearSessionCookie(w http.ResponseWriter, r *http.Request, trustProxy bool) {
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: "",
Path: "/",
HttpOnly: true,
- Secure: true,
+ Secure: sessionCookieSecure(r, trustProxy),
SameSite: http.SameSiteStrictMode,
MaxAge: -1,
Expires: time.Unix(0, 0),
})
}
+
+func sessionCookieSecure(r *http.Request, trustProxy bool) bool {
+ if requestScheme(r, trustProxy) == "https" {
+ return true
+ }
+ return !isLoopbackHost(requestHost(r, trustProxy))
+}
+
+func requestScheme(r *http.Request, trustProxy bool) string {
+ if r == nil {
+ return "http"
+ }
+ if trustProxy {
+ if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" {
+ return strings.ToLower(strings.TrimSpace(strings.Split(forwarded, ",")[0]))
+ }
+ if forwarded := strings.TrimSpace(r.Header.Get("Forwarded")); forwarded != "" {
+ for _, part := range strings.Split(forwarded, ";") {
+ key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
+ if !ok || !strings.EqualFold(key, "proto") {
+ continue
+ }
+ return strings.ToLower(strings.Trim(value, `"`))
+ }
+ }
+ }
+ if r.TLS != nil {
+ return "https"
+ }
+ return "http"
+}
+
+func requestHost(r *http.Request, trustProxy bool) string {
+ if r == nil {
+ return ""
+ }
+ if trustProxy {
+ if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")); forwarded != "" {
+ return strings.TrimSpace(strings.Split(forwarded, ",")[0])
+ }
+ if forwarded := strings.TrimSpace(r.Header.Get("Forwarded")); forwarded != "" {
+ for _, part := range strings.Split(forwarded, ";") {
+ key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
+ if !ok || !strings.EqualFold(key, "host") {
+ continue
+ }
+ return strings.Trim(value, `"`)
+ }
+ }
+ }
+ return strings.TrimSpace(r.Host)
+}
+
+func isLoopbackHost(host string) bool {
+ host = hostOnly(host)
+ if host == "" {
+ return false
+ }
+ if strings.EqualFold(host, "localhost") {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
+
+func hostOnly(hostport string) string {
+ hostport = strings.TrimSpace(hostport)
+ if hostport == "" {
+ return ""
+ }
+ if host, port, err := net.SplitHostPort(hostport); err == nil {
+ if port != "" {
+ return strings.Trim(host, "[]")
+ }
+ }
+ if strings.HasPrefix(hostport, "[") && strings.HasSuffix(hostport, "]") {
+ return strings.Trim(hostport, "[]")
+ }
+ if strings.Count(hostport, ":") > 1 {
+ return strings.Trim(hostport, "[]")
+ }
+ return hostport
+}
diff --git a/internal/authn/request.go b/internal/authn/request.go
index 2a1cc389..30e049a6 100644
--- a/internal/authn/request.go
+++ b/internal/authn/request.go
@@ -36,18 +36,15 @@ func CredentialsFromRequest(r *http.Request) Credentials {
}
cookie, err := r.Cookie(CookieName)
- if err != nil {
- return Credentials{}
- }
-
- value := strings.TrimSpace(cookie.Value)
- if value == "" {
- return Credentials{}
+ if err == nil {
+ if value := normalizeCookieValue(cookie.Value); value != "" {
+ return Credentials{Value: value, Method: MethodCookie}
+ }
}
- if decoded, err := url.QueryUnescape(value); err == nil {
- return Credentials{Value: strings.TrimSpace(decoded), Method: MethodCookie}
+ if value := cookieValueFromHeaders(r.Header.Values("Cookie"), CookieName); value != "" {
+ return Credentials{Value: value, Method: MethodCookie}
}
- return Credentials{Value: value, Method: MethodCookie}
+ return Credentials{}
}
// TokenFromRequest extracts the bearer token from the request.
@@ -80,3 +77,33 @@ func tokenFromAuthorizationHeader(auth string) string {
}
return auth
}
+
+func normalizeCookieValue(value string) string {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return ""
+ }
+ if decoded, err := url.QueryUnescape(value); err == nil {
+ return strings.TrimSpace(decoded)
+ }
+ return value
+}
+
+func cookieValueFromHeaders(headers []string, name string) string {
+ for _, header := range headers {
+ for _, part := range strings.Split(header, ";") {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ continue
+ }
+ key, value, ok := strings.Cut(part, "=")
+ if !ok || strings.TrimSpace(key) != name {
+ continue
+ }
+ if normalized := normalizeCookieValue(value); normalized != "" {
+ return normalized
+ }
+ }
+ }
+ return ""
+}
diff --git a/internal/authn/request_test.go b/internal/authn/request_test.go
index 09059cab..39c318d0 100644
--- a/internal/authn/request_test.go
+++ b/internal/authn/request_test.go
@@ -32,6 +32,17 @@ func TestTokenFromRequest_CookieFallback(t *testing.T) {
}
}
+func TestCookieValueFromHeaders(t *testing.T) {
+ const want = "cookie token/+"
+ headers := []string{
+ "theme=dark; " + CookieName + "=" + url.QueryEscape(want),
+ }
+
+ if got := cookieValueFromHeaders(headers, CookieName); got != want {
+ t.Fatalf("cookieValueFromHeaders() = %q, want %q", got, want)
+ }
+}
+
func TestTokenFromRequest_NoToken(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
diff --git a/internal/authn/request_wire_test.go b/internal/authn/request_wire_test.go
new file mode 100644
index 00000000..02689251
--- /dev/null
+++ b/internal/authn/request_wire_test.go
@@ -0,0 +1,36 @@
+package authn
+
+import (
+ "bufio"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestCredentialsFromRequest_WireParsedCookieHeader(t *testing.T) {
+ const want = "wire-cookie-token"
+ raw := strings.Join([]string{
+ "POST /action HTTP/1.1",
+ "Host: localhost:9867",
+ "Origin: http://localhost:9867",
+ "Content-Type: application/json",
+ "Cookie: " + CookieName + "=" + url.QueryEscape(want),
+ "Content-Length: 2",
+ "",
+ "{}",
+ }, "\r\n")
+
+ req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(raw)))
+ if err != nil {
+ t.Fatalf("ReadRequest() error = %v", err)
+ }
+
+ creds := CredentialsFromRequest(req)
+ if creds.Value != want {
+ t.Fatalf("CredentialsFromRequest().Value = %q, want %q", creds.Value, want)
+ }
+ if creds.Method != MethodCookie {
+ t.Fatalf("CredentialsFromRequest().Method = %q, want %q", creds.Method, MethodCookie)
+ }
+}
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index 9419da89..08fee374 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -8,6 +8,7 @@ import (
"github.com/chromedp/cdproto/target"
bridgetabs "github.com/pinchtab/pinchtab/internal/bridge/tabs"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
)
// BridgeAPI abstracts browser tab operations for handler testing.
@@ -35,6 +36,7 @@ type BridgeAPI interface {
Unlock(tabID, owner string) error
EnsureChrome(cfg *config.RuntimeConfig) error
+ StealthStatus() *stealth.Status
// Memory metrics
GetMemoryMetrics(tabID string) (*MemoryMetrics, error)
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index dcc48ee9..72d5a71c 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -2,8 +2,10 @@ package bridge
import (
"context"
+ "crypto/rand"
"fmt"
"log/slog"
+ "math/big"
"os"
"sync"
"time"
@@ -12,17 +14,19 @@ import (
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/ids"
+ "github.com/pinchtab/pinchtab/internal/stealth"
)
type TabEntry struct {
- Ctx context.Context
- Cancel context.CancelFunc
- Accessed bool
- CDPID string // raw CDP target ID
- CreatedAt time.Time // when the tab was first created/registered
- LastUsed time.Time // last time the tab was accessed via TabContext
- Policy TabPolicyState
- Watching bool
+ Ctx context.Context
+ Cancel context.CancelFunc
+ Accessed bool
+ CDPID string // raw CDP target ID
+ CreatedAt time.Time // when the tab was first created/registered
+ LastUsed time.Time // last time the tab was accessed via TabContext
+ Policy TabPolicyState
+ Watching bool
+ ConsoleCaptureEnabled bool
}
type RefCache struct {
@@ -38,7 +42,7 @@ type Bridge struct {
Config *config.RuntimeConfig
IdMgr *ids.Manager
*TabManager
- StealthScript string
+ StealthBundle *stealth.Bundle
Actions map[string]ActionFunc
Locks *LockManager
Dialogs *DialogManager
@@ -47,6 +51,10 @@ type Bridge struct {
// Network monitoring
netMonitor *NetworkMonitor
+ fingerprintMu sync.RWMutex
+ fingerprintOverlays map[string]bool
+ workerStealthTargets sync.Map
+
// Lazy initialization
initMu sync.Mutex
initialized bool
@@ -54,6 +62,8 @@ type Bridge struct {
// Temp profile cleanup: directories created as fallback when profile lock fails.
// These are removed on Cleanup() to prevent Chrome process/disk leaks.
tempProfileDir string
+
+ stealthLaunchMode stealth.LaunchMode
}
func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridge {
@@ -64,18 +74,23 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
}
logStore := NewConsoleLogStore(1000)
b := &Bridge{
- AllocCtx: allocCtx,
- BrowserCtx: browserCtx,
- Config: cfg,
- IdMgr: idMgr,
- netMonitor: NewNetworkMonitor(netBufSize),
- LogStore: logStore,
- }
+ AllocCtx: allocCtx,
+ BrowserCtx: browserCtx,
+ Config: cfg,
+ IdMgr: idMgr,
+ netMonitor: NewNetworkMonitor(netBufSize),
+ fingerprintOverlays: make(map[string]bool),
+ LogStore: logStore,
+ stealthLaunchMode: stealth.LaunchModeUninitialized,
+ }
+ b.ensureStealthBundle()
// Only initialize TabManager if browserCtx is provided (not lazy-init case)
if cfg != nil && browserCtx != nil {
b.TabManager = NewTabManager(browserCtx, cfg, idMgr, logStore, b.tabSetup)
b.SetDialogManager(b.Dialogs)
- b.StartBrowserGuards()
+ if !b.quietStealthObservers() {
+ b.StartBrowserGuards()
+ }
}
b.Locks = NewLockManager()
b.Dialogs = NewDialogManager()
@@ -83,13 +98,17 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg
return b
}
+func (b *Bridge) quietStealthObservers() bool {
+ return b != nil && b.Config != nil && stealth.NormalizeLevel(b.Config.StealthLevel) == stealth.LevelFull
+}
+
func (b *Bridge) injectStealth(ctx context.Context) {
- if b.StealthScript == "" {
+ if b.StealthBundle == nil || b.StealthBundle.Script == "" {
return
}
if err := chromedp.Run(ctx,
chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(b.StealthScript).Do(ctx)
+ _, err := page.AddScriptToEvaluateOnNewDocument(b.StealthBundle.Script).Do(ctx)
return err
}),
); err != nil {
@@ -97,27 +116,27 @@ func (b *Bridge) injectStealth(ctx context.Context) {
}
}
-func (b *Bridge) injectPopupGuards(ctx context.Context) {
- if err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(popupGuardInitScript).Do(ctx)
- return err
- }),
- ); err != nil {
- slog.Warn("popup guard injection failed", "err", err)
+func (b *Bridge) applyTargetStealth(ctx context.Context) {
+ if b == nil || b.Config == nil {
+ return
+ }
+
+ ua := ""
+ if b.StealthBundle != nil {
+ ua = b.StealthBundle.LaunchUserAgent()
+ }
+
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return stealth.ApplyTargetEmulation(ctx, b.Config, ua)
+ })); err != nil {
+ slog.Warn("stealth target emulation failed", "err", err)
}
}
func (b *Bridge) tabSetup(ctx context.Context) {
- if override := buildUserAgentOverride(b.Config.UserAgent, b.Config.ChromeVersion); override != nil {
- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
- return override.Do(c)
- })); err != nil {
- slog.Warn("ua override failed on tab setup", "err", err)
- }
- }
+ b.applyTargetStealth(ctx)
+ b.installWorkerStealthParity(ctx)
b.injectStealth(ctx)
- b.injectPopupGuards(ctx)
if b.Config.NoAnimations {
if err := b.InjectNoAnimations(ctx); err != nil {
slog.Warn("no-animations injection failed", "err", err)
@@ -151,6 +170,9 @@ func (b *Bridge) GetConsoleLogs(tabID string, limit int) []LogEntry {
if b.LogStore == nil {
return nil
}
+ if b.TabManager != nil {
+ b.EnsureConsoleCapture(tabID)
+ }
return b.LogStore.GetConsoleLogs(tabID, limit)
}
@@ -166,6 +188,9 @@ func (b *Bridge) GetErrorLogs(tabID string, limit int) []ErrorEntry {
if b.LogStore == nil {
return nil
}
+ if b.TabManager != nil {
+ b.EnsureConsoleCapture(tabID)
+ }
return b.LogStore.GetErrorLogs(tabID, limit)
}
@@ -229,7 +254,8 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
}
slog.Info("starting chrome with confirmed profile", "headless", cfg.Headless, "profile", cfg.ProfileDir)
- allocCtx, allocCancel, browserCtx, browserCancel, err := InitChrome(cfg)
+ b.ensureStealthBundle()
+ allocCtx, allocCancel, browserCtx, browserCancel, launchMode, err := InitChrome(cfg, b.StealthBundle)
if err != nil {
return fmt.Errorf("failed to initialize chrome: %w", err)
}
@@ -239,6 +265,7 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
b.BrowserCtx = browserCtx
b.BrowserCancel = browserCancel
b.initialized = true
+ b.stealthLaunchMode = launchMode
// Initialize TabManager now that browser is ready
if b.Config != nil && b.TabManager == nil {
@@ -250,7 +277,9 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
}
b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.LogStore, b.tabSetup)
b.SetDialogManager(b.Dialogs)
- b.StartBrowserGuards()
+ if !b.quietStealthObservers() {
+ b.StartBrowserGuards()
+ }
}
// Ensure action registry is populated (idempotent)
@@ -264,7 +293,9 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
}
// Start crash monitoring
- b.MonitorCrashes(nil)
+ if !b.quietStealthObservers() {
+ b.MonitorCrashes(nil)
+ }
return nil
}
@@ -329,6 +360,7 @@ func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel contex
b.BrowserCtx = browserCtx
b.BrowserCancel = browserCancel
b.initialized = true
+ b.stealthLaunchMode = stealth.LaunchModeAttached
// Now initialize TabManager with the browser context
if b.Config != nil && b.TabManager == nil {
@@ -343,6 +375,36 @@ func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel contex
}
}
+func (b *Bridge) ensureStealthBundle() {
+ if b.StealthBundle != nil || b.Config == nil {
+ return
+ }
+ b.StealthBundle = stealth.NewBundle(b.Config, cryptoRandSeed())
+}
+
+func (b *Bridge) StealthStatus() *stealth.Status {
+ b.ensureStealthBundle()
+ return stealth.StatusFromBundle(b.StealthBundle, b.Config, b.stealthLaunchMode)
+}
+
+func (b *Bridge) SetFingerprintRotateActive(tabID string, active bool) {
+ if tabID == "" {
+ return
+ }
+ b.fingerprintMu.Lock()
+ defer b.fingerprintMu.Unlock()
+ b.fingerprintOverlays[tabID] = active
+}
+
+func (b *Bridge) FingerprintRotateActive(tabID string) bool {
+ if tabID == "" {
+ return false
+ }
+ b.fingerprintMu.RLock()
+ defer b.fingerprintMu.RUnlock()
+ return b.fingerprintOverlays[tabID]
+}
+
func (b *Bridge) BrowserContext() context.Context {
return b.BrowserCtx
}
@@ -437,3 +499,11 @@ func (r *ActionRequest) NormalizeSelector() {
// If Selector is already set (either from JSON or from Ref promotion),
// leave it as-is — Parse() will auto-detect the kind.
}
+
+func cryptoRandSeed() int64 {
+ n, err := rand.Int(rand.Reader, big.NewInt(1000000000))
+ if err != nil {
+ return 42
+ }
+ return n.Int64()
+}
diff --git a/internal/bridge/bridge_test.go b/internal/bridge/bridge_test.go
index e5fe7a89..b16a5a61 100644
--- a/internal/bridge/bridge_test.go
+++ b/internal/bridge/bridge_test.go
@@ -116,6 +116,15 @@ func TestTabContext_RejectsUnknownRawCDPID(t *testing.T) {
}
}
+func TestQuietStealthObservers(t *testing.T) {
+ if (&Bridge{Config: &config.RuntimeConfig{StealthLevel: "full"}}).quietStealthObservers() != true {
+ t.Fatal("expected full stealth to suppress nonessential observers")
+ }
+ if (&Bridge{Config: &config.RuntimeConfig{StealthLevel: "medium"}}).quietStealthObservers() {
+ t.Fatal("did not expect medium stealth to suppress observers")
+ }
+}
+
func TestCreateTab_ReturnsRawCDPID(t *testing.T) {
// Verify TabIDFromCDPTarget returns raw CDP ID (no prefix)
tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil, nil)
diff --git a/internal/bridge/init.go b/internal/bridge/init.go
index a4053c81..1eee3012 100644
--- a/internal/bridge/init.go
+++ b/internal/bridge/init.go
@@ -3,16 +3,16 @@ package bridge
import (
"context"
- "github.com/pinchtab/pinchtab/internal/assets"
bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
)
-var popupGuardInitScript = assets.PopupGuardScript
+const popupGuardInitScript = stealth.PopupGuardInitScript
// InitChrome initializes a Chrome browser for a Bridge instance.
-func InitChrome(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, error) {
- return bridgeruntime.InitChrome(cfg, bridgeruntime.Hooks{
+func InitChrome(cfg *config.RuntimeConfig, bundle *stealth.Bundle) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, stealth.LaunchMode, error) {
+ return bridgeruntime.InitChrome(cfg, bundle, bridgeruntime.Hooks{
SetHumanRandSeed: SetHumanRandSeed,
IsChromeProfileLockError: isChromeProfileLockError,
ClearStaleChromeProfile: clearStaleChromeProfileLock,
@@ -20,8 +20,8 @@ func InitChrome(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc,
})
}
-func defaultChromeFlagArgs() []string {
- return bridgeruntime.DefaultChromeFlagArgs()
+func baseChromeFlagArgs() []string {
+ return bridgeruntime.BaseChromeFlagArgs()
}
func buildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
diff --git a/internal/bridge/init_test.go b/internal/bridge/init_test.go
index 6dc24a5d..2868f95f 100644
--- a/internal/bridge/init_test.go
+++ b/internal/bridge/init_test.go
@@ -22,6 +22,21 @@ func TestBuildChromeArgsSuppressesCrashDialogs(t *testing.T) {
}
}
+func TestBuildChromeArgsIncludesStealthLaunchFlags(t *testing.T) {
+ args := buildChromeArgs(&config.RuntimeConfig{}, 9222)
+
+ for _, want := range []string{
+ "--enable-automation=false",
+ "--enable-network-information-downlink-max",
+ "--disable-blink-features=AutomationControlled",
+ "--lang=en-US",
+ } {
+ if !slices.Contains(args, want) {
+ t.Fatalf("missing chrome arg %q in %v", want, args)
+ }
+ }
+}
+
func TestBuildChromeArgsHeadlessUsesSoftwareRendering(t *testing.T) {
args := buildChromeArgs(&config.RuntimeConfig{Headless: true}, 9222)
@@ -38,8 +53,42 @@ func TestBuildChromeArgsHeadlessUsesSoftwareRendering(t *testing.T) {
}
}
-func TestDefaultChromeFlagArgsDisablesMetricsReporting(t *testing.T) {
- args := defaultChromeFlagArgs()
+func TestBuildChromeArgsIncludesGlobalUserAgent(t *testing.T) {
+ args := buildChromeArgs(&config.RuntimeConfig{ChromeVersion: "144.0.7559.133"}, 9222)
+
+ found := false
+ for _, arg := range args {
+ if strings.HasPrefix(arg, "--user-agent=Mozilla/5.0") {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected global user-agent arg in %v", args)
+ }
+}
+
+func TestBuildChromeArgsSanitizesUnsafeAndReservedExtraFlags(t *testing.T) {
+ args := buildChromeArgs(&config.RuntimeConfig{
+ ChromeVersion: "144.0.7559.133",
+ ChromeExtraFlags: "--disable-gpu --user-agent=Bad/1.0 --disable-web-security --ash-no-nudges",
+ }, 9222)
+
+ if !slices.Contains(args, "--disable-gpu") {
+ t.Fatalf("expected safe extra flag to be preserved in %v", args)
+ }
+ if !slices.Contains(args, "--ash-no-nudges") {
+ t.Fatalf("expected safe extra flag to be preserved in %v", args)
+ }
+ for _, forbidden := range []string{"--user-agent=Bad/1.0", "--disable-web-security"} {
+ if slices.Contains(args, forbidden) {
+ t.Fatalf("did not expect forbidden extra flag %q in %v", forbidden, args)
+ }
+ }
+}
+
+func TestBaseChromeFlagArgsDisablesMetricsReporting(t *testing.T) {
+ args := baseChromeFlagArgs()
for _, want := range []string{"--disable-metrics-reporting", "--metrics-recording-only"} {
found := false
for _, arg := range args {
@@ -54,12 +103,15 @@ func TestDefaultChromeFlagArgsDisablesMetricsReporting(t *testing.T) {
}
}
-func TestDefaultChromeFlagArgsPreservesPopupBlockingAndSiteIsolation(t *testing.T) {
- args := defaultChromeFlagArgs()
+func TestBaseChromeFlagArgsPreservesPopupBlockingAndSiteIsolation(t *testing.T) {
+ args := baseChromeFlagArgs()
for _, forbidden := range []string{
"--disable-popup-blocking",
"--no-sandbox",
"--disable-features=site-per-process,Translate,BlinkGenPropertyTrees",
+ "--enable-automation=false",
+ "--disable-blink-features=AutomationControlled",
+ "--enable-network-information-downlink-max",
} {
if slices.Contains(args, forbidden) {
t.Fatalf("did not expect %s in args: %v", forbidden, args)
diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.go
index 3251d457..b72f3297 100644
--- a/internal/bridge/runtime/init.go
+++ b/internal/bridge/runtime/init.go
@@ -3,12 +3,13 @@ package runtime
import (
"bytes"
"context"
+ "crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
- "math/rand"
+ "math/big"
"net"
"net/http"
"os"
@@ -19,8 +20,14 @@ import (
"time"
"github.com/chromedp/chromedp"
- "github.com/pinchtab/pinchtab/internal/assets"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
+)
+
+var (
+ runtimeGOOS = goruntime.GOOS
+ osGeteuid = os.Geteuid
+ containerMarkerPath = "/.dockerenv"
)
type Hooks struct {
@@ -31,19 +38,20 @@ type Hooks struct {
}
// InitChrome initializes a Chrome browser for a Bridge instance.
-func InitChrome(cfg *config.RuntimeConfig, hooks Hooks) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, error) {
+func InitChrome(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, stealth.LaunchMode, error) {
slog.Info("starting chrome initialization", "headless", cfg.Headless, "profile", cfg.ProfileDir, "binary", cfg.ChromeBinary)
- allocCtx, allocCancel, opts, debugPort := setupAllocator(cfg, hooks)
- browserCtx, browserCancel, err := startChrome(allocCtx, cfg, opts, debugPort, hooks)
+ bundle = ensureStealthBundle(cfg, bundle)
+ allocCtx, allocCancel, opts, debugPort := setupAllocator(cfg, bundle, hooks)
+ browserCtx, browserCancel, launchMode, err := startChrome(allocCtx, cfg, bundle, opts, debugPort, hooks)
if err != nil {
allocCancel()
slog.Error("chrome initialization failed", "headless", cfg.Headless, "error", err.Error())
- return nil, nil, nil, nil, fmt.Errorf("failed to start chrome: %w", err)
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to start chrome: %w", err)
}
slog.Info("chrome initialized successfully", "headless", cfg.Headless, "profile", cfg.ProfileDir)
- return allocCtx, allocCancel, browserCtx, browserCancel, nil
+ return allocCtx, allocCancel, browserCtx, browserCancel, launchMode, nil
}
func findChromeBinary() string {
@@ -84,14 +92,27 @@ func appendExecAllocatorFlag(opts []chromedp.ExecAllocatorOption, flag string) [
return append(opts, chromedp.Flag(name, true))
}
-func setupAllocator(cfg *config.RuntimeConfig, hooks Hooks) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption, int) {
+func ensureStealthBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle) *stealth.Bundle {
+ if bundle != nil {
+ return bundle
+ }
+ return stealth.NewBundle(cfg, cryptoRandSeed())
+}
+
+func appendExecAllocatorFlags(opts []chromedp.ExecAllocatorOption, flags []string) []chromedp.ExecAllocatorOption {
+ for _, flag := range flags {
+ opts = appendExecAllocatorFlag(opts, flag)
+ }
+ return opts
+}
+
+func setupAllocator(cfg *config.RuntimeConfig, bundle *stealth.Bundle, hooks Hooks) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption, int) {
opts := []chromedp.ExecAllocatorOption{
chromedp.NoFirstRun,
chromedp.NoDefaultBrowserCheck,
}
- for _, flag := range DefaultChromeFlagArgs() {
- opts = appendExecAllocatorFlag(opts, flag)
- }
+ opts = appendExecAllocatorFlags(opts, BaseChromeFlagArgs())
+ opts = appendExecAllocatorFlags(opts, bundle.Launch.Args)
chromeBinary := cfg.ChromeBinary
if chromeBinary == "" {
@@ -124,13 +145,10 @@ func setupAllocator(cfg *config.RuntimeConfig, hooks Hooks) (context.Context, co
opts = append(opts, chromedp.Flag("disable-extensions", false))
opts = append(opts, chromedp.Flag("load-extension", joined))
opts = append(opts, chromedp.Flag("disable-extensions-except", joined))
- opts = append(opts, chromedp.Flag("enable-automation", false))
slog.Info("loading extensions", "paths", joined)
}
- opts = append(opts, chromedp.Flag("enable-automation", false))
} else {
opts = append(opts, chromedp.Flag("disable-extensions", true))
- opts = append(opts, chromedp.Flag("enable-automation", false))
}
if cfg.ProfileDir != "" {
@@ -144,11 +162,7 @@ func setupAllocator(cfg *config.RuntimeConfig, hooks Hooks) (context.Context, co
opts = append(opts, chromedp.Flag("tz", cfg.Timezone))
}
- if cfg.ChromeExtraFlags != "" {
- for _, f := range strings.Fields(cfg.ChromeExtraFlags) {
- opts = appendExecAllocatorFlag(opts, f)
- }
- }
+ opts = appendExecAllocatorFlags(opts, config.AllowedChromeExtraFlags(cfg.ChromeExtraFlags))
for _, flag := range appendChromeCompatibilityFlags(nil) {
opts = appendExecAllocatorFlag(opts, flag)
}
@@ -172,19 +186,18 @@ func setupAllocator(cfg *config.RuntimeConfig, hooks Hooks) (context.Context, co
return ctx, cancel, opts, debugPort
}
-func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks) (context.Context, context.CancelFunc, error) {
- return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, hooks, false)
+func startChrome(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
+ return startChromeWithRecovery(parentCtx, cfg, bundle, opts, debugPort, hooks, false)
}
-func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfig, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks, retriedProfileLock bool) (context.Context, context.CancelFunc, error) {
+func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, opts []chromedp.ExecAllocatorOption, debugPort int, hooks Hooks, retriedProfileLock bool) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
allocCtx, allocCancel := chromedp.NewExecAllocator(parentCtx, opts...)
browserCtx, browserCancel := chromedp.NewContext(allocCtx)
- stealthSeed := rand.Intn(1000000000)
+ bundle = ensureStealthBundle(cfg, bundle)
if hooks.SetHumanRandSeed != nil {
- hooks.SetHumanRandSeed(int64(stealthSeed))
+ hooks.SetHumanRandSeed(bundle.Seed)
}
- seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + assets.StealthScript + "\n" + assets.PopupGuardScript
const chromeStartupTimeout = 20 * time.Second
type runResult struct{ err error }
@@ -212,7 +225,7 @@ func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfi
if hooks.ClearStaleChromeProfile != nil {
if recovered, _ := hooks.ClearStaleChromeProfile(cfg.ProfileDir, errMsg); recovered {
time.Sleep(250 * time.Millisecond)
- return startChromeWithRecovery(parentCtx, cfg, opts, debugPort, hooks, true)
+ return startChromeWithRecovery(parentCtx, cfg, bundle, opts, debugPort, hooks, true)
}
}
}
@@ -220,24 +233,27 @@ func startChromeWithRecovery(parentCtx context.Context, cfg *config.RuntimeConfi
if isStartupTimeout(err) && debugPort > 0 {
slog.Warn("chrome startup timeout (Chrome 145+ regression), trying direct-launch fallback", "port", debugPort)
time.Sleep(500 * time.Millisecond)
- return startChromeWithRemoteAllocator(parentCtx, cfg, debugPort, seededScript)
+ return startChromeWithRemoteAllocator(parentCtx, cfg, bundle, debugPort, bundle.Script)
}
- return nil, nil, fmt.Errorf("failed to connect to chrome: %w", err)
+ return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to connect to chrome: %w", err)
}
if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return injectedScript(ctx, seededScript)
+ if err := stealth.ApplyTargetEmulation(ctx, cfg, bundle.LaunchUserAgent()); err != nil {
+ return err
+ }
+ return injectedScript(ctx, bundle.Script)
})); err != nil {
browserCancel()
allocCancel()
- return nil, nil, fmt.Errorf("failed to inject stealth script: %w", err)
+ return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to inject stealth script: %w", err)
}
return browserCtx, func() {
browserCancel()
allocCancel()
- }, nil
+ }, stealth.LaunchModeAllocator, nil
}
func isStartupTimeout(err error) bool {
@@ -248,47 +264,50 @@ func isStartupTimeout(err error) bool {
return strings.Contains(msg, "deadline exceeded") || strings.Contains(msg, "context deadline exceeded")
}
-func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.RuntimeConfig, debugPort int, seededScript string) (context.Context, context.CancelFunc, error) {
+func startChromeWithRemoteAllocator(parentCtx context.Context, cfg *config.RuntimeConfig, bundle *stealth.Bundle, debugPort int, injectedStealthScript string) (context.Context, context.CancelFunc, stealth.LaunchMode, error) {
chromeBinary := cfg.ChromeBinary
if chromeBinary == "" {
chromeBinary = findChromeBinary()
}
if chromeBinary == "" {
- return nil, nil, fmt.Errorf("chrome/chromium not found: please install chrome or chromium, or set 'binary' in config.json")
+ return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("chrome/chromium not found: please install chrome or chromium, or set 'binary' in config.json")
}
- args := BuildChromeArgs(cfg, debugPort)
+ args := buildChromeArgsWithBundle(cfg, bundle, debugPort)
// #nosec G204 -- chromeBinary from user config or findChromeBinary() known system paths
cmd := exec.Command(chromeBinary, args...)
cmd.Stdout = newPrefixedLogWriter(os.Stdout, "chrome stdout")
cmd.Stderr = newPrefixedLogWriter(os.Stderr, "chrome stderr")
if err := cmd.Start(); err != nil {
- return nil, nil, fmt.Errorf("failed to start chrome directly: %w", err)
+ return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to start chrome directly: %w", err)
}
wsURL, err := waitForChromeDevTools(debugPort, 30*time.Second)
if err != nil {
_ = cmd.Process.Kill()
- return nil, nil, fmt.Errorf("chrome devtools not ready on port %d: %w", debugPort, err)
+ return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("chrome devtools not ready on port %d: %w", debugPort, err)
}
remoteAllocCtx, remoteAllocCancel := chromedp.NewRemoteAllocator(parentCtx, wsURL)
browserCtx, browserCancel := chromedp.NewContext(remoteAllocCtx)
if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {
- return injectedScript(ctx, seededScript)
+ if err := stealth.ApplyTargetEmulation(ctx, cfg, bundle.LaunchUserAgent()); err != nil {
+ return err
+ }
+ return injectedScript(ctx, injectedStealthScript)
})); err != nil {
browserCancel()
remoteAllocCancel()
_ = cmd.Process.Kill()
- return nil, nil, fmt.Errorf("failed to connect/inject via remote: %w", err)
+ return nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to connect/inject via remote: %w", err)
}
return browserCtx, func() {
browserCancel()
remoteAllocCancel()
_ = cmd.Process.Kill()
- }, nil
+ }, stealth.LaunchModeDirectFallback, nil
}
func findFreePort(start, end int) (int, error) {
@@ -324,7 +343,7 @@ func waitForChromeDevTools(port int, timeout time.Duration) (string, error) {
return "", fmt.Errorf("chrome devtools not ready on port %d after %v", port, timeout)
}
-func DefaultChromeFlagArgs() []string {
+func BaseChromeFlagArgs() []string {
return []string{
"--disable-background-networking",
"--enable-features=NetworkService,NetworkServiceInProcess",
@@ -349,20 +368,40 @@ func DefaultChromeFlagArgs() []string {
"--safebrowsing-disable-auto-update",
"--password-store=basic",
"--use-mock-keychain",
- "--disable-automation",
- "--disable-blink-features=AutomationControlled",
}
}
func appendChromeCompatibilityFlags(args []string) []string {
- if goruntime.GOOS == "linux" && os.Geteuid() == 0 {
+ if chromeNeedsNoSandbox() {
return append(args, "--no-sandbox")
}
return args
}
+func chromeNeedsNoSandbox() bool {
+ if runtimeGOOS != "linux" {
+ return false
+ }
+ if os.Getenv(config.ChromeNoSandboxEnvVar()) == "1" {
+ return true
+ }
+ if osGeteuid() == 0 {
+ return true
+ }
+ if _, err := os.Stat(containerMarkerPath); err == nil {
+ return true
+ }
+ return false
+}
+
func BuildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
- args := append([]string{fmt.Sprintf("--remote-debugging-port=%d", port)}, DefaultChromeFlagArgs()...)
+ return buildChromeArgsWithBundle(cfg, nil, port)
+}
+
+func buildChromeArgsWithBundle(cfg *config.RuntimeConfig, bundle *stealth.Bundle, port int) []string {
+ bundle = ensureStealthBundle(cfg, bundle)
+ args := append([]string{fmt.Sprintf("--remote-debugging-port=%d", port)}, BaseChromeFlagArgs()...)
+ args = append(args, bundle.Launch.Args...)
if len(cfg.ExtensionPaths) > 0 {
joined := strings.Join(cfg.ExtensionPaths, ",")
@@ -392,9 +431,7 @@ func BuildChromeArgs(cfg *config.RuntimeConfig, port int) []string {
args = append(args, "--tz="+cfg.Timezone)
}
- if cfg.ChromeExtraFlags != "" {
- args = append(args, strings.Fields(cfg.ChromeExtraFlags)...)
- }
+ args = append(args, config.AllowedChromeExtraFlags(cfg.ChromeExtraFlags)...)
return appendChromeCompatibilityFlags(args)
}
@@ -412,7 +449,12 @@ func randomWindowSize() (int, int) {
{1920, 1080}, {1366, 768}, {1536, 864}, {1440, 900},
{1280, 720}, {1600, 900}, {2560, 1440}, {1280, 800},
}
- s := sizes[rand.Intn(len(sizes))]
+ n, err := rand.Int(rand.Reader, big.NewInt(int64(len(sizes))))
+ idx := 0
+ if err == nil {
+ idx = int(n.Int64())
+ }
+ s := sizes[idx]
return s[0], s[1]
}
@@ -443,3 +485,11 @@ func (w *prefixedLogWriter) Write(p []byte) (int, error) {
}
return len(p), nil
}
+
+func cryptoRandSeed() int64 {
+ n, err := rand.Int(rand.Reader, big.NewInt(1000000000))
+ if err != nil {
+ return 42
+ }
+ return n.Int64()
+}
diff --git a/internal/bridge/runtime/init_test.go b/internal/bridge/runtime/init_test.go
new file mode 100644
index 00000000..36998823
--- /dev/null
+++ b/internal/bridge/runtime/init_test.go
@@ -0,0 +1,47 @@
+package runtime
+
+import (
+ "os"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestChromeNeedsNoSandbox(t *testing.T) {
+ origGOOS := runtimeGOOS
+ origGeteuid := osGeteuid
+ origMarker := containerMarkerPath
+ t.Cleanup(func() {
+ runtimeGOOS = origGOOS
+ osGeteuid = origGeteuid
+ containerMarkerPath = origMarker
+ })
+
+ runtimeGOOS = "linux"
+ osGeteuid = func() int { return 1000 }
+ containerMarkerPath = t.TempDir() + "/missing-dockerenv"
+
+ if chromeNeedsNoSandbox() {
+ t.Fatal("expected no-sandbox compatibility to be disabled without root, env override, or container marker")
+ }
+
+ t.Setenv(config.ChromeNoSandboxEnvVar(), "1")
+ if !chromeNeedsNoSandbox() {
+ t.Fatal("expected env override to enable no-sandbox compatibility")
+ }
+ t.Setenv(config.ChromeNoSandboxEnvVar(), "")
+
+ osGeteuid = func() int { return 0 }
+ if !chromeNeedsNoSandbox() {
+ t.Fatal("expected root user to enable no-sandbox compatibility")
+ }
+ osGeteuid = func() int { return 1000 }
+
+ containerMarkerPath = t.TempDir() + "/.dockerenv"
+ if err := os.WriteFile(containerMarkerPath, []byte(""), 0o644); err != nil {
+ t.Fatalf("WriteFile() error = %v", err)
+ }
+ if !chromeNeedsNoSandbox() {
+ t.Fatal("expected container marker to enable no-sandbox compatibility")
+ }
+}
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index 44b5458e..bad1a837 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -358,11 +358,19 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
ListenDialogEvents(ctx, tabID, tm.dialogMgr, autoAccept)
}
- // Set up console and error log capturing
- tm.setupConsoleCapture(ctx, rawCDPID)
+ if tm.shouldEagerlyCaptureConsole() {
+ tm.setupConsoleCapture(ctx, rawCDPID)
+ }
tm.mu.Lock()
- tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID, CreatedAt: now, LastUsed: now}
+ tm.tabs[tabID] = &TabEntry{
+ Ctx: ctx,
+ Cancel: cancel,
+ CDPID: rawCDPID,
+ CreatedAt: now,
+ LastUsed: now,
+ ConsoleCaptureEnabled: tm.shouldEagerlyCaptureConsole(),
+ }
tm.accessed[tabID] = true
tm.currentTab = tabID
tm.mu.Unlock()
@@ -793,6 +801,35 @@ func (tm *TabManager) setupConsoleCapture(ctx context.Context, rawCDPID string)
}()
}
+func (tm *TabManager) shouldEagerlyCaptureConsole() bool {
+ if tm == nil || tm.config == nil {
+ return true
+ }
+ return !strings.EqualFold(strings.TrimSpace(tm.config.StealthLevel), "full")
+}
+
+func (tm *TabManager) EnsureConsoleCapture(tabID string) {
+ if tm == nil || tm.logStore == nil {
+ return
+ }
+
+ tm.mu.Lock()
+ entry := tm.tabs[tabID]
+ if entry == nil && tabID == "" {
+ entry = tm.tabs[tm.currentTab]
+ }
+ if entry == nil || entry.Ctx == nil || entry.ConsoleCaptureEnabled {
+ tm.mu.Unlock()
+ return
+ }
+ entry.ConsoleCaptureEnabled = true
+ ctx := entry.Ctx
+ rawCDPID := entry.CDPID
+ tm.mu.Unlock()
+
+ tm.setupConsoleCapture(ctx, rawCDPID)
+}
+
func executionContextSource(ctx *runtime.ExecutionContextDescription) string {
if ctx == nil {
return ""
diff --git a/internal/bridge/uameta.go b/internal/bridge/uameta.go
index 712a64d6..2d20e1e0 100644
--- a/internal/bridge/uameta.go
+++ b/internal/bridge/uameta.go
@@ -1,98 +1,14 @@
package bridge
import (
- "runtime"
- "strings"
-
"github.com/chromedp/cdproto/emulation"
+ "github.com/pinchtab/pinchtab/internal/stealth"
)
-// buildUserAgentOverride creates a SetUserAgentOverride action with full UserAgentMetadata.
-// chromeVersion should be the full version (e.g. "144.0.7559.133").
-// If userAgent is empty, generates a default one based on the platform.
-// If chromeVersion is also empty, returns nil.
func buildUserAgentOverride(userAgent, chromeVersion string) *emulation.SetUserAgentOverrideParams {
- if chromeVersion == "" {
- return nil
- }
-
- // If no custom user agent is provided, generate a default one based on OS
- if userAgent == "" {
- switch runtime.GOOS {
- case "darwin":
- userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + chromeVersion + " Safari/537.36"
- case "windows":
- userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + chromeVersion + " Safari/537.36"
- default:
- userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + chromeVersion + " Safari/537.36"
- }
- }
-
- major := chromeVersion
- if i := strings.Index(chromeVersion, "."); i > 0 {
- major = chromeVersion[:i]
- }
-
- platform, arch := detectPlatform()
-
- return emulation.SetUserAgentOverride(userAgent).
- WithAcceptLanguage("en-US,en").
- WithPlatform(platform).
- WithUserAgentMetadata(&emulation.UserAgentMetadata{
- Platform: platformName(),
- PlatformVersion: platformVersion(),
- Architecture: arch,
- Bitness: "64",
- Mobile: false,
- Brands: []*emulation.UserAgentBrandVersion{
- {Brand: "Not(A:Brand", Version: "99"},
- {Brand: "Google Chrome", Version: major},
- {Brand: "Chromium", Version: major},
- },
- FullVersionList: []*emulation.UserAgentBrandVersion{
- {Brand: "Not(A:Brand", Version: "99.0.0.0"},
- {Brand: "Google Chrome", Version: chromeVersion},
- {Brand: "Chromium", Version: chromeVersion},
- },
- })
-}
-
-func detectPlatform() (jsNavigatorPlatform, architecture string) {
- switch runtime.GOARCH {
- case "arm64":
- architecture = "arm"
- default:
- architecture = "x86"
- }
-
- switch runtime.GOOS {
- case "darwin":
- return "MacIntel", architecture
- case "windows":
- return "Win32", architecture
- default:
- return "Linux x86_64", architecture
- }
-}
-
-func platformName() string {
- switch runtime.GOOS {
- case "darwin":
- return "macOS"
- case "windows":
- return "Windows"
- default:
- return "Linux"
- }
+ return stealth.BuildUserAgentOverride(userAgent, chromeVersion)
}
-func platformVersion() string {
- switch runtime.GOOS {
- case "darwin":
- return "14.0.0"
- case "windows":
- return "15.0.0"
- default:
- return "6.5.0"
- }
+func buildLocaleOverride(userAgent, chromeVersion string) *emulation.SetLocaleOverrideParams {
+ return stealth.BuildLocaleOverride(userAgent, chromeVersion)
}
diff --git a/internal/bridge/uameta_test.go b/internal/bridge/uameta_test.go
index fa365b43..644bed3d 100644
--- a/internal/bridge/uameta_test.go
+++ b/internal/bridge/uameta_test.go
@@ -1,6 +1,7 @@
package bridge
import (
+ "strings"
"testing"
)
@@ -19,6 +20,16 @@ func TestBuild_Empty(t *testing.T) {
}
}
+func TestBuild_UsesResolvedUserAgent(t *testing.T) {
+ p := buildUserAgentOverride("", "144.0.0.0")
+ if p == nil {
+ t.Fatal("expected non-nil")
+ }
+ if !strings.Contains(p.UserAgent, "Chrome/144.0.0.0") {
+ t.Fatalf("expected resolved UA to contain full Chrome version, got %q", p.UserAgent)
+ }
+}
+
func TestBuild_Versions(t *testing.T) {
p := buildUserAgentOverride("Mozilla/5.0 Test", "144.0.7559.133")
if p == nil {
@@ -42,9 +53,28 @@ func TestBuild_Versions(t *testing.T) {
}
}
-func TestDetectPlatform(t *testing.T) {
- platform, arch := detectPlatform()
- if platform == "" || arch == "" {
- t.Fatal("expected non-empty platform and arch")
+func TestBuild_UsesPersonaMetadata(t *testing.T) {
+ p := buildUserAgentOverride("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.7559.133 Safari/537.36", "144.0.7559.133")
+ if p == nil || p.UserAgentMetadata == nil {
+ t.Fatal("expected metadata")
+ }
+ if p.AcceptLanguage != "en-US,en" {
+ t.Fatalf("expected accept language from persona, got %q", p.AcceptLanguage)
+ }
+ if p.Platform != "Win32" {
+ t.Fatalf("expected navigator platform Win32, got %q", p.Platform)
+ }
+ if got := p.UserAgentMetadata.Platform; got != "Windows" {
+ t.Fatalf("expected UA data platform Windows, got %q", got)
+ }
+}
+
+func TestBuildLocaleOverride_UsesPersonaLanguage(t *testing.T) {
+ p := buildLocaleOverride("", "144.0.7559.133")
+ if p == nil {
+ t.Fatal("expected locale override")
+ }
+ if p.Locale != "en-US" {
+ t.Fatalf("expected locale override en-US, got %q", p.Locale)
}
}
diff --git a/internal/bridge/worker_stealth.go b/internal/bridge/worker_stealth.go
new file mode 100644
index 00000000..9d85613e
--- /dev/null
+++ b/internal/bridge/worker_stealth.go
@@ -0,0 +1,96 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/stealth"
+)
+
+func (b *Bridge) installWorkerStealthParity(ctx context.Context) {
+ if b == nil || b.Config == nil {
+ return
+ }
+
+ chromedp.ListenTarget(ctx, func(ev any) {
+ attached, ok := ev.(*target.EventAttachedToTarget)
+ if !ok || attached.TargetInfo == nil || !strings.Contains(attached.TargetInfo.Type, "worker") {
+ return
+ }
+
+ targetID := string(attached.TargetInfo.TargetID)
+ if _, loaded := b.workerStealthTargets.LoadOrStore(targetID, struct{}{}); loaded {
+ return
+ }
+
+ go b.applyWorkerStealth(ctx, attached.TargetInfo.TargetID, attached.TargetInfo.Type)
+ })
+}
+
+func (b *Bridge) applyWorkerStealth(parent context.Context, targetID target.ID, targetType string) {
+ workerCtx, cancel := chromedp.NewContext(parent, chromedp.WithTargetID(targetID))
+ defer cancel()
+
+ runCtx, runCancel := context.WithTimeout(workerCtx, 5*time.Second)
+ defer runCancel()
+
+ ua := ""
+ if b.StealthBundle != nil {
+ ua = b.StealthBundle.LaunchUserAgent()
+ }
+
+ if err := chromedp.Run(runCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return stealth.ApplyTargetEmulation(ctx, b.Config, ua)
+ }),
+ chromedp.Evaluate(workerStealthParityScript(stealth.BuildPersona(ua, b.Config.ChromeVersion)), nil),
+ ); err != nil {
+ slog.Debug("worker stealth parity failed", "targetId", targetID, "targetType", targetType, "err", err)
+ }
+}
+
+func workerStealthParityScript(persona stealth.BrowserPersona) string {
+ languagesJSON := safeJSONStringArray(persona.Languages, `["en-US","en"]`)
+
+ return fmt.Sprintf(`(() => {
+ try {
+ const nav = self.navigator;
+ if (!nav) return;
+ const target = Object.getPrototypeOf(nav) || nav;
+ const define = (name, getter) => {
+ try { Object.defineProperty(target, name, { get: getter, configurable: true }); } catch (e) {}
+ try { Object.defineProperty(nav, name, { get: getter, configurable: true }); } catch (e) {}
+ };
+ const ua = %q || nav.userAgent || '';
+ const platform = %q || nav.platform || '';
+ const language = %q || nav.language || 'en-US';
+ const languages = JSON.parse(%q);
+ if (ua) define('userAgent', () => ua);
+ if (platform) define('platform', () => platform);
+ define('language', () => language);
+ define('languages', () => languages.slice());
+ define('webdriver', () => false);
+ } catch (e) {}
+})()`, persona.UserAgent, persona.NavigatorPlatform, persona.Language, languagesJSON)
+}
+
+// safeJSONStringArray marshals a string slice to JSON and validates the output
+// is a JSON array of strings. Returns fallback on any error.
+func safeJSONStringArray(values []string, fallback string) string {
+ data, err := json.Marshal(values)
+ if err != nil {
+ return fallback
+ }
+ // Round-trip to verify output is a valid string array
+ var check []string
+ if json.Unmarshal(data, &check) != nil {
+ return fallback
+ }
+ return string(data)
+}
diff --git a/internal/config/chrome_flags.go b/internal/config/chrome_flags.go
new file mode 100644
index 00000000..e2fedfdc
--- /dev/null
+++ b/internal/config/chrome_flags.go
@@ -0,0 +1,124 @@
+package config
+
+import (
+ "fmt"
+ "strings"
+)
+
+const chromeNoSandboxEnvVar = "PINCHTAB_CHROME_NO_SANDBOX"
+
+func ChromeNoSandboxEnvVar() string {
+ return chromeNoSandboxEnvVar
+}
+
+// AllowedChromeExtraFlags returns the subset of browser.extraFlags that are
+// allowed to reach the browser process after security and ownership checks.
+func AllowedChromeExtraFlags(raw string) []string {
+ allowed, _ := assessChromeExtraFlags(raw)
+ return allowed
+}
+
+// SanitizeChromeExtraFlags rewrites browser.extraFlags to contain only the
+// allowed subset. Invalid, unsafe, and reserved flags are dropped.
+func SanitizeChromeExtraFlags(raw string) string {
+ return strings.Join(AllowedChromeExtraFlags(raw), " ")
+}
+
+func validateChromeExtraFlags(raw string) []error {
+ _, errs := assessChromeExtraFlags(raw)
+ return errs
+}
+
+func assessChromeExtraFlags(raw string) ([]string, []error) {
+ fields := strings.Fields(raw)
+ allowed := make([]string, 0, len(fields))
+ var errs []error
+
+ for _, field := range fields {
+ if field == "" {
+ continue
+ }
+ if err := validateChromeExtraFlag(field); err != nil {
+ errs = append(errs, err)
+ continue
+ }
+ allowed = append(allowed, field)
+ }
+
+ return allowed, errs
+}
+
+func validateChromeExtraFlag(flag string) error {
+ if !strings.HasPrefix(flag, "--") {
+ return chromeExtraFlagsError(flag, "must use Chrome flag syntax like --name or --name=value")
+ }
+
+ name, value := splitChromeFlag(flag)
+ lowerName := strings.ToLower(name)
+
+ if reservedField, ok := reservedChromeExtraFlagFields[lowerName]; ok {
+ return chromeExtraFlagsError(flag, fmt.Sprintf("is owned by PinchTab launch config; use %s instead", reservedField))
+ }
+ if msg, ok := disallowedChromeExtraFlags[lowerName]; ok {
+ return chromeExtraFlagsError(flag, msg)
+ }
+ if lowerName == "--disable-features" && disablesSiteIsolation(value) {
+ return chromeExtraFlagsError(flag, "disables site isolation, which weakens browser security and is not allowed")
+ }
+
+ return nil
+}
+
+func splitChromeFlag(flag string) (name, value string) {
+ parts := strings.SplitN(flag, "=", 2)
+ name = parts[0]
+ if len(parts) == 2 {
+ value = parts[1]
+ }
+ return name, value
+}
+
+func disablesSiteIsolation(value string) bool {
+ for _, feature := range strings.Split(strings.ToLower(value), ",") {
+ feature = strings.TrimSpace(feature)
+ switch feature {
+ case "siteperprocess", "site-per-process", "isolateorigins", "isolate-origins":
+ return true
+ }
+ }
+ return false
+}
+
+func chromeExtraFlagsError(flag, message string) error {
+ return ValidationError{
+ Field: "browser.extraFlags",
+ Message: fmt.Sprintf("flag %q %s", flag, message),
+ }
+}
+
+var reservedChromeExtraFlagFields = map[string]string{
+ "--disable-automation": "the built-in stealth launch contract",
+ "--disable-blink-features": "the built-in stealth launch contract",
+ "--enable-automation": "the built-in stealth launch contract",
+ "--enable-network-information-downlink-max": "the built-in stealth launch contract",
+ "--headless": "instanceDefaults.mode",
+ "--load-extension": "browser.extensionPaths",
+ "--disable-extensions-except": "browser.extensionPaths",
+ "--remote-debugging-address": "browser.remoteDebuggingPort",
+ "--remote-debugging-pipe": "browser.remoteDebuggingPort",
+ "--remote-debugging-port": "browser.remoteDebuggingPort",
+ "--tz": "instanceDefaults.timezone",
+ "--user-agent": "instanceDefaults.userAgent",
+ "--user-data-dir": "profiles.baseDir / profiles.defaultProfile",
+ "--window-size": "the built-in runtime window model",
+}
+
+var disallowedChromeExtraFlags = map[string]string{
+ "--allow-running-insecure-content": "weakens browser security and is not allowed",
+ "--disable-site-isolation-for-policy": "weakens browser security and is not allowed",
+ "--disable-site-isolation-trials": "weakens browser security and is not allowed",
+ "--disable-web-security": "weakens browser security and is not allowed",
+ "--ignore-certificate-errors": "weakens TLS validation and is not allowed",
+ "--ignore-certificate-errors-spki-list": "weakens TLS validation and is not allowed",
+ "--no-sandbox": fmt.Sprintf("is not allowed in browser.extraFlags; PinchTab enables it only through runtime compatibility when needed, or via %s=1 for container compatibility", chromeNoSandboxEnvVar),
+}
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index f37ed40a..f9c22122 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -264,7 +264,7 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
cfg.ChromeDebugPort = *fc.Browser.ChromeDebugPort
}
if fc.Browser.ChromeExtraFlags != "" {
- cfg.ChromeExtraFlags = fc.Browser.ChromeExtraFlags
+ cfg.ChromeExtraFlags = SanitizeChromeExtraFlags(fc.Browser.ChromeExtraFlags)
}
if len(fc.Browser.ExtensionPaths) > 0 {
cfg.ExtensionPaths = fc.Browser.ExtensionPaths
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 568b1fa5..761318c0 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -448,6 +448,21 @@ func TestApplyFileConfigToRuntime_TrustProxyHeaders(t *testing.T) {
}
}
+func TestApplyFileConfigToRuntime_SanitizesChromeExtraFlags(t *testing.T) {
+ cfg := &RuntimeConfig{}
+ fc := &FileConfig{
+ Browser: BrowserConfig{
+ ChromeExtraFlags: "--disable-gpu --user-agent=Bad/1.0 --disable-web-security --ash-no-nudges",
+ },
+ }
+
+ ApplyFileConfigToRuntime(cfg, fc)
+
+ if cfg.ChromeExtraFlags != "--disable-gpu --ash-no-nudges" {
+ t.Fatalf("ChromeExtraFlags = %q, want %q", cfg.ChromeExtraFlags, "--disable-gpu --ash-no-nudges")
+ }
+}
+
// clearConfigEnvVars unsets all config-related env vars for clean tests.
func clearConfigEnvVars(t *testing.T) {
t.Helper()
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 9647ac85..ac04c95d 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -145,6 +145,10 @@ func ValidateFileConfig(fc *FileConfig) []error {
}
}
+ if fc.Browser.ChromeExtraFlags != "" {
+ errs = append(errs, validateChromeExtraFlags(fc.Browser.ChromeExtraFlags)...)
+ }
+
// IDPI validation
errs = append(errs, validateIDPIConfig(fc.Security.IDPI)...)
errs = append(errs, validateAllowedDomainList("security.downloadAllowedDomains", fc.Security.DownloadAllowedDomains)...)
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index 2d6d5947..f9527931 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -416,6 +416,60 @@ func TestValidateFileConfig_MultipleErrors(t *testing.T) {
}
}
+func TestValidateFileConfig_ChromeExtraFlags(t *testing.T) {
+ tests := []struct {
+ name string
+ flags string
+ wantErr bool
+ wantMsg string
+ }{
+ {
+ name: "safe flags",
+ flags: "--disable-gpu --ash-no-nudges --disable-focus-on-load",
+ },
+ {
+ name: "unsafe no sandbox",
+ flags: "--no-sandbox",
+ wantErr: true,
+ wantMsg: "PINCHTAB_CHROME_NO_SANDBOX",
+ },
+ {
+ name: "reserved user agent",
+ flags: "--user-agent=PinchTab-Test/1.0",
+ wantErr: true,
+ wantMsg: "instanceDefaults.userAgent",
+ },
+ {
+ name: "site isolation disabled",
+ flags: "--disable-features=Translate,SitePerProcess",
+ wantErr: true,
+ wantMsg: "site isolation",
+ },
+ {
+ name: "malformed token",
+ flags: "disable-gpu",
+ wantErr: true,
+ wantMsg: "--name",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ fc := &FileConfig{
+ Browser: BrowserConfig{ChromeExtraFlags: tt.flags},
+ }
+ errs := ValidateFileConfig(fc)
+ hasErr := len(errs) > 0
+ if hasErr != tt.wantErr {
+ t.Fatalf("ChromeExtraFlags=%q: got error=%v, want %v (errs: %v)", tt.flags, hasErr, tt.wantErr, errs)
+ }
+ if tt.wantErr && !strings.Contains(errs[0].Error(), tt.wantMsg) {
+ t.Fatalf("expected error containing %q, got %v", tt.wantMsg, errs[0])
+ }
+ })
+ }
+}
+
func TestValidationError_Error(t *testing.T) {
err := ValidationError{
Field: "server.port",
diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.go
index 45a7af69..7ab226b2 100644
--- a/internal/dashboard/auth_api.go
+++ b/internal/dashboard/auth_api.go
@@ -84,7 +84,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
if a.loginLimiter != nil {
a.loginLimiter.RecordFailure(clientIP)
}
- authn.ClearSessionCookie(w, r)
+ authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders)
authn.AuditWarn(r, "auth.login_failed", "reason", "bad_token")
w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
@@ -107,7 +107,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, http.StatusInternalServerError, err)
return
}
- authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime())
+ authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime(), a.runtime != nil && a.runtime.TrustProxyHeaders)
authn.AuditLog(r, "auth.session_created",
"sessionIdleSec", int(authn.DefaultSessionIdleTimeout.Seconds()),
"sessionMaxLifetimeSec", int(a.sessions.MaxLifetime().Seconds()),
@@ -122,7 +122,7 @@ func (a *AuthAPI) HandleLogout(w http.ResponseWriter, r *http.Request) {
authn.AuditLog(r, "auth.session_revoked", "reason", "logout")
}
}
- authn.ClearSessionCookie(w, r)
+ authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders)
httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
@@ -165,7 +165,7 @@ func (a *AuthAPI) HandleElevate(w http.ResponseWriter, r *http.Request) {
return
}
if !a.sessions.Elevate(creds.Value, token) {
- authn.ClearSessionCookie(w, r)
+ authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders)
w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
return
diff --git a/internal/dashboard/auth_api_test.go b/internal/dashboard/auth_api_test.go
index d5c09f63..c2087745 100644
--- a/internal/dashboard/auth_api_test.go
+++ b/internal/dashboard/auth_api_test.go
@@ -49,6 +49,57 @@ func TestAuthAPIHandleLogin(t *testing.T) {
}
}
+func TestAuthAPIHandleLogin_LocalhostHTTPUsesNonSecureCookie(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "http://localhost:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
+ req.Host = "localhost:9867"
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 {
+ t.Fatalf("cookies = %d, want 1", len(cookies))
+ }
+ if cookies[0].Secure {
+ t.Fatal("expected localhost http auth cookie to omit Secure so browser sessions work reliably")
+ }
+}
+
+func TestAuthAPIHandleLogin_TrustedProxyHTTPSUsesSecureCookie(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ api := NewAuthAPI(&config.RuntimeConfig{
+ Token: "secret-token",
+ TrustProxyHeaders: true,
+ }, sessions)
+
+ req := httptest.NewRequest("POST", "http://127.0.0.1:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
+ req.Host = "127.0.0.1:9867"
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Forwarded-Proto", "https")
+ req.Header.Set("X-Forwarded-Host", "pinchtab.example")
+ w := httptest.NewRecorder()
+
+ api.HandleLogin(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 {
+ t.Fatalf("cookies = %d, want 1", len(cookies))
+ }
+ if !cookies[0].Secure {
+ t.Fatal("expected proxied https auth cookie to remain Secure")
+ }
+}
+
func TestAuthAPIHandleLoginRejectsBadToken(t *testing.T) {
api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))
@@ -96,6 +147,33 @@ func TestAuthAPIHandleLogoutClearsCookie(t *testing.T) {
}
}
+func TestAuthAPIHandleLogout_LocalhostHTTPClearsNonSecureCookie(t *testing.T) {
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create("secret-token")
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+ api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+
+ req := httptest.NewRequest("POST", "http://localhost:9867/api/auth/logout", nil)
+ req.Host = "localhost:9867"
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ w := httptest.NewRecorder()
+
+ api.HandleLogout(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 || cookies[0].Name != authn.CookieName || cookies[0].MaxAge != -1 {
+ t.Fatalf("expected expired auth cookie, got %+v", cookies)
+ }
+ if cookies[0].Secure {
+ t.Fatal("expected localhost http logout cookie clearing to omit Secure")
+ }
+}
+
func TestAuthAPIHandleElevateMarksSessionElevated(t *testing.T) {
sessions := authn.NewSessionManager(authn.SessionConfig{})
sessionID, err := sessions.Create("secret-token")
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 29251bf1..0da45cf0 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -138,6 +138,7 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("GET /cookies", h.HandleGetCookies)
mux.HandleFunc("POST /cookies", h.HandleSetCookies)
mux.HandleFunc("POST /fingerprint/rotate", h.HandleFingerprintRotate)
+ mux.HandleFunc("GET /stealth/status", h.HandleStealthStatus)
mux.HandleFunc("GET /tabs/{id}/download", h.HandleTabDownload)
mux.HandleFunc("POST /tabs/{id}/upload", h.HandleTabUpload)
mux.HandleFunc("GET /download", h.HandleDownload)
diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.go
index 6558f2f4..2959054e 100644
--- a/internal/handlers/handlers_test.go
+++ b/internal/handlers/handlers_test.go
@@ -24,6 +24,7 @@ type mockBridge struct {
createTabURLs []string
lastConsoleLimit int
lastErrorLimit int
+ fingerprintTabs map[string]bool
}
func (m *mockBridge) TabContext(tabID string) (context.Context, string, error) {
@@ -119,6 +120,17 @@ func (m *mockBridge) Execute(ctx context.Context, tabID string, task func(ctx co
return task(ctx)
}
+func (m *mockBridge) SetFingerprintRotateActive(tabID string, active bool) {
+ if m.fingerprintTabs == nil {
+ m.fingerprintTabs = make(map[string]bool)
+ }
+ m.fingerprintTabs[tabID] = active
+}
+
+func (m *mockBridge) FingerprintRotateActive(tabID string) bool {
+ return m.fingerprintTabs != nil && m.fingerprintTabs[tabID]
+}
+
func TestHandlers(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
mux := http.NewServeMux()
diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.go
index ab5930f0..8c9af4dd 100644
--- a/internal/handlers/health_tabs_test.go
+++ b/internal/handlers/health_tabs_test.go
@@ -13,6 +13,7 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/engine"
+ "github.com/pinchtab/pinchtab/internal/stealth"
)
// TestHandleHealth_NilBridge verifies health endpoint returns 503 when bridge is nil
@@ -421,6 +422,17 @@ func (m *MockBridge) EnsureChrome(cfg *config.RuntimeConfig) error {
return nil
}
+func (m *MockBridge) StealthStatus() *stealth.Status {
+ return &stealth.Status{
+ Level: stealth.LevelLight,
+ LaunchMode: stealth.LaunchModeUninitialized,
+ WebdriverMode: stealth.WebdriverModeNativeBaseline,
+ Flags: map[string]bool{},
+ Capabilities: map[string]bool{},
+ TabOverrides: map[string]bool{"fingerprintRotateActive": false},
+ }
+}
+
func (m *MockBridge) GetMemoryMetrics(tabID string) (*bridge.MemoryMetrics, error) {
return &bridge.MemoryMetrics{JSHeapUsedMB: 10, JSHeapTotalMB: 20}, nil
}
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index 5b8f0fad..fabd5143 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -90,7 +90,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi
creds := authn.CredentialsFromRequest(r)
if creds.Value == "" {
- authn.ClearSessionCookie(w, r)
+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)
w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
httpx.ErrorCode(w, 401, "missing_token", "unauthorized", false, nil)
return
@@ -99,7 +99,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi
switch creds.Method {
case authn.MethodHeader:
if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {
- authn.ClearSessionCookie(w, r)
+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)
w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
return
@@ -112,7 +112,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi
return
}
if sessions == nil || !sessions.Validate(creds.Value, token) {
- authn.ClearSessionCookie(w, r)
+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)
w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
return
@@ -129,7 +129,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessi
return
}
default:
- authn.ClearSessionCookie(w, r)
+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)
w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
return
@@ -191,6 +191,8 @@ func cookieAuthAllowed(r *http.Request) bool {
return true
case path == "/instances/launch":
return true
+ case strings.HasPrefix(path, "/tabs/") && strings.HasSuffix(path, "/close"):
+ return true
case strings.HasPrefix(path, "/instances/") && strings.HasSuffix(path, "/stop"):
return true
case path == "/profiles":
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index c7c7b136..539ce8c6 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -208,6 +208,62 @@ func TestAuthMiddleware_CookieRestrictedEndpointRejected(t *testing.T) {
}
}
+func TestAuthMiddleware_CookieAllowsTabCloseEndpoint(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_123/close", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Referer", "http://example.com/dashboard")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should allow same-origin cookie-authenticated tab close")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_CookieAllowsActionEndpoint(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ sessions := authn.NewSessionManager(authn.SessionConfig{})
+ sessionID, err := sessions.Create(cfg.Token)
+ if err != nil {
+ t.Fatalf("Create() error = %v", err)
+ }
+
+ called := false
+ handler := AuthMiddlewareWithSessions(cfg, sessions, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest(http.MethodPost, "/action", nil)
+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
+ req.Header.Set("Origin", "http://example.com")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should allow same-origin cookie-authenticated actions from the dashboard")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
func TestAuthMiddleware_CookieCrossOriginRejected(t *testing.T) {
cfg := &config.RuntimeConfig{Token: "secret123"}
sessions := authn.NewSessionManager(authn.SessionConfig{})
diff --git a/internal/handlers/stealth.go b/internal/handlers/stealth.go
index 2e92c3a3..02593543 100644
--- a/internal/handlers/stealth.go
+++ b/internal/handlers/stealth.go
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
- "log/slog"
"math/rand"
"net/http"
"time"
@@ -58,33 +57,44 @@ func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Reques
if err != nil {
return fmt.Errorf("setUserAgentOverride: %w", err)
}
+ if fp.Language != "" {
+ if err := emulation.SetLocaleOverride().WithLocale(fp.Language).Do(ctx); err != nil {
+ return fmt.Errorf("setLocaleOverride: %w", err)
+ }
+ }
+ if timezoneID := timezoneIDFromOffset(fp.TimezoneOffset); timezoneID != "" {
+ if err := emulation.SetTimezoneOverride(timezoneID).Do(ctx); err != nil {
+ return fmt.Errorf("setTimezoneOverride: %w", err)
+ }
+ }
+ if fp.ScreenWidth > 0 && fp.ScreenHeight > 0 {
+ if err := emulation.SetDeviceMetricsOverride(int64(fp.ScreenWidth), int64(fp.ScreenHeight), 1, false).
+ WithScreenWidth(int64(fp.ScreenWidth)).
+ WithScreenHeight(int64(fp.ScreenHeight)).
+ Do(ctx); err != nil {
+ return fmt.Errorf("setDeviceMetricsOverride: %w", err)
+ }
+ }
return nil
}),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ if fp.Platform == "" {
+ return nil
+ }
+ overlayScript := fingerprintRotatePlatformOverlayScript(fp.Platform)
+ if _, err := page.AddScriptToEvaluateOnNewDocument(overlayScript).Do(ctx); err != nil {
+ return fmt.Errorf("add platform overlay: %w", err)
+ }
+ return nil
+ }),
+ chromedp.Evaluate(fingerprintRotatePlatformOverlayScript(fp.Platform), nil),
); err != nil {
httpx.Error(w, 500, fmt.Errorf("CDP UA override: %w", err))
return
}
- script := fmt.Sprintf(`
-(function() {
- Object.defineProperty(screen, 'width', { get: () => %d, configurable: true });
- Object.defineProperty(screen, 'height', { get: () => %d, configurable: true });
- Object.defineProperty(screen, 'availWidth', { get: () => %d, configurable: true });
- Object.defineProperty(screen, 'availHeight', { get: () => %d, configurable: true });
- Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => %d, configurable: true });
- Object.defineProperty(navigator, 'deviceMemory', { get: () => %d, configurable: true });
-})();
- `, fp.ScreenWidth, fp.ScreenHeight, fp.ScreenWidth-20, fp.ScreenHeight-80,
- fp.CPUCores, fp.Memory)
-
- if err := chromedp.Run(tCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(script).Do(ctx)
- return err
- }),
- chromedp.Evaluate(script, nil),
- ); err != nil {
- slog.Warn("JS fingerprint extras failed", "err", err)
+ if tracker, ok := h.Bridge.(interface{ SetFingerprintRotateActive(string, bool) }); ok {
+ tracker.SetFingerprintRotateActive(resolvedTabID, true)
}
httpx.JSON(w, 200, map[string]any{
@@ -189,3 +199,46 @@ func (h *Handlers) generateFingerprint(req fingerprintRequest) fingerprint {
return fp
}
+
+func timezoneIDFromOffset(offset int) string {
+ switch offset {
+ case -480:
+ return "America/Los_Angeles"
+ case -420:
+ return "America/Denver"
+ case -360:
+ return "America/Chicago"
+ case -300:
+ return "America/New_York"
+ case -240:
+ return "America/Halifax"
+ case 0:
+ return "UTC"
+ case 60:
+ return "Europe/Berlin"
+ case 120:
+ return "Europe/Helsinki"
+ case 330:
+ return "Asia/Kolkata"
+ case 480:
+ return "Asia/Shanghai"
+ case 540:
+ return "Asia/Tokyo"
+ default:
+ return ""
+ }
+}
+
+func fingerprintRotatePlatformOverlayScript(platform string) string {
+ return fmt.Sprintf(`(() => {
+ try {
+ const nav = navigator;
+ const proto = Object.getPrototypeOf(nav) || Navigator.prototype;
+ Object.defineProperty(proto, 'platform', {
+ get: () => %q,
+ configurable: true,
+ enumerable: true
+ });
+ } catch (e) {}
+})()`, platform)
+}
diff --git a/internal/handlers/stealth_status.go b/internal/handlers/stealth_status.go
new file mode 100644
index 00000000..7be08cc7
--- /dev/null
+++ b/internal/handlers/stealth_status.go
@@ -0,0 +1,24 @@
+package handlers
+
+import (
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+func (h *Handlers) HandleStealthStatus(w http.ResponseWriter, r *http.Request) {
+ status := h.Bridge.StealthStatus()
+ if status == nil {
+ httpx.JSON(w, 503, map[string]any{
+ "status": "error",
+ "reason": "stealth bundle unavailable",
+ })
+ return
+ }
+ if tabID := r.URL.Query().Get("tabId"); tabID != "" {
+ if tracker, ok := h.Bridge.(interface{ FingerprintRotateActive(string) bool }); ok {
+ status.TabOverrides["fingerprintRotateActive"] = tracker.FingerprintRotateActive(tabID)
+ }
+ }
+ httpx.JSON(w, 200, status)
+}
diff --git a/internal/handlers/stealth_test.go b/internal/handlers/stealth_test.go
index 8f8f0629..db6c6124 100644
--- a/internal/handlers/stealth_test.go
+++ b/internal/handlers/stealth_test.go
@@ -3,6 +3,7 @@ package handlers
import (
"bytes"
"context"
+ "encoding/json"
"net/http/httptest"
"strings"
"testing"
@@ -10,6 +11,7 @@ import (
"github.com/pinchtab/pinchtab/internal/assets"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
)
func TestHandleFingerprintRotate_InvalidJSON(t *testing.T) {
@@ -76,6 +78,25 @@ func TestGenerateFingerprint_Config(t *testing.T) {
}
}
+func TestTimezoneIDFromOffset(t *testing.T) {
+ if got := timezoneIDFromOffset(-300); got != "America/New_York" {
+ t.Fatalf("timezoneIDFromOffset(-300) = %q, want America/New_York", got)
+ }
+ if got := timezoneIDFromOffset(999); got != "" {
+ t.Fatalf("timezoneIDFromOffset(999) = %q, want empty string", got)
+ }
+}
+
+func TestFingerprintRotatePlatformOverlayScript(t *testing.T) {
+ script := fingerprintRotatePlatformOverlayScript("Win32")
+ if !strings.Contains(script, "Object.defineProperty(proto, 'platform'") {
+ t.Fatalf("expected platform overlay script to patch navigator platform, got %q", script)
+ }
+ if !strings.Contains(script, "\"Win32\"") {
+ t.Fatalf("expected platform overlay script to embed platform, got %q", script)
+ }
+}
+
func TestStealthScript_Content(t *testing.T) {
if assets.StealthScript == "" {
t.Fatal("StealthScript is empty")
@@ -83,16 +104,88 @@ func TestStealthScript_Content(t *testing.T) {
if !strings.Contains(assets.StealthScript, "navigator") || !strings.Contains(assets.StealthScript, "webdriver") {
t.Error("stealth script missing webdriver protection")
}
- if !strings.Contains(assets.StealthScript, "new Proxy") || !strings.Contains(assets.StealthScript, "Object.defineProperty(window, 'navigator'") {
- t.Error("stealth script missing navigator proxy protection")
+ if strings.Contains(assets.StealthScript, "proxyNavigator") || strings.Contains(assets.StealthScript, "Object.defineProperty(window, 'navigator'") {
+ t.Error("stealth script should not proxy window.navigator in light mode")
+ }
+ if !strings.Contains(assets.StealthScript, "downlinkMax") {
+ t.Error("stealth script missing downlinkMax coverage")
}
}
func TestStealthScript_Populated(t *testing.T) {
b := bridge.New(context.Background(), context.Background(), &config.RuntimeConfig{})
- b.StealthScript = assets.StealthScript
- if b.StealthScript == "" {
- t.Error("expected stealth script to be populated")
+ if b.StealthBundle == nil || b.StealthBundle.Script == "" {
+ t.Error("expected stealth bundle script to be populated")
+ }
+}
+
+func (m *mockBridge) StealthStatus() *stealth.Status {
+ return &stealth.Status{
+ Level: stealth.LevelMedium,
+ Headless: true,
+ LaunchMode: stealth.LaunchModeAllocator,
+ ScriptHash: "sha256:test",
+ WebdriverMode: stealth.WebdriverModeNativeBaseline,
+ Flags: map[string]bool{
+ "headlessNew": true,
+ },
+ Capabilities: map[string]bool{
+ "userAgentData": true,
+ "webdriverNativeStrategy": true,
+ "downlinkMax": true,
+ },
+ TabOverrides: map[string]bool{
+ "fingerprintRotateActive": false,
+ },
+ }
+}
+
+func TestHandleStealthStatus(t *testing.T) {
+ mb := &mockBridge{fingerprintTabs: map[string]bool{"tab1": true}}
+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/stealth/status", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleStealthStatus(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to parse response: %v", err)
+ }
+ if got := resp["level"]; got != "medium" {
+ t.Fatalf("expected level=medium, got %v", got)
+ }
+ if got := resp["launchMode"]; got != "allocator" {
+ t.Fatalf("expected launchMode=allocator, got %v", got)
+ }
+}
+
+func TestHandleStealthStatus_WithTabOverride(t *testing.T) {
+ mb := &mockBridge{fingerprintTabs: map[string]bool{"tab-special": true}}
+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/stealth/status?tabId=tab-special", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleStealthStatus(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to parse response: %v", err)
+ }
+ tabOverrides, ok := resp["tabOverrides"].(map[string]any)
+ if !ok {
+ t.Fatalf("expected tabOverrides object, got %T", resp["tabOverrides"])
+ }
+ if got := tabOverrides["fingerprintRotateActive"]; got != true {
+ t.Fatalf("expected fingerprintRotateActive=true, got %v", got)
}
}
diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.go
index 33163f20..c9493374 100644
--- a/internal/orchestrator/health.go
+++ b/internal/orchestrator/health.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"log/slog"
+ "net"
"net/http"
"net/url"
"strings"
@@ -189,6 +190,11 @@ func (o *Orchestrator) probeInstanceHealth(inst *InstanceInternal) (bool, string
lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())
continue
}
+ if !isAllowedProbeHost(parsed.Hostname()) {
+ lastProbe = fmt.Sprintf("%s -> blocked: non-loopback host", baseURL)
+ slog.Warn("health probe blocked: non-loopback host", "url", baseURL, "host", parsed.Hostname())
+ continue
+ }
target := &url.URL{
Scheme: parsed.Scheme,
Host: parsed.Host,
@@ -296,6 +302,16 @@ func isInstanceHealthyStatus(code int) bool {
return code > 0 && code < http.StatusInternalServerError
}
+// isAllowedProbeHost restricts health probes to loopback addresses to
+// prevent SSRF when inst.URL is attacker-controlled.
+func isAllowedProbeHost(host string) bool {
+ if strings.EqualFold(host, "localhost") {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
+
func instanceBaseURLs(port int) []string {
return []string{
fmt.Sprintf("http://127.0.0.1:%d", port),
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 287a1855..396c5317 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -382,8 +382,6 @@ func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, i
} else {
fc.InstanceDefaults.Mode = "headed"
}
- noRestore := true
- fc.InstanceDefaults.NoRestore = &noRestore
if len(extensionPaths) > 0 {
seen := make(map[string]bool)
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index 6d19f7d3..859d4e06 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -132,6 +132,20 @@ func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, target
})
}
+// ProxyToTarget proxies a shorthand dashboard request to a managed instance URL,
+// preserving orchestrator-side auth injection for the child bridge.
+func (o *Orchestrator) ProxyToTarget(w http.ResponseWriter, r *http.Request, target string) {
+ targetURL, err := url.Parse(target)
+ if err != nil {
+ httpx.Error(w, 502, fmt.Errorf("proxy error: %w", err))
+ return
+ }
+ if targetURL.RawQuery == "" {
+ targetURL.RawQuery = r.URL.RawQuery
+ }
+ o.proxyToURL(w, r, targetURL)
+}
+
// findRunningInstanceByTabID finds the instance that owns the given tab.
func (o *Orchestrator) findRunningInstanceByTabID(tabID string) (*InstanceInternal, error) {
o.mu.RLock()
diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.go
index fc8b8ce9..4e8d5ef1 100644
--- a/internal/orchestrator/proxy_test.go
+++ b/internal/orchestrator/proxy_test.go
@@ -116,3 +116,38 @@ func TestProxyToURL_UsesAttachedBridgeOriginAndAuth(t *testing.T) {
t.Fatalf("status = %d, want 200", w.Code)
}
}
+
+func TestProxyToTarget_InjectsChildAuthAndStripsCookie(t *testing.T) {
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Authorization"); got != "Bearer child-token" {
+ t.Fatalf("authorization = %q, want %q", got, "Bearer child-token")
+ }
+ if got := r.Header.Get("Cookie"); got != "" {
+ t.Fatalf("cookie = %q, want empty", got)
+ }
+ if r.URL.Path != "/action" {
+ t.Fatalf("path = %q, want /action", r.URL.Path)
+ }
+ _, _ = io.WriteString(w, `ok`)
+ }))
+ defer backend.Close()
+
+ o := NewOrchestrator(t.TempDir())
+ o.client = backend.Client()
+ o.childAuthToken = "child-token"
+ o.instances["inst_1"] = &InstanceInternal{
+ Instance: bridge.Instance{ID: "inst_1", Status: "running"},
+ URL: backend.URL,
+ cmd: &mockCmd{pid: 1234, isAlive: true},
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/action", nil)
+ req.Header.Set("Cookie", "pinchtab_auth_token=session-secret")
+ w := httptest.NewRecorder()
+
+ o.ProxyToTarget(w, req, backend.URL+"/action")
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+}
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index 36929d8f..d5b6708e 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -11,7 +11,6 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/activity"
- "github.com/pinchtab/pinchtab/internal/assets"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
@@ -32,7 +31,6 @@ func RunBridgeServer(cfg *config.RuntimeConfig) {
bridge.CleanupOrphanedChromeProcesses(cfg.ProfileDir)
bridgeInstance := bridge.New(context.Background(), nil, cfg)
- bridgeInstance.StealthScript = assets.StealthScript
actStore, err := activity.NewRecorder(activity.Config{
Enabled: cfg.Observability.Activity.Enabled,
SessionIdle: time.Duration(cfg.Observability.Activity.SessionIdleSec) * time.Second,
diff --git a/internal/stealth/bundle.go b/internal/stealth/bundle.go
new file mode 100644
index 00000000..74b5f184
--- /dev/null
+++ b/internal/stealth/bundle.go
@@ -0,0 +1,302 @@
+package stealth
+
+import (
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type Level string
+
+const (
+ LevelLight Level = "light"
+ LevelMedium Level = "medium"
+ LevelFull Level = "full"
+)
+
+type LaunchMode string
+
+const (
+ LaunchModeUninitialized LaunchMode = "uninitialized"
+ LaunchModeAllocator LaunchMode = "allocator"
+ LaunchModeDirectFallback LaunchMode = "direct_fallback"
+ LaunchModeAttached LaunchMode = "attached"
+)
+
+type WebdriverMode string
+
+const (
+ WebdriverModeNativeBaseline WebdriverMode = "native_baseline"
+)
+
+type Bundle struct {
+ Level Level `json:"level"`
+ Seed int64 `json:"seed"`
+ Script string `json:"-"`
+ ScriptHash string `json:"scriptHash"`
+ Launch LaunchContract `json:"-"`
+ PatchIDs []string `json:"patchIds"`
+ Capabilities map[string]bool `json:"capabilities"`
+ Tradeoffs []string `json:"tradeoffs,omitempty"`
+ Webdriver WebdriverMode `json:"webdriverMode"`
+}
+
+type Status struct {
+ Level Level `json:"level"`
+ Headless bool `json:"headless"`
+ LaunchMode LaunchMode `json:"launchMode"`
+ ScriptHash string `json:"scriptHash"`
+ UserAgent string `json:"userAgent,omitempty"`
+ WebdriverMode WebdriverMode `json:"webdriverMode"`
+ PatchIDs []string `json:"patchIds"`
+ Flags map[string]bool `json:"flags"`
+ Capabilities map[string]bool `json:"capabilities"`
+ Tradeoffs []string `json:"tradeoffs,omitempty"`
+ TabOverrides map[string]bool `json:"tabOverrides"`
+}
+
+func NewBundle(cfg *config.RuntimeConfig, seed int64) *Bundle {
+ levelName := ""
+ headless := false
+ if cfg != nil {
+ levelName = cfg.StealthLevel
+ headless = cfg.Headless
+ }
+ level := NormalizeLevel(levelName)
+ personaJSON := "{}"
+ if cfg != nil {
+ if encoded, err := json.Marshal(BuildPersona(cfg.UserAgent, cfg.ChromeVersion)); err == nil {
+ personaJSON = string(encoded)
+ }
+ }
+ script := renderBundleScript(level, personaJSON, seed, headless)
+
+ return &Bundle{
+ Level: level,
+ Seed: seed,
+ Script: script,
+ // Keep the status hash stable across identical configs even when the
+ // per-process seed changes. The seed is runtime entropy, not contract.
+ ScriptHash: hashScript(renderBundleScript(level, personaJSON, 0, headless)),
+ Launch: BuildLaunchContract(cfg, level),
+ PatchIDs: patchIDsForLevel(level, headless),
+ Capabilities: capabilityMap(level, headless),
+ Tradeoffs: tradeoffs(level),
+ Webdriver: WebdriverModeNativeBaseline,
+ }
+}
+
+func renderBundleScript(level Level, personaJSON string, seed int64, headless bool) string {
+ return fmt.Sprintf(
+ "var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\nvar __pinchtab_headless = %t;\nvar __pinchtab_profile = %s;\n%s\n%s",
+ seed,
+ level,
+ headless,
+ personaJSON,
+ assets.StealthScript,
+ PopupGuardInitScript,
+ )
+}
+
+func NormalizeLevel(level string) Level {
+ switch strings.ToLower(strings.TrimSpace(level)) {
+ case string(LevelMedium):
+ return LevelMedium
+ case string(LevelFull):
+ return LevelFull
+ default:
+ return LevelLight
+ }
+}
+
+func StatusFromBundle(bundle *Bundle, cfg *config.RuntimeConfig, launchMode LaunchMode) *Status {
+ if bundle == nil {
+ return nil
+ }
+
+ status := &Status{
+ Level: bundle.Level,
+ Headless: cfg != nil && cfg.Headless,
+ LaunchMode: launchMode,
+ ScriptHash: bundle.ScriptHash,
+ UserAgent: bundle.LaunchUserAgent(),
+ WebdriverMode: bundle.Webdriver,
+ PatchIDs: append([]string(nil), bundle.PatchIDs...),
+ Flags: statusFlags(bundle, cfg),
+ Capabilities: cloneBoolMap(bundle.Capabilities),
+ Tradeoffs: append([]string(nil), bundle.Tradeoffs...),
+ TabOverrides: map[string]bool{
+ "fingerprintRotateActive": false,
+ },
+ }
+ if status.LaunchMode == "" {
+ status.LaunchMode = LaunchModeUninitialized
+ }
+ return status
+}
+
+func hashScript(script string) string {
+ sum := sha256.Sum256([]byte(script))
+ return fmt.Sprintf("sha256:%x", sum)
+}
+
+func statusFlags(bundle *Bundle, cfg *config.RuntimeConfig) map[string]bool {
+ var extraFlags []string
+ headless := false
+ if cfg != nil {
+ extraFlags = config.AllowedChromeExtraFlags(cfg.ChromeExtraFlags)
+ headless = cfg.Headless
+ }
+
+ flags := map[string]bool{}
+ if bundle != nil {
+ flags = cloneBoolMap(bundle.Launch.Flags)
+ }
+ flags["headlessNew"] = headless
+ flags["swiftshader"] = headless
+ flags["testTypeGPU"] = hasFlag(extraFlags, "--test-type=gpu")
+ flags["disableInfobars"] = hasFlag(extraFlags, "--disable-infobars")
+ flags["disableDesktopNotifications"] = hasFlag(extraFlags, "--disable-desktop-notifications")
+ flags["disableWindowActivation"] = hasFlag(extraFlags, "--disable-window-activation")
+ flags["silentDebuggerExtensionAPI"] = hasFlag(extraFlags, "--silent-debugger-extension-api")
+ return flags
+}
+
+func hasFlag(args []string, want string) bool {
+ for _, field := range args {
+ if field == want {
+ return true
+ }
+ }
+ return false
+}
+
+func capabilityMap(level Level, headless bool) map[string]bool {
+ caps := map[string]bool{
+ "webdriverNotTrue": true,
+ "webdriverNativeStrategy": true,
+ "batteryAPIBaseline": true,
+ "pluginArray": true,
+ "workerHardwareConsistency": true,
+ "workerUserAgentConsistency": true,
+ "serviceWorkerHardwareConsistency": true,
+ "serviceWorkerUserAgentConsistency": true,
+ "userAgentData": false,
+ "chromeRuntimeConnect": false,
+ "chromeRuntimeSendMessage": false,
+ "chromeApp": false,
+ "videoCodecs": false,
+ "maxTouchPoints": false,
+ "iframeIsolation": false,
+ "errorStackSanitized": false,
+ "functionToStringMasked": false,
+ "functionToStringNative": true,
+ "intlLocaleCoherent": true,
+ "errorPrepareStackTraceNative": true,
+ "navigatorOverridesAbsent": true,
+ "userAgentDataVersionCoherent": true,
+ "downlinkMax": true,
+ "webglSpoofing": false,
+ "canvasNoise": false,
+ "systemColorFix": false,
+ "transparentPixelCanvasNoise": false,
+ "audioNoise": false,
+ "webrtcMitigation": false,
+ }
+
+ if level == LevelMedium || level == LevelFull {
+ caps["userAgentData"] = true
+ caps["maxTouchPoints"] = true
+ }
+ if level == LevelMedium {
+ caps["iframeIsolation"] = true
+ caps["chromeRuntimeConnect"] = true
+ caps["chromeRuntimeSendMessage"] = true
+ }
+ if level == LevelFull && headless {
+ caps["webglSpoofing"] = true
+ }
+
+ return caps
+}
+
+func patchIDsForLevel(level Level, headless bool) []string {
+ patches := []string{
+ "marker-cleanup",
+ "webdriver-native-baseline",
+ "plugins",
+ "languages",
+ "platform",
+ "downlink-max",
+ "permissions",
+ "battery",
+ }
+ if headless {
+ patches = append(patches, "screen")
+ }
+
+ if level == LevelMedium || level == LevelFull {
+ patches = append(patches,
+ "user-agent-data",
+ "touch-points",
+ )
+ }
+ if level == LevelMedium {
+ patches = append(patches, "chrome-runtime", "iframe-isolation")
+ }
+ if level == LevelFull {
+ if headless {
+ patches = append(patches, "screen-position")
+ }
+ if headless {
+ patches = append(patches, "webgl")
+ }
+ }
+
+ return patches
+}
+
+func tradeoffs(level Level) []string {
+ switch level {
+ case LevelMedium:
+ return []string{
+ "non-default-risk-mode",
+ "api-realism-risk",
+ }
+ case LevelFull:
+ return []string{
+ "non-default-risk-mode",
+ "api-realism-risk",
+ "graphics-and-media-breakage-risk",
+ }
+ default:
+ return nil
+ }
+}
+
+func cloneBoolMap(src map[string]bool) map[string]bool {
+ if src == nil {
+ return nil
+ }
+ dst := make(map[string]bool, len(src))
+ for k, v := range src {
+ dst[k] = v
+ }
+ return dst
+}
+
+func (b *Bundle) LaunchUserAgent() string {
+ if b == nil {
+ return ""
+ }
+ for _, arg := range b.Launch.Args {
+ if strings.HasPrefix(arg, "--user-agent=") {
+ return strings.TrimPrefix(arg, "--user-agent=")
+ }
+ }
+ return ""
+}
diff --git a/internal/stealth/bundle_test.go b/internal/stealth/bundle_test.go
new file mode 100644
index 00000000..fb74caa2
--- /dev/null
+++ b/internal/stealth/bundle_test.go
@@ -0,0 +1,141 @@
+package stealth
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestNewBundleIncludesSeedLevelAndPopupGuard(t *testing.T) {
+ bundle := NewBundle(&config.RuntimeConfig{StealthLevel: "medium"}, 1234)
+ if bundle == nil {
+ t.Fatal("expected non-nil bundle")
+ }
+ if bundle.Level != LevelMedium {
+ t.Fatalf("expected level medium, got %s", bundle.Level)
+ }
+ for _, want := range []string{
+ "var __pinchtab_seed = 1234;",
+ `var __pinchtab_stealth_level = "medium";`,
+ "var __pinchtab_headless = false;",
+ "var __pinchtab_profile = ",
+ "window.open",
+ "window.opener",
+ } {
+ if !strings.Contains(bundle.Script, want) {
+ t.Fatalf("expected bundle script to contain %q", want)
+ }
+ }
+ if !strings.HasPrefix(bundle.ScriptHash, "sha256:") {
+ t.Fatalf("expected script hash prefix, got %q", bundle.ScriptHash)
+ }
+}
+
+func TestScriptHashStableAcrossSeeds(t *testing.T) {
+ cfg := &config.RuntimeConfig{StealthLevel: "full", ChromeVersion: "144.0.7559.133"}
+ first := NewBundle(cfg, 111)
+ second := NewBundle(cfg, 222)
+ if first.ScriptHash != second.ScriptHash {
+ t.Fatalf("expected script hash to stay stable across seeds, got %q vs %q", first.ScriptHash, second.ScriptHash)
+ }
+ if first.Script == second.Script {
+ t.Fatalf("expected runtime script to still vary with seed")
+ }
+}
+
+func TestStatusFromBundleReflectsCurrentCapabilityShape(t *testing.T) {
+ cfg := &config.RuntimeConfig{StealthLevel: "full", Headless: true}
+ bundle := NewBundle(cfg, 7)
+ status := StatusFromBundle(bundle, cfg, LaunchModeAllocator)
+ if status == nil {
+ t.Fatal("expected non-nil status")
+ }
+ if !status.Capabilities["webglSpoofing"] {
+ t.Fatal("expected full mode to report webgl spoofing")
+ }
+ if !status.Capabilities["webdriverNativeStrategy"] {
+ t.Fatal("expected current status to report native webdriver strategy")
+ }
+ if !status.Capabilities["downlinkMax"] {
+ t.Fatal("expected light/full baseline to report downlinkMax capability")
+ }
+ if status.Capabilities["iframeIsolation"] {
+ t.Fatal("expected current full mode to keep iframe isolation capability disabled")
+ }
+ if status.Capabilities["errorStackSanitized"] {
+ t.Fatal("expected current full mode to keep stack sanitization disabled")
+ }
+ if status.Capabilities["functionToStringMasked"] {
+ t.Fatal("expected current full mode to keep function-toString masking disabled")
+ }
+ if !status.Capabilities["functionToStringNative"] {
+ t.Fatal("expected full mode to report native Function.prototype.toString semantics")
+ }
+ if !status.Capabilities["intlLocaleCoherent"] {
+ t.Fatal("expected full mode to report locale coherence capability")
+ }
+ if !status.Capabilities["errorPrepareStackTraceNative"] {
+ t.Fatal("expected full mode to report native Error.prepareStackTrace semantics")
+ }
+ if status.Capabilities["systemColorFix"] {
+ t.Fatal("expected current full mode to keep system color wrappers disabled")
+ }
+ if status.Capabilities["videoCodecs"] {
+ t.Fatal("expected current full mode to keep codec spoofing disabled")
+ }
+ if status.Capabilities["canvasNoise"] {
+ t.Fatal("expected full mode to keep canvas noise disabled in the current public-site profile")
+ }
+ if status.Capabilities["transparentPixelCanvasNoise"] {
+ t.Fatal("expected full mode to keep transparent pixel canvas noise disabled in the current public-site profile")
+ }
+ if status.Capabilities["audioNoise"] {
+ t.Fatal("expected full mode to keep audio noise disabled in the current public-site profile")
+ }
+ if status.Capabilities["webrtcMitigation"] {
+ t.Fatal("expected full mode to keep JS WebRTC mitigation disabled in the current public-site profile")
+ }
+ if !status.Flags["headlessNew"] {
+ t.Fatal("expected headlessNew flag to be true for headless config")
+ }
+}
+
+func TestStatusFromBundleDisablesWebGLSpoofingWhenHeaded(t *testing.T) {
+ cfg := &config.RuntimeConfig{StealthLevel: "full", Headless: false}
+ bundle := NewBundle(cfg, 7)
+ status := StatusFromBundle(bundle, cfg, LaunchModeAllocator)
+ if status == nil {
+ t.Fatal("expected non-nil status")
+ }
+ if status.Capabilities["webglSpoofing"] {
+ t.Fatal("expected headed full mode to avoid WebGL spoofing")
+ }
+}
+
+func TestResolveUserAgent(t *testing.T) {
+ if got := ResolveUserAgent("custom-agent", "144.0.0.0"); got != "custom-agent" {
+ t.Fatalf("expected explicit UA to win, got %q", got)
+ }
+ got := ResolveUserAgent("", "144.0.0.0")
+ if !strings.Contains(got, "Chrome/144.0.0.0") {
+ t.Fatalf("expected generated UA to include chrome version, got %q", got)
+ }
+}
+
+func TestBuildLaunchContractOwnsStealthLaunchFlags(t *testing.T) {
+ launch := BuildLaunchContract(&config.RuntimeConfig{ChromeVersion: "144.0.0.0"}, LevelLight)
+ for _, want := range []string{
+ "--enable-automation=false",
+ "--disable-blink-features=AutomationControlled",
+ "--enable-network-information-downlink-max",
+ "--lang=en-US",
+ } {
+ if !HasLaunchArg(launch.Args, want) {
+ t.Fatalf("expected stealth launch arg %q in %v", want, launch.Args)
+ }
+ }
+ if !HasLaunchArgPrefix(launch.Args, "--user-agent=Mozilla/5.0") {
+ t.Fatalf("expected stealth launch contract to own user-agent, got %v", launch.Args)
+ }
+}
diff --git a/internal/stealth/emulation.go b/internal/stealth/emulation.go
new file mode 100644
index 00000000..151852f6
--- /dev/null
+++ b/internal/stealth/emulation.go
@@ -0,0 +1,85 @@
+package stealth
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// BuildUserAgentOverride creates a SetUserAgentOverride action with persona-backed
+// metadata. chromeVersion should be the full version (for example
+// "144.0.7559.133"). If chromeVersion is empty, returns nil.
+func BuildUserAgentOverride(userAgent, chromeVersion string) *emulation.SetUserAgentOverrideParams {
+ if chromeVersion == "" {
+ return nil
+ }
+
+ persona := BuildPersona(userAgent, chromeVersion)
+ if persona.UserAgent == "" {
+ return nil
+ }
+
+ brands := make([]*emulation.UserAgentBrandVersion, 0, len(persona.UserAgentData.Brands))
+ for _, brand := range persona.UserAgentData.Brands {
+ brands = append(brands, &emulation.UserAgentBrandVersion{
+ Brand: brand.Brand,
+ Version: brand.Version,
+ })
+ }
+ fullVersionList := make([]*emulation.UserAgentBrandVersion, 0, len(persona.UserAgentData.FullVersionList))
+ for _, brand := range persona.UserAgentData.FullVersionList {
+ fullVersionList = append(fullVersionList, &emulation.UserAgentBrandVersion{
+ Brand: brand.Brand,
+ Version: brand.Version,
+ })
+ }
+
+ return emulation.SetUserAgentOverride(persona.UserAgent).
+ WithAcceptLanguage(persona.AcceptLanguage).
+ WithPlatform(persona.NavigatorPlatform).
+ WithUserAgentMetadata(&emulation.UserAgentMetadata{
+ Platform: persona.UserAgentData.Platform,
+ PlatformVersion: persona.UserAgentData.PlatformVersion,
+ Architecture: persona.UserAgentData.Architecture,
+ Bitness: persona.UserAgentData.Bitness,
+ Mobile: persona.UserAgentData.Mobile,
+ Brands: brands,
+ FullVersionList: fullVersionList,
+ })
+}
+
+func BuildLocaleOverride(userAgent, chromeVersion string) *emulation.SetLocaleOverrideParams {
+ persona := BuildPersona(userAgent, chromeVersion)
+ if persona.Language == "" {
+ return nil
+ }
+ return emulation.SetLocaleOverride().WithLocale(persona.Language)
+}
+
+// ApplyTargetEmulation applies the launch persona to a page/worker target so
+// navigator.*, client hints, Accept-Language, and Intl locale stay coherent.
+func ApplyTargetEmulation(ctx context.Context, cfg *config.RuntimeConfig, userAgent string) error {
+ if cfg == nil {
+ return nil
+ }
+
+ if err := emulation.SetAutomationOverride(false).Do(ctx); err != nil {
+ return fmt.Errorf("automation override: %w", err)
+ }
+
+ if localeOverride := BuildLocaleOverride(userAgent, cfg.ChromeVersion); localeOverride != nil {
+ if err := localeOverride.Do(ctx); err != nil {
+ return fmt.Errorf("locale override: %w", err)
+ }
+ }
+
+ if uaOverride := BuildUserAgentOverride(userAgent, cfg.ChromeVersion); uaOverride != nil {
+ if err := uaOverride.Do(ctx); err != nil {
+ return fmt.Errorf("user agent override: %w", err)
+ }
+ }
+
+ return nil
+}
diff --git a/internal/stealth/launch.go b/internal/stealth/launch.go
new file mode 100644
index 00000000..95c1e927
--- /dev/null
+++ b/internal/stealth/launch.go
@@ -0,0 +1,61 @@
+package stealth
+
+import (
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type LaunchContract struct {
+ Args []string
+ Flags map[string]bool
+}
+
+func BuildLaunchContract(cfg *config.RuntimeConfig, level Level) LaunchContract {
+ persona := BrowserPersona{}
+ if cfg != nil {
+ persona = BuildPersona(cfg.UserAgent, cfg.ChromeVersion)
+ }
+
+ args := []string{
+ "--disable-automation",
+ "--enable-automation=false",
+ "--disable-blink-features=AutomationControlled",
+ "--enable-network-information-downlink-max",
+ }
+ if persona.UserAgent != "" {
+ args = append(args, "--user-agent="+persona.UserAgent)
+ }
+ if persona.Language != "" {
+ args = append(args, "--lang="+persona.Language)
+ }
+
+ return LaunchContract{
+ Args: args,
+ Flags: map[string]bool{
+ "automationControlledDisabled": true,
+ "enableAutomationFalse": true,
+ "downlinkMaxFlag": true,
+ "globalUserAgent": persona.UserAgent != "",
+ "globalLanguage": persona.Language != "",
+ },
+ }
+}
+
+func HasLaunchArg(args []string, want string) bool {
+ for _, arg := range args {
+ if arg == want {
+ return true
+ }
+ }
+ return false
+}
+
+func HasLaunchArgPrefix(args []string, prefix string) bool {
+ for _, arg := range args {
+ if strings.HasPrefix(arg, prefix) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/stealth/popup_guard.go b/internal/stealth/popup_guard.go
new file mode 100644
index 00000000..f62dd03a
--- /dev/null
+++ b/internal/stealth/popup_guard.go
@@ -0,0 +1,42 @@
+package stealth
+
+const PopupGuardInitScript = `(function() {
+ const mergeWindowFeatures = function(features) {
+ const parts = typeof features === 'string'
+ ? features.split(',').map(function(part) { return String(part).trim(); }).filter(Boolean)
+ : [];
+ const seen = new Set(parts.map(function(part) { return part.toLowerCase(); }));
+ if (!seen.has('noopener')) {
+ parts.push('noopener');
+ }
+ if (!seen.has('noreferrer')) {
+ parts.push('noreferrer');
+ }
+ return parts.join(',');
+ };
+
+ try {
+ const originalOpen = window.open;
+ if (typeof originalOpen === 'function') {
+ Object.defineProperty(window, 'open', {
+ configurable: true,
+ writable: true,
+ value: function(url, target, features) {
+ return originalOpen.call(window, url, target, mergeWindowFeatures(features));
+ }
+ });
+ }
+ } catch (_) {}
+
+ try {
+ Object.defineProperty(window, 'opener', {
+ configurable: true,
+ get: function() { return null; },
+ set: function() { return true; }
+ });
+ } catch (_) {
+ try {
+ window.opener = null;
+ } catch (_) {}
+ }
+})();`
diff --git a/internal/stealth/ua.go b/internal/stealth/ua.go
new file mode 100644
index 00000000..27fa08bc
--- /dev/null
+++ b/internal/stealth/ua.go
@@ -0,0 +1,131 @@
+package stealth
+
+import (
+ goruntime "runtime"
+ "strings"
+)
+
+type BrandVersion struct {
+ Brand string `json:"brand"`
+ Version string `json:"version"`
+}
+
+type UserAgentDataProfile struct {
+ Brands []BrandVersion `json:"brands"`
+ FullVersionList []BrandVersion `json:"fullVersionList"`
+ Mobile bool `json:"mobile"`
+ Platform string `json:"platform"`
+ PlatformVersion string `json:"platformVersion"`
+ Architecture string `json:"architecture"`
+ Bitness string `json:"bitness"`
+ Model string `json:"model"`
+ Wow64 bool `json:"wow64"`
+}
+
+type BrowserPersona struct {
+ UserAgent string `json:"userAgent"`
+ Language string `json:"language"`
+ Languages []string `json:"languages"`
+ AcceptLanguage string `json:"acceptLanguage"`
+ NavigatorPlatform string `json:"navigatorPlatform"`
+ UserAgentData UserAgentDataProfile `json:"userAgentData"`
+}
+
+func ResolveUserAgent(userAgent, chromeVersion string) string {
+ if userAgent != "" {
+ return userAgent
+ }
+ if chromeVersion == "" {
+ return ""
+ }
+
+ switch goruntime.GOOS {
+ case "darwin":
+ return "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + chromeVersion + " Safari/537.36"
+ case "windows":
+ return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + chromeVersion + " Safari/537.36"
+ default:
+ return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + chromeVersion + " Safari/537.36"
+ }
+}
+
+func BuildPersona(userAgent, chromeVersion string) BrowserPersona {
+ ua := ResolveUserAgent(userAgent, chromeVersion)
+ language := "en-US"
+ languages := []string{"en-US", "en"}
+ acceptLanguage := "en-US,en"
+ if ua == "" {
+ return BrowserPersona{
+ Language: language,
+ Languages: languages,
+ AcceptLanguage: acceptLanguage,
+ }
+ }
+
+ major := chromeVersion
+ if i := strings.Index(chromeVersion, "."); i > 0 {
+ major = chromeVersion[:i]
+ }
+ if major == "" {
+ major = "144"
+ }
+
+ navigatorPlatform := "Linux x86_64"
+ uaDataPlatform := "Linux"
+ platformVersion := "6.5.0"
+ switch {
+ case strings.Contains(ua, "Windows"):
+ navigatorPlatform = "Win32"
+ uaDataPlatform = "Windows"
+ platformVersion = "15.0.0"
+ case strings.Contains(ua, "Macintosh"), strings.Contains(ua, "Mac OS X"):
+ navigatorPlatform = "MacIntel"
+ uaDataPlatform = "macOS"
+ platformVersion = "14.0.0"
+ }
+
+ architecture := "x86"
+ switch {
+ case strings.Contains(ua, "arm64"), strings.Contains(ua, "aarch64"), strings.Contains(ua, "ARM"):
+ architecture = "arm"
+ case goruntime.GOARCH == "arm64":
+ architecture = "arm"
+ }
+
+ brands := []BrandVersion{
+ {Brand: "Not(A:Brand", Version: "99"},
+ {Brand: "Google Chrome", Version: major},
+ {Brand: "Chromium", Version: major},
+ }
+ fullVersionList := []BrandVersion{
+ {Brand: "Not(A:Brand", Version: "99.0.0.0"},
+ {Brand: "Google Chrome", Version: chromeVersionOrFallback(chromeVersion)},
+ {Brand: "Chromium", Version: chromeVersionOrFallback(chromeVersion)},
+ }
+
+ return BrowserPersona{
+ UserAgent: ua,
+ Language: language,
+ Languages: languages,
+ AcceptLanguage: acceptLanguage,
+ NavigatorPlatform: navigatorPlatform,
+ UserAgentData: UserAgentDataProfile{
+ Brands: brands,
+ FullVersionList: fullVersionList,
+ Mobile: false,
+ Platform: uaDataPlatform,
+ PlatformVersion: platformVersion,
+ Architecture: architecture,
+ Bitness: "64",
+ Model: "",
+ Wow64: false,
+ },
+ }
+}
+
+func chromeVersionOrFallback(chromeVersion string) string {
+ if chromeVersion != "" {
+ return chromeVersion
+ }
+ return "144.0.0.0"
+}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index ca1ae508..219ad092 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -20,7 +20,6 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
- "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
)
@@ -445,7 +444,7 @@ func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {
return
}
strategy.EnrichForTarget(r, s.orch, target)
- proxy.HTTP(w, r, target+r.URL.Path)
+ s.orch.ProxyToTarget(w, r, target+r.URL.Path)
}
// ensureRunning returns the URL of the managed instance if running.
@@ -465,7 +464,7 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxy.HTTP(w, r, target+"/tabs")
+ s.orch.ProxyToTarget(w, r, target+"/tabs")
}
func (s *Strategy) handleStatus(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index 2d09dc71..8eb893fb 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -11,7 +11,6 @@ import (
"github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
- "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
)
@@ -74,7 +73,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
return
}
strategy.EnrichForTarget(r, s.orch, target)
- proxy.HTTP(w, r, target+r.URL.Path)
+ s.orch.ProxyToTarget(w, r, target+r.URL.Path)
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
@@ -83,5 +82,5 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxy.HTTP(w, r, target+"/tabs")
+ s.orch.ProxyToTarget(w, r, target+"/tabs")
}
diff --git a/internal/strategy/noinstance/noinstance.go b/internal/strategy/noinstance/noinstance.go
index d8d26301..dfc2303a 100644
--- a/internal/strategy/noinstance/noinstance.go
+++ b/internal/strategy/noinstance/noinstance.go
@@ -10,7 +10,6 @@ import (
"github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
- "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
)
@@ -69,7 +68,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
return
}
strategy.EnrichForTarget(r, s.orch, target)
- proxy.HTTP(w, r, target+r.URL.Path)
+ s.orch.ProxyToTarget(w, r, target+r.URL.Path)
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
@@ -78,5 +77,5 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxy.HTTP(w, r, target+"/tabs")
+ s.orch.ProxyToTarget(w, r, target+"/tabs")
}
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index fbbfffb0..afc06fab 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -17,7 +17,6 @@ import (
"github.com/pinchtab/pinchtab/internal/httpx"
"github.com/pinchtab/pinchtab/internal/orchestrator"
- "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
)
@@ -85,7 +84,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
return
}
strategy.EnrichForTarget(r, s.orch, target)
- proxy.HTTP(w, r, target+r.URL.Path)
+ s.orch.ProxyToTarget(w, r, target+r.URL.Path)
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
@@ -94,7 +93,7 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxy.HTTP(w, r, target+"/tabs")
+ s.orch.ProxyToTarget(w, r, target+"/tabs")
}
// ensureRunning returns the URL of a running instance, auto-launching one if needed.
diff --git a/scripts/docker-smoke.sh b/scripts/docker-smoke.sh
index 0940a4b2..52768296 100644
--- a/scripts/docker-smoke.sh
+++ b/scripts/docker-smoke.sh
@@ -54,13 +54,6 @@ if [ "$bind_addr" != "0.0.0.0" ]; then
exit 1
fi
-extra_flags="$(docker exec "$NAME" pinchtab config get browser.extraFlags | tr -d '\r')"
-if [ "$extra_flags" != "--no-sandbox --disable-gpu" ]; then
- FAILED=1
- echo "unexpected browser.extraFlags: $extra_flags"
- exit 1
-fi
-
docker exec "$NAME" test -f /data/.config/pinchtab/config.json
echo "Docker smoke test passed."
diff --git a/tests/e2e/config/pinchtab-bridge.json b/tests/e2e/config/pinchtab-bridge.json
index 362f8908..998a0a4d 100644
--- a/tests/e2e/config/pinchtab-bridge.json
+++ b/tests/e2e/config/pinchtab-bridge.json
@@ -4,9 +4,6 @@
"port": "9999",
"token": "e2e-bridge-token"
},
- "browser": {
- "extraFlags": "--no-sandbox --disable-dev-shm-usage"
- },
"security": {
"allowEvaluate": false,
"allowDownload": false,
diff --git a/tests/e2e/config/pinchtab-full-permissive.json b/tests/e2e/config/pinchtab-full-permissive.json
index bc258689..627cf0f9 100644
--- a/tests/e2e/config/pinchtab-full-permissive.json
+++ b/tests/e2e/config/pinchtab-full-permissive.json
@@ -5,7 +5,6 @@
"token": "e2e-token"
},
"browser": {
- "extraFlags": "--no-sandbox --disable-dev-shm-usage",
"extensionPaths": [
"/extensions/test-extension"
]
diff --git a/tests/e2e/config/pinchtab-medium-permissive.json b/tests/e2e/config/pinchtab-medium-permissive.json
index d5b11a49..cb2658c1 100644
--- a/tests/e2e/config/pinchtab-medium-permissive.json
+++ b/tests/e2e/config/pinchtab-medium-permissive.json
@@ -5,7 +5,6 @@
"token": "e2e-token"
},
"browser": {
- "extraFlags": "--no-sandbox --disable-dev-shm-usage",
"extensionPaths": [
"/extensions/test-extension"
]
diff --git a/tests/e2e/config/pinchtab-secure.json b/tests/e2e/config/pinchtab-secure.json
index daafb95e..7a810c56 100644
--- a/tests/e2e/config/pinchtab-secure.json
+++ b/tests/e2e/config/pinchtab-secure.json
@@ -4,9 +4,6 @@
"port": "9999",
"token": "e2e-token"
},
- "browser": {
- "extraFlags": "--no-sandbox --disable-dev-shm-usage"
- },
"instanceDefaults": {
"maxTabs": 2,
"stealthLevel": "full"
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index 8526e1e5..86cb6edb 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -5,7 +5,6 @@
"token": "e2e-token"
},
"browser": {
- "extraFlags": "--no-sandbox --disable-dev-shm-usage",
"extensionPaths": [
"/extensions/test-extension"
]
diff --git a/tests/e2e/docker-compose-multi.yml b/tests/e2e/docker-compose-multi.yml
index bf99aa69..3d878c4e 100644
--- a/tests/e2e/docker-compose-multi.yml
+++ b/tests/e2e/docker-compose-multi.yml
@@ -155,6 +155,7 @@ services:
- E2E_BRIDGE_TOKEN=e2e-bridge-token
- FIXTURES_URL=http://fixtures:80
- E2E_SCENARIO_FILTER
+ - STEALTH_MATRIX
volumes:
- ./:/e2e:ro
- ./results:/results
diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.yml
index 76d0dccf..b4e01435 100644
--- a/tests/e2e/docker-compose.yml
+++ b/tests/e2e/docker-compose.yml
@@ -43,6 +43,7 @@ services:
- E2E_SERVER_TOKEN=e2e-token
- FIXTURES_URL=http://fixtures:80
- E2E_SCENARIO_FILTER
+ - STEALTH_MATRIX
volumes:
- ./:/e2e:ro
- ./results:/results
diff --git a/tests/e2e/fixtures/bot-detect.html b/tests/e2e/fixtures/bot-detect.html
index 8d554f1a..3991a432 100644
--- a/tests/e2e/fixtures/bot-detect.html
+++ b/tests/e2e/fixtures/bot-detect.html
@@ -63,10 +63,11 @@
addResult('webdriver_value', webdriverValue === undefined || webdriverValue === false,
`navigator.webdriver = ${webdriverValue}`);
- // Test: "webdriver" in navigator (property should not exist)
+ // Test: webdriver property semantics look native enough.
+ // A native false is acceptable; a truthy webdriver is not.
const webdriverExists = 'webdriver' in navigator;
- addResult('webdriver_in_navigator', !webdriverExists,
- `"webdriver" in navigator = ${webdriverExists}`);
+ addResult('webdriver_in_navigator', !webdriverExists || webdriverValue === false,
+ `"webdriver" in navigator = ${webdriverExists}, value = ${webdriverValue}`);
// Test: Plugins instanceof PluginArray
const pluginsValid = navigator.plugins instanceof PluginArray;
@@ -122,17 +123,17 @@
// Test: chrome.runtime.connect exists (required by Cloudflare Turnstile)
const hasChromeConnect = !!(window.chrome && window.chrome.runtime && typeof window.chrome.runtime.connect === 'function');
addResult('chrome_runtime_connect', hasChromeConnect,
- hasChromeConnect ? 'Available' : 'Missing');
+ hasChromeConnect ? 'Available' : 'Missing', 'warn');
- // Test: chrome.csi exists (Chrome Speed Index - some sites check)
+ // Test: chrome.csi exists (deprecated legacy surface)
const hasChromeCsi = !!(window.chrome && typeof window.chrome.csi === 'function');
addResult('chrome_csi', hasChromeCsi,
- hasChromeCsi ? 'Available' : 'Missing');
+ hasChromeCsi ? 'Available' : 'Missing', 'warn');
- // Test: chrome.loadTimes exists (deprecated but still checked)
+ // Test: chrome.loadTimes exists (deprecated legacy surface)
const hasChromeLoadTimes = !!(window.chrome && typeof window.chrome.loadTimes === 'function');
addResult('chrome_loadtimes', hasChromeLoadTimes,
- hasChromeLoadTimes ? 'Available' : 'Missing');
+ hasChromeLoadTimes ? 'Available' : 'Missing', 'warn');
// Test: No CDP markers in window object
let cdpMarkerCount = 0;
@@ -182,8 +183,8 @@
// Test: Device memory exists
const deviceMem = navigator.deviceMemory;
- const hasDeviceMem = deviceMem && deviceMem > 0;
- addResult('device_memory', hasDeviceMem, `${deviceMem || 0} GB`, 'warn');
+ const hasDeviceMem = deviceMem === undefined || deviceMem === null || deviceMem > 0;
+ addResult('device_memory', hasDeviceMem, deviceMem == null ? 'absent' : `${deviceMem} GB`, 'warn');
// Test: Connection RTT exists
const rtt = navigator.connection?.rtt;
@@ -209,14 +210,65 @@
addResult('notification_api', notifOk,
`Notification.permission = ${Notification.permission}`, 'warn');
- // Test: Function.toString not modified (automation tools sometimes wrap functions)
+ // Test: global Function.prototype.toString looks native
let toStringOk = true;
try {
- const fnStr = Function.prototype.toString.call(navigator.permissions.query);
- toStringOk = fnStr.includes('[native code]');
+ const ownNames = Object.getOwnPropertyNames(Function.prototype.toString);
+ toStringOk = Function.prototype.toString.name === 'toString' &&
+ ownNames.every((name) => name === 'length' || name === 'name');
} catch (e) { toStringOk = false; }
- addResult('function_tostring', toStringOk,
- toStringOk ? 'Native' : 'Modified', 'warn');
+ addResult('function_tostring', toStringOk,
+ toStringOk ? 'Native' : `Modified (${Function.prototype.toString.name})`, 'warn');
+
+ // Test: Intl locale family matches navigator.language
+ let intlLocaleOk = true;
+ let intlDateTimeLocale = '';
+ let intlNumberLocale = '';
+ try {
+ const expected = String(navigator.language || '').toLowerCase();
+ const localeMatchesExpected = (locale) => (
+ locale === expected || locale.startsWith(expected + '-') || expected.startsWith(locale + '-')
+ );
+ const locales = [
+ Intl.DateTimeFormat,
+ Intl.NumberFormat,
+ Intl.Collator,
+ Intl.PluralRules,
+ Intl.RelativeTimeFormat,
+ Intl.ListFormat,
+ Intl.DisplayNames,
+ Intl.Segmenter
+ ].filter((Ctor) => typeof Ctor === 'function').map((Ctor) => {
+ try {
+ const options = Ctor === Intl.DisplayNames
+ ? new Ctor(undefined, { type: 'language' }).resolvedOptions()
+ : new Ctor().resolvedOptions();
+ return String(options.locale || '').toLowerCase();
+ } catch (_) {
+ return '';
+ }
+ }).filter(Boolean);
+ intlDateTimeLocale = locales[0] || '';
+ intlNumberLocale = locales[1] || '';
+ intlLocaleOk = locales.every((locale) => (
+ localeMatchesExpected(locale)
+ ));
+ addResult('intl_datetime_locale_coherent', localeMatchesExpected(intlDateTimeLocale), intlDateTimeLocale || 'none', 'warn');
+ addResult('intl_number_locale_coherent', localeMatchesExpected(intlNumberLocale), intlNumberLocale || 'none', 'warn');
+ addResult('intl_locale_coherent', intlLocaleOk, locales.join(', '), 'warn');
+ } catch (e) {
+ addResult('intl_datetime_locale_coherent', false, String(e), 'warn');
+ addResult('intl_number_locale_coherent', false, String(e), 'warn');
+ addResult('intl_locale_coherent', false, String(e), 'warn');
+ }
+
+ // Test: Error.prepareStackTrace left untouched
+ let prepareStackTraceOk = true;
+ try {
+ prepareStackTraceOk = !Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
+ } catch (e) { prepareStackTraceOk = false; }
+ addResult('prepare_stacktrace_native', prepareStackTraceOk,
+ prepareStackTraceOk ? 'Absent' : 'Descriptor present', 'warn');
// Test: maxTouchPoints is 0 for desktop
const touchPoints = navigator.maxTouchPoints;
@@ -248,6 +300,22 @@
}
addResult('useragentdata_platform_match', uaPlatformMatch,
navigator.userAgentData ? `${navigator.userAgentData.platform} / ${navigator.platform}` : 'N/A', 'warn');
+
+ // Test: userAgentData version aligns with Chrome major in UA
+ let uaVersionMatch = true;
+ if (navigator.userAgentData) {
+ const uaMatch = navigator.userAgent.match(/Chrome\/(\d+)/);
+ const uaMajor = uaMatch ? uaMatch[1] : '';
+ const brands = navigator.userAgentData.brands || [];
+ if (uaMajor) {
+ uaVersionMatch = brands.some((brand) => (
+ (brand.brand === 'Google Chrome' || brand.brand === 'Chromium') &&
+ String(brand.version) === uaMajor
+ ));
+ }
+ }
+ addResult('useragentdata_version_match', uaVersionMatch,
+ navigator.userAgentData ? JSON.stringify(navigator.userAgentData.brands) : 'N/A', 'warn');
// ═══════════════════════════════════════════════════════════════════
// INFO - Just for debugging
@@ -256,6 +324,8 @@
addInfo('Platform', navigator.platform);
addInfo('Vendor', navigator.vendor);
addInfo('Languages', navigator.languages?.join(', '));
+ addInfo('Intl DateTime Locale', intlDateTimeLocale || 'N/A');
+ addInfo('Intl Number Locale', intlNumberLocale || 'N/A');
addInfo('Timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
addInfo('Screen', `${screen.width}x${screen.height} @ ${screen.colorDepth}bit`);
addInfo('Window Inner', `${window.innerWidth}x${window.innerHeight}`);
diff --git a/tests/e2e/fixtures/stealth-capabilities.html b/tests/e2e/fixtures/stealth-capabilities.html
new file mode 100644
index 00000000..d5e3acb6
--- /dev/null
+++ b/tests/e2e/fixtures/stealth-capabilities.html
@@ -0,0 +1,493 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Stealth Capabilities</title>
+ <style>
+ body {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ margin: 24px;
+ background: #10161f;
+ color: #e6edf3;
+ }
+ h1 {
+ font-size: 20px;
+ margin: 0 0 16px;
+ }
+ table {
+ border-collapse: collapse;
+ width: 100%;
+ margin-top: 16px;
+ }
+ th, td {
+ border: 1px solid #2f3b4d;
+ padding: 8px;
+ text-align: left;
+ vertical-align: top;
+ }
+ th {
+ background: #17202d;
+ }
+ .ok {
+ color: #5ee27a;
+ }
+ .bad {
+ color: #ff7b72;
+ }
+ pre {
+ white-space: pre-wrap;
+ word-break: break-word;
+ background: #17202d;
+ padding: 12px;
+ border: 1px solid #2f3b4d;
+ }
+ </style>
+</head>
+<body>
+ <h1>Stealth Capabilities</h1>
+ <table id="results">
+ <tr><th>Check</th><th>Pass</th><th>Value</th></tr>
+ </table>
+ <h2>Raw</h2>
+ <pre id="raw"></pre>
+
+ <script>
+ (async function() {
+ function safe(fn, fallback) {
+ try {
+ return fn();
+ } catch (_) {
+ return fallback;
+ }
+ }
+
+ async function safeAsync(fn, fallback) {
+ try {
+ return await fn();
+ } catch (_) {
+ return fallback;
+ }
+ }
+
+ async function probeIframeIsolation() {
+ const iframe = document.createElement('iframe');
+ iframe.style.display = 'none';
+ iframe.srcdoc = '<!doctype html><html><body>iframe probe</body></html>';
+ document.body.appendChild(iframe);
+
+ await new Promise((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ resolve();
+ };
+ iframe.addEventListener('load', finish, { once: true });
+ setTimeout(finish, 150);
+ });
+
+ const childWindow = safe(() => iframe.contentWindow, null);
+ const childNavigator = childWindow ? childWindow.navigator : null;
+ const parentRuntime = window.chrome && window.chrome.runtime ? window.chrome.runtime : null;
+ const childRuntime = childWindow && childWindow.chrome && childWindow.chrome.runtime ? childWindow.chrome.runtime : null;
+ const parentUADataPlatform = safe(() => navigator.userAgentData && navigator.userAgentData.platform, '');
+ const childUADataPlatform = safe(() => childNavigator && childNavigator.userAgentData && childNavigator.userAgentData.platform, '');
+ const isolated = !!childWindow &&
+ !!childNavigator &&
+ childNavigator.platform === (navigator.platform || '') &&
+ (!parentUADataPlatform || childUADataPlatform === parentUADataPlatform) &&
+ childNavigator.maxTouchPoints === navigator.maxTouchPoints &&
+ !!childRuntime &&
+ !!parentRuntime &&
+ typeof parentRuntime.connect === 'function' &&
+ typeof parentRuntime.sendMessage === 'function' &&
+ typeof childRuntime.connect === 'function' &&
+ typeof childRuntime.sendMessage === 'function';
+
+ iframe.remove();
+ return isolated;
+ }
+
+ function probeStackSanitization() {
+ function __pinchtab_stack_probe__() {
+ return new Error('stack probe');
+ }
+
+ const error = __pinchtab_stack_probe__();
+ const stack = safe(() => String(error.stack || ''), '');
+ return {
+ sanitized: !/__pinchtab_stack_probe__/.test(stack),
+ stack
+ };
+ }
+
+ async function collect() {
+ const nativeLikeFunction = (fn) => {
+ if (typeof fn !== 'function') return false;
+ const source = safe(() => Function.prototype.toString.call(fn), '');
+ return /\[native code\]/.test(source);
+ };
+ const extractChromeFullVersion = (value) => {
+ const match = String(value || '').match(/Chrome\/([0-9.]+)/);
+ return match ? match[1] : '';
+ };
+ const extractChromeMajor = (value) => {
+ const match = String(value || '').match(/Chrome\/(\d+)/);
+ return match ? match[1] : '';
+ };
+ const now = new Date();
+ const plugin0 = safe(() => navigator.plugins[0], null);
+ const connection = navigator.connection || null;
+ const connectionProto = connection ? Object.getPrototypeOf(connection) : null;
+ const video = safe(() => document.createElement('video'), null);
+ const uaData = navigator.userAgentData || null;
+ const uaDataHighEntropy = uaData && typeof uaData.getHighEntropyValues === 'function'
+ ? await safeAsync(() => uaData.getHighEntropyValues(['fullVersionList', 'uaFullVersion', 'platformVersion']), {})
+ : {};
+ const uaDataPlatform = uaData ? uaData.platform : '';
+ const navPlatform = navigator.platform || '';
+ const pluginObjectTag = plugin0 ? Object.prototype.toString.call(plugin0) : '';
+ const h264 = video ? video.canPlayType('video/mp4; codecs="avc1.42E01E"') : '';
+ const vp9 = video ? video.canPlayType('video/webm; codecs="vp9"') : '';
+ const uaFullVersion = extractChromeFullVersion(navigator.userAgent || '');
+ const appVersionFull = extractChromeFullVersion(navigator.appVersion || '');
+ const uaMajorMatch = extractChromeMajor(navigator.userAgent || '');
+ const timeZone = safe(() => Intl.DateTimeFormat().resolvedOptions().timeZone || '', '');
+ const timeZoneOffsetMinutes = safe(() => now.getTimezoneOffset(), NaN);
+ const timeZoneOffsetSane = Number.isInteger(timeZoneOffsetMinutes) && Math.abs(timeZoneOffsetMinutes) <= (14 * 60);
+ const localClock = {
+ year: String(now.getFullYear()).padStart(4, '0'),
+ month: String(now.getMonth() + 1).padStart(2, '0'),
+ day: String(now.getDate()).padStart(2, '0'),
+ hour: String(now.getHours()).padStart(2, '0'),
+ minute: String(now.getMinutes()).padStart(2, '0')
+ };
+ const zonedClock = safe(() => {
+ if (!timeZone) return null;
+ const parts = new Intl.DateTimeFormat('en-CA', {
+ timeZone,
+ hourCycle: 'h23',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit'
+ }).formatToParts(now);
+ const out = {};
+ for (const part of parts) {
+ if (part.type !== 'literal') out[part.type] = part.value;
+ }
+ return out;
+ }, null);
+ const timeZoneDateCoherent = !!zonedClock &&
+ zonedClock.year === localClock.year &&
+ zonedClock.month === localClock.month &&
+ zonedClock.day === localClock.day &&
+ zonedClock.hour === localClock.hour &&
+ zonedClock.minute === localClock.minute;
+ const uaDataFullVersionList = safe(() => Array.isArray(uaDataHighEntropy.fullVersionList) ? uaDataHighEntropy.fullVersionList : [], []);
+ const uaDataFullVersion = safe(() => String(uaDataHighEntropy.uaFullVersion || ''), '');
+ const userAgentVersionCoherent = !uaFullVersion || !appVersionFull || uaFullVersion === appVersionFull;
+ const systemColorProbe = document.createElement('div');
+ systemColorProbe.style.color = 'CanvasText';
+ systemColorProbe.style.backgroundColor = 'Canvas';
+ systemColorProbe.style.borderTop = '1px solid ButtonText';
+ document.body.appendChild(systemColorProbe);
+ const systemColorStyle = safe(() => window.getComputedStyle(systemColorProbe), null);
+ const systemColorsResolved = !!systemColorStyle &&
+ /^rgb/.test(systemColorStyle.color || '') &&
+ /^rgb/.test(systemColorStyle.backgroundColor || '') &&
+ /^rgb/.test(systemColorStyle.borderTopColor || '');
+ systemColorProbe.remove();
+ const iframeIsolation = await probeIframeIsolation();
+ const stackProbe = probeStackSanitization();
+ const permissionsQueryToString = safe(() => Function.prototype.toString.call(navigator.permissions.query), '');
+ const runtimeConnectToString = safe(() => {
+ return window.chrome && window.chrome.runtime && typeof window.chrome.runtime.connect === 'function'
+ ? Function.prototype.toString.call(window.chrome.runtime.connect)
+ : '';
+ }, '');
+ const ownNav = safe(() => Object.getOwnPropertyNames(navigator).filter((name) => [
+ 'plugins', 'mimeTypes', 'language', 'languages', 'platform', 'userAgentData', 'maxTouchPoints'
+ ].includes(name)), []);
+ const webdriverDescriptor = safe(() => {
+ const proto = Object.getPrototypeOf(navigator);
+ const descriptor = Object.getOwnPropertyDescriptor(proto, 'webdriver') || Object.getOwnPropertyDescriptor(navigator, 'webdriver');
+ if (!descriptor) return null;
+ return {
+ configurable: !!descriptor.configurable,
+ enumerable: !!descriptor.enumerable,
+ hasGetter: typeof descriptor.get === 'function',
+ getterString: descriptor.get ? Function.prototype.toString.call(descriptor.get) : ''
+ };
+ }, null);
+ const webdriverDescriptorNativeLike = !webdriverDescriptor ||
+ (!!webdriverDescriptor.hasGetter && /\[native code\]/.test(webdriverDescriptor.getterString || ''));
+ const functionToStringOwnNames = safe(() => Object.getOwnPropertyNames(Function.prototype.toString), []);
+ const functionToStringDescriptor = safe(() => Object.getOwnPropertyDescriptor(Function.prototype, 'toString'), null);
+ const functionToStringNative = safe(() => {
+ if (Function.prototype.toString.name !== 'toString') return false;
+ if (functionToStringOwnNames.some((name) => name !== 'length' && name !== 'name')) return false;
+ return !functionToStringDescriptor || functionToStringDescriptor.value === Function.prototype.toString;
+ }, false);
+ const intlLocaleValues = safe(() => {
+ const ctors = [
+ Intl.DateTimeFormat,
+ Intl.NumberFormat,
+ Intl.Collator,
+ Intl.PluralRules,
+ Intl.RelativeTimeFormat,
+ Intl.ListFormat,
+ Intl.DisplayNames,
+ Intl.Segmenter
+ ].filter((ctor) => typeof ctor === 'function');
+ return ctors.map((Ctor) => {
+ try {
+ const options = Ctor === Intl.DisplayNames
+ ? new Ctor(undefined, { type: 'language' }).resolvedOptions()
+ : new Ctor().resolvedOptions();
+ return options && options.locale ? String(options.locale) : '';
+ } catch (_) {
+ return '';
+ }
+ }).filter(Boolean);
+ }, []);
+ const intlDateTimeLocale = intlLocaleValues[0] || '';
+ const intlNumberLocale = intlLocaleValues[1] || '';
+ const primaryLanguage = String(navigator.language || '').toLowerCase();
+ const localeMatchesPrimary = (locale) => {
+ const lower = String(locale || '').toLowerCase();
+ return !lower || lower === primaryLanguage || lower.indexOf(primaryLanguage + '-') === 0 || primaryLanguage.indexOf(lower + '-') === 0;
+ };
+ const intlDateTimeLocaleCoherent = localeMatchesPrimary(intlDateTimeLocale);
+ const intlNumberLocaleCoherent = localeMatchesPrimary(intlNumberLocale);
+ const intlLocaleCoherent = intlLocaleValues.every(localeMatchesPrimary);
+ const prepareStackTraceDescriptor = safe(() => Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace'), null);
+ const uaDataBrands = safe(() => uaData ? uaData.brands || [] : [], []);
+ const userAgentDataBrandMajorCoherent = !uaDataBrands.length || !uaMajorMatch || uaDataBrands.some((brand) => {
+ if (!brand || (brand.brand !== 'Google Chrome' && brand.brand !== 'Chromium')) return false;
+ return String(brand.version || '') === uaMajorMatch;
+ });
+ const userAgentDataVersionCoherent = userAgentDataBrandMajorCoherent;
+ const userAgentDataFullVersionCoherent = !uaData || !uaFullVersion ||
+ (!uaDataFullVersion && !uaDataFullVersionList.length) ||
+ uaDataFullVersion === uaFullVersion ||
+ uaDataFullVersionList.some((brand) => (
+ brand &&
+ (brand.brand === 'Google Chrome' || brand.brand === 'Chromium') &&
+ String(brand.version || '') === uaFullVersion
+ ));
+ const blankCanvas = safe(() => document.createElement('canvas'), null);
+ if (blankCanvas) {
+ blankCanvas.width = 2;
+ blankCanvas.height = 2;
+ }
+ const blankCtx = blankCanvas ? safe(() => blankCanvas.getContext('2d'), null) : null;
+ const transparentPixel = blankCtx ? safe(() => Array.from(blankCtx.getImageData(0, 0, 1, 1).data), []) : [];
+ const canvasTransparentPixelPreserved = transparentPixel.length === 4 && transparentPixel.every((value) => value === 0);
+ const canvasToDataURLNativeLike = nativeLikeFunction(HTMLCanvasElement.prototype.toDataURL);
+ const canvasToBlobNativeLike = typeof HTMLCanvasElement.prototype.toBlob !== 'function' || nativeLikeFunction(HTMLCanvasElement.prototype.toBlob);
+ const canvasGetImageDataNativeLike = nativeLikeFunction(CanvasRenderingContext2D.prototype.getImageData);
+ const canvasMeasureTextNativeLike = nativeLikeFunction(CanvasRenderingContext2D.prototype.measureText);
+ const webglGetParameterNativeLike = safe(() => {
+ if (typeof WebGLRenderingContext === 'undefined') return true;
+ return nativeLikeFunction(WebGLRenderingContext.prototype.getParameter);
+ }, false);
+ const rtcPeerConnectionNativeLike = safe(() => {
+ if (typeof window.RTCPeerConnection !== 'function') return true;
+ return nativeLikeFunction(window.RTCPeerConnection);
+ }, false);
+ const audioContextCreateOscillatorNativeLike = safe(() => {
+ const AudioContextClass = window.AudioContext || window.webkitAudioContext;
+ if (!AudioContextClass || !AudioContextClass.prototype || typeof AudioContextClass.prototype.createOscillator !== 'function') return true;
+ return nativeLikeFunction(AudioContextClass.prototype.createOscillator);
+ }, false);
+ const glCanvas = safe(() => document.createElement('canvas'), null);
+ const gl = glCanvas ? safe(() => glCanvas.getContext('webgl') || glCanvas.getContext('experimental-webgl'), null) : null;
+ const webglRendererProbe = safe(() => {
+ const debugInfo = gl && gl.getExtension('WEBGL_debug_renderer_info');
+ const renderer = debugInfo ? String(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '') : '';
+ const lower = renderer.toLowerCase();
+ const platform = navigator.platform || '';
+ return {
+ available: !!debugInfo,
+ renderer,
+ noSwiftShader: !debugInfo || !lower.includes('swiftshader'),
+ platformCoherent: !debugInfo || (
+ (platform === 'MacIntel' && !lower.includes('direct3d')) ||
+ (platform.includes('Linux') && !lower.includes('direct3d')) ||
+ (platform.includes('Win') && lower.includes('direct3d'))
+ )
+ };
+ }, { available: false, renderer: '', noSwiftShader: true, platformCoherent: true });
+ const devtoolsFormattersAbsentByDefault = !Array.isArray(window.devtoolsFormatters) || window.devtoolsFormatters.length === 0;
+
+ return {
+ webdriverValue: safe(() => navigator.webdriver, 'error'),
+ webdriverNotTrue: safe(() => navigator.webdriver !== true, false),
+ webdriverNativeLike: safe(() => !('webdriver' in navigator) || navigator.webdriver === false, false),
+ webdriverDescriptorNativeLike,
+ webdriverDescriptor,
+ pluginArray: safe(() => navigator.plugins instanceof PluginArray, false),
+ pluginsPresent: safe(() => navigator.plugins.length > 0, false),
+ pluginObjectSemantics: pluginObjectTag === '[object Plugin]',
+ pluginObjectTag,
+ batteryApi: typeof navigator.getBattery === 'function',
+ outerDimensions: window.outerWidth > 0 && window.outerHeight > 0,
+ screenWindowCoherent: screen.width >= window.outerWidth && screen.height >= window.outerHeight,
+ screenAvailCoherent: screen.availWidth <= screen.width && screen.availHeight <= screen.height,
+ devicePixelRatioPositive: window.devicePixelRatio > 0,
+ screenYDefined: typeof window.screenY === 'number' && typeof window.screenTop === 'number',
+ userAgent: navigator.userAgent,
+ userAgentFullVersion: uaFullVersion,
+ appVersionFull,
+ userAgentVersionCoherent,
+ navigatorPlatform: navPlatform,
+ userAgentData: !!(uaData && uaData.brands),
+ userAgentDataPlatform: uaDataPlatform,
+ userAgentDataPlatformCoherent: safe(() => {
+ if (!uaDataPlatform) return true;
+ if (uaDataPlatform === 'Windows') return navPlatform.indexOf('Win') >= 0;
+ if (uaDataPlatform === 'macOS') return navPlatform === 'MacIntel';
+ if (uaDataPlatform === 'Linux') return navPlatform.indexOf('Linux') >= 0;
+ return false;
+ }, false),
+ userAgentDataFullVersion: uaDataFullVersion,
+ userAgentDataFullVersionList: uaDataFullVersionList,
+ userAgentDataFullVersionCoherent,
+ chromeRuntime: !!(window.chrome && window.chrome.runtime),
+ chromeRuntimeConnect: !!(window.chrome && window.chrome.runtime && typeof window.chrome.runtime.connect === 'function'),
+ chromeRuntimeSendMessage: !!(window.chrome && window.chrome.runtime && typeof window.chrome.runtime.sendMessage === 'function'),
+ chromeRuntimeConnectNativeLike: !(window.chrome && window.chrome.runtime && typeof window.chrome.runtime.connect === 'function') || nativeLikeFunction(window.chrome.runtime.connect),
+ chromeApp: !!(window.chrome && window.chrome.app),
+ chromeCsi: !!(window.chrome && typeof window.chrome.csi === 'function'),
+ chromeLoadTimes: !!(window.chrome && typeof window.chrome.loadTimes === 'function'),
+ canPlayTypeNativeLike: nativeLikeFunction(HTMLMediaElement.prototype.canPlayType),
+ canvasToDataURLNativeLike,
+ canvasToBlobNativeLike,
+ canvasGetImageDataNativeLike,
+ canvasMeasureTextNativeLike,
+ canvasTransparentPixelPreserved,
+ webglGetParameterNativeLike,
+ rtcPeerConnectionNativeLike,
+ audioContextCreateOscillatorNativeLike,
+ webglRendererNoSwiftShader: webglRendererProbe.noSwiftShader,
+ webglRendererPlatformCoherent: webglRendererProbe.platformCoherent,
+ webglRenderer: webglRendererProbe.renderer,
+ getComputedStyleNativeLike: nativeLikeFunction(window.getComputedStyle),
+ getComputedStyleNameNative: safe(() => window.getComputedStyle.name === 'getComputedStyle', false),
+ matchMediaNativeLike: nativeLikeFunction(window.matchMedia),
+ matchMediaNameNative: typeof window.matchMedia !== 'function' || safe(() => window.matchMedia.name === 'matchMedia', false),
+ maxTouchPointsDefined: typeof navigator.maxTouchPoints !== 'undefined',
+ iframeIsolation,
+ errorStackSanitized: false,
+ stackProbe: stackProbe.stack,
+ functionToStringMasked: false,
+ functionToStringNative,
+ functionToStringName: safe(() => Function.prototype.toString.name, ''),
+ functionToStringOwnNames,
+ permissionsQueryToString,
+ runtimeConnectToString,
+ navigatorOverridesAbsent: ownNav.length === 0,
+ navigatorOverrideNames: ownNav,
+ timeZone,
+ timeZoneOffsetMinutes,
+ timeZoneOffsetSane,
+ timeZoneDateCoherent,
+ intlDateTimeLocaleCoherent,
+ intlDateTimeLocale,
+ intlNumberLocaleCoherent,
+ intlNumberLocale,
+ intlLocaleCoherent,
+ intlLocaleValues,
+ errorPrepareStackTraceNative: !prepareStackTraceDescriptor,
+ devtoolsFormattersAbsentByDefault,
+ userAgentDataBrandMajorCoherent,
+ userAgentDataBrands: uaDataBrands,
+ userAgentDataVersionCoherent,
+ downlinkMaxPresent: !!(connection && (('downlinkMax' in connection) || (connectionProto && 'downlinkMax' in connectionProto))),
+ h264,
+ vp9,
+ prefersColorSchemeLight: safe(() => window.matchMedia('(prefers-color-scheme: light)').matches, false),
+ systemColorsResolved
+ };
+ }
+
+ const capabilities = await collect();
+ window.__stealthCapabilities = capabilities;
+
+ const rows = [
+ ['webdriverNotTrue', capabilities.webdriverNotTrue, capabilities.webdriverValue],
+ ['webdriverNativeLike', capabilities.webdriverNativeLike, String(capabilities.webdriverNativeLike)],
+ ['webdriverDescriptorNativeLike', capabilities.webdriverDescriptorNativeLike, JSON.stringify(capabilities.webdriverDescriptor)],
+ ['pluginArray', capabilities.pluginArray, String(capabilities.pluginArray)],
+ ['pluginsPresent', capabilities.pluginsPresent, String(navigator.plugins.length)],
+ ['pluginObjectSemantics', capabilities.pluginObjectSemantics, capabilities.pluginObjectTag],
+ ['batteryApi', capabilities.batteryApi, String(capabilities.batteryApi)],
+ ['outerDimensions', capabilities.outerDimensions, window.outerWidth + 'x' + window.outerHeight],
+ ['screenWindowCoherent', capabilities.screenWindowCoherent, screen.width + 'x' + screen.height],
+ ['screenAvailCoherent', capabilities.screenAvailCoherent, screen.availWidth + 'x' + screen.availHeight],
+ ['devicePixelRatioPositive', capabilities.devicePixelRatioPositive, String(window.devicePixelRatio)],
+ ['screenYDefined', capabilities.screenYDefined, String(window.screenY) + ' / ' + String(window.screenTop)],
+ ['timeZoneDateCoherent', capabilities.timeZoneDateCoherent, capabilities.timeZone + ' / ' + String(capabilities.timeZoneOffsetMinutes)],
+ ['timeZoneOffsetSane', capabilities.timeZoneOffsetSane, String(capabilities.timeZoneOffsetMinutes)],
+ ['userAgentVersionCoherent', capabilities.userAgentVersionCoherent, capabilities.userAgentFullVersion + ' / ' + capabilities.appVersionFull],
+ ['userAgentData', capabilities.userAgentData, String(capabilities.userAgentData)],
+ ['userAgentDataPlatformCoherent', capabilities.userAgentDataPlatformCoherent, capabilities.navigatorPlatform + ' / ' + capabilities.userAgentDataPlatform],
+ ['userAgentDataFullVersionCoherent', capabilities.userAgentDataFullVersionCoherent, capabilities.userAgentFullVersion + ' / ' + (capabilities.userAgentDataFullVersion || JSON.stringify(capabilities.userAgentDataFullVersionList))],
+ ['chromeRuntimeConnect', capabilities.chromeRuntimeConnect, String(capabilities.chromeRuntimeConnect)],
+ ['chromeRuntimeSendMessage', capabilities.chromeRuntimeSendMessage, String(capabilities.chromeRuntimeSendMessage)],
+ ['chromeRuntimeConnectNativeLike', capabilities.chromeRuntimeConnectNativeLike, capabilities.runtimeConnectToString || 'none'],
+ ['chromeApp', capabilities.chromeApp, String(capabilities.chromeApp)],
+ ['canPlayTypeNativeLike', capabilities.canPlayTypeNativeLike, String(capabilities.canPlayTypeNativeLike)],
+ ['canvasToDataURLNativeLike', capabilities.canvasToDataURLNativeLike, String(capabilities.canvasToDataURLNativeLike)],
+ ['canvasToBlobNativeLike', capabilities.canvasToBlobNativeLike, String(capabilities.canvasToBlobNativeLike)],
+ ['canvasGetImageDataNativeLike', capabilities.canvasGetImageDataNativeLike, String(capabilities.canvasGetImageDataNativeLike)],
+ ['canvasMeasureTextNativeLike', capabilities.canvasMeasureTextNativeLike, String(capabilities.canvasMeasureTextNativeLike)],
+ ['canvasTransparentPixelPreserved', capabilities.canvasTransparentPixelPreserved, String(capabilities.canvasTransparentPixelPreserved)],
+ ['webglGetParameterNativeLike', capabilities.webglGetParameterNativeLike, String(capabilities.webglGetParameterNativeLike)],
+ ['rtcPeerConnectionNativeLike', capabilities.rtcPeerConnectionNativeLike, String(capabilities.rtcPeerConnectionNativeLike)],
+ ['audioContextCreateOscillatorNativeLike', capabilities.audioContextCreateOscillatorNativeLike, String(capabilities.audioContextCreateOscillatorNativeLike)],
+ ['webglRendererNoSwiftShader', capabilities.webglRendererNoSwiftShader, capabilities.webglRenderer || 'none'],
+ ['webglRendererPlatformCoherent', capabilities.webglRendererPlatformCoherent, capabilities.webglRenderer || 'none'],
+ ['getComputedStyleNativeLike', capabilities.getComputedStyleNativeLike, String(capabilities.getComputedStyleNativeLike)],
+ ['getComputedStyleNameNative', capabilities.getComputedStyleNameNative, window.getComputedStyle.name],
+ ['matchMediaNativeLike', capabilities.matchMediaNativeLike, String(capabilities.matchMediaNativeLike)],
+ ['matchMediaNameNative', capabilities.matchMediaNameNative, typeof window.matchMedia === 'function' ? window.matchMedia.name : 'absent'],
+ ['maxTouchPointsDefined', capabilities.maxTouchPointsDefined, String(navigator.maxTouchPoints)],
+ ['iframeIsolation', capabilities.iframeIsolation, String(capabilities.iframeIsolation)],
+ ['navigatorOverridesAbsent', capabilities.navigatorOverridesAbsent, capabilities.navigatorOverrideNames.join(', ') || 'none'],
+ ['intlDateTimeLocaleCoherent', capabilities.intlDateTimeLocaleCoherent, capabilities.intlDateTimeLocale || 'none'],
+ ['intlNumberLocaleCoherent', capabilities.intlNumberLocaleCoherent, capabilities.intlNumberLocale || 'none'],
+ ['intlLocaleCoherent', capabilities.intlLocaleCoherent, capabilities.intlLocaleValues.join(', ') || 'none'],
+ ['errorPrepareStackTraceNative', capabilities.errorPrepareStackTraceNative, String(capabilities.errorPrepareStackTraceNative)],
+ ['functionToStringNative', capabilities.functionToStringNative, capabilities.functionToStringName + ' [' + capabilities.functionToStringOwnNames.join(', ') + ']'],
+ ['devtoolsFormattersAbsentByDefault', capabilities.devtoolsFormattersAbsentByDefault, String(capabilities.devtoolsFormattersAbsentByDefault)],
+ ['userAgentDataBrandMajorCoherent', capabilities.userAgentDataBrandMajorCoherent, JSON.stringify(capabilities.userAgentDataBrands)],
+ ['userAgentDataVersionCoherent', capabilities.userAgentDataVersionCoherent, capabilities.userAgent + ' / ' + capabilities.userAgentDataPlatform],
+ ['downlinkMaxPresent', capabilities.downlinkMaxPresent, String(capabilities.downlinkMaxPresent)],
+ ['prefersColorSchemeLight', capabilities.prefersColorSchemeLight, String(capabilities.prefersColorSchemeLight)],
+ ['systemColorsResolved', capabilities.systemColorsResolved, String(capabilities.systemColorsResolved)],
+ ['videoCodecSummary', capabilities.h264 === 'probably' || capabilities.vp9 === 'probably', 'H264=' + capabilities.h264 + ' VP9=' + capabilities.vp9]
+ ];
+
+ const table = document.getElementById('results');
+ for (const row of rows) {
+ const tr = table.insertRow();
+ const tdCheck = document.createElement('td');
+ tdCheck.textContent = row[0];
+ const tdStatus = document.createElement('td');
+ tdStatus.className = row[1] ? 'ok' : 'bad';
+ tdStatus.textContent = row[1] ? 'PASS' : 'FAIL';
+ const tdValue = document.createElement('td');
+ tdValue.textContent = String(row[2]);
+ tr.appendChild(tdCheck);
+ tr.appendChild(tdStatus);
+ tr.appendChild(tdValue);
+ }
+
+ document.getElementById('raw').textContent = JSON.stringify(capabilities, null, 2);
+ })();
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/fixtures/stealth-devtools-probe.html b/tests/e2e/fixtures/stealth-devtools-probe.html
new file mode 100644
index 00000000..f543ebaa
--- /dev/null
+++ b/tests/e2e/fixtures/stealth-devtools-probe.html
@@ -0,0 +1,94 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Stealth DevTools Probe</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <style>
+ body {
+ font-family: system-ui, sans-serif;
+ margin: 24px;
+ line-height: 1.5;
+ }
+ pre {
+ padding: 12px;
+ background: #f4f4f4;
+ border-radius: 8px;
+ overflow: auto;
+ }
+ </style>
+</head>
+<body>
+ <h1>Stealth DevTools Probe</h1>
+ <pre id="report">running...</pre>
+ <script>
+ (function() {
+ const reportEl = document.getElementById('report');
+ const report = {
+ ready: false,
+ initialFormattersLen: 0,
+ formatterCalled: false,
+ formatterCalls: 0,
+ getterCalled: false,
+ getterCalls: 0,
+ stackGetterCalled: false,
+ stackGetterCalls: 0,
+ error: ''
+ };
+
+ window.__stealthDevtoolsProbe = report;
+
+ try {
+ const existingFormatters = Array.isArray(window.devtoolsFormatters) ? window.devtoolsFormatters.slice() : [];
+ report.initialFormattersLen = existingFormatters.length;
+ const formatterMarker = { __pinchtabFormatterProbe: true };
+ const formatter = {
+ header(object) {
+ if (object && object.__pinchtabFormatterProbe) {
+ report.formatterCalled = true;
+ report.formatterCalls += 1;
+ }
+ return null;
+ },
+ hasBody() {
+ return false;
+ }
+ };
+
+ window.devtoolsFormatters = existingFormatters.concat(formatter);
+
+ const getterProbe = document.createElement('div');
+ Object.defineProperty(getterProbe, 'id', {
+ get() {
+ report.getterCalled = true;
+ report.getterCalls += 1;
+ return 'pinchtab-devtools-probe';
+ },
+ configurable: true
+ });
+
+ const stackProbe = new Error('pinchtab-devtools-stack');
+ Object.defineProperty(stackProbe, 'stack', {
+ get() {
+ report.stackGetterCalled = true;
+ report.stackGetterCalls += 1;
+ return 'pinchtab-devtools-stack';
+ },
+ configurable: true
+ });
+
+ console.log('pinchtab-devtools-formatter', formatterMarker);
+ console.dir(getterProbe);
+ console.log(stackProbe);
+ } catch (error) {
+ report.error = String((error && error.message) || error || '');
+ }
+
+ setTimeout(() => {
+ report.ready = true;
+ reportEl.textContent = JSON.stringify(report, null, 2);
+ }, 1200);
+ })();
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/fixtures/stealth-service-worker.html b/tests/e2e/fixtures/stealth-service-worker.html
new file mode 100644
index 00000000..ab975e5c
--- /dev/null
+++ b/tests/e2e/fixtures/stealth-service-worker.html
@@ -0,0 +1,154 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Stealth Service Worker Parity</title>
+ <style>
+ body {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ margin: 24px;
+ background: #10161f;
+ color: #e6edf3;
+ }
+ table {
+ border-collapse: collapse;
+ width: 100%;
+ margin-top: 16px;
+ }
+ th, td {
+ border: 1px solid #2f3b4d;
+ padding: 8px;
+ text-align: left;
+ }
+ th {
+ background: #17202d;
+ }
+ .ok {
+ color: #5ee27a;
+ }
+ .bad {
+ color: #ff7b72;
+ }
+ .skip {
+ color: #f2cc60;
+ }
+ </style>
+</head>
+<body>
+ <h1>Stealth Service Worker Parity</h1>
+ <table id="results">
+ <tr><th>Check</th><th>Pass</th><th>Value</th></tr>
+ </table>
+
+ <script>
+ (async function() {
+ function render(report) {
+ const table = document.getElementById('results');
+ const rows = [
+ ['secureContext', report.secureContext, String(report.secureContext)],
+ ['serviceWorkerSupported', report.supported, String(report.supported)],
+ ['serviceWorkerReady', report.skipped ? null : report.ready, report.skipped ? ('skipped: ' + report.skipReason) : (report.error || 'ready')],
+ ['webdriverNotTrue', report.skipped ? null : report.matches.webdriverNotTrue, report.skipped ? 'skipped' : String(report.serviceWorker.webdriverValue)],
+ ['userAgentMatch', report.skipped ? null : report.matches.userAgent, report.skipped ? 'skipped' : (report.page.userAgent + ' / ' + report.serviceWorker.userAgent)],
+ ['platformMatch', report.skipped ? null : report.matches.platform, report.skipped ? 'skipped' : (report.page.platform + ' / ' + report.serviceWorker.platform)],
+ ['hardwareConcurrencyMatch', report.skipped ? null : report.matches.hardwareConcurrency, report.skipped ? 'skipped' : (String(report.page.hardwareConcurrency) + ' / ' + String(report.serviceWorker.hardwareConcurrency))],
+ ['deviceMemoryMatch', report.skipped ? null : report.matches.deviceMemory, report.skipped ? 'skipped' : (String(report.page.deviceMemory) + ' / ' + String(report.serviceWorker.deviceMemory))]
+ ];
+
+ for (const row of rows) {
+ const tr = table.insertRow();
+ const stateClass = row[1] === null ? 'skip' : (row[1] ? 'ok' : 'bad');
+ const stateLabel = row[1] === null ? 'SKIP' : (row[1] ? 'PASS' : 'FAIL');
+ tr.innerHTML =
+ '<td>' + row[0] + '</td>' +
+ '<td class="' + stateClass + '">' + stateLabel + '</td>' +
+ '<td>' + String(row[2]) + '</td>';
+ }
+ }
+
+ function finalize(serviceWorkerData, options) {
+ const settings = options || {};
+ const page = {
+ userAgent: navigator.userAgent || '',
+ platform: navigator.platform || '',
+ hardwareConcurrency: typeof navigator.hardwareConcurrency === 'number' ? navigator.hardwareConcurrency : null,
+ deviceMemory: typeof navigator.deviceMemory === 'number' ? navigator.deviceMemory : null
+ };
+
+ const report = {
+ ready: !!serviceWorkerData && !settings.error && !settings.skipReason,
+ error: settings.error || '',
+ secureContext: window.isSecureContext === true,
+ supported: 'serviceWorker' in navigator,
+ skipped: !!settings.skipReason,
+ skipReason: settings.skipReason || '',
+ page,
+ serviceWorker: serviceWorkerData || {},
+ matches: {
+ webdriverNotTrue: !!serviceWorkerData && serviceWorkerData.webdriverNotTrue === true,
+ userAgent: !!serviceWorkerData && serviceWorkerData.userAgent === page.userAgent,
+ platform: !!serviceWorkerData && serviceWorkerData.platform === page.platform,
+ hardwareConcurrency: !!serviceWorkerData && serviceWorkerData.hardwareConcurrency === page.hardwareConcurrency,
+ deviceMemory: !!serviceWorkerData && serviceWorkerData.deviceMemory === page.deviceMemory
+ }
+ };
+ window.__stealthServiceWorkerReport = report;
+ render(report);
+ }
+
+ if (!window.isSecureContext) {
+ finalize(null, { skipReason: 'service worker requires a secure context' });
+ return;
+ }
+
+ if (!('serviceWorker' in navigator)) {
+ finalize(null, { skipReason: 'service worker unavailable in this browser context' });
+ return;
+ }
+
+ try {
+ const registrations = await navigator.serviceWorker.getRegistrations();
+ await Promise.all(registrations.map((registration) => registration.unregister()));
+
+ const registration = await navigator.serviceWorker.register('./stealth-service-worker.js?ts=' + Date.now(), { scope: './' });
+ await navigator.serviceWorker.ready;
+
+ const worker = registration.active || registration.waiting || registration.installing;
+ if (!worker) {
+ finalize(null, { error: 'no active service worker' });
+ return;
+ }
+
+ if (worker.state !== 'activated') {
+ await new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error('service worker activation timeout')), 5000);
+ worker.addEventListener('statechange', function onStateChange() {
+ if (worker.state === 'activated') {
+ clearTimeout(timeout);
+ worker.removeEventListener('statechange', onStateChange);
+ resolve();
+ }
+ });
+ });
+ }
+
+ const channel = new MessageChannel();
+ const timeout = setTimeout(() => finalize(null, { error: 'service worker response timeout' }), 5000);
+
+ channel.port1.onmessage = function(event) {
+ clearTimeout(timeout);
+ finalize(event.data, {});
+ };
+ channel.port1.onmessageerror = function() {
+ clearTimeout(timeout);
+ finalize(null, { error: 'service worker message error' });
+ };
+
+ worker.postMessage({ type: 'collect' }, [channel.port2]);
+ } catch (error) {
+ finalize(null, { error: error && error.message ? error.message : String(error) });
+ }
+ })();
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/fixtures/stealth-service-worker.js b/tests/e2e/fixtures/stealth-service-worker.js
new file mode 100644
index 00000000..f99b9eaa
--- /dev/null
+++ b/tests/e2e/fixtures/stealth-service-worker.js
@@ -0,0 +1,25 @@
+self.addEventListener('install', (event) => {
+ event.waitUntil(self.skipWaiting());
+});
+
+self.addEventListener('activate', (event) => {
+ event.waitUntil(self.clients.claim());
+});
+
+self.addEventListener('message', async (event) => {
+ const port = event.ports && event.ports[0];
+ if (!port) return;
+
+ const nav = self.navigator || {};
+ const uaData = nav.userAgentData || null;
+
+ port.postMessage({
+ userAgent: nav.userAgent || '',
+ platform: nav.platform || '',
+ webdriverNotTrue: !('webdriver' in nav) || nav.webdriver !== true,
+ webdriverValue: ('webdriver' in nav) ? nav.webdriver : 'absent',
+ hardwareConcurrency: typeof nav.hardwareConcurrency === 'number' ? nav.hardwareConcurrency : null,
+ deviceMemory: typeof nav.deviceMemory === 'number' ? nav.deviceMemory : null,
+ userAgentDataPlatform: uaData ? uaData.platform : ''
+ });
+});
diff --git a/tests/e2e/fixtures/stealth-workers.html b/tests/e2e/fixtures/stealth-workers.html
new file mode 100644
index 00000000..eb038c35
--- /dev/null
+++ b/tests/e2e/fixtures/stealth-workers.html
@@ -0,0 +1,121 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Stealth Worker Parity</title>
+ <style>
+ body {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ margin: 24px;
+ background: #0f1720;
+ color: #e6edf3;
+ }
+ table {
+ border-collapse: collapse;
+ width: 100%;
+ margin-top: 16px;
+ }
+ th, td {
+ border: 1px solid #2f3b4d;
+ padding: 8px;
+ text-align: left;
+ }
+ th {
+ background: #17202d;
+ }
+ .ok {
+ color: #5ee27a;
+ }
+ .bad {
+ color: #ff7b72;
+ }
+ </style>
+</head>
+<body>
+ <h1>Stealth Worker Parity</h1>
+ <table id="results">
+ <tr><th>Check</th><th>Pass</th><th>Value</th></tr>
+ </table>
+
+ <script>
+ (function() {
+ const page = {
+ userAgent: navigator.userAgent || '',
+ platform: navigator.platform || '',
+ hardwareConcurrency: typeof navigator.hardwareConcurrency === 'number' ? navigator.hardwareConcurrency : null,
+ deviceMemory: typeof navigator.deviceMemory === 'number' ? navigator.deviceMemory : null
+ };
+
+ function render(report) {
+ const table = document.getElementById('results');
+ const rows = [
+ ['workerReady', report.ready, report.error || 'ready'],
+ ['userAgentMatch', report.matches.userAgent, page.userAgent + ' / ' + report.worker.userAgent],
+ ['platformMatch', report.matches.platform, page.platform + ' / ' + report.worker.platform],
+ ['hardwareConcurrencyMatch', report.matches.hardwareConcurrency, String(page.hardwareConcurrency) + ' / ' + String(report.worker.hardwareConcurrency)],
+ ['deviceMemoryMatch', report.matches.deviceMemory, String(page.deviceMemory) + ' / ' + String(report.worker.deviceMemory)]
+ ];
+
+ for (const row of rows) {
+ const tr = table.insertRow();
+ tr.innerHTML =
+ '<td>' + row[0] + '</td>' +
+ '<td class="' + (row[1] ? 'ok' : 'bad') + '">' + (row[1] ? 'PASS' : 'FAIL') + '</td>' +
+ '<td>' + String(row[2]) + '</td>';
+ }
+ }
+
+ function finalize(workerData, error) {
+ const report = {
+ ready: !error,
+ error: error || '',
+ page: page,
+ worker: workerData || {},
+ matches: {
+ userAgent: !!workerData && workerData.userAgent === page.userAgent,
+ platform: !!workerData && workerData.platform === page.platform,
+ hardwareConcurrency: !!workerData && workerData.hardwareConcurrency === page.hardwareConcurrency,
+ deviceMemory: !!workerData && workerData.deviceMemory === page.deviceMemory
+ }
+ };
+ window.__stealthWorkerReport = report;
+ render(report);
+ }
+
+ const source = `
+ self.onmessage = function() {
+ const nav = self.navigator || {};
+ self.postMessage({
+ userAgent: nav.userAgent || '',
+ platform: nav.platform || '',
+ hardwareConcurrency: typeof nav.hardwareConcurrency === 'number' ? nav.hardwareConcurrency : null,
+ deviceMemory: typeof nav.deviceMemory === 'number' ? nav.deviceMemory : null
+ });
+ };
+ `;
+
+ try {
+ const blob = new Blob([source], { type: 'application/javascript' });
+ const worker = new Worker(URL.createObjectURL(blob));
+ const timeout = setTimeout(function() {
+ finalize(null, 'worker timeout');
+ }, 5000);
+
+ worker.onmessage = function(event) {
+ clearTimeout(timeout);
+ finalize(event.data, '');
+ worker.terminate();
+ };
+ worker.onerror = function(event) {
+ clearTimeout(timeout);
+ finalize(null, event.message || 'worker error');
+ worker.terminate();
+ };
+ worker.postMessage({ type: 'collect' });
+ } catch (error) {
+ finalize(null, error && error.message ? error.message : String(error));
+ }
+ })();
+ </script>
+</body>
+</html>
diff --git a/tests/e2e/helpers/api-http.sh b/tests/e2e/helpers/api-http.sh
index 9472cd32..c158e5ec 100644
--- a/tests/e2e/helpers/api-http.sh
+++ b/tests/e2e/helpers/api-http.sh
@@ -111,6 +111,16 @@ wait_for_instances_running() {
RESULT=""
HTTP_STATUS=""
+split_pinchtab_response() {
+ local response="$1"
+ HTTP_STATUS="${response##*$'\n'}"
+ if [[ "$response" == *$'\n'* ]]; then
+ RESULT="${response%$'\n'*}"
+ else
+ RESULT=""
+ fi
+}
+
pinchtab() {
local method="$1"
local path="$2"
@@ -125,8 +135,7 @@ pinchtab() {
-H "Content-Type: application/json" \
"$@")
- RESULT=$(echo "$response" | head -n -1)
- HTTP_STATUS=$(echo "$response" | tail -n 1)
+ split_pinchtab_response "$response"
if [[ ! "$HTTP_STATUS" =~ ^2 ]]; then
echo -e "${ERROR} HTTP $HTTP_STATUS: $RESULT${NC}" >&2
@@ -165,8 +174,7 @@ pt_patch() {
"${E2E_SERVER}$path" \
-H "Content-Type: application/json" \
-d "$body")
- RESULT=$(echo "$response" | head -n -1)
- HTTP_STATUS=$(echo "$response" | tail -n 1)
+ split_pinchtab_response "$response"
_echo_truncated
}
@@ -177,8 +185,7 @@ pt_delete() {
response=$(e2e_curl -s -w "\n%{http_code}" \
-X DELETE \
"${E2E_SERVER}$path")
- RESULT=$(echo "$response" | head -n -1)
- HTTP_STATUS=$(echo "$response" | tail -n 1)
+ split_pinchtab_response "$response"
_echo_truncated
}
@@ -192,8 +199,7 @@ pt_post_raw() {
"${E2E_SERVER}$path" \
-H "Content-Type: application/json" \
-d "$body")
- RESULT=$(echo "$response" | head -n -1)
- HTTP_STATUS=$(echo "$response" | tail -n 1)
+ split_pinchtab_response "$response"
_echo_truncated
}
@@ -304,6 +310,43 @@ get_tab_id() {
echo "$RESULT" | jq -r '.tabId'
}
+normalize_default_port_url() {
+ local raw="${1:-}"
+ raw="${raw/http:\/\/127.0.0.1:80\//http:\/\/127.0.0.1/}"
+ raw="${raw/http:\/\/localhost:80\//http:\/\/localhost/}"
+ raw="${raw/https:\/\/127.0.0.1:443\//https:\/\/127.0.0.1/}"
+ raw="${raw/https:\/\/localhost:443\//https:\/\/localhost/}"
+ printf '%s' "$raw" | sed -E \
+ -e 's#^http://([^/:]+):80(/|$)#http://\1\2#' \
+ -e 's#^https://([^/:]+):443(/|$)#https://\1\2#'
+}
+
+poll_instance_tab_id_by_url() {
+ local instance_id="$1"
+ local url="$2"
+ local attempts="${3:-20}"
+ local delay="${4:-0.5}"
+ local base_url="${5:-$E2E_SERVER}"
+ local normalized_url
+ normalized_url=$(normalize_default_port_url "$url")
+
+ for i in $(seq 1 "$attempts"); do
+ local tabs_json
+ tabs_json=$(e2e_curl -sf "${base_url}/instances/${instance_id}/tabs" 2>/dev/null || true)
+ if [ -n "$tabs_json" ]; then
+ local tab_id
+ tab_id=$(echo "$tabs_json" | jq -r --arg url "$url" --arg normalized_url "$normalized_url" '[.[] | select(.url == $url or .url == $normalized_url) | .id] | first // empty' 2>/dev/null || true)
+ if [ -n "$tab_id" ] && [ "$tab_id" != "null" ]; then
+ printf '%s' "$tab_id"
+ return 0
+ fi
+ fi
+ sleep "$delay"
+ done
+
+ return 1
+}
+
assert_tab_id() {
local desc="${1:-tabId returned}"
TAB_ID=$(echo "$RESULT" | jq -r '.tabId')
@@ -422,12 +465,19 @@ assert_eval_poll() {
for i in $(seq 1 "$attempts"); do
local json_body
if [ -n "$tab_id" ]; then
- json_body=$(jq -n --arg expr "$expr" --arg tabId "$tab_id" '{"expression": $expr, "tabId": $tabId}')
+ json_body=$(jq -n --arg expr "$expr" '{"expression": $expr}')
+ pt_post "/tabs/${tab_id}/evaluate" "$json_body"
else
json_body=$(jq -n --arg expr "$expr" '{"expression": $expr}')
+ pt_post /evaluate "$json_body"
fi
- pt_post /evaluate "$json_body"
- actual=$(echo "$RESULT" | jq -r '.result // empty' 2>/dev/null)
+ actual=$(echo "$RESULT" | jq -r '
+ if has("result") then
+ .result | if . == null then "null" else tostring end
+ else
+ empty
+ end
+ ' 2>/dev/null)
if [ "$actual" = "$expected" ]; then
ok=true
break
diff --git a/tests/e2e/helpers/base.sh b/tests/e2e/helpers/base.sh
index 5ad11c9f..c1b6add3 100644
--- a/tests/e2e/helpers/base.sh
+++ b/tests/e2e/helpers/base.sh
@@ -92,6 +92,8 @@ wait_for_instance_ready() {
}
start_test() {
+ ASSERTIONS_PASSED=0
+ ASSERTIONS_FAILED=0
if [ -n "${CURRENT_SCENARIO_FILE}" ]; then
CURRENT_TEST="[${CURRENT_SCENARIO_FILE}] $1"
else
@@ -111,7 +113,7 @@ end_test() {
TEST_RESULTS+=("✅ ${CURRENT_TEST}|${duration}ms|passed")
((TESTS_PASSED++)) || true
else
- echo -e "${RED}✗ ${CURRENT_TEST} failed${NC} ${MUTED}(${duration}ms)${NC}\n"
+ echo -e "${RED}✗ ${CURRENT_TEST} failed${NC} ${MUTED}(${duration}ms, failed assertions: ${ASSERTIONS_FAILED})${NC}\n"
TEST_RESULTS+=("❌ ${CURRENT_TEST}|${duration}ms|failed")
((TESTS_FAILED++)) || true
fi
diff --git a/tests/e2e/scenarios-api/stealth-basic.sh b/tests/e2e/scenarios-api/stealth-basic.sh
index a06fc771..4616907b 100644
--- a/tests/e2e/scenarios-api/stealth-basic.sh
+++ b/tests/e2e/scenarios-api/stealth-basic.sh
@@ -11,9 +11,30 @@ assert_ok "navigate"
sleep 1
# ─────────────────────────────────────────────────────────────────
-start_test "stealth: webdriver is undefined"
+start_test "stealth: status endpoint available"
+
+pt_get /stealth/status
+assert_json_eq "$RESULT" '.level' 'light' "default level is light"
+assert_json_exists "$RESULT" '.scriptHash' "status includes script hash"
+assert_json_eq "$RESULT" '.capabilities.webdriverNotTrue' 'true' "status reports webdriver-not-true capability"
+assert_json_eq "$RESULT" '.capabilities.webdriverNativeStrategy' 'true' "status reports native webdriver strategy"
+assert_json_eq "$RESULT" '.capabilities.downlinkMax' 'true' "status reports downlinkMax capability"
+assert_json_eq "$RESULT" '.flags.globalUserAgent' 'true' "status reports global launch UA"
+assert_json_eq "$RESULT" '.flags.downlinkMaxFlag' 'true' "status reports downlinkMax launch flag"
+assert_json_eq "$RESULT" '.capabilities.iframeIsolation' 'false' "light status keeps iframe isolation disabled"
+assert_json_eq "$RESULT" '.capabilities.errorStackSanitized' 'false' "light status keeps stack sanitization disabled"
+assert_json_eq "$RESULT" '.capabilities.functionToStringMasked' 'false' "light status keeps toString masking disabled"
+assert_json_eq "$RESULT" '.capabilities.functionToStringNative' 'true' "light status keeps Function.prototype.toString native"
+assert_json_eq "$RESULT" '.capabilities.intlLocaleCoherent' 'true' "light status keeps Intl locale coherence"
+assert_json_eq "$RESULT" '.capabilities.errorPrepareStackTraceNative' 'true' "light status keeps Error.prepareStackTrace native"
+assert_json_eq "$RESULT" '.capabilities.navigatorOverridesAbsent' 'true' "light status avoids navigator own-property overrides"
-assert_eval_poll "navigator.webdriver === undefined" "true" "navigator.webdriver is undefined"
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "stealth: webdriver is not true"
+
+assert_eval_poll "navigator.webdriver !== true" "true" "navigator.webdriver is not true"
end_test
@@ -54,8 +75,50 @@ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"
assert_ok "navigate"
TAB_ID=$(get_tab_id)
-pt_post /fingerprint/rotate "{\"tabId\":\"${TAB_ID}\",\"os\":\"mac\"}"
+pt_post "/tabs/${TAB_ID}/evaluate" '{"expression":"JSON.stringify({userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight})"}'
+assert_ok "capture pre-rotate tab fingerprint"
+PRE_ROTATE_SURFACE=$(echo "$RESULT" | jq -r '.result // "{}"')
+PRE_ROTATE_UA=$(echo "$PRE_ROTATE_SURFACE" | jq -r '.userAgent // ""')
+PRE_ROTATE_PLATFORM=$(echo "$PRE_ROTATE_SURFACE" | jq -r '.platform // ""')
+PRE_ROTATE_LANGUAGE=$(echo "$PRE_ROTATE_SURFACE" | jq -r '.language // ""')
+
+pt_post /fingerprint/rotate "{\"tabId\":\"${TAB_ID}\",\"os\":\"windows\",\"screen\":\"1366x768\",\"language\":\"en-US\"}"
assert_ok "fingerprint rotate on tab"
+ROTATE_FINGERPRINT_JSON=$(echo "$RESULT" | jq -c '.fingerprint // {}')
+ROTATE_USER_AGENT=$(echo "$ROTATE_FINGERPRINT_JSON" | jq -r '.userAgent // empty')
+ROTATE_PLATFORM=$(echo "$ROTATE_FINGERPRINT_JSON" | jq -r '.platform // empty')
+ROTATE_WIDTH=$(echo "$ROTATE_FINGERPRINT_JSON" | jq -r '.screenWidth // 0')
+ROTATE_HEIGHT=$(echo "$ROTATE_FINGERPRINT_JSON" | jq -r '.screenHeight // 0')
+ROTATE_LANGUAGE=$(echo "$ROTATE_FINGERPRINT_JSON" | jq -r '.language // empty')
+
+pt_get "/stealth/status?tabId=${TAB_ID}"
+assert_json_eq "$RESULT" '.tabOverrides.fingerprintRotateActive' 'true' "status reports fingerprint rotate overlay on tab"
+
+if [ -n "$ROTATE_USER_AGENT" ] && { [ "$PRE_ROTATE_UA" != "$ROTATE_USER_AGENT" ] || [ "$PRE_ROTATE_PLATFORM" != "$ROTATE_PLATFORM" ] || [ "$PRE_ROTATE_LANGUAGE" != "$ROTATE_LANGUAGE" ]; }; then
+ echo -e " ${GREEN}✓${NC} fingerprint rotate changes tab persona"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} fingerprint rotate did not change tab persona"
+ echo -e " ${MUTED}before:${NC} ua=${PRE_ROTATE_UA} platform=${PRE_ROTATE_PLATFORM} language=${PRE_ROTATE_LANGUAGE}"
+ echo -e " ${MUTED}after:${NC} ua=${ROTATE_USER_AGENT} platform=${ROTATE_PLATFORM} language=${ROTATE_LANGUAGE}"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+assert_eval_poll "navigator.userAgent === $(jq -Rn --arg v "$ROTATE_USER_AGENT" '$v')" "true" "rotated tab userAgent matches fingerprint" 8 0.3 "$TAB_ID"
+assert_eval_poll "navigator.platform === $(jq -Rn --arg v "$ROTATE_PLATFORM" '$v')" "true" "rotated tab platform matches fingerprint" 8 0.3 "$TAB_ID"
+assert_eval_poll "navigator.language === $(jq -Rn --arg v "$ROTATE_LANGUAGE" '$v')" "true" "rotated tab language matches fingerprint" 8 0.3 "$TAB_ID"
+assert_eval_poll "window.innerWidth === ${ROTATE_WIDTH}" "true" "rotated tab viewport width matches fingerprint" 8 0.3 "$TAB_ID"
+assert_eval_poll "window.innerHeight === ${ROTATE_HEIGHT}" "true" "rotated tab viewport height matches fingerprint" 8 0.3 "$TAB_ID"
+
+pt_post "/tabs/${TAB_ID}/navigate" "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "navigate rotated tab"
+sleep 1
+
+assert_eval_poll "navigator.userAgent === $(jq -Rn --arg v "$ROTATE_USER_AGENT" '$v')" "true" "rotated userAgent persists across navigation" 8 0.3 "$TAB_ID"
+assert_eval_poll "navigator.platform === $(jq -Rn --arg v "$ROTATE_PLATFORM" '$v')" "true" "rotated platform persists across navigation" 8 0.3 "$TAB_ID"
+assert_eval_poll "navigator.language === $(jq -Rn --arg v "$ROTATE_LANGUAGE" '$v')" "true" "rotated language persists across navigation" 8 0.3 "$TAB_ID"
+assert_eval_poll "window.innerWidth === ${ROTATE_WIDTH}" "true" "rotated viewport width persists across navigation" 8 0.3 "$TAB_ID"
+assert_eval_poll "window.innerHeight === ${ROTATE_HEIGHT}" "true" "rotated viewport height persists across navigation" 8 0.3 "$TAB_ID"
end_test
@@ -76,15 +139,15 @@ assert_eval_poll "navigator.webdriver !== true" "true" "navigator.webdriver is n
end_test
-start_test "bot-detect: navigator.webdriver is undefined"
+start_test "bot-detect: navigator.webdriver is not true"
-assert_eval_poll "navigator.webdriver === undefined || navigator.webdriver === false" "true" "navigator.webdriver is undefined or false"
+assert_eval_poll "navigator.webdriver !== true" "true" "navigator.webdriver is undefined or false"
end_test
-start_test "bot-detect: webdriver property does not exist"
+start_test "bot-detect: webdriver property semantics are acceptable"
-assert_eval_poll "!('webdriver' in navigator)" "true" "webdriver property not in navigator"
+assert_eval_poll "!('webdriver' in navigator) || navigator.webdriver === false" "true" "webdriver property is hidden or native false"
end_test
@@ -163,3 +226,175 @@ start_test "bot-detect: battery API exists"
assert_eval_poll "typeof navigator.getBattery === 'function'" "true" "getBattery exists"
end_test
+
+start_test "stealth-capabilities: navigate to capability fixture"
+
+pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-capabilities.html\"}"
+assert_ok "navigate to stealth-capabilities fixture"
+sleep 1
+
+end_test
+
+start_test "stealth-capabilities: plugin object semantics"
+
+assert_eval_poll "window.__stealthCapabilities.pluginObjectSemantics" "true" "plugin object semantics are coherent"
+
+end_test
+
+start_test "stealth-capabilities: outer dimensions available"
+
+assert_eval_poll "window.__stealthCapabilities.outerDimensions" "true" "outer dimensions exist"
+
+end_test
+
+start_test "stealth-capabilities: screen and window coherent"
+
+assert_eval_poll "window.__stealthCapabilities.screenWindowCoherent" "true" "screen and outer window are coherent"
+assert_eval_poll "window.__stealthCapabilities.screenAvailCoherent" "true" "available screen stays within screen bounds"
+
+end_test
+
+start_test "stealth-capabilities: devicePixelRatio positive"
+
+assert_eval_poll "window.__stealthCapabilities.devicePixelRatioPositive" "true" "devicePixelRatio stays positive"
+
+end_test
+
+start_test "stealth-capabilities: battery API reported"
+
+assert_eval_poll "window.__stealthCapabilities.batteryApi" "true" "battery API reported by capability fixture"
+
+end_test
+
+start_test "stealth-capabilities: downlinkMax reported"
+
+assert_eval_poll "window.__stealthCapabilities.downlinkMaxPresent" "true" "downlinkMax reported by capability fixture"
+
+end_test
+
+start_test "stealth-capabilities: medium-only iframe isolation absent at light"
+
+assert_eval_poll "window.__stealthCapabilities.iframeIsolation" "false" "iframe isolation remains disabled at light"
+
+end_test
+
+start_test "stealth-capabilities: native Function.prototype.toString preserved"
+
+assert_eval_poll "window.__stealthCapabilities.functionToStringNative" "true" "Function.prototype.toString remains native-like"
+assert_eval_poll "window.__stealthCapabilities.canPlayTypeNativeLike" "true" "canPlayType remains native-like"
+assert_eval_poll "window.__stealthCapabilities.getComputedStyleNameNative" "true" "getComputedStyle keeps its native name"
+assert_eval_poll "window.__stealthCapabilities.matchMediaNameNative" "true" "matchMedia keeps its native name"
+
+end_test
+
+start_test "stealth-capabilities: Intl locale stays coherent"
+
+assert_eval_poll "window.__stealthCapabilities.timeZoneDateCoherent" "true" "resolved timezone matches local Date clock"
+assert_eval_poll "window.__stealthCapabilities.timeZoneOffsetSane" "true" "timezone offset stays in a sane range"
+assert_eval_poll "window.__stealthCapabilities.intlLocaleCoherent" "true" "Intl locale family stays coherent"
+assert_eval_poll "window.__stealthCapabilities.intlDateTimeLocaleCoherent" "true" "Intl.DateTimeFormat locale matches navigator.language"
+assert_eval_poll "window.__stealthCapabilities.intlNumberLocaleCoherent" "true" "Intl.NumberFormat locale matches navigator.language"
+
+end_test
+
+start_test "stealth-capabilities: Error.prepareStackTrace remains native"
+
+assert_eval_poll "window.__stealthCapabilities.errorPrepareStackTraceNative" "true" "Error.prepareStackTrace is not trapped"
+
+end_test
+
+start_test "stealth-capabilities: navigator own-property overrides absent"
+
+assert_eval_poll "window.__stealthCapabilities.navigatorOverridesAbsent" "true" "navigator keeps core properties off the instance"
+
+end_test
+
+start_test "stealth-capabilities: userAgentData versions coherent"
+
+assert_eval_poll "window.__stealthCapabilities.userAgentVersionCoherent" "true" "appVersion aligns with the UA version"
+assert_eval_poll "window.__stealthCapabilities.userAgentDataBrandMajorCoherent" "true" "userAgentData brand major aligns with UA major"
+assert_eval_poll "window.__stealthCapabilities.userAgentDataVersionCoherent" "true" "userAgentData versions align with UA major"
+assert_eval_poll "window.__stealthCapabilities.userAgentDataFullVersionCoherent" "true" "userAgentData full version aligns with the UA version"
+
+end_test
+
+start_test "stealth-capabilities: canvas and WebGL probes stay low-noise"
+
+assert_eval_poll "window.__stealthCapabilities.canvasToDataURLNativeLike" "true" "canvas toDataURL remains native-like"
+assert_eval_poll "window.__stealthCapabilities.canvasGetImageDataNativeLike" "true" "canvas getImageData remains native-like"
+assert_eval_poll "window.__stealthCapabilities.canvasTransparentPixelPreserved" "true" "transparent canvas pixels stay untouched"
+assert_eval_poll "window.__stealthCapabilities.webglGetParameterNativeLike" "true" "WebGL getParameter remains native-like"
+
+end_test
+
+start_test "stealth-capabilities: webdriver descriptor remains native-like"
+
+assert_eval_poll "window.__stealthCapabilities.webdriverDescriptorNativeLike" "true" "webdriver descriptor getter stays native-like"
+
+end_test
+
+start_test "stealth-devtools-probe: navigate to local probe fixture"
+
+pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-devtools-probe.html\"}"
+assert_ok "navigate to devtools probe fixture"
+sleep 2
+
+end_test
+
+start_test "stealth-devtools-probe: report ready"
+
+assert_eval_poll "!!window.__stealthDevtoolsProbe && window.__stealthDevtoolsProbe.ready" "true" "devtools probe report ready"
+
+end_test
+
+start_test "stealth-devtools-probe: formatter probe not triggered"
+
+assert_eval_poll "window.__stealthDevtoolsProbe.formatterCalled" "false" "console formatter probe stays untouched"
+assert_eval_poll "window.__stealthDevtoolsProbe.initialFormattersLen" "0" "page starts without preinstalled devtools formatters"
+
+end_test
+
+start_test "stealth-devtools-probe: getter probe not triggered"
+
+assert_eval_poll "window.__stealthDevtoolsProbe.getterCalled" "false" "console getter probe stays untouched"
+assert_eval_poll "window.__stealthDevtoolsProbe.stackGetterCalls <= 1" "true" "error stack getter stays within baseline console access"
+
+end_test
+
+start_test "stealth-workers: navigate to worker parity fixture"
+
+pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-workers.html\"}"
+assert_ok "navigate to stealth-workers fixture"
+sleep 1
+
+end_test
+
+start_test "stealth-workers: worker report ready"
+
+assert_eval_poll "!!window.__stealthWorkerReport && window.__stealthWorkerReport.ready" "true" "worker report ready"
+
+end_test
+
+start_test "stealth-workers: user agent matches worker"
+
+assert_eval_poll "window.__stealthWorkerReport.matches.userAgent" "true" "page and worker userAgent match"
+
+end_test
+
+start_test "stealth-workers: platform matches worker"
+
+assert_eval_poll "window.__stealthWorkerReport.matches.platform" "true" "page and worker platform match"
+
+end_test
+
+start_test "stealth-workers: hardware concurrency matches worker"
+
+assert_eval_poll "window.__stealthWorkerReport.matches.hardwareConcurrency" "true" "page and worker hardwareConcurrency match"
+
+end_test
+
+start_test "stealth-workers: device memory matches worker"
+
+assert_eval_poll "window.__stealthWorkerReport.matches.deviceMemory" "true" "page and worker deviceMemory match"
+
+end_test
diff --git a/tests/e2e/scenarios-api/stealth-full.sh b/tests/e2e/scenarios-api/stealth-full.sh
index 8b446c4e..d147fca8 100644
--- a/tests/e2e/scenarios-api/stealth-full.sh
+++ b/tests/e2e/scenarios-api/stealth-full.sh
@@ -24,6 +24,7 @@ run_stealth_level_matrix() {
ORIG_URL="$E2E_SERVER"
E2E_SERVER="$MATRIX_URL"
+ MATRIX_STATUS=""
echo -e "${BLUE}Testing stealth level: ${STEALTH_LEVEL}${NC}\n"
start_test "stealth-levels: navigate to test page"
@@ -32,9 +33,19 @@ run_stealth_level_matrix() {
sleep 1
end_test
+ start_test "stealth-levels: status reports configured level"
+ pt_get /stealth/status
+ MATRIX_STATUS="$RESULT"
+ assert_json_eq "$RESULT" '.level' "$STEALTH_LEVEL" "status level matches instance"
+ assert_json_exists "$RESULT" '.scriptHash' "status includes script hash"
+ assert_json_eq "$RESULT" '.flags.globalUserAgent' 'true' "status reports global launch UA"
+ assert_json_eq "$RESULT" '.capabilities.webdriverNativeStrategy' 'true' "status reports native webdriver strategy"
+ assert_json_eq "$RESULT" '.capabilities.downlinkMax' 'true' "status reports downlinkMax capability"
+ end_test
+
start_test "stealth-levels: [light] webdriver hidden"
- pt_post /evaluate '{"expression":"navigator.webdriver === true"}'
- assert_json_eq "$RESULT" '.result' 'false' "webdriver !== true"
+ pt_post /evaluate '{"expression":"navigator.webdriver !== true"}'
+ assert_json_eq "$RESULT" '.result' 'true' "webdriver !== true"
end_test
start_test "stealth-levels: [light] plugins array exists"
@@ -53,39 +64,35 @@ run_stealth_level_matrix() {
end_test
start_test "stealth-levels: [medium] userAgentData exists"
- pt_post /evaluate '{"expression":"!!(navigator.userAgentData && navigator.userAgentData.brands)"}'
+ pt_get /stealth/status
if [ "$STEALTH_LEVEL" = "light" ]; then
- echo -e " ${MUTED}(skipped - native behavior at light level)${NC}"
- ((ASSERTIONS_PASSED++)) || true
+ assert_json_eq "$RESULT" '.capabilities.userAgentData' 'false' "status keeps userAgentData disabled at light"
+ assert_json_eq "$RESULT" '.capabilities.iframeIsolation' 'false' "status keeps iframe isolation disabled at light"
+ assert_json_eq "$RESULT" '.capabilities.errorStackSanitized' 'false' "status keeps stack sanitization disabled at light"
+ assert_json_eq "$RESULT" '.capabilities.functionToStringMasked' 'false' "status keeps toString masking disabled at light"
+ assert_json_eq "$RESULT" '.capabilities.functionToStringNative' 'true' "status keeps native Function.prototype.toString at light"
else
- assert_json_eq "$RESULT" '.result' 'true' "userAgentData.brands exists"
+ assert_json_eq "$RESULT" '.capabilities.userAgentData' 'true' "status enables userAgentData at medium+"
+ if [ "$STEALTH_LEVEL" = "medium" ]; then
+ assert_json_eq "$RESULT" '.capabilities.iframeIsolation' 'true' "status enables iframe isolation at medium"
+ else
+ assert_json_eq "$RESULT" '.capabilities.iframeIsolation' 'false' "status keeps iframe isolation disabled at full"
+ fi
+ assert_json_eq "$RESULT" '.capabilities.errorStackSanitized' 'false' "status keeps stack sanitization disabled at medium+"
+ assert_json_eq "$RESULT" '.capabilities.functionToStringMasked' 'false' "status keeps toString masking disabled at medium+"
+ assert_json_eq "$RESULT" '.capabilities.functionToStringNative' 'true' "status keeps native Function.prototype.toString at medium+"
fi
+ assert_json_eq "$RESULT" '.capabilities.intlLocaleCoherent' 'true' "status reports locale coherence"
+ assert_json_eq "$RESULT" '.capabilities.errorPrepareStackTraceNative' 'true' "status reports native Error.prepareStackTrace semantics"
+ assert_json_eq "$RESULT" '.capabilities.navigatorOverridesAbsent' 'true' "status reports no navigator own-property overrides"
end_test
start_test "stealth-levels: [medium] chrome.runtime.connect exists"
pt_post /evaluate '{"expression":"typeof window.chrome.runtime.connect === \"function\""}'
- if [ "$STEALTH_LEVEL" = "light" ]; then
- assert_json_eq "$RESULT" '.result' 'false' "connect not spoofed at light"
- else
- assert_json_eq "$RESULT" '.result' 'true' "connect exists at medium+"
- fi
- end_test
-
- start_test "stealth-levels: [medium] chrome.csi exists"
- pt_post /evaluate '{"expression":"typeof window.chrome.csi === \"function\""}'
- if [ "$STEALTH_LEVEL" = "light" ]; then
- assert_json_eq "$RESULT" '.result' 'false' "csi not spoofed at light"
+ if [ "$STEALTH_LEVEL" = "medium" ]; then
+ assert_json_eq "$RESULT" '.result' 'true' "connect exists at medium"
else
- assert_json_eq "$RESULT" '.result' 'true' "csi exists at medium+"
- fi
- end_test
-
- start_test "stealth-levels: [medium] chrome.loadTimes exists"
- pt_post /evaluate '{"expression":"typeof window.chrome.loadTimes === \"function\""}'
- if [ "$STEALTH_LEVEL" = "light" ]; then
- assert_json_eq "$RESULT" '.result' 'false' "loadTimes not spoofed at light"
- else
- assert_json_eq "$RESULT" '.result' 'true' "loadTimes exists at medium+"
+ assert_json_eq "$RESULT" '.result' 'false' "connect remains absent outside medium"
fi
end_test
@@ -130,7 +137,251 @@ run_stealth_level_matrix() {
assert_json_eq "$RESULT" '.result' 'true' "toDataURL exists"
end_test
+ start_test "stealth-levels: capability fixture reports expected page surface"
+ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-capabilities.html\"}"
+ assert_ok "navigate to capability fixture"
+ sleep 1
+
+ if [ "$STEALTH_LEVEL" = "light" ]; then
+ assert_eval_poll "window.__stealthCapabilities.chromeRuntimeConnect" "false" "connect remains absent at light"
+ assert_eval_poll "window.__stealthCapabilities.iframeIsolation" "false" "iframe isolation remains absent at light"
+ assert_eval_poll "window.__stealthCapabilities.errorStackSanitized" "false" "stack sanitization remains absent at light"
+ assert_eval_poll "window.__stealthCapabilities.functionToStringMasked" "false" "native-looking toString masking remains absent at light"
+ elif [ "$STEALTH_LEVEL" = "medium" ]; then
+ assert_eval_poll "window.__stealthCapabilities.chromeRuntimeConnect" "true" "connect present at medium"
+ assert_eval_poll "window.__stealthCapabilities.iframeIsolation" "true" "iframe isolation present at medium"
+ assert_eval_poll "window.__stealthCapabilities.errorStackSanitized" "false" "stack sanitization remains absent at medium"
+ assert_eval_poll "window.__stealthCapabilities.functionToStringMasked" "false" "native-looking toString masking remains absent at medium"
+ else
+ assert_eval_poll "window.__stealthCapabilities.chromeRuntimeConnect" "false" "connect remains absent at full"
+ assert_eval_poll "window.__stealthCapabilities.iframeIsolation" "false" "iframe isolation remains absent at full"
+ assert_eval_poll "window.__stealthCapabilities.errorStackSanitized" "false" "stack sanitization remains absent at full"
+ assert_eval_poll "window.__stealthCapabilities.functionToStringMasked" "false" "native-looking toString masking remains absent at full"
+ fi
+ assert_eval_poll "window.__stealthCapabilities.functionToStringNative" "true" "Function.prototype.toString remains native-like"
+ assert_eval_poll "window.__stealthCapabilities.webdriverDescriptorNativeLike" "true" "webdriver descriptor getter stays native-like"
+ assert_eval_poll "window.__stealthCapabilities.canPlayTypeNativeLike" "true" "canPlayType remains native-like"
+ assert_eval_poll "window.__stealthCapabilities.canvasToDataURLNativeLike" "true" "canvas toDataURL remains native-like"
+ assert_eval_poll "window.__stealthCapabilities.canvasToBlobNativeLike" "true" "canvas toBlob remains native-like"
+ assert_eval_poll "window.__stealthCapabilities.canvasGetImageDataNativeLike" "true" "canvas getImageData remains native-like"
+ assert_eval_poll "window.__stealthCapabilities.canvasMeasureTextNativeLike" "true" "canvas measureText remains native-like"
+ assert_eval_poll "window.__stealthCapabilities.canvasTransparentPixelPreserved" "true" "transparent canvas pixels stay untouched"
+ assert_eval_poll "window.__stealthCapabilities.webglGetParameterNativeLike" "true" "WebGL getParameter remains native-like"
+ assert_eval_poll "window.__stealthCapabilities.rtcPeerConnectionNativeLike" "true" "RTCPeerConnection stays native-like"
+ assert_eval_poll "window.__stealthCapabilities.audioContextCreateOscillatorNativeLike" "true" "AudioContext.createOscillator stays native-like"
+ assert_eval_poll "window.__stealthCapabilities.getComputedStyleNameNative" "true" "getComputedStyle keeps its native name"
+ assert_eval_poll "window.__stealthCapabilities.matchMediaNameNative" "true" "matchMedia keeps its native name"
+ assert_eval_poll "window.__stealthCapabilities.timeZoneDateCoherent" "true" "resolved timezone matches local Date clock"
+ assert_eval_poll "window.__stealthCapabilities.timeZoneOffsetSane" "true" "timezone offset stays in a sane range"
+ assert_eval_poll "window.__stealthCapabilities.intlLocaleCoherent" "true" "Intl locale family stays coherent"
+ assert_eval_poll "window.__stealthCapabilities.intlDateTimeLocaleCoherent" "true" "Intl.DateTimeFormat locale matches navigator.language"
+ assert_eval_poll "window.__stealthCapabilities.intlNumberLocaleCoherent" "true" "Intl.NumberFormat locale matches navigator.language"
+ assert_eval_poll "window.__stealthCapabilities.errorPrepareStackTraceNative" "true" "Error.prepareStackTrace is not trapped"
+ assert_eval_poll "window.__stealthCapabilities.navigatorOverridesAbsent" "true" "navigator keeps core properties off the instance"
+ assert_eval_poll "window.__stealthCapabilities.userAgentVersionCoherent" "true" "appVersion aligns with the UA version"
+ assert_eval_poll "window.__stealthCapabilities.userAgentDataBrandMajorCoherent" "true" "userAgentData brand major matches UA major"
+ assert_eval_poll "window.__stealthCapabilities.userAgentDataVersionCoherent" "true" "userAgentData versions align with UA major"
+ assert_eval_poll "window.__stealthCapabilities.userAgentDataFullVersionCoherent" "true" "userAgentData full version aligns with the UA version"
+
+ if [ "$STEALTH_LEVEL" = "full" ]; then
+ assert_eval_poll "window.__stealthCapabilities.getComputedStyleNativeLike" "true" "getComputedStyle remains native-like at full"
+ assert_eval_poll "window.__stealthCapabilities.matchMediaNativeLike" "true" "matchMedia remains native-like at full"
+ assert_eval_poll "window.__stealthCapabilities.pluginObjectSemantics" "true" "plugin semantics still coherent at full"
+ assert_eval_poll "window.__stealthCapabilities.webglRendererNoSwiftShader" "true" "WebGL renderer avoids SwiftShader at full"
+ assert_eval_poll "window.__stealthCapabilities.webglRendererPlatformCoherent" "true" "WebGL renderer stays coherent with platform at full"
+ assert_eval_poll "window.__stealthCapabilities.systemColorsResolved" "true" "system colors resolve cleanly at full"
+ assert_eval_poll "window.__stealthCapabilities.screenYDefined" "true" "screenY/screenTop defined at full"
+ fi
+ assert_eval_poll "window.__stealthCapabilities.downlinkMaxPresent" "true" "downlinkMax present in capability fixture"
+ assert_eval_poll "window.__stealthCapabilities.devicePixelRatioPositive" "true" "devicePixelRatio stays positive"
+ assert_eval_poll "window.__stealthCapabilities.screenAvailCoherent" "true" "available screen stays within screen bounds"
+ assert_eval_poll "window.__stealthCapabilities.devtoolsFormattersAbsentByDefault" "true" "page starts without preinstalled devtools formatters"
+ end_test
+
+ start_test "stealth-levels: created tab inherits stealth contract"
+ base_status=""
+ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-capabilities.html\"}"
+ assert_ok "navigate baseline capability tab"
+ base_tab_id=$(echo "$RESULT" | jq -r '.tabId // empty')
+ if [ -n "$base_tab_id" ]; then
+ pt_get "/stealth/status?tabId=${base_tab_id}"
+ base_status="$RESULT"
+ echo "$base_status" | jq -e '.scriptHash and .level' >/dev/null 2>&1
+ if [ $? -eq 0 ]; then
+ echo -e " ${GREEN}✓${NC} baseline tab exposes stealth status"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} baseline tab missing stealth status fields"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+ else
+ echo -e " ${RED}✗${NC} baseline capability tab missing tabId"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-capabilities.html\",\"newTab\":true}"
+ assert_ok "navigate created capability tab"
+ sleep 1
+ created_tab_id=$(echo "$RESULT" | jq -r '.tabId // empty')
+ if [ -n "$created_tab_id" ] && [ -n "$base_status" ]; then
+ pt_get "/stealth/status?tabId=${created_tab_id}"
+ created_status="$RESULT"
+
+ base_level=$(echo "$base_status" | jq -r '.level // empty')
+ created_level=$(echo "$created_status" | jq -r '.level // empty')
+ if [ "$created_level" = "$base_level" ] && [ -n "$created_level" ]; then
+ echo -e " ${GREEN}✓${NC} created tab keeps same stealth level"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} created tab level drifted (${created_level} vs ${base_level})"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ base_hash=$(echo "$base_status" | jq -r '.scriptHash // empty')
+ created_hash=$(echo "$created_status" | jq -r '.scriptHash // empty')
+ if [ "$created_hash" = "$base_hash" ] && [ -n "$created_hash" ]; then
+ echo -e " ${GREEN}✓${NC} created tab keeps same script hash"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} created tab script hash drifted (${created_hash} vs ${base_hash})"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ base_launch_mode=$(echo "$base_status" | jq -r '.launchMode // empty')
+ created_launch_mode=$(echo "$created_status" | jq -r '.launchMode // empty')
+ if [ "$created_launch_mode" = "$base_launch_mode" ] && [ -n "$created_launch_mode" ]; then
+ echo -e " ${GREEN}✓${NC} created tab keeps same launch mode"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} created tab launch mode drifted (${created_launch_mode} vs ${base_launch_mode})"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ pt_post "/tabs/${created_tab_id}/evaluate" '{"expression":"!!window.__stealthCapabilities && window.__stealthCapabilities.webdriverDescriptorNativeLike && window.__stealthCapabilities.userAgentVersionCoherent"}'
+ assert_json_eq "$RESULT" '.result' 'true' "created tab exposes the same capability fixture contract"
+ else
+ echo -e " ${RED}✗${NC} created capability tab missing tabId or baseline status"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+ end_test
+
+ start_test "stealth-levels: restored tab keeps stealth contract"
+ restore_profile_name="stealth-restore-${STEALTH_LEVEL}-$$-$(date +%s)"
+ restore_profile_id=""
+ restore_instance_id=""
+ matrix_hash=$(echo "$MATRIX_STATUS" | jq -r '.scriptHash // empty')
+ matrix_launch_mode=$(echo "$MATRIX_STATUS" | jq -r '.launchMode // empty')
+
+ pt_post /profiles "{\"name\":\"${restore_profile_name}\"}"
+ assert_ok "create restore profile"
+ restore_profile_id=$(echo "$RESULT" | jq -r '.id // empty')
+
+ if [ -n "$restore_profile_id" ]; then
+ pt_post "/profiles/${restore_profile_id}/start" '{"headless":true}'
+ assert_http_status "201" "start restore profile instance"
+ restore_instance_id=$(echo "$RESULT" | jq -r '.id // empty')
+
+ if [ -n "$restore_instance_id" ] && wait_for_orchestrator_instance_status "${E2E_SERVER}" "${restore_instance_id}" "running" 30; then
+ echo -e " ${GREEN}✓${NC} restore profile instance reached running"
+ ((ASSERTIONS_PASSED++)) || true
+ pt_post "/instances/${restore_instance_id}/tabs/open" "{\"url\":\"${FIXTURES_URL}/stealth-capabilities.html\"}"
+ assert_ok "open tab on restore profile instance"
+ sleep 1
+
+ pt_post "/profiles/${restore_profile_id}/stop" '{}'
+ assert_ok "stop restore profile instance"
+ wait_for_instances_gone "${E2E_SERVER}" 15 "${restore_instance_id}" || true
+
+ pt_post "/profiles/${restore_profile_id}/start" '{"headless":true}'
+ assert_http_status "201" "restart restore profile instance"
+ restore_instance_id=$(echo "$RESULT" | jq -r '.id // empty')
+
+ if [ -n "$restore_instance_id" ] && wait_for_orchestrator_instance_status "${E2E_SERVER}" "${restore_instance_id}" "running" 30; then
+ restored_tab_id=$(poll_instance_tab_id_by_url "${restore_instance_id}" "${FIXTURES_URL}/stealth-capabilities.html" 30 0.5)
+ if [ -n "${restored_tab_id:-}" ]; then
+ echo -e " ${GREEN}✓${NC} restored tab reappeared after restart"
+ ((ASSERTIONS_PASSED++)) || true
+ pt_get "/stealth/status?tabId=${restored_tab_id}"
+ restored_status="$RESULT"
+
+ restored_level=$(echo "$restored_status" | jq -r '.level // empty')
+ restored_hash=$(echo "$restored_status" | jq -r '.scriptHash // empty')
+ restored_launch_mode=$(echo "$restored_status" | jq -r '.launchMode // empty')
+
+ if [ "$restored_level" = "$STEALTH_LEVEL" ] && [ -n "$restored_level" ]; then
+ echo -e " ${GREEN}✓${NC} restored tab keeps same stealth level"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} restored tab level drifted (${restored_level} vs ${STEALTH_LEVEL})"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ if [ "$restored_hash" = "$matrix_hash" ] && [ -n "$restored_hash" ]; then
+ echo -e " ${GREEN}✓${NC} restored tab keeps same script hash"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} restored tab script hash drifted (${restored_hash} vs ${matrix_hash})"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ if [ "$restored_launch_mode" = "$matrix_launch_mode" ] && [ -n "$restored_launch_mode" ]; then
+ echo -e " ${GREEN}✓${NC} restored tab keeps same launch mode"
+ ((ASSERTIONS_PASSED++)) || true
+ else
+ echo -e " ${RED}✗${NC} restored tab launch mode drifted (${restored_launch_mode} vs ${matrix_launch_mode})"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ assert_eval_poll "!!window.__stealthCapabilities && window.__stealthCapabilities.webdriverDescriptorNativeLike && window.__stealthCapabilities.userAgentVersionCoherent" "true" "restored tab exposes the same capability fixture contract" 10 0.5 "${restored_tab_id}"
+ else
+ echo -e " ${RED}✗${NC} restored tab did not reappear after restart"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+ else
+ echo -e " ${RED}✗${NC} restore profile instance failed to restart"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+ else
+ echo -e " ${RED}✗${NC} restore profile instance failed to reach running"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+
+ if [ -n "$restore_instance_id" ]; then
+ pt_post "/profiles/${restore_profile_id}/stop" '{}' >/dev/null 2>&1 || true
+ fi
+ pt_delete "/profiles/${restore_profile_id}" >/dev/null 2>&1 || true
+ else
+ echo -e " ${RED}✗${NC} restore profile creation did not return an id"
+ ((ASSERTIONS_FAILED++)) || true
+ fi
+ end_test
+
+ start_test "stealth-levels: local devtools probe stays quiet"
+ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-devtools-probe.html\"}"
+ assert_ok "navigate to devtools probe fixture"
+ sleep 2
+ assert_eval_poll "!!window.__stealthDevtoolsProbe && window.__stealthDevtoolsProbe.ready" "true" "devtools probe report ready"
+ assert_eval_poll "window.__stealthDevtoolsProbe.initialFormattersLen" "0" "page starts without preinstalled devtools formatters"
+ assert_eval_poll "window.__stealthDevtoolsProbe.formatterCalled" "false" "console formatter probe stays untouched"
+ assert_eval_poll "window.__stealthDevtoolsProbe.getterCalled" "false" "console getter probe stays untouched"
+ assert_eval_poll "window.__stealthDevtoolsProbe.stackGetterCalls <= 1" "true" "error stack getter stays within baseline console access"
+ end_test
+
+ start_test "stealth-levels: worker parity fixture stays coherent"
+ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/stealth-workers.html\"}"
+ assert_ok "navigate to worker parity fixture"
+ sleep 1
+ assert_eval_poll "!!window.__stealthWorkerReport && window.__stealthWorkerReport.ready" "true" "worker report ready"
+ assert_eval_poll "window.__stealthWorkerReport.matches.userAgent" "true" "worker userAgent matches page"
+ assert_eval_poll "window.__stealthWorkerReport.matches.platform" "true" "worker platform matches page"
+ assert_eval_poll "window.__stealthWorkerReport.matches.hardwareConcurrency" "true" "worker hardwareConcurrency matches page"
+ assert_eval_poll "window.__stealthWorkerReport.matches.deviceMemory" "true" "worker deviceMemory matches page"
+ end_test
+
start_test "stealth-levels: comprehensive score at ${STEALTH_LEVEL} level"
+ pt_post /navigate "{\"url\":\"${FIXTURES_URL}/bot-detect.html\"}"
+ assert_ok "navigate back to bot-detect fixture"
+ sleep 1
pt_post /evaluate '{"expression":"JSON.stringify(window.__botDetectScore || {})"}'
score_json=$(echo "$RESULT" | jq -r '.result // "{}"')
critical_passed=$(echo "$score_json" | jq -r '.critical // 0')
@@ -150,14 +401,34 @@ run_stealth_level_matrix() {
;;
esac
- echo -e " ${GREEN}✓${NC} score meets ${STEALTH_LEVEL} level expectations"
+ if [ "$ASSERTIONS_FAILED" -eq 0 ]; then
+ echo -e " ${GREEN}✓${NC} score meets ${STEALTH_LEVEL} level expectations"
+ else
+ echo -e " ${RED}✗${NC} score below ${STEALTH_LEVEL} level expectations"
+ fi
end_test
E2E_SERVER="$ORIG_URL"
}
if [ "${STEALTH_MATRIX:-0}" = "1" ]; then
- run_stealth_level_matrix
+ matrix_levels=()
+ if [ -n "${STEALTH_LEVEL:-}" ]; then
+ matrix_levels=("${STEALTH_LEVEL}")
+ else
+ matrix_levels=(light medium full)
+ fi
+
+ original_level="${STEALTH_LEVEL:-}"
+ for matrix_level in "${matrix_levels[@]}"; do
+ STEALTH_LEVEL="${matrix_level}"
+ run_stealth_level_matrix
+ done
+ if [ -n "${original_level}" ]; then
+ STEALTH_LEVEL="${original_level}"
+ else
+ unset STEALTH_LEVEL
+ fi
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
print_summary
fi
@@ -192,10 +463,10 @@ assert_json_eq "$RESULT" '.result' 'true' "hardwareConcurrency >= 2"
end_test
-start_test "bot-detect-full: device memory exists"
+start_test "bot-detect-full: device memory shape acceptable"
-pt_post /evaluate '{"expression":"navigator.deviceMemory > 0"}'
-assert_json_eq "$RESULT" '.result' 'true' "deviceMemory > 0"
+pt_post /evaluate '{"expression":"navigator.deviceMemory === undefined || navigator.deviceMemory > 0"}'
+assert_json_eq "$RESULT" '.result' 'true' "deviceMemory is absent or > 0"
end_test
@@ -248,16 +519,6 @@ if [ -n "$FULL_URL" ]; then
end_test
- start_test "bot-detect-full: permissive full legacy shims are present"
-
- pt_post /evaluate '{"expression":"typeof window.chrome.csi === \"function\""}'
- assert_json_eq "$RESULT" '.result' 'true' "chrome.csi exists"
-
- pt_post /evaluate '{"expression":"typeof window.chrome.loadTimes === \"function\""}'
- assert_json_eq "$RESULT" '.result' 'true' "chrome.loadTimes exists"
-
- end_test
-
start_test "bot-detect-full: WebGL not SwiftShader (full stealth spoofs GPU)"
pt_post /evaluate '{"expression":"(() => { try { const c = document.createElement(\"canvas\"); const gl = c.getContext(\"webgl\"); const d = gl.getExtension(\"WEBGL_debug_renderer_info\"); return gl.getParameter(d.UNMASKED_RENDERER_WEBGL).toLowerCase().includes(\"swiftshader\"); } catch(e) { return false; } })()"}'
diff --git a/tests/e2e/scenarios-cli/stealth-basic.sh b/tests/e2e/scenarios-cli/stealth-basic.sh
index 7bf5986a..f372173a 100644
--- a/tests/e2e/scenarios-cli/stealth-basic.sh
+++ b/tests/e2e/scenarios-cli/stealth-basic.sh
@@ -47,6 +47,48 @@ assert_json_field '.result' 'true' "chrome.runtime"
end_test
+# ─────────────────────────────────────────────────────────────────────────────
+start_test "stealth-cli: capability fixture reports native webdriver contract"
+
+pt_ok nav "${FIXTURES_URL}/stealth-capabilities.html"
+sleep 1
+
+pt_ok eval "window.__stealthCapabilities.webdriverDescriptorNativeLike"
+assert_json_field '.result' 'true' "webdriver descriptor stays native-like"
+
+pt_ok eval "window.__stealthCapabilities.userAgentVersionCoherent"
+assert_json_field '.result' 'true' "user agent version remains coherent"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────────────────
+start_test "stealth-cli: created tab keeps stealth capability contract"
+
+pt_ok tab new
+assert_output_json "tab new returns JSON"
+TAB_ID=$(echo "$PT_OUT" | jq -r '.tabId // empty')
+
+if [ -n "$TAB_ID" ]; then
+ echo -e " ${GREEN}✓${NC} created tab returned id"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} created tab did not return id"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+pt_ok nav "${FIXTURES_URL}/stealth-capabilities.html" --tab "$TAB_ID"
+sleep 1
+
+pt_ok eval "window.__stealthCapabilities.webdriverDescriptorNativeLike" --tab "$TAB_ID"
+assert_json_field '.result' 'true' "created tab keeps native webdriver descriptor"
+
+pt_ok eval "window.__stealthCapabilities.intlLocaleCoherent" --tab "$TAB_ID"
+assert_json_field '.result' 'true' "created tab keeps locale coherence"
+
+pt_ok tab close "$TAB_ID"
+
+end_test
+
# ─────────────────────────────────────────────────────────────────────────────
start_test "bot-detect-cli: full test suite score"
diff --git a/tests/manual/stealth-check.md b/tests/manual/stealth-check.md
new file mode 100644
index 00000000..7f9a2317
--- /dev/null
+++ b/tests/manual/stealth-check.md
@@ -0,0 +1,519 @@
+# Manual Stealth Checks
+
+## Purpose
+
+This document records how to manually validate PinchTab stealth on public anti-bot and fingerprint sites.
+
+It is not a replacement for e2e tests.
+
+Use it to answer different questions:
+
+- how does a third-party detection site classify the current runtime?
+- which public sites are useful gates?
+- which public sites are better used as debugging labs?
+
+Current baseline observations in this document were collected on March 23, 2026 with `full` stealth in both headless and headed runs.
+
+Service-worker stealth parity is manual-only. The automated E2E suites no longer provision a localhost secure-context fixture path for it.
+
+## Environment Used
+
+Baseline headless run:
+
+- local server on `127.0.0.1:9988`
+- `full` stealth enabled
+- headless browser
+- manual page navigation through the local API
+- visible page text extracted with `/evaluate`
+
+Headed recheck:
+
+- local server on `127.0.0.1:9988`
+- `full` stealth enabled
+- headed browser
+- manual page navigation through the local API
+- visible page text extracted with `/evaluate`
+
+Important headed note:
+
+- verify `/stealth/status` actually reports `headless = false` before trusting the run
+
+Important environment notes:
+
+- host timezone during the sweep was `Europe/Rome`
+- several sites geolocated the network to Germany / Frankfurt
+- IP and DNS outputs varied across sites
+- some site findings are therefore environment-sensitive
+
+## Start The Local Server
+
+Build:
+
+```bash
+go build -o ./pinchtab ./cmd/pinchtab
+```
+
+Run:
+
+```bash
+PINCHTAB_CONFIG=/tmp/pinchtab-live-full.json ./pinchtab server
+```
+
+Verify the runtime contract:
+
+```bash
+curl -sf -H 'Authorization: Bearer live-test-token' \
+ http://127.0.0.1:9988/stealth/status
+```
+
+Expected for this manual suite:
+
+- `level = full`
+- `launchMode = allocator`
+- `webdriverMode = native_baseline`
+
+## Generic Manual Flow
+
+1. Navigate to the public site.
+
+```bash
+curl -sf -H 'Authorization: Bearer live-test-token' \
+ -H 'Content-Type: application/json' \
+ http://127.0.0.1:9988/navigate \
+ -d '{"url":"https://example.com"}'
+```
+
+2. Wait for the page to settle.
+
+Typical waits:
+
+- 5 seconds for most sites
+- 6 to 7 seconds for heavier pages such as CreepJS or AmiUnique
+
+3. Extract the visible page text.
+
+```bash
+curl -sf -H 'Authorization: Bearer live-test-token' \
+ -H 'Content-Type: application/json' \
+ http://127.0.0.1:9988/evaluate \
+ -d '{"expression":"JSON.stringify({title:document.title,body:document.body.innerText.slice(0,6000)})"}'
+```
+
+4. If the site is a debugging lab rather than a one-page verdict, inspect targeted values with additional `evaluate` calls.
+
+## Secure-Context Manual Checks
+
+Service workers require a secure context. Use one of these when you want to validate service-worker stealth manually:
+
+- `https://...` on an origin you control
+- `http://localhost`
+- `http://127.0.0.1`
+
+Recommended manual fixture:
+
+- `/Users/luigi/dev/prj/pinchtab/pinchtab/tests/e2e/fixtures/stealth-service-worker.html`
+
+What to verify:
+
+- the report becomes `ready`
+- `webdriver` remains hidden or `false`
+- service-worker `userAgent` matches the page
+- service-worker `platform` matches the page
+- service-worker `hardwareConcurrency` matches the page
+- service-worker `deviceMemory` matches the page
+
+## Sites We Tested
+
+### Pixelscan
+
+URL:
+
+- `https://pixelscan.net/bot-check`
+
+Wait:
+
+- 5 seconds
+
+What to record:
+
+- overall `Bot Behavior Detected` or not
+- top cards
+- detailed rows for:
+ - `TamperedFunctions`
+ - `IsDevtoolOpen`
+ - `NavigatorWebdriver`
+ - `ChromeDriverSignature`
+ - `HeadlessChrome`
+
+Current baseline:
+
+- still fails
+- summary shows `Webdriver Detected` and `CDP Detected`
+- detailed rows still show `TamperedFunctions Detected` and `IsDevtoolOpen Detected`
+
+Headed recheck:
+
+- no material improvement
+- still showed `Bot Behavior Detected`
+- detailed rows still showed `TamperedFunctions Detected` and `IsDevtoolOpen Detected`
+
+Important note:
+
+- use the detailed rows, not only the top summary cards
+
+### Bot.Sannysoft
+
+URL:
+
+- `https://bot.sannysoft.com/`
+
+Wait:
+
+- 5 seconds
+
+What to record:
+
+- `WebDriver`
+- `WebDriver Advanced`
+- plugin presence
+- languages
+- WebGL vendor / renderer
+- permission state
+
+Current baseline:
+
+- passes WebDriver and WebDriver Advanced
+- good smoke test
+- too forgiving to use as the main gate
+
+### BrowserLeaks
+
+Recommended URLs:
+
+- `https://browserleaks.com/javascript`
+- `https://browserleaks.com/webrtc`
+- `https://browserleaks.com/canvas`
+- `https://browserleaks.com/webgl`
+
+Do not rely on:
+
+- `https://browserleaks.com/` homepage alone
+
+Wait:
+
+- 5 seconds
+
+What to record on `javascript`:
+
+- `webdriver`
+- `userAgentData`
+- plugins
+- network information
+- timezone
+- locale
+- audio and speech synthesis exposure
+
+Current baseline on `javascript`:
+
+- no direct pass/fail verdict
+- useful raw collector page
+- current run showed `webdriver false`, populated `userAgentData`, PDF viewer plugins, `Europe/Rome` timezone, and a visible network info block
+
+### Whoer
+
+URL:
+
+- `https://whoer.net/`
+
+Wait:
+
+- 6 seconds
+
+What to record:
+
+- `Your disguise` percentage
+- proxy / anonymizer / blacklist sections
+- browser and OS summary
+- IP and timezone sections
+
+Current baseline:
+
+- `Your disguise: 100%`
+- did not classify the setup as suspicious
+
+Important note:
+
+- useful for coarse anonymity checks
+- too lenient to gate browser stealth work
+
+### IPHey
+
+URL:
+
+- `https://iphey.com/`
+
+Wait:
+
+- 6 seconds
+
+What to record:
+
+- overall verdict
+- location finding
+- hardware finding
+- software finding
+- any remote / VNC / local-network anomaly callouts
+
+Current baseline:
+
+- `Your digital identity looks Unreliable`
+- flagged:
+ - `Local network anomaly detected: Virtual Network Computing (VNC)`
+ - `Looks like you're trying to hide your location`
+ - `It seems you are masking your fingerprint`
+
+Important note:
+
+- useful for realism pressure
+- mixes browser stealth with host environment artifacts
+
+### CreepJS
+
+URL:
+
+- `https://creepjs.org/`
+
+Wait:
+
+- 6 seconds
+
+What to record:
+
+- fingerprint ID
+- coverage
+- WebGL / GPU values
+- platform
+- language
+- screen resolution
+- timezone
+- locale
+- font and speech synthesis counts
+
+Current baseline:
+
+- provides rich fingerprint introspection
+- no simple anti-bot pass/fail verdict
+
+Use it for:
+
+- explaining differences after a stealth change
+- comparing collector-level outputs across runs
+
+### AmIUnique
+
+Use:
+
+- `https://amiunique.org/fingerprint`
+
+Do not use only:
+
+- `https://amiunique.org/` homepage
+
+Wait:
+
+- 7 seconds
+
+What to record:
+
+- HTTP headers section
+- JavaScript attributes section
+- plugins
+- permissions
+- WebGL vendor / renderer
+- screen values
+- audio and codec sections
+
+Current baseline:
+
+- useful collector page
+- no anti-bot verdict
+
+### FV.pro
+
+URL:
+
+- `https://fv.pro/check-privacy/general`
+
+Wait:
+
+- 6 seconds
+
+What to record:
+
+- browser score
+- fraud score
+- summary mismatches
+- platform / browser / videocard / language / resolution / timezone
+
+Current baseline:
+
+- `Browser 0%`
+- `FP similarity 7%`
+- explicitly flagged:
+ - `Your screen is not real`
+
+Headed recheck:
+
+- `Browser 15%`
+- `FP similarity 7%`
+- still explicitly flagged:
+ - `Your screen is not real`
+
+### Botchecker
+
+URL:
+
+- `https://botchecker.net/`
+
+Wait:
+
+- 6 seconds
+
+Current baseline:
+
+- site reported that the service was temporarily unavailable
+
+Rule:
+
+- do not use as a gate until the site is operational again
+
+### BrowserScan
+
+URL:
+
+- `https://www.browserscan.net/`
+
+Wait:
+
+- 6 seconds
+
+What to record:
+
+- `Bot Detection`
+- `Browser fingerprint authenticity`
+- penalty list
+- IP timezone
+- JavaScript timezone
+- browser and browser version
+- canvas / WebGL related notes
+
+Current baseline:
+
+- `Bot Detection: No`
+- `Browser fingerprint authenticity: 67%`
+- penalties:
+ - `Different time zones`
+ - `WebGL exception`
+ - `IP addresses are different`
+ - `DNS Leak`
+ - `Different browser version`
+
+Headed recheck:
+
+- `Bot Detection: No`
+- `Browser fingerprint authenticity: 67%`
+- penalties:
+ - `Different time zones`
+ - `WebGL exception`
+ - `IP addresses are different`
+ - `DNS Leak`
+ - `Different browser version`
+
+Important notes:
+
+- in the headed recheck, `Canvas Tampering` disappeared, but the main coherence issues remained
+- this is one of the most useful public consistency checks in the current set
+
+## Recommended Gate Order
+
+Use these as the main external gates:
+
+1. `pixelscan.net/bot-check`
+2. `fv.pro/check-privacy/general`
+3. `www.browserscan.net`
+4. `iphey.com`
+5. `bot.sannysoft.com`
+
+Use these as debugging labs:
+
+- `browserleaks.com/javascript`
+- `browserleaks.com/webrtc`
+- `browserleaks.com/canvas`
+- `browserleaks.com/webgl`
+- `creepjs.org`
+- `amiunique.org/fingerprint`
+
+Use these only as supporting context:
+
+- `whoer.net`
+
+Skip for now:
+
+- `botchecker.net`
+
+## What To Capture In Every Manual Run
+
+For every site checked, store:
+
+- date
+- stealth level
+- launch mode
+- headless or headed
+- site URL
+- short verdict
+- exact detection strings
+- whether the issue looks like:
+ - browser surface
+ - CDP / devtools
+ - environment / network
+
+## Interpreting Failures
+
+If a site flags:
+
+- `TamperedFunctions`
+ - suspect JS patching, especially canvas, graphics, or wrapped platform APIs
+- `IsDevtoolOpen` or `CDP`
+ - suspect active CDP / listener behavior, not only `navigator.webdriver`
+- `Different time zones`
+ - compare JS timezone, locale, IP geography, and persona settings
+- `Different browser version`
+ - verify that UA and client hints exactly match the running browser version
+- `canvas not real` or `Canvas Tampering`
+ - inspect graphics noise and readback hooks
+- `screen not real`
+ - inspect window / screen metric realism
+- `VNC` or local-network anomaly
+ - treat as environment-sensitive until reproduced on a clean host
+
+## Current Baseline Summary
+
+As of March 23, 2026:
+
+- strong passes:
+ - Sannysoft
+ - Whoer
+- mixed:
+ - BrowserScan
+- headed recheck improved BrowserScan only slightly
+- strong failures:
+ - Pixelscan
+ - FV.pro
+ - IPHey
+- headed recheck did not clear Pixelscan and only marginally improved FV.pro
+- labs without a direct pass/fail:
+ - CreepJS
+ - BrowserLeaks
+ - AmIUnique
+- unavailable:
+ - Botchecker