Skip to content

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

fix: fingerprint rotate with no os at all is refused, when the host's identity is the obvious answer (PIN-123)

Luigi Agosti1ae4e93197f8
diff --git a/internal/bridge/handler_support.go b/internal/bridge/handler_support.go
index 1a379828..6bcf78c0 100644
--- a/internal/bridge/handler_support.go
+++ b/internal/bridge/handler_support.go
@@ -3,6 +3,7 @@ package bridge
import (
"context"
"fmt"
+ "strings"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/fetch"
@@ -170,7 +171,23 @@ func (b *Bridge) GetRawCookies(ctx context.Context) ([]RawCookie, error) {
return result, nil
}
+// SetUserAgentOverride refuses an empty UserAgent rather than forwarding it. An
+// empty string is not "leave it alone" at the CDP layer: Emulation.setUserAgentOverride
+// applies it, so the tab then advertises an empty navigator.userAgent and sends a
+// blank User-Agent header — louder than whatever it replaced, on the path whose
+// purpose is to be quieter. The guard lives here because this is an exported
+// BridgeAPI method: the implementation is what covers future callers and any other
+// implementation of the interface, not the one handler that calls it today.
+//
+// It does not make an empty override unreachable everywhere: internal/stealth's
+// launch path builds emulation.SetUserAgentOverride(persona.UserAgent) directly. That
+// path needs no guard for a checked reason — BuildPersona reduces the version first
+// and ReducedBrowserVersion falls back, so persona.UserAgent cannot be empty — so do
+// not add a second copy of this check there.
func (b *Bridge) SetUserAgentOverride(ctx context.Context, params UserAgentOverrideParams) error {
+ if strings.TrimSpace(params.UserAgent) == "" {
+ return fmt.Errorf("user agent override must not be empty")
+ }
return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
p := emulation.SetUserAgentOverride(params.UserAgent).WithPlatform(params.Platform)
if params.AcceptLanguage != "" {
diff --git a/internal/bridge/handler_support_test.go b/internal/bridge/handler_support_test.go
new file mode 100644
index 00000000..328057d8
--- /dev/null
+++ b/internal/bridge/handler_support_test.go
@@ -0,0 +1,39 @@
+package bridge
+
+import (
+ "context"
+ "strings"
+ "testing"
+)
+
+// An empty UserAgent is not "leave it alone" at the CDP layer — Emulation applies
+// it, and the tab then advertises an empty navigator.userAgent and sends a blank
+// User-Agent header. The rotate handler wrote this field through without a non-empty
+// check while guarding every other one, so the refusal belongs in the exported
+// BridgeAPI implementation.
+//
+// Both halves matter. The empty case must be refused BEFORE any CDP call, which is
+// why a background context suffices; the non-empty case must get past the guard and
+// fail on the context instead, which is what proves the guard is refusing the value
+// rather than everything.
+func TestSetUserAgentOverrideRefusesAnEmptyUserAgent(t *testing.T) {
+ b := &Bridge{}
+
+ for _, empty := range []string{"", " "} {
+ err := b.SetUserAgentOverride(context.Background(), UserAgentOverrideParams{UserAgent: empty, Platform: "Win32"})
+ if err == nil {
+ t.Fatalf("SetUserAgentOverride(%q) = nil; an empty override blanks navigator.userAgent instead of leaving it alone", empty)
+ }
+ if !strings.Contains(err.Error(), "user agent") {
+ t.Errorf("SetUserAgentOverride(%q) failed with %v, which does not name the argument it refused — the guard is gone and this is the CDP layer failing later", empty, err)
+ }
+ }
+
+ err := b.SetUserAgentOverride(context.Background(), UserAgentOverrideParams{UserAgent: "Mozilla/5.0 probe", Platform: "Win32"})
+ if err == nil {
+ t.Fatal("a non-empty override on a bare context reached CDP and succeeded, so this test cannot tell the guard from the transport")
+ }
+ if strings.Contains(err.Error(), "user agent must not be empty") {
+ t.Errorf("a non-empty override was refused by the empty-value guard: %v", err)
+ }
+}
diff --git a/internal/handlers/stealth.go b/internal/handlers/stealth.go
index b0aa8556..af72e191 100644
--- a/internal/handlers/stealth.go
+++ b/internal/handlers/stealth.go
@@ -145,7 +145,7 @@ func (h *Handlers) fingerprintMatrix() map[string]map[string]fingerprint {
linuxChrome := stealth.ChromeUserAgent(stealth.PlatformLinux, reducedBrowserVersion)
osConfigs := map[string]map[string]fingerprint{
- "windows": {
+ stealth.FingerprintOSWindows: {
"chrome": {
UserAgent: windowsChrome,
Platform: "Win32",
@@ -157,7 +157,7 @@ func (h *Handlers) fingerprintMatrix() map[string]map[string]fingerprint {
Vendor: "Google Inc.",
},
},
- "mac": {
+ stealth.FingerprintOSMac: {
"chrome": {
UserAgent: macChrome,
Platform: "MacIntel",
@@ -174,7 +174,7 @@ func (h *Handlers) fingerprintMatrix() map[string]map[string]fingerprint {
// adding it there would change what a default request returns — but it is a
// fallback candidate for any browser no weighted row holds, so a browser only
// this row carries is reachable through os: "random" rather than refused.
- "linux": {
+ stealth.FingerprintOSLinux: {
"chrome": {
UserAgent: linuxChrome,
Platform: "Linux x86_64",
@@ -205,13 +205,32 @@ type weightedFingerprintOS struct {
weight float64
}
+// resolveFingerprintBrowser defaults an absent browser to chrome and matches a
+// named one against the matrix keys case-insensitively, so "Chrome" is the same
+// request as "chrome". An unknown value is returned untouched: the refusal must name
+// what the caller sent rather than a normalised guess.
+func resolveFingerprintBrowser(matrix map[string]map[string]fingerprint, requested string) string {
+ trimmed := strings.TrimSpace(requested)
+ if trimmed == "" {
+ return "chrome"
+ }
+ for _, browsers := range matrix {
+ for name := range browsers {
+ if strings.EqualFold(trimmed, name) {
+ return name
+ }
+ }
+ }
+ return trimmed
+}
+
// randomFingerprintOSWeights is the weighting behind os: "random". linux is absent
// on purpose: adding it here would change what a default request returns. Absent
// from the WEIGHTING is not absent from the draw — fingerprintOSCandidates falls
// back to the unweighted rows when no weighted one holds the requested browser.
var randomFingerprintOSWeights = []weightedFingerprintOS{
- {name: "windows", weight: 0.7},
- {name: "mac", weight: 0.3},
+ {name: stealth.FingerprintOSWindows, weight: 0.7},
+ {name: stealth.FingerprintOSMac, weight: 0.3},
}
// fingerprintOSCandidates is the set os: "random" draws from for one browser: the
@@ -297,15 +316,30 @@ func (h *Handlers) generateFingerprint(req fingerprintRequest) (fingerprint, err
fp := fingerprint{}
osConfigs := h.fingerprintMatrix()
- browser := req.Browser
- if browser == "" {
- browser = "chrome"
+ browser := resolveFingerprintBrowser(osConfigs, req.Browser)
+
+ // A request naming no os is not a miss: it named nothing to contradict, so the
+ // host's own identity is the answer — see stealth.HostFingerprintOS for why
+ // coherence beats population size here. A named os is translated through the
+ // persona vocabulary, so "macOS" resolves the way "mac" does; anything else is
+ // left exactly as it arrived, so a genuine unknown still refuses naming what the
+ // caller sent.
+ os := req.OS
+ switch {
+ case strings.TrimSpace(os) == "":
+ os = stealth.HostFingerprintOS()
+ case os == "random":
+ // Left exactly as it arrived: the sentinel is compared verbatim, so this
+ // card widens nothing about what random accepts or draws over.
+ default:
+ if key, ok := stealth.ResolveFingerprintOS(os); ok {
+ os = key
+ }
}
// The random pick is constrained by the browser, so the message can only ever
// name an os the caller supplied. A refusal reporting "windows" to someone who
// asked for os: "random" is not actionable — retrying may well succeed.
- os := req.OS
if os == "random" {
picked, ok := resolveRandomFingerprintOS(osConfigs, browser)
if !ok {
diff --git a/internal/handlers/stealth_test.go b/internal/handlers/stealth_test.go
index 59e2a52e..d5658bc9 100644
--- a/internal/handlers/stealth_test.go
+++ b/internal/handlers/stealth_test.go
@@ -291,13 +291,7 @@ func TestGenerateFingerprintAgreesWithTheLaunchPersonaOnThisHost(t *testing.T) {
const version = "144.0.7559.133"
h := Handlers{Config: &config.RuntimeConfig{BrowserVersion: version}}
- hostOS := map[string]string{
- stealth.PlatformWindows: "windows",
- stealth.PlatformMacOS: "mac",
- stealth.PlatformLinux: "linux",
- }[stealth.HostPlatform()]
-
- fp, err := h.generateFingerprint(fingerprintRequest{OS: hostOS, Browser: "chrome"})
+ fp, err := h.generateFingerprint(fingerprintRequest{OS: stealth.HostFingerprintOS(), Browser: "chrome"})
if err != nil {
t.Fatalf("generateFingerprint: %v", err)
}
@@ -809,3 +803,156 @@ func TestEveryBrowserTheMatrixHoldsIsReachableThroughRandom(t *testing.T) {
})
}
}
+
+// The simplest possible call, and the one an agent or a curl writes first. It named
+// no os, so there is nothing to contradict by answering with this host's identity —
+// and the launch persona already resolves from the host, so this is also what makes
+// the endpoint and the browser PinchTab launches agree. Refusing it was PIN-121's
+// rule applied one input too far.
+func TestGenerateFingerprintWithNoOSAnswersWithThisHostsIdentity(t *testing.T) {
+ const version = "144.0.7559.133"
+ h := Handlers{Config: &config.RuntimeConfig{BrowserVersion: version}}
+ persona := stealth.BuildPersona("", version)
+
+ fp, err := h.generateFingerprint(fingerprintRequest{})
+ if err != nil {
+ t.Fatalf("the bare request was refused: %v", err)
+ }
+ if fp.UserAgent != persona.UserAgent {
+ t.Fatalf("bare request userAgent =\n %q\nwant this host's persona\n %q", fp.UserAgent, persona.UserAgent)
+ }
+ if fp.Platform != persona.NavigatorPlatform {
+ t.Errorf("bare request platform = %q, want the persona's %q", fp.Platform, persona.NavigatorPlatform)
+ }
+ if fp.UserAgent == "" {
+ t.Error("the bare request produced an empty userAgent, which is the blank identity this card exists to stop")
+ }
+}
+
+// identityOf is the part of a fingerprint that the os/browser selection decides.
+// CPUCores, Memory and a random screen are drawn per call, so comparing whole
+// structs would compare the dice.
+func identityOf(fp fingerprint) [3]string {
+ return [3]string{fp.UserAgent, fp.Platform, fp.Vendor}
+}
+
+// Two vocabularies for the same three platforms: internal/stealth spells them
+// Windows/macOS/Linux, the matrix keys them windows/mac/linux. "macOS" is the one
+// that dies under case folding — and it is the spelling a caller who has read
+// stealth.PlatformMacOS will send — so every member is asserted, both spellings and
+// mixed case, against the fingerprint the canonical key returns.
+func TestEverySpellingOfAPlatformResolvesToTheSameFingerprint(t *testing.T) {
+ const version = "144.0.7559.133"
+ h := Handlers{Config: &config.RuntimeConfig{BrowserVersion: version}}
+
+ for _, tc := range []struct{ key, spelling string }{
+ {key: stealth.FingerprintOSWindows, spelling: stealth.PlatformWindows},
+ {key: stealth.FingerprintOSWindows, spelling: "WINDOWS"},
+ {key: stealth.FingerprintOSMac, spelling: stealth.PlatformMacOS},
+ {key: stealth.FingerprintOSMac, spelling: "MacOS"},
+ {key: stealth.FingerprintOSLinux, spelling: stealth.PlatformLinux},
+ {key: stealth.FingerprintOSLinux, spelling: " linux "},
+ } {
+ t.Run(tc.spelling, func(t *testing.T) {
+ want, err := h.generateFingerprint(fingerprintRequest{OS: tc.key})
+ if err != nil {
+ t.Fatalf("os=%q was refused: %v", tc.key, err)
+ }
+ got, err := h.generateFingerprint(fingerprintRequest{OS: tc.spelling})
+ if err != nil {
+ t.Fatalf("os=%q was refused although it is the same platform as %q: %v", tc.spelling, tc.key, err)
+ }
+ if identityOf(got) != identityOf(want) {
+ t.Errorf("os=%q returned\n %v\nwant the same identity as os=%q\n %v", tc.spelling, identityOf(got), tc.key, identityOf(want))
+ }
+ })
+ }
+
+ // The browser name folds too, and an absent one still defaults to chrome.
+ lower, err := h.generateFingerprint(fingerprintRequest{OS: stealth.FingerprintOSWindows, Browser: "edge"})
+ if err != nil {
+ t.Fatalf("browser=edge was refused: %v", err)
+ }
+ for _, spelling := range []string{"Edge", "EDGE", " edge "} {
+ got, err := h.generateFingerprint(fingerprintRequest{OS: stealth.FingerprintOSWindows, Browser: spelling})
+ if err != nil {
+ t.Fatalf("browser=%q was refused: %v", spelling, err)
+ }
+ if identityOf(got) != identityOf(lower) {
+ t.Errorf("browser=%q returned %v, want the same identity as browser=edge %v", spelling, identityOf(got), identityOf(lower))
+ }
+ }
+}
+
+// The host default must not become a catch-all: an os that is not a platform at all
+// is still a miss, and PIN-121's refusal is what a caller needs to see. Asserted
+// alongside an unlisted pair, because the two refusals share the message.
+func TestAnUnknownOSStillRefusesRatherThanFallingBackToTheHost(t *testing.T) {
+ h := Handlers{Config: &config.RuntimeConfig{BrowserVersion: "144.0.7559.133"}}
+ pairs := availableFingerprintPairs(h.fingerprintMatrix())
+
+ for _, tc := range []struct {
+ name string
+ req fingerprintRequest
+ }{
+ {name: "unknown os", req: fingerprintRequest{OS: "ubuntu"}},
+ {name: "unknown os with a known browser", req: fingerprintRequest{OS: "ubuntu", Browser: "chrome"}},
+ {name: "unlisted pair", req: fingerprintRequest{OS: stealth.FingerprintOSLinux, Browser: "edge"}},
+ {name: "unknown browser", req: fingerprintRequest{OS: stealth.FingerprintOSWindows, Browser: "firefox"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fp, err := h.generateFingerprint(tc.req)
+ if err == nil {
+ t.Fatalf("%+v was accepted with userAgent %q; the host default must not swallow a genuine miss", tc.req, fp.UserAgent)
+ }
+ if fp != (fingerprint{}) {
+ t.Errorf("refused request returned a populated fingerprint: %+v", fp)
+ }
+ for _, want := range pairs {
+ if !strings.Contains(err.Error(), want) {
+ t.Errorf("error %q omits the available pair %q", err, want)
+ }
+ }
+ })
+ }
+
+ // The message names what the caller sent, not a translated or defaulted value.
+ _, err := h.generateFingerprint(fingerprintRequest{OS: "ubuntu"})
+ if err == nil {
+ t.Fatal("os=ubuntu was accepted")
+ }
+ if !strings.Contains(err.Error(), `"ubuntu"`) {
+ t.Errorf("error %q does not name the os the caller sent", err)
+ }
+ if strings.Contains(err.Error(), stealth.HostFingerprintOS()+`" with`) {
+ t.Errorf("error %q reports the host default instead of the requested os", err)
+ }
+}
+
+// The two vocabularies must stay in step: every platform internal/stealth knows maps
+// to a key the matrix holds, and every os key the matrix holds is one internal/stealth
+// owns. Derived from both sides, so adding a row to either without the other reds.
+func TestThePlatformAndMatrixVocabulariesAgree(t *testing.T) {
+ h := Handlers{Config: &config.RuntimeConfig{BrowserVersion: "144.0.7559.133"}}
+ matrix := h.fingerprintMatrix()
+
+ owned := map[string]bool{}
+ for _, platform := range []string{stealth.PlatformWindows, stealth.PlatformMacOS, stealth.PlatformLinux} {
+ key, ok := stealth.FingerprintOSKey(platform)
+ if !ok {
+ t.Fatalf("internal/stealth knows platform %q but maps it to no fingerprint os key", platform)
+ }
+ owned[key] = true
+ if _, held := matrix[key]; !held {
+ t.Errorf("platform %q maps to os key %q, which the matrix does not hold — a request naming that platform would refuse", platform, key)
+ }
+ }
+ for key := range matrix {
+ if !owned[key] {
+ t.Errorf("the matrix holds os key %q that no platform in internal/stealth maps to, so no persona spelling can reach it", key)
+ }
+ }
+ if got := stealth.HostFingerprintOS(); !owned[got] {
+ t.Fatalf("HostFingerprintOS() = %q, which is not one of the keys it owns", got)
+ }
+}
diff --git a/internal/stealth/bundle_test.go b/internal/stealth/bundle_test.go
index dcdba707..100a5840 100644
--- a/internal/stealth/bundle_test.go
+++ b/internal/stealth/bundle_test.go
@@ -434,3 +434,30 @@ func TestChromeUserAgentTemplateHasOneOwner(t *testing.T) {
t.Errorf("%s spells the template %d times, want 3 (one arm per platform)", owner, owners[owner])
}
}
+
+// The rotate path now refuses an empty UA at Bridge.SetUserAgentOverride, and that
+// guard must not be satisfiable by quietly making the launch override empty too. The
+// launch path does not go through it: emulation.go hands persona.UserAgent to
+// Emulation directly, which needs no guard for a checked reason rather than an
+// assumed one — BuildPersona reduces the version first and ReducedBrowserVersion
+// falls back, so the field cannot be empty whatever the configured version is.
+func TestTheLaunchOverrideUserAgentIsNeverEmpty(t *testing.T) {
+ for _, version := range []string{"", " ", "144.0.7559.133", "144", "0", "not-a-version"} {
+ for _, customUA := range []string{"", " "} {
+ persona := BuildPersona(customUA, version)
+ if strings.TrimSpace(persona.UserAgent) == "" {
+ t.Errorf("BuildPersona(%q, %q).UserAgent is empty; the launch path would apply it and blank navigator.userAgent", customUA, version)
+ }
+ }
+ }
+
+ // The field asserted above is the one the launch path applies. Without this the
+ // test would keep passing after the launch override started reading something else.
+ raw, err := os.ReadFile("emulation.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "emulation.SetUserAgentOverride(persona.UserAgent)") {
+ t.Error("emulation.go no longer applies persona.UserAgent, so the non-empty guarantee above is about a field the launch path does not use")
+ }
+}
diff --git a/internal/stealth/ua.go b/internal/stealth/ua.go
index 372f9e06..c6df60d8 100644
--- a/internal/stealth/ua.go
+++ b/internal/stealth/ua.go
@@ -98,13 +98,77 @@ func HostPlatform() string {
}
}
+// The /fingerprint endpoint keys its matrix by these lowercase os names while the
+// persona vocabulary above spells the same three platforms "Windows", "macOS" and
+// "Linux". Two spellings of one thing drift, so the endpoint's names are DERIVED
+// from the persona's here rather than written a second time: fingerprintOSKeys is
+// the only place the two meet, and the endpoint keys its matrix by these constants.
+const (
+ FingerprintOSWindows = "windows"
+ FingerprintOSMac = "mac"
+ FingerprintOSLinux = "linux"
+)
+
+var fingerprintOSKeys = map[string]string{
+ PlatformWindows: FingerprintOSWindows,
+ PlatformMacOS: FingerprintOSMac,
+ PlatformLinux: FingerprintOSLinux,
+}
+
+// FingerprintOSKey is the endpoint's os key for a persona platform.
+func FingerprintOSKey(platform string) (string, bool) {
+ key, ok := fingerprintOSKeys[platform]
+ return key, ok
+}
+
+// HostFingerprintOS is the endpoint's os key for the machine this process runs on,
+// which is what a fingerprint request naming no os means: the caller delegated the
+// choice, and the honest answer is this host. A Linux host does advertise a rarer
+// desktop population than Windows would, and coherence still wins — a Linux browser
+// claiming Windows contradicts everything else it leaks (fonts, WebGL, UA-CH
+// platform), which is louder than a rare but consistent platform. The launch persona
+// already resolves from the host through GOOS, so defaulting the endpoint to the
+// host is what makes the two agree. This is not the same question as os: "random",
+// which means "surprise me within the usual desktop population" and deliberately
+// draws over the weighted rows only.
+func HostFingerprintOS() string {
+ key, _ := FingerprintOSKey(HostPlatform())
+ return key
+}
+
+// ResolveFingerprintOS translates a requested os into the endpoint's key, accepting
+// either vocabulary in any case — "macOS" and "mac" and "MACOS" all resolve. It is
+// an alias translation rather than case folding because "macOS" to "mac" is not a
+// case difference, and "macOS" is the spelling a caller who has read PlatformMacOS
+// will send. It reports false for anything else, so a genuinely unknown os stays a
+// refusal that names what the caller sent.
+func ResolveFingerprintOS(requested string) (string, bool) {
+ trimmed := strings.TrimSpace(requested)
+ if trimmed == "" {
+ return "", false
+ }
+ for platform, key := range fingerprintOSKeys {
+ if strings.EqualFold(trimmed, platform) || strings.EqualFold(trimmed, key) {
+ return key, true
+ }
+ }
+ return "", false
+}
+
// resolveUserAgent honours an explicit custom UA verbatim and otherwise builds the
// host's. It stays unexported: the only correct entry point is BuildPersona, which
// reduces the version first — an exported form invites a caller to pass
// cfg.BrowserVersion straight through and reintroduce the version drift the
// fingerprint endpoint already had to be resynced for by hand.
+//
+// A blank-but-present custom UA counts as absent. Returning it verbatim made the
+// persona's UserAgent empty, and the launch path applies that field to
+// Emulation.setUserAgentOverride directly — so a configured " " blanked
+// navigator.userAgent on every page, which is the one thing the whole persona exists
+// to avoid. It also makes the guarantee the rotate path's guard relies on true
+// without exception: persona.UserAgent is never empty.
func resolveUserAgent(userAgent, chromeVersion string) string {
- if userAgent != "" {
+ if strings.TrimSpace(userAgent) != "" {
return userAgent
}
return ChromeUserAgent(HostPlatform(), chromeVersion)