package app import ( "crypto/sha256" "encoding/binary" "fmt" "log/slog" "os/exec" "regexp" "runtime" "strings" "sync" ) // chromeVersion identifies the browser being driven by its major version, which // is all the user agent needs. type chromeVersion struct { major string } // pinnedChromeVersion is the cloaking fallback when no browser binary can be // probed. It matches the pinned version used by the reference implementation. var pinnedChromeVersion = chromeVersion{major: "150"} // chromeVersionCandidates are tried in order when BROWSER_PATH is unset or // cannot be executed. The Linux entries are the ones that matter in // containers and on servers, where the service actually runs. var chromeVersionCandidates = []string{ "chromium", "chromium-browser", "google-chrome", "google-chrome-stable", } var chromeVersionPattern = regexp.MustCompile(`\d+(?:\.\d+)*`) var ( chromeVersionMu sync.Mutex chromeVersionCache = map[string]chromeVersion{} ) // probeChromeVersion reports the version of the configured browser, falling // back to a pinned version when nothing can be executed. The answer for a // given path cannot change while the process runs and probing spawns a // process, so results are cached per path. func probeChromeVersion(path string) chromeVersion { chromeVersionMu.Lock() defer chromeVersionMu.Unlock() if cached, ok := chromeVersionCache[path]; ok { return cached } detected := detectChromeVersion(path) chromeVersionCache[path] = detected return detected } func detectChromeVersion(path string) chromeVersion { var candidates []string if path != "" { candidates = append(candidates, path) } candidates = append(candidates, chromeVersionCandidates...) for _, candidate := range candidates { out, err := exec.Command(candidate, "--version").Output() if err != nil { continue } if found := chromeVersionPattern.FindString(string(out)); found != "" { major, _, _ := strings.Cut(found, ".") return chromeVersion{major: major} } } // Cloaking as a version the browser is not is worse than saying nothing, // so make the degraded case visible. slog.Warn("could not probe the browser version; falling back to pinned Chrome cloaking", "browser_path", path, "pinned_major", pinnedChromeVersion.major) return pinnedChromeVersion } // browserIdentity is the platform shape this service presents to pages. // // It follows the host the browser actually runs on. Claiming a different // platform than the host is what bot detection looks for: an Apple GPU, Mac // fonts, and a macOS TLS fingerprint alongside a Linux user agent describe a // machine that cannot exist. The stealth Chromium builds handle this the same // way, running macOS as a native Mac browser rather than spoofing one. type browserIdentity struct { userAgent string // template; %s is the Chrome major version platform string // navigator.platform spoofGPU bool // replace the WebGL vendor and renderer strings } func hostIdentity() browserIdentity { switch runtime.GOOS { case "darwin": // Headless Chrome on macOS already reports the machine's real Apple // GPU, so the WebGL strings are left alone here. return browserIdentity{ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.0.0 Safari/537.36", platform: "MacIntel", } case "windows": return browserIdentity{ userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.0.0 Safari/537.36", platform: "Win32", spoofGPU: true, } default: return browserIdentity{ userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s.0.0.0 Safari/537.36", platform: "Linux x86_64", spoofGPU: true, } } } // chromeUserAgent is the host's Chrome user agent with the probed major // version, so the browser does not announce itself as HeadlessChrome. func chromeUserAgent(v chromeVersion) string { return fmt.Sprintf(hostIdentity().userAgent, v.major) } // windowSize derives a viewport that is stable for a URL but varies between // them, so every request is not rendered at one machine-identifiable size. func windowSize(raw string) (width, height int) { sum := sha256.Sum256([]byte(raw)) seed := binary.BigEndian.Uint64(sum[:8]) return 1200 + int(seed%160), 800 + int((seed>>8)%160) } // stealthScriptHead is the platform-neutral part of the script injected into // every new document before any page script runs. It removes the automation // fingerprints that bot detection reads directly, and makes every patch // stringify like a native implementation so Function.prototype.toString cannot // reveal it. // // Each section is isolated: this executes in the context of arbitrary, // untrusted pages, and one failing patch must never break the rest. const stealthScriptHead = ` (() => { // Make overridden functions stringify like native implementations; // Function.prototype.toString is the standard bot-detection tell. const nativeToString = Function.prototype.toString; const spoofedSources = new WeakMap(); const asNative = (fn, source) => { spoofedSources.set(fn, source); return fn; }; const nativeGetter = (name) => 'function get ' + name + '() { [native code] }'; const nativeFunc = (name) => 'function ' + name + '() { [native code] }'; Function.prototype.toString = asNative(function toString() { const spoofed = spoofedSources.get(this); return spoofed !== undefined ? spoofed : nativeToString.call(this); }, 'function toString() { [native code] }'); const define = (object, prop, descriptor) => { try { Object.defineProperty(object, prop, { configurable: true, ...descriptor }); } catch (_) {} }; // navigator.webdriver is true under automation; real Chrome exposes false. define(Navigator.prototype, 'webdriver', { get: asNative(() => false, nativeGetter('webdriver')), }); define(Navigator.prototype, 'vendor', { get: asNative(() => 'Google Inc.', nativeGetter('vendor')), }); define(Navigator.prototype, 'languages', { get: asNative(() => ['en-US', 'en'], nativeGetter('languages')), }); // Plugin list: empty under automation, five PDF-related entries in real // Chrome. Mid-fidelity PluginArray with named access and iteration. try { const mimeTypesData = [ { type: 'application/pdf', suffixes: 'pdf', description: '' }, { type: 'text/pdf', suffixes: 'pdf', description: '' }, ]; const pluginsData = [ ['PDF Viewer', 'Portable Document Format', 'internal-pdf-viewer'], ['Chrome PDF Viewer', 'Portable Document Format', 'internal-pdf-viewer'], ['Chromium PDF Viewer', 'Portable Document Format', 'internal-pdf-viewer'], ['Microsoft Edge PDF Viewer', 'Portable Document Format', 'internal-pdf-viewer'], ['WebKit built-in PDF', 'Portable Document Format', 'internal-pdf-viewer'], ]; const mimeTypes = mimeTypesData.map((m) => { const mt = { ...m, enabledPlugin: null }; mt.enabledPlugin = mt; return mt; }); const plugins = pluginsData.map(([name, description, filename]) => { const plugin = { name, description, filename, length: mimeTypes.length, item: (i) => mimeTypes[i] || null, namedItem: (n) => mimeTypes.find((m) => m.type === n) || null, }; mimeTypes.forEach((m, i) => { plugin[i] = m; plugin[m.type] = m; }); return plugin; }); const pluginArray = { length: plugins.length, item: asNative((i) => plugins[i] || null, nativeFunc('item')), namedItem: asNative((n) => plugins.find((p) => p.name === n) || null, nativeFunc('namedItem')), refresh: asNative(() => undefined, nativeFunc('refresh')), [Symbol.iterator]: function* () { yield* plugins; }, }; plugins.forEach((p, i) => { pluginArray[i] = p; pluginArray[p.name] = p; }); define(Navigator.prototype, 'plugins', { get: asNative(() => pluginArray, nativeGetter('plugins')) }); const mimeTypeArray = { length: mimeTypes.length, item: asNative((i) => mimeTypes[i] || null, nativeFunc('item')), namedItem: asNative((n) => mimeTypes.find((m) => m.type === n) || null, nativeFunc('namedItem')), [Symbol.iterator]: function* () { yield* mimeTypes; }, }; define(Navigator.prototype, 'mimeTypes', { get: asNative(() => mimeTypeArray, nativeGetter('mimeTypes')) }); } catch (_) {} // window.chrome with the surface feature-detection scripts probe. try { if (!window.chrome) window.chrome = {}; 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: asNative(() => null, nativeFunc('getDetails')), getIsInstalled: asNative(() => false, nativeFunc('getIsInstalled')), installState: asNative((cb) => cb('not_installed'), nativeFunc('installState')), runningState: asNative(() => 'cannot_run', nativeFunc('runningState')), }; window.chrome.runtime = window.chrome.runtime || { OnInstalledReason: { CHROME_UPDATE: 'chrome_update', INSTALL: 'install', SHARED_MODULE_UPDATE: 'shared_module_update', UPDATE: 'update' }, OnRestartRequiredReason: { APP_UPDATE: 'app_update', OS_UPDATE: 'os_update', PERIODIC: 'periodic' }, PlatformArch: { ARM: 'arm', ARM64: 'arm64', MIPS: 'mips', MIPS64: 'mips64', X86_32: 'x86-32', X86_64: 'x86-64' }, PlatformNaclArch: { ARM: 'arm', MIPS: 'mips', MIPS64: 'mips64', X86_32: 'x86-32', X86_64: 'x86-64' }, PlatformOs: { ANDROID: 'android', CROS: 'cros', FUCHSIA: 'fuchsia', LINUX: 'linux', MAC: 'mac', OPENBSD: 'openbsd', WIN: 'win' }, RequestUpdateCheckStatus: { NO_UPDATE: 'no_update', THROTTLED: 'throttled', UPDATE_AVAILABLE: 'update_available' }, connect: asNative(() => { throw new Error('Could not establish connection.'); }, nativeFunc('connect')), sendMessage: asNative(() => { throw new Error('Could not establish connection.'); }, nativeFunc('sendMessage')), id: undefined, }; window.chrome.csi = window.chrome.csi || asNative(function csi() { const now = Date.now(); return { onloadT: now, pageT: 400 + Math.random() * 800, startE: now - 500, tran: 15 }; }, nativeFunc('csi')); window.chrome.loadTimes = window.chrome.loadTimes || asNative(function loadTimes() { const now = Date.now() / 1000; return { commitLoadTime: now - 0.4, connectionInfo: 'h2', finishDocumentLoadTime: now, finishLoadTime: now + 0.1, firstPaintAfterLoadTime: 0, firstPaintTime: now - 0.2, navigationType: 'Other', npnNegotiatedProtocol: 'h2', requestTime: now - 0.6, startLoadTime: now - 0.6, wasAlternateProtocolAvailable: false, wasFetchedViaSpdy: true, wasNpnNegotiated: true, }; }, nativeFunc('loadTimes')); } catch (_) {} // Notification permission query must agree with Notification.permission. try { const originalQuery = window.Permissions && window.Permissions.prototype.query; if (originalQuery) { window.Permissions.prototype.query = asNative(function query(parameters) { if (parameters && parameters.name === 'notifications') { return Promise.resolve({ state: Notification.permission, onchange: null, addEventListener() {}, removeEventListener() {}, removeListener() {}, addListener() {}, dispatchEvent: () => false, }); } return originalQuery.call(this, parameters); }, nativeFunc('query')); } } catch (_) {} ` // stealthGPUPatches replace the WebGL vendor and renderer strings. Headless // Linux and Windows render through SwiftShader, whose renderer string no real // user browser produces, so it is replaced with a common desktop adapter. // // This is deliberately not applied on macOS, where headless Chrome already // reports the machine's real Apple GPU and claiming Intel graphics would // contradict every other signal the page can read. const stealthGPUPatches = ` try { const patchGetParameter = (proto) => { if (!proto) return; const original = proto.getParameter; proto.getParameter = asNative(function getParameter(parameter) { if (parameter === 0x9245) return 'Google Inc. (Intel)'; if (parameter === 0x9246) { return 'ANGLE (Intel, Mesa Intel(R) UHD Graphics 630 (CFL GT2), OpenGL 4.6 (Core Profile) Mesa 23.2.1)'; } return original.call(this, parameter); }, nativeFunc('getParameter')); }; patchGetParameter(window.WebGLRenderingContext && window.WebGLRenderingContext.prototype); patchGetParameter(window.WebGL2RenderingContext && window.WebGL2RenderingContext.prototype); } catch (_) {} ` // stealthScriptTail closes the injected script. const stealthScriptTail = ` // Headless windows have no browser chrome; fake sane outer dimensions. define(window, 'outerWidth', { get: asNative(() => window.innerWidth, nativeGetter('outerWidth')) }); define(window, 'outerHeight', { get: asNative(() => window.innerHeight + 85, nativeGetter('outerHeight')) }); })(); ` // stealthSnapshot builds the script to inject for a host identity. func stealthSnapshot(identity browserIdentity) string { if identity.spoofGPU { return stealthScriptHead + stealthGPUPatches + stealthScriptTail } return stealthScriptHead + stealthScriptTail }