High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: give the fallback Chrome version a single owner in browserprobe (PIN-074)
Luigi Agosti65101e744208
diff --git a/internal/browserprobe/version.go b/internal/browserprobe/version.goindex 8f67147b..79569b5d 100644--- a/internal/browserprobe/version.go+++ b/internal/browserprobe/version.go@@ -7,6 +7,20 @@ import ("time")+// FallbackChromeVersion is the Chrome version advertised when the real one is not+// known — no browser.version in config and no successful probe of the launched binary.+//+// It lives here, beside RunVersion, because this package is the only leaf all three+// consumers can import: internal/stealth imports internal/config, so config can never+// read a constant owned by stealth, and internal/handlers reads both. Before it had one+// owner the same digits were written out in config's file default, config's runtime+// default and two fallbacks in stealth's UA builder, so a Chrome release meant four+// edits in lockstep across three packages and nothing failed when they drifted.+//+// Bumping it is a stopgap, not the fix: the version a page sees should come from the+// binary RunVersion probes, and this is what is left when that cannot be answered.+const FallbackChromeVersion = "144.0.7559.133"+func RunVersion(ctx context.Context, binary string) (string, error) {cctx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()diff --git a/internal/browserprobe/version_test.go b/internal/browserprobe/version_test.gonew file mode 100644index 00000000..10700e0d--- /dev/null+++ b/internal/browserprobe/version_test.go@@ -0,0 +1,43 @@+package browserprobe++import (+ "strconv"+ "strings"+ "testing"+)++// The fallback is what every version surface advertises when the launched binary cannot+// be probed, and it reaches the wire unvalidated: the UA string, the Sec-CH-UA brands and+// fullVersionList are all derived from it. A malformed value is therefore not a config+// error someone sees — it is a browser describing itself in a shape no Chrome ever sends,+// which is louder than the stale version it replaces.+func TestFallbackChromeVersionHasTheShapeChromeActuallySends(t *testing.T) {+ parts := strings.Split(FallbackChromeVersion, ".")+ if len(parts) != 4 {+ t.Fatalf("FallbackChromeVersion = %q has %d components, want the four-part major.minor.build.patch Chrome reports", FallbackChromeVersion, len(parts))+ }+ for i, part := range parts {+ if part == "" {+ t.Fatalf("FallbackChromeVersion = %q has an empty component %d", FallbackChromeVersion, i)+ }+ if _, err := strconv.Atoi(part); err != nil {+ t.Errorf("FallbackChromeVersion component %d = %q is not numeric", i, part)+ }+ }+ if major, _ := strconv.Atoi(parts[0]); major < 100 {+ t.Errorf("FallbackChromeVersion major = %d; Chrome's UA reduction assumes v100+, and every reduced UA derived from this would be a version Chrome never shipped", major)+ }+}++// The fallback and the probe answer the same question, so the probe's own extractor must+// read the fallback back unchanged. If it cannot, the two disagree about what a version+// looks like and a probed value would take a different path through the callers than the+// literal it replaces.+func TestTheProbeExtractorReadsTheFallbackBackUnchanged(t *testing.T) {+ if got := ExtractVersionToken("Google Chrome " + FallbackChromeVersion); got != FallbackChromeVersion {+ t.Errorf("ExtractVersionToken(...%s) = %q, want the fallback read back unchanged", FallbackChromeVersion, got)+ }+ if got := CompareSemver(FallbackChromeVersion, FallbackChromeVersion); got != 0 {+ t.Errorf("CompareSemver(fallback, fallback) = %d, want 0", got)+ }+}diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 3cbe1dc9..be3370ee 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -3,6 +3,8 @@ package configimport ("strconv""strings"++ "github.com/pinchtab/pinchtab/internal/browserprobe")// CurrentConfigVersion is bumped when config schema changes require migration or wizard re-run.@@ -165,7 +167,7 @@ func DefaultFileConfig() FileConfig {StateDir: userConfigDir(),},Browser: BrowserConfig{- BrowserVersion: "144.0.7559.133",+ BrowserVersion: browserprobe.FallbackChromeVersion,ExtensionPaths: []string{defaultExtensionsDir(userConfigDir())},},Browsers: BrowsersConfig{diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 14577df9..3b4d4f4a 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -11,6 +11,7 @@ import ("time""github.com/pinchtab/pinchtab/internal/autosolver"+ "github.com/pinchtab/pinchtab/internal/browserprobe""github.com/pinchtab/pinchtab/internal/browsers")@@ -224,7 +225,7 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {ProfilesBaseDir: "",DefaultProfile: "default",ProfileQuarantineKeep: DefaultProfileQuarantineKeep,- BrowserVersion: "144.0.7559.133",+ BrowserVersion: browserprobe.FallbackChromeVersion,Timezone: "",BlockImages: false,BlockMedia: false,diff --git a/internal/stealth/emulation.go b/internal/stealth/emulation.goindex 9ce5e5b0..4ba69e25 100644--- a/internal/stealth/emulation.go+++ b/internal/stealth/emulation.go@@ -10,8 +10,8 @@ import ()// 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.+// metadata. chromeVersion should be the full four-part build, the shape+// browserprobe.FallbackChromeVersion has. If chromeVersion is empty, returns nil.func BuildUserAgentOverride(userAgent, chromeVersion string) *emulation.SetUserAgentOverrideParams {if chromeVersion == "" {return nildiff --git a/internal/stealth/ua.go b/internal/stealth/ua.goindex d10c60c8..676179b4 100644--- a/internal/stealth/ua.go+++ b/internal/stealth/ua.go@@ -7,6 +7,8 @@ import ("sync""github.com/shirou/gopsutil/v4/host"++ "github.com/pinchtab/pinchtab/internal/browserprobe")type BrandVersion struct {@@ -41,13 +43,13 @@ type BrowserPersona struct {// lives in the high-entropy UA Client Hints. Falls back to the default major// when chromeVersion is empty so all callers agree on a single value.func ReducedBrowserVersion(chromeVersion string) string {+ if chromeVersion == "" {+ chromeVersion = browserprobe.FallbackChromeVersion+ }major := chromeVersionif i := strings.Index(chromeVersion, "."); i > 0 {major = chromeVersion[:i]}- if major == "" {- major = "144"- }return major + ".0.0.0"}@@ -387,5 +389,5 @@ func chromeVersionOrFallback(chromeVersion string) string {if chromeVersion != "" {return chromeVersion}- return "144.0.0.0"+ return ReducedBrowserVersion("")}diff --git a/internal/stealth/version_owner_test.go b/internal/stealth/version_owner_test.gonew file mode 100644index 00000000..445a5b45--- /dev/null+++ b/internal/stealth/version_owner_test.go@@ -0,0 +1,235 @@+package stealth++import (+ "go/ast"+ "go/parser"+ "go/token"+ "regexp"+ "strconv"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/browserprobe"+ "github.com/pinchtab/pinchtab/internal/srccensus"+)++// versionShaped is the full four-part Chrome build ("144.0.7559.133") and the UA-reduced+// form ("144.0.0.0") that every version surface derives from it.+var versionShaped = regexp.MustCompile(`^\d+\.\d+\.\d+\.\d+$`)++// bareMajorShaped is the Chrome major on its own, the third spelling the fallback had+// before it was owned in one place — ReducedBrowserVersion carried `major = "144"`.+var bareMajorShaped = regexp.MustCompile(`^\d{3}$`)++// versionLiteralExemptions are the four-part numeric literals in these packages that are+// NOT a browser version, listed by VALUE with the reason. Exempting by value rather than+// by file keeps the exemption from widening: a new literal at an exempt site still fails.+var versionLiteralExemptions = map[string]string{+ "127.0.0.1": "the loopback address, not a version",+ "0.0.0.0": "the wildcard bind address, not a version",+ "99.0.0.0": "the Sec-CH-UA GREASE placeholder, which is deliberately not a real Chrome build and must not track the fallback",+}++// versionOwnerPackages are the packages that build or default a browser version. They are+// listed as PREFIXES over a derived module walk rather than as a file list, so a new file+// in any of them is scanned without an edit here.+var versionOwnerPackages = []string{+ "internal/config/",+ "internal/stealth/",+ "internal/handlers/",+}++// The fallback Chrome version had four independent copies across three packages — two+// config defaults and two fallbacks in this file's UA builder — so a Chrome release meant+// four edits in lockstep and nothing failed when they drifted. browserprobe now owns it,+// and this census is what keeps it owned: any version-shaped literal reintroduced in the+// packages that build a version fails here, by value, with the owner named.+//+// browserprobe itself is not scanned — it is the owner, and the one definition lives+// there.+func TestNoPackageKeepsItsOwnCopyOfTheFallbackBrowserVersion(t *testing.T) {+ exemptionSeen := map[string]bool{}+ scanned := 0++ for _, file := range srccensus.Tree(t, "../..", 200) {+ if !inVersionOwnerPackage(file.Name) {+ continue+ }+ scanned++++ parsed, err := parser.ParseFile(token.NewFileSet(), file.Path, nil, 0)+ if err != nil {+ t.Fatalf("cannot parse %s, so this census would skip it silently: %v", file.Name, err)+ }+ ast.Inspect(parsed, func(node ast.Node) bool {+ lit, ok := node.(*ast.BasicLit)+ if !ok || lit.Kind != token.STRING {+ return true+ }+ value, uErr := strconv.Unquote(lit.Value)+ if uErr != nil {+ return true+ }+ if !versionShaped.MatchString(value) && !bareMajorShaped.MatchString(value) {+ return true+ }+ if reason, exempt := versionLiteralExemptions[value]; exempt {+ exemptionSeen[value] = true+ _ = reason+ return true+ }+ t.Errorf("%s writes the browser version %q out as a literal; read browserprobe.FallbackChromeVersion instead, or add %q to versionLiteralExemptions with the reason it is not a version", file.Name, value, value)+ return true+ })+ }++ if scanned < 20 {+ t.Fatalf("scanned %d files across %v; the walk matched almost nothing and this census would pass vacuously", scanned, versionOwnerPackages)+ }+ for value, reason := range versionLiteralExemptions {+ if !exemptionSeen[value] {+ t.Errorf("%q is exempted as %q but no longer appears in these packages; drop the entry rather than leaving a stale exemption", value, reason)+ }+ }+}++// The other direction: the packages that lost their literal must actually READ the owner,+// or the census above passes because the default went missing rather than because it is+// shared. Each site is named with the default it supplies.+func TestTheVersionDefaultsReadTheOneOwner(t *testing.T) {+ // The two config defaults are asserted at the VALUE POSITION of the BrowserVersion+ // field, not merely somewhere in the file: a file that reads the constant for some+ // other purpose while its default comes from elsewhere is exactly the drift this+ // census exists to catch, and a file-level check passes on it.+ for _, tc := range []struct{ dir, file, what string }{+ {"../config", "config_file.go", "the file-config default written into a new config"},+ {"../config", "config_load.go", "the RuntimeConfig default used when no file config applies"},+ } {+ // Load fails when the package yields too few files, so a census pointed at a+ // directory that moved fatals here instead of finding nothing and passing.+ pkg := srccensus.Load(t, tc.dir, 3)+ present := false+ for _, name := range pkg.Files() {+ if name == tc.file {+ present = true+ }+ }+ if !present {+ t.Fatalf("%s is not in %s; this census is reading the wrong package", tc.file, tc.dir)+ }++ assigned, ok := browserVersionFieldValue(t, tc.dir+"/"+tc.file)+ if !ok {+ t.Errorf("%s no longer sets a BrowserVersion field, so %s is gone rather than shared", tc.file, tc.what)+ continue+ }+ if !assigned {+ t.Errorf("%s sets BrowserVersion from something other than browserprobe.FallbackChromeVersion, so %s can drift from the owner again", tc.file, tc.what)+ }+ }++ // The UA builder's fallback is an assignment inside ReducedBrowserVersion rather than+ // a struct field, so it is pinned to that function's body.+ if !funcReferencesFallbackConstant(t, "ua.go", "ReducedBrowserVersion") {+ t.Error("ReducedBrowserVersion no longer reads browserprobe.FallbackChromeVersion, so the UA fallback comes from somewhere else and the value can drift again")+ }+}++// The fallback the UA builder actually produces must be the owner's value, reduced. This+// is the behavioural half: the census above proves the constant is referenced, this+// proves it is the value that comes out.+func TestTheAdvertisedFallbackIsTheOwnersValue(t *testing.T) {+ major, _, _ := strings.Cut(browserprobe.FallbackChromeVersion, ".")+ if major == "" {+ t.Fatalf("browserprobe.FallbackChromeVersion = %q has no major", browserprobe.FallbackChromeVersion)+ }++ if got, want := ReducedBrowserVersion(""), major+".0.0.0"; got != want {+ t.Errorf("ReducedBrowserVersion(\"\") = %q, want %q derived from the owner", got, want)+ }+ if got, want := chromeVersionOrFallback(""), major+".0.0.0"; got != want {+ t.Errorf("chromeVersionOrFallback(\"\") = %q, want %q derived from the owner", got, want)+ }++ persona := BuildPersona(ChromeUserAgent(PlatformMacOS, ReducedBrowserVersion("")), "")+ if !strings.Contains(persona.UserAgent, "Chrome/"+major+".0.0.0") {+ t.Errorf("fallback persona UA = %q, want the owner's major %s", persona.UserAgent, major)+ }+ for _, brand := range persona.UserAgentData.Brands {+ if brand.Brand == BrandChrome && brand.Version != major {+ t.Errorf("fallback Sec-CH-UA brand version = %q, want the owner's major %s", brand.Version, major)+ }+ }+}++func inVersionOwnerPackage(name string) bool {+ for _, prefix := range versionOwnerPackages {+ if strings.HasPrefix(name, prefix) {+ return true+ }+ }+ return false+}++func isFallbackConstant(node ast.Node) bool {+ sel, ok := node.(*ast.SelectorExpr)+ if !ok || sel.Sel.Name != "FallbackChromeVersion" {+ return false+ }+ pkg, ok := sel.X.(*ast.Ident)+ return ok && pkg.Name == "browserprobe"+}++func parseSource(t *testing.T, path string) *ast.File {+ t.Helper()++ parsed, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)+ if err != nil {+ t.Fatalf("cannot parse %s: %v", path, err)+ }+ return parsed+}++// browserVersionFieldValue reports whether every BrowserVersion field set in path takes+// its value from the owner, and whether any such field was found at all — an absent field+// and a field set from a literal are different failures and must not collapse.+func browserVersionFieldValue(t *testing.T, path string) (fromOwner bool, found bool) {+ t.Helper()++ fromOwner = true+ ast.Inspect(parseSource(t, path), func(node ast.Node) bool {+ kv, ok := node.(*ast.KeyValueExpr)+ if !ok {+ return true+ }+ key, ok := kv.Key.(*ast.Ident)+ if !ok || key.Name != "BrowserVersion" {+ return true+ }+ found = true+ if !isFallbackConstant(kv.Value) {+ fromOwner = false+ }+ return true+ })+ return fromOwner, found+}++func funcReferencesFallbackConstant(t *testing.T, path, funcName string) bool {+ t.Helper()++ found := false+ for _, decl := range parseSource(t, path).Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok || fn.Name.Name != funcName {+ continue+ }+ ast.Inspect(fn, func(node ast.Node) bool {+ if isFallbackConstant(node) {+ found = true+ }+ return true+ })+ }+ return found+}