Skip to content

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

fix: fingerprint rotate drops all User-Agent Client Hint headers, leaving a UA that claims Edge on Windows with no matching hints (PIN-127)

Luigi Agosti528baecd4691
diff --git a/internal/bridge/fingerprint_hints_test.go b/internal/bridge/fingerprint_hints_test.go
new file mode 100644
index 00000000..c84e96f6
--- /dev/null
+++ b/internal/bridge/fingerprint_hints_test.go
@@ -0,0 +1,135 @@
+package bridge
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+)
+
+// The identity the endpoint hands out is only as good as what the browser puts on the
+// wire, and the returned payload was already correct while the headers were not — so this
+// reads the request Chrome actually made. Rotating used to set the UA and silence every
+// Sec-CH-UA header for the life of the tab, which advertised a Windows Edge that sent none
+// of the hints a Windows Edge sends.
+func TestRotatedIdentitySendsClientHintsThatAgreeWithTheUserAgent(t *testing.T) {
+ chromePath := testbrowser.Path(t)
+
+ var mu sync.Mutex
+ var last http.Header
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ last = r.Header.Clone()
+ mu.Unlock()
+ w.Header().Set("Content-Type", "text/html")
+ _, _ = w.Write([]byte("<title>hints</title>"))
+ }))
+ t.Cleanup(server.Close)
+
+ profile, err := os.MkdirTemp("", "pinchtab-ua-hints-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 40*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ load := func() http.Header {
+ t.Helper()
+ if err := chromedp.Run(ctx, chromedp.Navigate(server.URL)); err != nil {
+ t.Fatal(err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ return last
+ }
+
+ // An un-rotated tab is the baseline the fix must not spend: it sends the hints it sends
+ // today, so nothing here can be satisfied by moving where they come from.
+ baseline := load()
+ for _, header := range []string{"Sec-Ch-Ua", "Sec-Ch-Ua-Mobile", "Sec-Ch-Ua-Platform"} {
+ if baseline.Get(header) == "" {
+ t.Fatalf("an un-rotated tab sent no %s, so this browser does not emit client hints on %s and the test cannot tell the fix from the fixture", header, server.URL)
+ }
+ }
+
+ b := &Bridge{Config: &config.RuntimeConfig{BrowserVersion: "144.0.7559.133"}}
+ reduced := stealth.ReducedBrowserVersion(b.Config.BrowserVersion)
+ windowsChrome := stealth.ChromeUserAgent(stealth.PlatformWindows, reduced)
+
+ for _, tc := range []struct {
+ name string
+ userAgent string
+ platform string
+ wantBrand string
+ absentBrand string
+ wantPlatform string
+ }{
+ {
+ name: "windows/edge",
+ userAgent: stealth.EdgeUserAgent(windowsChrome, reduced),
+ platform: "Win32",
+ wantBrand: stealth.BrandEdge,
+ absentBrand: stealth.BrandChrome,
+ wantPlatform: `"Windows"`,
+ },
+ {
+ name: "mac/chrome",
+ userAgent: stealth.ChromeUserAgent(stealth.PlatformMacOS, reduced),
+ platform: "MacIntel",
+ wantBrand: stealth.BrandChrome,
+ absentBrand: stealth.BrandEdge,
+ wantPlatform: `"macOS"`,
+ },
+ } {
+ if err := b.SetUserAgentOverride(ctx, UserAgentOverrideParams{
+ UserAgent: tc.userAgent,
+ Platform: tc.platform,
+ AcceptLanguage: "en-US",
+ }); err != nil {
+ t.Fatalf("%s: %v", tc.name, err)
+ }
+
+ headers := load()
+ if got := headers.Get("User-Agent"); got != tc.userAgent {
+ t.Errorf("%s: User-Agent = %q, want %q", tc.name, got, tc.userAgent)
+ }
+ brands := headers.Get("Sec-Ch-Ua")
+ if brands == "" {
+ t.Errorf("%s: no sec-ch-ua header; their total absence is a bot signal on its own", tc.name)
+ }
+ if !strings.Contains(brands, tc.wantBrand) {
+ t.Errorf("%s: sec-ch-ua = %q, want the %q brand the UA claims", tc.name, brands, tc.wantBrand)
+ }
+ if strings.Contains(brands, tc.absentBrand) {
+ t.Errorf("%s: sec-ch-ua = %q, want no %q brand; a UA and hints naming two browsers is a browser that cannot exist", tc.name, brands, tc.absentBrand)
+ }
+ if got := headers.Get("Sec-Ch-Ua-Platform"); got != tc.wantPlatform {
+ t.Errorf("%s: sec-ch-ua-platform = %q, want %s", tc.name, got, tc.wantPlatform)
+ }
+ if got := headers.Get("Sec-Ch-Ua-Mobile"); got != "?0" {
+ t.Errorf("%s: sec-ch-ua-mobile = %q, want ?0", tc.name, got)
+ }
+ }
+}
diff --git a/internal/bridge/handler_support.go b/internal/bridge/handler_support.go
index 6bcf78c0..9e59de87 100644
--- a/internal/bridge/handler_support.go
+++ b/internal/bridge/handler_support.go
@@ -188,15 +188,19 @@ func (b *Bridge) SetUserAgentOverride(ctx context.Context, params UserAgentOverr
if strings.TrimSpace(params.UserAgent) == "" {
return fmt.Errorf("user agent override must not be empty")
}
+ override := userAgentOverrideAction(params, b.browserVersion())
return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- p := emulation.SetUserAgentOverride(params.UserAgent).WithPlatform(params.Platform)
- if params.AcceptLanguage != "" {
- p = p.WithAcceptLanguage(params.AcceptLanguage)
- }
- return p.Do(ctx)
+ return override.Do(ctx)
}))
}
+func (b *Bridge) browserVersion() string {
+ if b.Config == nil {
+ return ""
+ }
+ return b.Config.BrowserVersion
+}
+
func (b *Bridge) SetLocaleOverride(ctx context.Context, locale string) error {
return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return emulation.SetLocaleOverride().WithLocale(locale).Do(ctx)
diff --git a/internal/bridge/uameta.go b/internal/bridge/uameta.go
index 2d20e1e0..fdabf71e 100644
--- a/internal/bridge/uameta.go
+++ b/internal/bridge/uameta.go
@@ -12,3 +12,23 @@ func buildUserAgentOverride(userAgent, chromeVersion string) *emulation.SetUserA
func buildLocaleOverride(userAgent, chromeVersion string) *emulation.SetLocaleOverrideParams {
return stealth.BuildLocaleOverride(userAgent, chromeVersion)
}
+
+// userAgentOverrideAction builds the CDP override for a caller-supplied identity: the
+// persona's client-hint metadata for that UA, with the caller's own platform and
+// accept-language laid over it. The metadata is the point — Chrome stops emitting every
+// Sec-CH-UA header once setUserAgentOverride arrives without it, so a rotated tab
+// advertised a UA that no client hint backed, which is a louder signal than the identity
+// it was meant to present.
+func userAgentOverrideAction(params UserAgentOverrideParams, chromeVersion string) *emulation.SetUserAgentOverrideParams {
+ override := buildUserAgentOverride(params.UserAgent, chromeVersion)
+ if override == nil {
+ override = emulation.SetUserAgentOverride(params.UserAgent)
+ }
+ if params.Platform != "" {
+ override = override.WithPlatform(params.Platform)
+ }
+ if params.AcceptLanguage != "" {
+ override = override.WithAcceptLanguage(params.AcceptLanguage)
+ }
+ return override
+}
diff --git a/internal/bridge/uameta_test.go b/internal/bridge/uameta_test.go
index 594e6726..ab41a76a 100644
--- a/internal/bridge/uameta_test.go
+++ b/internal/bridge/uameta_test.go
@@ -35,7 +35,7 @@ func TestBuild_UsesResolvedUserAgent(t *testing.T) {
}
func TestBuild_Versions(t *testing.T) {
- p := buildUserAgentOverride("Mozilla/5.0 Test", "144.0.7559.133")
+ p := buildUserAgentOverride(chromeUserAgentFixture, "144.0.7559.133")
if p == nil {
t.Fatal("expected non-nil")
return
@@ -88,3 +88,75 @@ func TestBuildLocaleOverride_UsesPersonaLanguage(t *testing.T) {
return
}
}
+
+const (
+ chromeUserAgentFixture = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36"
+ edgeUserAgentFixture = chromeUserAgentFixture + " Edg/144.0.0.0"
+ safariUserAgentFixture = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15"
+)
+
+// The rotate path reaches CDP through SetUserAgentOverride, which built the override by
+// hand and passed no metadata — so every Sec-CH-UA header stopped being sent for the life
+// of the tab, and the UA it did set had nothing backing it.
+func TestUserAgentOverrideActionCarriesClientHintMetadata(t *testing.T) {
+ params := UserAgentOverrideParams{UserAgent: edgeUserAgentFixture, Platform: "Win32", AcceptLanguage: "en-GB"}
+ override := userAgentOverrideAction(params, "144.0.7559.133")
+
+ if override.UserAgentMetadata == nil {
+ t.Fatal("rotate sends no userAgentMetadata, so Chrome drops sec-ch-ua, sec-ch-ua-mobile and sec-ch-ua-platform entirely")
+ }
+ if got := override.UserAgentMetadata.Platform; got != "Windows" {
+ t.Errorf("metadata platform = %q, want Windows to agree with the UA", got)
+ }
+ if override.Platform != params.Platform {
+ t.Errorf("navigator platform = %q, want the caller's %q", override.Platform, params.Platform)
+ }
+ if override.AcceptLanguage != params.AcceptLanguage {
+ t.Errorf("accept-language = %q, want the caller's %q; the persona's own value must not win", override.AcceptLanguage, params.AcceptLanguage)
+ }
+}
+
+// A UA claiming Edge with Google Chrome brands is a browser that cannot exist, which is
+// more detectable than either half alone.
+func TestUserAgentOverrideActionBrandsAgreeWithTheUserAgent(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ userAgent string
+ want string
+ absent string
+ }{
+ {name: "edge", userAgent: edgeUserAgentFixture, want: "Microsoft Edge", absent: "Google Chrome"},
+ {name: "chrome", userAgent: chromeUserAgentFixture, want: "Google Chrome", absent: "Microsoft Edge"},
+ } {
+ override := userAgentOverrideAction(UserAgentOverrideParams{UserAgent: tc.userAgent, Platform: "Win32"}, "144.0.7559.133")
+ if override.UserAgentMetadata == nil {
+ t.Fatalf("%s: no metadata", tc.name)
+ }
+ brands := map[string]string{}
+ for _, brand := range override.UserAgentMetadata.Brands {
+ brands[brand.Brand] = brand.Version
+ }
+ if _, ok := brands[tc.want]; !ok {
+ t.Errorf("%s: brands = %v, want %q, which is what a detector cross-checks against the UA string", tc.name, brands, tc.want)
+ }
+ if _, ok := brands[tc.absent]; ok {
+ t.Errorf("%s: brands = %v, want %q absent; the UA and the hints must describe one browser", tc.name, brands, tc.absent)
+ }
+ if _, ok := brands["Chromium"]; !ok {
+ t.Errorf("%s: brands = %v, want the Chromium brand every Chromium build sends", tc.name, brands)
+ }
+ }
+}
+
+// Real Safari sends no Sec-CH-UA at all, so metadata there would be the tell rather than
+// the cover — the absence is the coherent answer, not an omission.
+func TestUserAgentOverrideActionSendsNoMetadataForANonChromiumIdentity(t *testing.T) {
+ override := userAgentOverrideAction(UserAgentOverrideParams{UserAgent: safariUserAgentFixture, Platform: "MacIntel"}, "144.0.7559.133")
+
+ if override.UserAgentMetadata != nil {
+ t.Errorf("safari identity carries %+v; a Safari UA advertising Chromium brands is the mismatch this guards against", override.UserAgentMetadata)
+ }
+ if override.UserAgent != safariUserAgentFixture {
+ t.Errorf("UserAgent = %q, want the caller's Safari UA", override.UserAgent)
+ }
+}
diff --git a/internal/handlers/stealth.go b/internal/handlers/stealth.go
index efd22c20..14c98561 100644
--- a/internal/handlers/stealth.go
+++ b/internal/handlers/stealth.go
@@ -54,6 +54,15 @@ func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Reques
tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)
defer tCancel()
+ // The locale override goes first because it is the one that fails: Chrome answers
+ // "Another locale override is already in effect" often enough to matter, and applying
+ // the UA before it left the tab wearing half a new identity with no way back.
+ if fp.Language != "" {
+ if err := h.Bridge.SetLocaleOverride(tCtx, fp.Language); err != nil {
+ httpx.Error(w, 500, fmt.Errorf("setLocaleOverride: %w", err))
+ return
+ }
+ }
if err := h.Bridge.SetUserAgentOverride(tCtx, bridge.UserAgentOverrideParams{
UserAgent: fp.UserAgent,
Platform: fp.Platform,
@@ -62,12 +71,6 @@ func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Reques
httpx.Error(w, 500, fmt.Errorf("setUserAgentOverride: %w", err))
return
}
- if fp.Language != "" {
- if err := h.Bridge.SetLocaleOverride(tCtx, fp.Language); err != nil {
- httpx.Error(w, 500, fmt.Errorf("setLocaleOverride: %w", err))
- return
- }
- }
if timezoneID := timezoneIDFromOffset(fp.TimezoneOffset); timezoneID != "" {
if err := h.Bridge.SetTimezoneOverride(tCtx, timezoneID); err != nil {
httpx.Error(w, 500, fmt.Errorf("setTimezoneOverride: %w", err))
diff --git a/internal/handlers/stealth_test.go b/internal/handlers/stealth_test.go
index 9dbb5b86..a605fd45 100644
--- a/internal/handlers/stealth_test.go
+++ b/internal/handlers/stealth_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"net/http/httptest"
"reflect"
"sort"
@@ -992,3 +993,60 @@ func TestThePlatformAndMatrixVocabulariesAgree(t *testing.T) {
t.Fatalf("HostFingerprintOS() = %q, which is not one of the keys it owns", got)
}
}
+
+// rotateOrderBridge records the override calls a rotation makes, in the order it makes
+// them, and can fail the locale override the way Chrome intermittently does.
+type rotateOrderBridge struct {
+ *mockBridge
+ calls []string
+ localeErr error
+}
+
+func (m *rotateOrderBridge) SetUserAgentOverride(ctx context.Context, p bridge.UserAgentOverrideParams) error {
+ m.calls = append(m.calls, "userAgent")
+ return nil
+}
+
+func (m *rotateOrderBridge) SetLocaleOverride(ctx context.Context, locale string) error {
+ m.calls = append(m.calls, "locale")
+ return m.localeErr
+}
+
+func rotate(t *testing.T, mb *rotateOrderBridge, body string) *httptest.ResponseRecorder {
+ t.Helper()
+
+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)
+ w := httptest.NewRecorder()
+ h.HandleFingerprintRotate(w, httptest.NewRequest("POST", "/fingerprint/rotate", bytes.NewReader([]byte(body))))
+ return w
+}
+
+// The locale override is the one that fails — Chrome answers "Another locale override is
+// already in effect" often enough to matter — so it goes first. Applying the UA before it
+// left the tab wearing half a new identity, with no rollback and no correct meaning.
+func TestRotateAppliesTheFailureProneLocaleOverrideBeforeTheUserAgent(t *testing.T) {
+ mb := &rotateOrderBridge{mockBridge: &mockBridge{}}
+
+ if w := rotate(t, mb, `{"os":"windows","browser":"edge","tabId":"tab1"}`); w.Code != 200 {
+ t.Fatalf("rotate returned %d: %s", w.Code, w.Body.String())
+ }
+
+ if len(mb.calls) < 2 || mb.calls[0] != "locale" || mb.calls[1] != "userAgent" {
+ t.Fatalf("rotate applied %v, want the locale override before the user agent", mb.calls)
+ }
+}
+
+func TestAFailedLocaleOverrideLeavesTheUserAgentUntouched(t *testing.T) {
+ mb := &rotateOrderBridge{mockBridge: &mockBridge{}, localeErr: errors.New("Another locale override is already in effect (-32000)")}
+
+ w := rotate(t, mb, `{"os":"windows","browser":"edge","tabId":"tab1"}`)
+
+ if w.Code != 500 {
+ t.Fatalf("rotate returned %d, want 500 when the locale override fails", w.Code)
+ }
+ for _, call := range mb.calls {
+ if call == "userAgent" {
+ t.Fatalf("rotate applied %v after the locale override failed, so the tab is half-rotated with no way back", mb.calls)
+ }
+ }
+}
diff --git a/internal/stealth/emulation.go b/internal/stealth/emulation.go
index bbbde7bf..9ce5e5b0 100644
--- a/internal/stealth/emulation.go
+++ b/internal/stealth/emulation.go
@@ -22,33 +22,43 @@ func BuildUserAgentOverride(userAgent, chromeVersion string) *emulation.SetUserA
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,
- })
+ override := emulation.SetUserAgentOverride(persona.UserAgent).
+ WithAcceptLanguage(persona.AcceptLanguage).
+ WithPlatform(persona.NavigatorPlatform)
+ if metadata := personaUserAgentMetadata(persona); metadata != nil {
+ override = override.WithUserAgentMetadata(metadata)
+ }
+ return override
+}
+
+// personaUserAgentMetadata is the UA-CH half of a persona, or nil for a persona that
+// claims no Chromium brand. Nil is the honest answer there rather than an omission:
+// Chrome stops emitting Sec-CH-UA when setUserAgentOverride carries no metadata, and a
+// non-Chromium identity sends none of those headers either.
+func personaUserAgentMetadata(persona BrowserPersona) *emulation.UserAgentMetadata {
+ if len(persona.UserAgentData.Brands) == 0 {
+ return nil
+ }
+ return &emulation.UserAgentMetadata{
+ Platform: persona.UserAgentData.Platform,
+ PlatformVersion: persona.UserAgentData.PlatformVersion,
+ Architecture: persona.UserAgentData.Architecture,
+ Bitness: persona.UserAgentData.Bitness,
+ Mobile: persona.UserAgentData.Mobile,
+ Brands: brandVersions(persona.UserAgentData.Brands),
+ FullVersionList: brandVersions(persona.UserAgentData.FullVersionList),
}
- fullVersionList := make([]*emulation.UserAgentBrandVersion, 0, len(persona.UserAgentData.FullVersionList))
- for _, brand := range persona.UserAgentData.FullVersionList {
- fullVersionList = append(fullVersionList, &emulation.UserAgentBrandVersion{
+}
+
+func brandVersions(brands []BrandVersion) []*emulation.UserAgentBrandVersion {
+ converted := make([]*emulation.UserAgentBrandVersion, 0, len(brands))
+ for _, brand := range brands {
+ converted = append(converted, &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,
- })
+ return converted
}
func BuildLocaleOverride(userAgent, chromeVersion string) *emulation.SetLocaleOverrideParams {
diff --git a/internal/stealth/emulation_test.go b/internal/stealth/emulation_test.go
index 59e97722..0065021a 100644
--- a/internal/stealth/emulation_test.go
+++ b/internal/stealth/emulation_test.go
@@ -33,3 +33,26 @@ func TestApplyTargetEmulation_NilConfig(t *testing.T) {
t.Fatalf("nil cfg should no-op, got %v", err)
}
}
+
+// Chrome stops emitting Sec-CH-UA the moment setUserAgentOverride arrives without
+// metadata, so attaching it is what keeps a persona's hints on the wire — and omitting it
+// for a non-Chromium identity is what keeps them off, which is what real Safari does.
+func TestBuildUserAgentOverrideAttachesMetadataOnlyForAChromiumIdentity(t *testing.T) {
+ const version = "144.0.7559.133"
+
+ chrome := BuildUserAgentOverride(ChromeUserAgent(PlatformMacOS, ReducedBrowserVersion(version)), version)
+ if chrome == nil || chrome.UserAgentMetadata == nil {
+ t.Fatal("a Chrome persona carries no userAgentMetadata, so every sec-ch-ua header stops being sent")
+ }
+ if chrome.UserAgentMetadata.Platform != PlatformMacOS {
+ t.Errorf("metadata platform = %q, want %q", chrome.UserAgentMetadata.Platform, PlatformMacOS)
+ }
+
+ safari := BuildUserAgentOverride("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15", version)
+ if safari == nil {
+ t.Fatal("a Safari persona built no override at all; the UA still has to be applied")
+ }
+ if safari.UserAgentMetadata != nil {
+ t.Errorf("a Safari identity advertises %+v; Safari implements no UA-CH, so the hints must stay absent", safari.UserAgentMetadata)
+ }
+}
diff --git a/internal/stealth/ua.go b/internal/stealth/ua.go
index aa2beb97..cb337529 100644
--- a/internal/stealth/ua.go
+++ b/internal/stealth/ua.go
@@ -51,6 +51,47 @@ func ReducedBrowserVersion(chromeVersion string) string {
return major + ".0.0.0"
}
+// The Sec-CH-UA brand vocabulary. A Chromium build sends its own vendor brand next to
+// "Chromium" and a GREASE placeholder, and the vendor brand is what a detector
+// cross-checks against the UA string: Edge sends "Microsoft Edge" where Chrome sends
+// "Google Chrome", so an Edg/ UA shipping Chrome brands describes a browser that cannot
+// exist.
+const (
+ BrandChrome = "Google Chrome"
+ BrandEdge = "Microsoft Edge"
+ brandChromium = "Chromium"
+ brandGrease = "Not(A:Brand"
+ greaseMajorVersion = "99"
+ greaseFullVersion = "99.0.0.0"
+)
+
+// brandList is the brand vocabulary a UA claims, read back out of the string the same way
+// the platform is. A UA naming no Chromium build gets no brands at all: real Safari sends
+// no Sec-CH-UA header, so brands there are the tell rather than the cover, and the callers
+// that build CDP metadata omit it entirely rather than describing a Chrome that is not
+// there.
+func brandList(ua, version, greaseVersion string) []BrandVersion {
+ vendor, ok := chromiumVendorBrand(ua)
+ if !ok {
+ return nil
+ }
+ return []BrandVersion{
+ {Brand: brandGrease, Version: greaseVersion},
+ {Brand: vendor, Version: version},
+ {Brand: brandChromium, Version: version},
+ }
+}
+
+func chromiumVendorBrand(ua string) (string, bool) {
+ switch {
+ case strings.Contains(ua, "Edg/"):
+ return BrandEdge, true
+ case strings.Contains(ua, "Chrome/"):
+ return BrandChrome, true
+ }
+ return "", false
+}
+
// The platform vocabulary of the persona: the same values UserAgentDataProfile
// reports and PlatformVersionFor is keyed on, so a caller names a platform once
// and every UA fact follows from it.
@@ -228,16 +269,8 @@ func BuildPersona(userAgent, chromeVersion string) BrowserPersona {
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)},
- }
+ brands := brandList(ua, major, greaseMajorVersion)
+ fullVersionList := brandList(ua, chromeVersionOrFallback(chromeVersion), greaseFullVersion)
return BrowserPersona{
UserAgent: ua,
diff --git a/internal/stealth/ua_test.go b/internal/stealth/ua_test.go
index f488e0a6..8547ccb9 100644
--- a/internal/stealth/ua_test.go
+++ b/internal/stealth/ua_test.go
@@ -510,3 +510,69 @@ func TestBuildPersonaPlatformVersionMatchesPlatform(t *testing.T) {
t.Fatalf("host persona platformVersion = %q, want %q", persona.UserAgentData.PlatformVersion, PlatformVersionFor(uaDataPlatform))
}
}
+
+// The brand list is where the UA string and the client hints have to agree. A detector
+// cross-checking the two sees a browser that cannot exist when they disagree, which is
+// louder than either being wrong alone — so the vendor brand is read out of the UA rather
+// than fixed at Chrome, and a UA naming no Chromium build claims no brands at all.
+func TestPersonaBrandsNameTheBrowserTheUserAgentClaims(t *testing.T) {
+ const version = "144.0.7559.133"
+ windowsChrome := ChromeUserAgent(PlatformWindows, ReducedBrowserVersion(version))
+
+ for _, tc := range []struct {
+ name string
+ userAgent string
+ want []string
+ }{
+ {
+ name: "chrome",
+ userAgent: windowsChrome,
+ want: []string{"Not(A:Brand", "Google Chrome", "Chromium"},
+ },
+ {
+ name: "edge",
+ userAgent: EdgeUserAgent(windowsChrome, ReducedBrowserVersion(version)),
+ want: []string{"Not(A:Brand", "Microsoft Edge", "Chromium"},
+ },
+ {
+ // Real Safari implements no UA-CH at all, so brands here would be the tell.
+ name: "safari",
+ userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
+ want: nil,
+ },
+ } {
+ persona := BuildPersona(tc.userAgent, version)
+
+ for _, list := range [][]BrandVersion{persona.UserAgentData.Brands, persona.UserAgentData.FullVersionList} {
+ if len(list) != len(tc.want) {
+ t.Errorf("%s: brands = %v, want %v", tc.name, list, tc.want)
+ continue
+ }
+ for i, want := range tc.want {
+ if list[i].Brand != want {
+ t.Errorf("%s: brand %d = %q, want %q", tc.name, i, list[i].Brand, want)
+ }
+ if list[i].Version == "" {
+ t.Errorf("%s: brand %q carries no version", tc.name, list[i].Brand)
+ }
+ }
+ }
+ }
+}
+
+// The two lists differ in one way only, and it is the way real Chrome differs: sec-ch-ua
+// carries majors, the full version list carries builds.
+func TestPersonaBrandVersionsAreMajorInBrandsAndFullInTheVersionList(t *testing.T) {
+ persona := BuildPersona(ChromeUserAgent(PlatformMacOS, ReducedBrowserVersion("144.0.7559.133")), "144.0.7559.133")
+
+ for _, brand := range persona.UserAgentData.Brands {
+ if brand.Brand == BrandChrome && brand.Version != "144" {
+ t.Errorf("sec-ch-ua %s version = %q, want the major 144", brand.Brand, brand.Version)
+ }
+ }
+ for _, brand := range persona.UserAgentData.FullVersionList {
+ if brand.Brand == BrandChrome && brand.Version != "144.0.7559.133" {
+ t.Errorf("fullVersionList %s version = %q, want the full build", brand.Brand, brand.Version)
+ }
+ }
+}