Skip to content

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

refactor: replace global config vars with RuntimeConfig struct

Mario7fdca154165f
diff --git a/animations_test.go b/animations_test.go
index 771af6dd..3bb80cae 100644
--- a/animations_test.go
+++ b/animations_test.go
@@ -39,7 +39,7 @@ func TestDisableAnimationsCSSIsIIFE(t *testing.T) {
func TestNoAnimationsConfigDefault(t *testing.T) {
- if noAnimations {
+ if cfg.NoAnimations {
t.Error("noAnimations should default to false")
}
}
diff --git a/bridge.go b/bridge.go
index 44a294cf..a68b5cc7 100644
--- a/bridge.go
+++ b/bridge.go
@@ -87,7 +87,7 @@ func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {
}
b.injectStealth(ctx)
- if noAnimations {
+ if cfg.NoAnimations {
b.injectNoAnimations(ctx)
}
@@ -157,13 +157,13 @@ func (b *Bridge) CreateTab(url string) (string, context.Context, context.CancelF
b.injectStealth(ctx)
- if noAnimations {
+ if cfg.NoAnimations {
b.injectNoAnimations(ctx)
}
- if blockMedia {
+ if cfg.BlockMedia {
_ = setResourceBlocking(ctx, mediaBlockPatterns)
- } else if blockImages {
+ } else if cfg.BlockImages {
_ = setResourceBlocking(ctx, imageBlockPatterns)
}
diff --git a/cmd_connect.go b/cmd_connect.go
index 02df516e..346ebe7e 100644
--- a/cmd_connect.go
+++ b/cmd_connect.go
@@ -48,7 +48,7 @@ func handleConnectCommand() {
os.Exit(2)
}
if dashboardURL == "" {
- dashboardURL = "http://localhost:" + port
+ dashboardURL = "http://localhost:" + cfg.Port
}
reqURL := stringsTrimRightSlash(dashboardURL) + "/profiles/" + url.PathEscape(profile) + "/instance"
diff --git a/cmd_dashboard.go b/cmd_dashboard.go
index 06ba8706..c21af632 100644
--- a/cmd_dashboard.go
+++ b/cmd_dashboard.go
@@ -17,14 +17,14 @@ import (
// runDashboard starts a lightweight dashboard server — no Chrome, no bridge.
// It manages Pinchtab instances via the orchestrator and serves the dashboard UI.
func runDashboard() {
- dashPort := port
+ dashPort := cfg.Port
if dashPort == "" {
dashPort = "9870"
}
slog.Info("🦀 Pinchtab Dashboard", "port", dashPort)
- profilesDir := filepath.Join(stateDir, "profiles")
+ profilesDir := filepath.Join(cfg.StateDir, "profiles")
if err := os.MkdirAll(profilesDir, 0755); err != nil {
slog.Error("cannot create profiles dir", "err", err)
os.Exit(1)
diff --git a/config.go b/config.go
index b3e345d0..dbe4e010 100644
--- a/config.go
+++ b/config.go
@@ -44,27 +44,32 @@ var readabilityJS string
//go:embed welcome.html
var welcomeHTML string
-var (
- port = envOr("BRIDGE_PORT", "9867")
- cdpURL = os.Getenv("CDP_URL")
- token = os.Getenv("BRIDGE_TOKEN")
- stateDir = envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".pinchtab"))
- headless = envBoolOr("BRIDGE_HEADLESS", true)
- noRestore = os.Getenv("BRIDGE_NO_RESTORE") == "true"
- profileDir = envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".pinchtab", "chrome-profile"))
- chromeVersion = envOr("BRIDGE_CHROME_VERSION", "144.0.7559.133")
- timezone = os.Getenv("BRIDGE_TIMEZONE")
- blockImages = os.Getenv("BRIDGE_BLOCK_IMAGES") == "true"
- blockMedia = os.Getenv("BRIDGE_BLOCK_MEDIA") == "true"
- chromeBinary = os.Getenv("CHROME_BINARY")
- chromeExtraFlags = os.Getenv("CHROME_FLAGS")
- noAnimations = os.Getenv("BRIDGE_NO_ANIMATIONS") == "true"
- stealthLevel = envOr("BRIDGE_STEALTH", "light")
- actionTimeout = 15 * time.Second
- navigateTimeout = 30 * time.Second
- shutdownTimeout = 10 * time.Second
- waitNavDelay = 1 * time.Second
-)
+// RuntimeConfig holds all runtime configuration in a single struct.
+// Loaded once at startup from environment variables and optional config file.
+type RuntimeConfig struct {
+ Port string
+ CdpURL string
+ Token string
+ StateDir string
+ Headless bool
+ NoRestore bool
+ ProfileDir string
+ ChromeVersion string
+ Timezone string
+ BlockImages bool
+ BlockMedia bool
+ ChromeBinary string
+ ChromeExtraFlags string
+ NoAnimations bool
+ StealthLevel string
+ ActionTimeout time.Duration
+ NavigateTimeout time.Duration
+ ShutdownTimeout time.Duration
+ WaitNavDelay time.Duration
+}
+
+// cfg is the package-level runtime configuration, populated by loadConfig().
+var cfg RuntimeConfig
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
@@ -93,65 +98,93 @@ func homeDir() string {
return h
}
-type Config struct {
+// FileConfig is the JSON config file format.
+type FileConfig struct {
Port string `json:"port"`
CdpURL string `json:"cdpUrl,omitempty"`
Token string `json:"token,omitempty"`
StateDir string `json:"stateDir"`
ProfileDir string `json:"profileDir"`
- Headless bool `json:"headless"`
+ Headless *bool `json:"headless,omitempty"`
NoRestore bool `json:"noRestore"`
TimeoutSec int `json:"timeoutSec,omitempty"`
NavigateSec int `json:"navigateSec,omitempty"`
}
func loadConfig() {
+ // Populate from environment with defaults
+ cfg = RuntimeConfig{
+ Port: envOr("BRIDGE_PORT", "9867"),
+ CdpURL: os.Getenv("CDP_URL"),
+ Token: os.Getenv("BRIDGE_TOKEN"),
+ StateDir: envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".pinchtab")),
+ Headless: envBoolOr("BRIDGE_HEADLESS", true),
+ NoRestore: os.Getenv("BRIDGE_NO_RESTORE") == "true",
+ ProfileDir: envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".pinchtab", "chrome-profile")),
+ ChromeVersion: envOr("BRIDGE_CHROME_VERSION", "144.0.7559.133"),
+ Timezone: os.Getenv("BRIDGE_TIMEZONE"),
+ BlockImages: os.Getenv("BRIDGE_BLOCK_IMAGES") == "true",
+ BlockMedia: os.Getenv("BRIDGE_BLOCK_MEDIA") == "true",
+ ChromeBinary: os.Getenv("CHROME_BINARY"),
+ ChromeExtraFlags: os.Getenv("CHROME_FLAGS"),
+ NoAnimations: os.Getenv("BRIDGE_NO_ANIMATIONS") == "true",
+ StealthLevel: envOr("BRIDGE_STEALTH", "light"),
+ ActionTimeout: 15 * time.Second,
+ NavigateTimeout: 30 * time.Second,
+ ShutdownTimeout: 10 * time.Second,
+ WaitNavDelay: 1 * time.Second,
+ }
+ // Override from config file (env vars take precedence)
configPath := envOr("BRIDGE_CONFIG", filepath.Join(homeDir(), ".pinchtab", "config.json"))
- if data, err := os.ReadFile(configPath); err == nil {
- var cfg Config
- if err := json.Unmarshal(data, &cfg); err != nil {
- slog.Warn("invalid JSON in config file, ignoring", "path", configPath, "err", err)
- } else {
+ data, err := os.ReadFile(configPath)
+ if err != nil {
+ return
+ }
- if cfg.Port != "" && os.Getenv("BRIDGE_PORT") == "" {
- port = cfg.Port
- }
- if cfg.CdpURL != "" && os.Getenv("CDP_URL") == "" {
- cdpURL = cfg.CdpURL
- }
- if cfg.Token != "" && os.Getenv("BRIDGE_TOKEN") == "" {
- token = cfg.Token
- }
- if cfg.StateDir != "" && os.Getenv("BRIDGE_STATE_DIR") == "" {
- stateDir = cfg.StateDir
- }
- if cfg.ProfileDir != "" && os.Getenv("BRIDGE_PROFILE") == "" {
- profileDir = cfg.ProfileDir
- }
- if cfg.Headless && os.Getenv("BRIDGE_HEADLESS") == "" {
- headless = true
- }
- if cfg.NoRestore && os.Getenv("BRIDGE_NO_RESTORE") == "" {
- noRestore = true
- }
- if cfg.TimeoutSec > 0 && os.Getenv("BRIDGE_TIMEOUT") == "" {
- actionTimeout = time.Duration(cfg.TimeoutSec) * time.Second
- }
- if cfg.NavigateSec > 0 && os.Getenv("BRIDGE_NAV_TIMEOUT") == "" {
- navigateTimeout = time.Duration(cfg.NavigateSec) * time.Second
- }
- }
+ var fc FileConfig
+ if err := json.Unmarshal(data, &fc); err != nil {
+ slog.Warn("invalid JSON in config file, ignoring", "path", configPath, "err", err)
+ return
+ }
+
+ if fc.Port != "" && os.Getenv("BRIDGE_PORT") == "" {
+ cfg.Port = fc.Port
+ }
+ if fc.CdpURL != "" && os.Getenv("CDP_URL") == "" {
+ cfg.CdpURL = fc.CdpURL
+ }
+ if fc.Token != "" && os.Getenv("BRIDGE_TOKEN") == "" {
+ cfg.Token = fc.Token
+ }
+ if fc.StateDir != "" && os.Getenv("BRIDGE_STATE_DIR") == "" {
+ cfg.StateDir = fc.StateDir
+ }
+ if fc.ProfileDir != "" && os.Getenv("BRIDGE_PROFILE") == "" {
+ cfg.ProfileDir = fc.ProfileDir
+ }
+ if fc.Headless != nil && os.Getenv("BRIDGE_HEADLESS") == "" {
+ cfg.Headless = *fc.Headless
+ }
+ if fc.NoRestore && os.Getenv("BRIDGE_NO_RESTORE") == "" {
+ cfg.NoRestore = true
+ }
+ if fc.TimeoutSec > 0 && os.Getenv("BRIDGE_TIMEOUT") == "" {
+ cfg.ActionTimeout = time.Duration(fc.TimeoutSec) * time.Second
+ }
+ if fc.NavigateSec > 0 && os.Getenv("BRIDGE_NAV_TIMEOUT") == "" {
+ cfg.NavigateTimeout = time.Duration(fc.NavigateSec) * time.Second
}
}
-func defaultConfig() Config {
- return Config{
+func defaultFileConfig() FileConfig {
+ h := true
+ return FileConfig{
Port: "9867",
StateDir: filepath.Join(homeDir(), ".pinchtab"),
ProfileDir: filepath.Join(homeDir(), ".pinchtab", "chrome-profile"),
- Headless: true,
+ Headless: &h,
NoRestore: false,
TimeoutSec: 15,
NavigateSec: 30,
@@ -186,8 +219,8 @@ func handleConfigCommand() {
os.Exit(1)
}
- cfg := defaultConfig()
- data, _ := json.MarshalIndent(cfg, "", " ")
+ fc := defaultFileConfig()
+ data, _ := json.MarshalIndent(fc, "", " ")
if err := os.WriteFile(configPath, data, 0644); err != nil {
fmt.Printf("Error writing config: %v\n", err)
os.Exit(1)
@@ -199,20 +232,20 @@ func handleConfigCommand() {
"port": "9867",
"token": "your-secret-token",
"headless": true,
- "stateDir": "` + cfg.StateDir + `",
- "profileDir": "` + cfg.ProfileDir + `"
+ "stateDir": "` + fc.StateDir + `",
+ "profileDir": "` + fc.ProfileDir + `"
}`)
case "show":
fmt.Println("Current configuration:")
- fmt.Printf(" Port: %s\n", port)
- fmt.Printf(" CDP URL: %s\n", cdpURL)
- fmt.Printf(" Token: %s\n", maskToken(token))
- fmt.Printf(" State Dir: %s\n", stateDir)
- fmt.Printf(" Profile: %s\n", profileDir)
- fmt.Printf(" Headless: %v\n", headless)
- fmt.Printf(" No Restore: %v\n", noRestore)
- fmt.Printf(" Timeouts: action=%v navigate=%v\n", actionTimeout, navigateTimeout)
+ fmt.Printf(" Port: %s\n", cfg.Port)
+ fmt.Printf(" CDP URL: %s\n", cfg.CdpURL)
+ fmt.Printf(" Token: %s\n", maskToken(cfg.Token))
+ fmt.Printf(" State Dir: %s\n", cfg.StateDir)
+ fmt.Printf(" Profile: %s\n", cfg.ProfileDir)
+ fmt.Printf(" Headless: %v\n", cfg.Headless)
+ fmt.Printf(" No Restore: %v\n", cfg.NoRestore)
+ fmt.Printf(" Timeouts: action=%v navigate=%v\n", cfg.ActionTimeout, cfg.NavigateTimeout)
default:
fmt.Printf("Unknown command: %s\n", os.Args[2])
diff --git a/config_test.go b/config_test.go
index e257a0b0..e1aaf42e 100644
--- a/config_test.go
+++ b/config_test.go
@@ -61,7 +61,7 @@ func TestMaskToken(t *testing.T) {
{"short", "***"},
{"12345678", "***"},
{"123456789", "1234...6789"},
- {"my-super-secret-token", "my-s...oken"},
+ {"my-super-secret-cfg.Token", "my-s...oken"},
}
for _, tt := range tests {
if got := maskToken(tt.input); got != tt.want {
@@ -71,28 +71,28 @@ func TestMaskToken(t *testing.T) {
}
func TestDefaultConfig(t *testing.T) {
- cfg := defaultConfig()
- if cfg.Port != "9867" {
- t.Errorf("default port = %q, want 9867", cfg.Port)
+ fc := defaultFileConfig()
+ if fc.Port != "9867" {
+ t.Errorf("default Port = %q, want 9867", fc.Port)
}
- if !cfg.Headless {
+ if fc.Headless == nil || !*fc.Headless {
t.Error("default config should be headless")
}
- if cfg.NoRestore {
- t.Error("default config should not have noRestore")
+ if fc.NoRestore {
+ t.Error("default config should not have NoRestore")
}
- if cfg.TimeoutSec != 15 {
- t.Errorf("default timeout = %d, want 15", cfg.TimeoutSec)
+ if fc.TimeoutSec != 15 {
+ t.Errorf("default timeout = %d, want 15", fc.TimeoutSec)
}
- if cfg.NavigateSec != 30 {
- t.Errorf("default navigate timeout = %d, want 30", cfg.NavigateSec)
+ if fc.NavigateSec != 30 {
+ t.Errorf("default navigate timeout = %d, want 30", fc.NavigateSec)
}
}
func TestLoadConfig_FromFile(t *testing.T) {
- origPort := port
- defer func() { port = origPort }()
+ origPort := cfg.Port
+ defer func() { cfg.Port = origPort }()
dir := t.TempDir()
configPath := dir + "/config.json"
@@ -102,14 +102,14 @@ func TestLoadConfig_FromFile(t *testing.T) {
t.Setenv("BRIDGE_CONFIG", configPath)
loadConfig()
- if port != "7777" {
- t.Errorf("loadConfig from file: port = %q, want 7777", port)
+ if cfg.Port != "7777" {
+ t.Errorf("loadConfig from file: port = %q, want 7777", cfg.Port)
}
}
func TestLoadConfig_EnvOverridesFile(t *testing.T) {
- origPort := port
- defer func() { port = origPort }()
+ origPort := cfg.Port
+ defer func() { cfg.Port = origPort }()
dir := t.TempDir()
configPath := dir + "/config.json"
@@ -118,11 +118,11 @@ func TestLoadConfig_EnvOverridesFile(t *testing.T) {
t.Setenv("BRIDGE_CONFIG", configPath)
t.Setenv("BRIDGE_PORT", "8888")
- port = "8888"
+ cfg.Port = "8888"
loadConfig()
- if port != "8888" {
- t.Errorf("env should override file: port = %q, want 8888", port)
+ if cfg.Port != "8888" {
+ t.Errorf("env should override file: port = %q, want 8888", cfg.Port)
}
}
@@ -131,15 +131,15 @@ func TestLoadConfig_InvalidJSON(t *testing.T) {
configPath := dir + "/config.json"
_ = os.WriteFile(configPath, []byte("{broken json!!!"), 0644)
- origPort := port
- defer func() { port = origPort }()
+ origPort := cfg.Port
+ defer func() { cfg.Port = origPort }()
t.Setenv("BRIDGE_CONFIG", configPath)
t.Setenv("BRIDGE_PORT", "")
- port = "9867"
+ cfg.Port = "9867"
loadConfig()
- if port != "9867" {
- t.Errorf("invalid config should not change port, got %q", port)
+ if cfg.Port != "9867" {
+ t.Errorf("invalid config should not change port, got %q", cfg.Port)
}
}
diff --git a/handler_actions.go b/handler_actions.go
index 159c098b..703dfd26 100644
--- a/handler_actions.go
+++ b/handler_actions.go
@@ -45,7 +45,7 @@ func (b *Bridge) initActionRegistry() {
return nil, err
}
if req.WaitNav {
- _ = chromedp.Run(ctx, chromedp.Sleep(waitNavDelay))
+ _ = chromedp.Run(ctx, chromedp.Sleep(cfg.WaitNavDelay))
}
return map[string]any{"clicked": true}, nil
},
@@ -199,7 +199,7 @@ func (b *Bridge) handleAction(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
@@ -301,7 +301,7 @@ func (b *Bridge) handleActions(w http.ResponseWriter, r *http.Request) {
}
}
- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
if action.Ref != "" && action.NodeID == 0 && action.Selector == "" {
cache := b.GetRefCache(resolvedTabID)
diff --git a/handler_health_tabs.go b/handler_health_tabs.go
index 9c028e74..d7c5030b 100644
--- a/handler_health_tabs.go
+++ b/handler_health_tabs.go
@@ -8,10 +8,10 @@ import (
func (b *Bridge) handleHealth(w http.ResponseWriter, r *http.Request) {
targets, err := b.ListTargets()
if err != nil {
- jsonResp(w, 200, map[string]any{"status": "disconnected", "error": err.Error(), "cdp": cdpURL})
+ jsonResp(w, 200, map[string]any{"status": "disconnected", "error": err.Error(), "cdp": cfg.CdpURL})
return
}
- jsonResp(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": cdpURL})
+ jsonResp(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": cfg.CdpURL})
}
func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {
diff --git a/handler_media.go b/handler_media.go
index 33074a8c..44e95efa 100644
--- a/handler_media.go
+++ b/handler_media.go
@@ -26,11 +26,11 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
- if reqNoAnim && !noAnimations {
+ if reqNoAnim && !cfg.NoAnimations {
disableAnimationsOnce(tCtx)
}
@@ -57,7 +57,7 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
}
if output == "file" {
- screenshotDir := filepath.Join(stateDir, "screenshots")
+ screenshotDir := filepath.Join(cfg.StateDir, "screenshots")
if err := os.MkdirAll(screenshotDir, 0755); err != nil {
jsonErr(w, 500, fmt.Errorf("create screenshot dir: %w", err))
return
@@ -105,7 +105,7 @@ func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
diff --git a/handler_navigation.go b/handler_navigation.go
index 4a504a2b..a5c53186 100644
--- a/handler_navigation.go
+++ b/handler_navigation.go
@@ -37,7 +37,7 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
titleWait = time.Duration(req.WaitTitle * float64(time.Second))
}
- navTimeout := navigateTimeout
+ navTimeout := cfg.NavigateTimeout
if req.Timeout > 0 {
if req.Timeout > 120 {
req.Timeout = 120
@@ -52,9 +52,9 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
blockPatterns = imageBlockPatterns
} else if req.BlockImages != nil && !*req.BlockImages {
blockPatterns = nil
- } else if blockMedia {
+ } else if cfg.BlockMedia {
blockPatterns = mediaBlockPatterns
- } else if blockImages {
+ } else if cfg.BlockImages {
blockPatterns = imageBlockPatterns
}
@@ -93,7 +93,7 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
if blockPatterns != nil {
_ = setResourceBlocking(tCtx, blockPatterns)
- } else if blockImages {
+ } else if cfg.BlockImages {
_ = setResourceBlocking(tCtx, nil)
}
@@ -131,7 +131,7 @@ func (b *Bridge) handleEvaluate(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
diff --git a/handler_snapshot.go b/handler_snapshot.go
index 54f62752..54f977b3 100644
--- a/handler_snapshot.go
+++ b/handler_snapshot.go
@@ -44,11 +44,11 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
- if reqNoAnim && !noAnimations {
+ if reqNoAnim && !cfg.NoAnimations {
disableAnimationsOnce(tCtx)
}
@@ -153,7 +153,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
if output == "file" {
- snapshotDir := filepath.Join(stateDir, "snapshots")
+ snapshotDir := filepath.Join(cfg.StateDir, "snapshots")
if err := os.MkdirAll(snapshotDir, 0755); err != nil {
jsonErr(w, 500, fmt.Errorf("create snapshot dir: %w", err))
return
diff --git a/handler_stealth.go b/handler_stealth.go
index ca95cd79..377ed051 100644
--- a/handler_stealth.go
+++ b/handler_stealth.go
@@ -50,7 +50,7 @@ func (b *Bridge) handleStealthStatus(w http.ResponseWriter, r *http.Request) {
features := map[string]bool{
"automation_controlled": !result.WebDriver,
"webdriver_hidden": !result.WebDriver,
- "chrome_headless_new": headless,
+ "chrome_headless_new": cfg.Headless,
"user_agent_override": result.UserAgent != "",
"webgl_vendor_override": true,
"plugins_spoofed": result.Plugins > 0,
@@ -74,7 +74,7 @@ func staticStealthFeatures() map[string]bool {
return map[string]bool{
"automation_controlled": true,
"webdriver_hidden": true,
- "chrome_headless_new": headless,
+ "chrome_headless_new": cfg.Headless,
"user_agent_override": true,
"webgl_vendor_override": true,
"plugins_spoofed": true,
@@ -139,9 +139,9 @@ func (b *Bridge) sendStealthResponse(w http.ResponseWriter, features map[string]
"score": stealthScore,
"features": features,
"chrome_flags": chromeFlags,
- "headless_mode": headless,
+ "headless_mode": cfg.Headless,
"user_agent": userAgent,
- "profile_path": profileDir,
+ "profile_path": cfg.ProfileDir,
"recommendations": getStealthRecommendations(features),
})
}
@@ -159,7 +159,7 @@ func getStealthRecommendations(features map[string]bool) []string {
recommendations = append(recommendations, "Block WebRTC to prevent IP leaks")
}
if !features["timezone_spoofed"] {
- recommendations = append(recommendations, "Spoof timezone to match target locale")
+ recommendations = append(recommendations, "Spoof cfg.Timezone to match target locale")
}
if !features["canvas_noise"] {
recommendations = append(recommendations, "Add canvas fingerprint noise")
@@ -270,19 +270,19 @@ func generateFingerprint(req fingerprintRequest) fingerprint {
osConfigs := map[string]map[string]fingerprint{
"windows": {
"chrome": {
- UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", chromeVersion),
+ UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", cfg.ChromeVersion),
Platform: "Win32",
Vendor: "Google Inc.",
},
"edge": {
- UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 Edg/%s", chromeVersion, chromeVersion),
+ UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 Edg/%s", cfg.ChromeVersion, cfg.ChromeVersion),
Platform: "Win32",
Vendor: "Google Inc.",
},
},
"mac": {
"chrome": {
- UserAgent: fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", chromeVersion),
+ UserAgent: fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", cfg.ChromeVersion),
Platform: "MacIntel",
Vendor: "Google Inc.",
},
diff --git a/handlers_extra_test.go b/handlers_extra_test.go
index 3fc6c43c..378b9c1f 100644
--- a/handlers_extra_test.go
+++ b/handlers_extra_test.go
@@ -158,11 +158,11 @@ func TestLoadConfig_TimeoutFromFile(t *testing.T) {
t.Setenv("BRIDGE_TIMEOUT", "")
t.Setenv("BRIDGE_NAV_TIMEOUT", "")
- origAction := actionTimeout
- origNav := navigateTimeout
+ origAction := cfg.ActionTimeout
+ origNav := cfg.NavigateTimeout
defer func() {
- actionTimeout = origAction
- navigateTimeout = origNav
+ cfg.ActionTimeout = origAction
+ cfg.NavigateTimeout = origNav
}()
loadConfig()
@@ -172,7 +172,7 @@ func TestLoadConfig_TimeoutFromFile(t *testing.T) {
func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
tmp := t.TempDir()
cfgPath := filepath.Join(tmp, "config.json")
- cfg := `{
+ jsonData := `{
"port": "9999",
"headless": true,
"token": "test-token",
@@ -180,19 +180,19 @@ func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
"timeoutSec": 20,
"navigateSec": 45
}`
- _ = os.WriteFile(cfgPath, []byte(cfg), 0644)
+ _ = os.WriteFile(cfgPath, []byte(jsonData), 0644)
- origPort := port
- origNoRestore := noRestore
- origToken := token
- origAction := actionTimeout
- origNav := navigateTimeout
+ origPort := cfg.Port
+ origNoRestore := cfg.NoRestore
+ origToken := cfg.Token
+ origAction := cfg.ActionTimeout
+ origNav := cfg.NavigateTimeout
defer func() {
- port = origPort
- noRestore = origNoRestore
- token = origToken
- actionTimeout = origAction
- navigateTimeout = origNav
+ cfg.Port = origPort
+ cfg.NoRestore = origNoRestore
+ cfg.Token = origToken
+ cfg.ActionTimeout = origAction
+ cfg.NavigateTimeout = origNav
}()
t.Setenv("BRIDGE_CONFIG", cfgPath)
@@ -203,20 +203,20 @@ func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
t.Setenv("BRIDGE_NAV_TIMEOUT", "")
loadConfig()
- if port != "9999" {
- t.Errorf("expected port 9999, got %q", port)
+ if cfg.Port != "9999" {
+ t.Errorf("expected port 9999, got %q", cfg.Port)
}
- if !noRestore {
+ if !cfg.NoRestore {
t.Error("expected noRestore true from config")
}
- if token != "test-token" {
- t.Errorf("expected test-token, got %q", token)
+ if cfg.Token != "test-token" {
+ t.Errorf("expected test-token, got %q", cfg.Token)
}
- if actionTimeout != 20*time.Second {
- t.Errorf("expected 20s timeout, got %v", actionTimeout)
+ if cfg.ActionTimeout != 20*time.Second {
+ t.Errorf("expected 20s timeout, got %v", cfg.ActionTimeout)
}
- if navigateTimeout != 45*time.Second {
- t.Errorf("expected 45s navTimeout, got %v", navigateTimeout)
+ if cfg.NavigateTimeout != 45*time.Second {
+ t.Errorf("expected 45s navTimeout, got %v", cfg.NavigateTimeout)
}
}
diff --git a/integration_test.go b/integration_test.go
index ff29fb0c..91f2950c 100644
--- a/integration_test.go
+++ b/integration_test.go
@@ -215,7 +215,7 @@ func TestWebGLVendorSpoofed(t *testing.T) {
}
if !result.Available {
- t.Skip("WebGL not available in headless mode — skipping vendor check")
+ t.Skip("WebGL not available in cfg.Headless mode — skipping vendor check")
}
if result.Vendor != "Intel Inc." {
diff --git a/main.go b/main.go
index 8974d4ac..d408c263 100644
--- a/main.go
+++ b/main.go
@@ -52,7 +52,7 @@ func main() {
return
}
- if err := os.MkdirAll(stateDir, 0755); err != nil {
+ if err := os.MkdirAll(cfg.StateDir, 0755); err != nil {
slog.Error("cannot create state dir", "err", err)
os.Exit(1)
}
@@ -61,7 +61,7 @@ func main() {
defer allocCancel()
stealthSeed := rand.Intn(1000000000)
- seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, stealthLevel) + stealthScript
+ seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + stealthScript
bridge.stealthScript = seededScript
bridge.allocCtx = allocCtx
@@ -82,7 +82,7 @@ func main() {
slog.Error("Chrome failed to start after retry",
"err", err,
"hint", "try BRIDGE_NO_RESTORE=true or delete your profile directory",
- "profile", profileDir,
+ "profile", cfg.ProfileDir,
)
allocCancel()
os.Exit(1)
@@ -99,7 +99,7 @@ func main() {
bridge.initActionRegistry()
bridge.locks = newLockManager()
- profilesDir := filepath.Join(filepath.Dir(profileDir), "profiles")
+ profilesDir := filepath.Join(filepath.Dir(cfg.ProfileDir), "profiles")
profMgr := NewProfileManager(profilesDir)
dashboard := NewDashboard(nil)
orchestrator := NewOrchestrator(profilesDir)
@@ -108,20 +108,20 @@ func main() {
bridge.tabs[string(initTargetID)] = &TabEntry{ctx: browserCtx}
slog.Info("initial tab", "id", string(initTargetID))
- if !headless {
+ if !cfg.Headless {
go func() {
time.Sleep(200 * time.Millisecond)
- _ = chromedp.Run(browserCtx, chromedp.Navigate("http://localhost:"+port+"/welcome"))
+ _ = chromedp.Run(browserCtx, chromedp.Navigate("http://localhost:"+cfg.Port+"/welcome"))
}()
}
- if !noRestore {
+ if !cfg.NoRestore {
go bridge.RestoreState()
}
cleanupCtx, cleanupCancel := context.WithCancel(context.Background())
defer cleanupCancel()
- go bridge.CleanStaleTabs(cleanupCtx, 30*actionTimeout)
+ go bridge.CleanStaleTabs(cleanupCtx, 30*cfg.ActionTimeout)
mux := http.NewServeMux()
registerRoutes(mux, &bridge, profMgr, dashboard, orchestrator)
@@ -140,7 +140,7 @@ func main() {
}
}
- srv := &http.Server{Addr: ":" + port, Handler: dashboard.TrackingMiddleware(
+ srv := &http.Server{Addr: ":" + cfg.Port, Handler: dashboard.TrackingMiddleware(
[]EventObserver{profileObserver},
loggingMiddleware(corsMiddleware(authMiddleware(mux))),
)}
@@ -154,7 +154,7 @@ func main() {
bridge.SaveState()
markCleanExit()
- shutdownCtx, shutdownDone := context.WithTimeout(context.Background(), shutdownTimeout)
+ shutdownCtx, shutdownDone := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer shutdownDone()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown http", "err", err)
@@ -175,8 +175,8 @@ func main() {
allocCancel()
})
- slog.Info("🦀 PINCH! PINCH!", "port", port, "cdp", cdpURL, "stealth", stealthLevel)
- if token != "" {
+ slog.Info("🦀 PINCH! PINCH!", "port", cfg.Port, "cdp", cfg.CdpURL, "stealth", cfg.StealthLevel)
+ if cfg.Token != "" {
slog.Info("auth enabled")
} else {
slog.Info("auth disabled (set BRIDGE_TOKEN to enable)")
@@ -192,19 +192,19 @@ func main() {
// setupAllocator creates the Chrome allocator context (remote or local).
func setupAllocator() (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption) {
- if cdpURL != "" {
- slog.Info("connecting to Chrome", "url", cdpURL)
- ctx, cancel := chromedp.NewRemoteAllocator(context.Background(), cdpURL)
+ if cfg.CdpURL != "" {
+ slog.Info("connecting to Chrome", "url", cfg.CdpURL)
+ ctx, cancel := chromedp.NewRemoteAllocator(context.Background(), cfg.CdpURL)
return ctx, cancel, nil
}
- if err := os.MkdirAll(profileDir, 0755); err != nil {
+ if err := os.MkdirAll(cfg.ProfileDir, 0755); err != nil {
slog.Error("cannot create profile dir", "err", err)
os.Exit(1)
}
for _, lockName := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
- lockPath := fmt.Sprintf("%s/%s", profileDir, lockName)
+ lockPath := fmt.Sprintf("%s/%s", cfg.ProfileDir, lockName)
if err := os.Remove(lockPath); err == nil {
slog.Warn("removed stale lock", "file", lockName)
}
@@ -215,7 +215,7 @@ func setupAllocator() (context.Context, context.CancelFunc, []chromedp.ExecAlloc
clearChromeSessions()
}
- slog.Info("launching Chrome", "profile", profileDir, "headless", headless)
+ slog.Info("launching Chrome", "profile", cfg.ProfileDir, "headless", cfg.Headless)
opts := buildChromeOpts()
@@ -227,7 +227,7 @@ func setupAllocator() (context.Context, context.CancelFunc, []chromedp.ExecAlloc
// buildChromeOpts assembles the Chrome flags for local execution.
func buildChromeOpts() []chromedp.ExecAllocatorOption {
opts := []chromedp.ExecAllocatorOption{
- chromedp.UserDataDir(profileDir),
+ chromedp.UserDataDir(cfg.ProfileDir),
chromedp.NoFirstRun,
chromedp.NoDefaultBrowserCheck,
@@ -258,11 +258,11 @@ func buildChromeOpts() []chromedp.ExecAllocatorOption {
chromedp.WindowSize(1366, 768),
}
- if chromeBinary != "" {
- opts = append(opts, chromedp.ExecPath(chromeBinary))
+ if cfg.ChromeBinary != "" {
+ opts = append(opts, chromedp.ExecPath(cfg.ChromeBinary))
}
- if chromeExtraFlags != "" {
- for _, f := range strings.Fields(chromeExtraFlags) {
+ if cfg.ChromeExtraFlags != "" {
+ for _, f := range strings.Fields(cfg.ChromeExtraFlags) {
if k, v, ok := strings.Cut(f, "="); ok {
opts = append(opts, chromedp.Flag(strings.TrimLeft(k, "-"), v))
} else {
@@ -271,7 +271,7 @@ func buildChromeOpts() []chromedp.ExecAllocatorOption {
}
}
- if headless {
+ if cfg.Headless {
opts = append(opts, chromedp.Headless)
} else {
opts = append(opts, chromedp.Flag("headless", false))
@@ -312,17 +312,17 @@ func startChrome(seededScript string) (context.Context, context.CancelFunc, erro
// applyTimezone sets the browser timezone override if configured.
func applyTimezone(browserCtx context.Context) {
- if timezone == "" {
+ if cfg.Timezone == "" {
return
}
if err := chromedp.Run(browserCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
- return emulation.SetTimezoneOverride(timezone).Do(ctx)
+ return emulation.SetTimezoneOverride(cfg.Timezone).Do(ctx)
}),
); err != nil {
- slog.Warn("timezone override failed", "tz", timezone, "err", err)
+ slog.Warn("timezone override failed", "tz", cfg.Timezone, "err", err)
} else {
- slog.Info("timezone override", "tz", timezone)
+ slog.Info("timezone override", "tz", cfg.Timezone)
}
}
@@ -376,7 +376,7 @@ func setupSignalHandler(shutdownFn func(), forceFn func()) {
func runStartupHealthCheck() {
time.Sleep(500 * time.Millisecond)
client := &http.Client{Timeout: 5 * time.Second}
- resp, err := client.Get(fmt.Sprintf("http://localhost:%s/health", port))
+ resp, err := client.Get(fmt.Sprintf("http://localhost:%s/health", cfg.Port))
if err != nil {
slog.Error("startup health check failed",
"err", err,
diff --git a/middleware.go b/middleware.go
index 94ca84be..2e14afaa 100644
--- a/middleware.go
+++ b/middleware.go
@@ -52,9 +52,9 @@ func loggingMiddleware(next http.Handler) http.Handler {
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if token != "" {
+ if cfg.Token != "" {
auth := r.Header.Get("Authorization")
- if auth != "Bearer "+token {
+ if auth != "Bearer "+cfg.Token {
jsonErr(w, 401, fmt.Errorf("unauthorized"))
return
}
diff --git a/middleware_test.go b/middleware_test.go
index 470bcf92..97c4c8b2 100644
--- a/middleware_test.go
+++ b/middleware_test.go
@@ -41,9 +41,9 @@ func TestJsonErr(t *testing.T) {
func TestAuthMiddleware_NoToken(t *testing.T) {
- origToken := token
- token = ""
- defer func() { token = origToken }()
+ origToken := cfg.Token
+ cfg.Token = ""
+ defer func() { cfg.Token = origToken }()
called := false
handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -61,9 +61,9 @@ func TestAuthMiddleware_NoToken(t *testing.T) {
}
func TestAuthMiddleware_ValidToken(t *testing.T) {
- origToken := token
- token = "secret123"
- defer func() { token = origToken }()
+ origToken := cfg.Token
+ cfg.Token = "secret123"
+ defer func() { cfg.Token = origToken }()
called := false
handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -82,9 +82,9 @@ func TestAuthMiddleware_ValidToken(t *testing.T) {
}
func TestAuthMiddleware_InvalidToken(t *testing.T) {
- origToken := token
- token = "secret123"
- defer func() { token = origToken }()
+ origToken := cfg.Token
+ cfg.Token = "secret123"
+ defer func() { cfg.Token = origToken }()
called := false
handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/state.go b/state.go
index 681f76b8..d8f00a74 100644
--- a/state.go
+++ b/state.go
@@ -31,7 +31,7 @@ type SessionState struct {
}
func markCleanExit() {
- prefsPath := filepath.Join(profileDir, "Default", "Preferences")
+ prefsPath := filepath.Join(cfg.ProfileDir, "Default", "Preferences")
data, err := os.ReadFile(prefsPath)
if err != nil {
return
@@ -45,7 +45,7 @@ func markCleanExit() {
}
func wasUncleanExit() bool {
- prefsPath := filepath.Join(profileDir, "Default", "Preferences")
+ prefsPath := filepath.Join(cfg.ProfileDir, "Default", "Preferences")
data, err := os.ReadFile(prefsPath)
if err != nil {
return false
@@ -55,7 +55,7 @@ func wasUncleanExit() bool {
}
func clearChromeSessions() {
- sessionsDir := filepath.Join(profileDir, "Default", "Sessions")
+ sessionsDir := filepath.Join(cfg.ProfileDir, "Default", "Sessions")
if err := os.RemoveAll(sessionsDir); err != nil {
slog.Warn("failed to clear Chrome sessions dir", "err", err)
} else {
@@ -91,11 +91,11 @@ func (b *Bridge) SaveState() {
slog.Error("save state: marshal", "err", err)
return
}
- if err := os.MkdirAll(stateDir, 0755); err != nil {
+ if err := os.MkdirAll(cfg.StateDir, 0755); err != nil {
slog.Error("save state: mkdir", "err", err)
return
}
- path := filepath.Join(stateDir, "sessions.json")
+ path := filepath.Join(cfg.StateDir, "sessions.json")
if err := os.WriteFile(path, data, 0644); err != nil {
slog.Error("save state: write", "err", err)
} else {
@@ -104,7 +104,7 @@ func (b *Bridge) SaveState() {
}
func (b *Bridge) RestoreState() {
- path := filepath.Join(stateDir, "sessions.json")
+ path := filepath.Join(cfg.StateDir, "sessions.json")
data, err := os.ReadFile(path)
if err != nil {
return
diff --git a/state_test.go b/state_test.go
index 5e6650d2..9bea0320 100644
--- a/state_test.go
+++ b/state_test.go
@@ -8,19 +8,19 @@ import (
)
func TestMarkCleanExit_NoFile(t *testing.T) {
- origProfileDir := profileDir
- profileDir = t.TempDir()
- defer func() { profileDir = origProfileDir }()
+ origProfileDir := cfg.ProfileDir
+ cfg.ProfileDir = t.TempDir()
+ defer func() { cfg.ProfileDir = origProfileDir }()
markCleanExit()
}
func TestMarkCleanExit_PatchesCrashed(t *testing.T) {
- origProfileDir := profileDir
- profileDir = t.TempDir()
- defer func() { profileDir = origProfileDir }()
+ origProfileDir := cfg.ProfileDir
+ cfg.ProfileDir = t.TempDir()
+ defer func() { cfg.ProfileDir = origProfileDir }()
- prefsDir := filepath.Join(profileDir, "Default")
+ prefsDir := filepath.Join(cfg.ProfileDir, "Default")
_ = os.MkdirAll(prefsDir, 0755)
prefsPath := filepath.Join(prefsDir, "Preferences")
@@ -40,11 +40,11 @@ func TestMarkCleanExit_PatchesCrashed(t *testing.T) {
}
func TestMarkCleanExit_NoPatch(t *testing.T) {
- origProfileDir := profileDir
- profileDir = t.TempDir()
- defer func() { profileDir = origProfileDir }()
+ origProfileDir := cfg.ProfileDir
+ cfg.ProfileDir = t.TempDir()
+ defer func() { cfg.ProfileDir = origProfileDir }()
- prefsDir := filepath.Join(profileDir, "Default")
+ prefsDir := filepath.Join(cfg.ProfileDir, "Default")
_ = os.MkdirAll(prefsDir, 0755)
prefsPath := filepath.Join(prefsDir, "Preferences")
@@ -93,9 +93,9 @@ func TestSaveState_NoBrowser(t *testing.T) {
}
func TestRestoreState_NoFile(t *testing.T) {
- origStateDir := stateDir
- stateDir = t.TempDir()
- defer func() { stateDir = origStateDir }()
+ origStateDir := cfg.StateDir
+ cfg.StateDir = t.TempDir()
+ defer func() { cfg.StateDir = origStateDir }()
b := newTestBridge()
@@ -103,13 +103,13 @@ func TestRestoreState_NoFile(t *testing.T) {
}
func TestRestoreState_EmptyTabs(t *testing.T) {
- origStateDir := stateDir
- stateDir = t.TempDir()
- defer func() { stateDir = origStateDir }()
+ origStateDir := cfg.StateDir
+ cfg.StateDir = t.TempDir()
+ defer func() { cfg.StateDir = origStateDir }()
state := SessionState{Tabs: []TabState{}, SavedAt: "2026-02-17T07:00:00Z"}
data, _ := json.Marshal(state)
- _ = os.WriteFile(filepath.Join(stateDir, "sessions.json"), data, 0644)
+ _ = os.WriteFile(filepath.Join(cfg.StateDir, "sessions.json"), data, 0644)
b := newTestBridge()
@@ -117,11 +117,11 @@ func TestRestoreState_EmptyTabs(t *testing.T) {
}
func TestRestoreState_InvalidJSON(t *testing.T) {
- origStateDir := stateDir
- stateDir = t.TempDir()
- defer func() { stateDir = origStateDir }()
+ origStateDir := cfg.StateDir
+ cfg.StateDir = t.TempDir()
+ defer func() { cfg.StateDir = origStateDir }()
- _ = os.WriteFile(filepath.Join(stateDir, "sessions.json"), []byte("{broken"), 0644)
+ _ = os.WriteFile(filepath.Join(cfg.StateDir, "sessions.json"), []byte("{broken"), 0644)
b := newTestBridge()
@@ -130,9 +130,9 @@ func TestRestoreState_InvalidJSON(t *testing.T) {
func TestWasUncleanExit_Crashed(t *testing.T) {
tmp := t.TempDir()
- origProfile := profileDir
- profileDir = tmp
- defer func() { profileDir = origProfile }()
+ origProfile := cfg.ProfileDir
+ cfg.ProfileDir = tmp
+ defer func() { cfg.ProfileDir = origProfile }()
defaultDir := filepath.Join(tmp, "Default")
_ = os.MkdirAll(defaultDir, 0755)
@@ -146,9 +146,9 @@ func TestWasUncleanExit_Crashed(t *testing.T) {
func TestWasUncleanExit_Normal(t *testing.T) {
tmp := t.TempDir()
- origProfile := profileDir
- profileDir = tmp
- defer func() { profileDir = origProfile }()
+ origProfile := cfg.ProfileDir
+ cfg.ProfileDir = tmp
+ defer func() { cfg.ProfileDir = origProfile }()
defaultDir := filepath.Join(tmp, "Default")
_ = os.MkdirAll(defaultDir, 0755)
@@ -162,9 +162,9 @@ func TestWasUncleanExit_Normal(t *testing.T) {
func TestWasUncleanExit_NoFile(t *testing.T) {
tmp := t.TempDir()
- origProfile := profileDir
- profileDir = tmp
- defer func() { profileDir = origProfile }()
+ origProfile := cfg.ProfileDir
+ cfg.ProfileDir = tmp
+ defer func() { cfg.ProfileDir = origProfile }()
if wasUncleanExit() {
t.Error("expected wasUncleanExit to return false when no Preferences file exists")
@@ -173,9 +173,9 @@ func TestWasUncleanExit_NoFile(t *testing.T) {
func TestClearChromeSessions(t *testing.T) {
tmp := t.TempDir()
- origProfile := profileDir
- profileDir = tmp
- defer func() { profileDir = origProfile }()
+ origProfile := cfg.ProfileDir
+ cfg.ProfileDir = tmp
+ defer func() { cfg.ProfileDir = origProfile }()
sessionsDir := filepath.Join(tmp, "Default", "Sessions")
_ = os.MkdirAll(sessionsDir, 0755)
@@ -190,9 +190,9 @@ func TestClearChromeSessions(t *testing.T) {
func TestClearChromeSessions_NoDir(t *testing.T) {
tmp := t.TempDir()
- origProfile := profileDir
- profileDir = tmp
- defer func() { profileDir = origProfile }()
+ origProfile := cfg.ProfileDir
+ cfg.ProfileDir = tmp
+ defer func() { cfg.ProfileDir = origProfile }()
clearChromeSessions()
}
diff --git a/stealth_test.go b/stealth_test.go
index 615b803e..a5dc4a06 100644
--- a/stealth_test.go
+++ b/stealth_test.go
@@ -106,7 +106,7 @@ func TestGenerateFingerprint(t *testing.T) {
OS: "windows",
Browser: "chrome",
},
- wantUA: "Chrome/" + chromeVersion,
+ wantUA: "Chrome/" + cfg.ChromeVersion,
wantPlat: "Win32",
},
{
@@ -115,7 +115,7 @@ func TestGenerateFingerprint(t *testing.T) {
OS: "mac",
Browser: "chrome",
},
- wantUA: "Chrome/" + chromeVersion,
+ wantUA: "Chrome/" + cfg.ChromeVersion,
wantPlat: "MacIntel",
},
{
@@ -124,7 +124,7 @@ func TestGenerateFingerprint(t *testing.T) {
OS: "random",
Browser: "chrome",
},
- wantUA: "Chrome/" + chromeVersion,
+ wantUA: "Chrome/" + cfg.ChromeVersion,
wantPlat: "",
},
}