High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: align health auth and browser preflight
Mario1b3df63781e0
diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.goindex 9d7fe8d3..b5d6f4bc 100644--- a/cmd/pinchtab/cmd_cli_runtime.go+++ b/cmd/pinchtab/cmd_cli_runtime.go@@ -74,22 +74,23 @@ func preflightBrowserBinary(cfg *config.RuntimeConfig) error {if cfg == nil || strings.TrimSpace(cfg.CDPAttachURL) != "" {return nil // attaching to an external CDP endpoint; no local binary needed}- browserID := config.NormalizeBrowser(cfg.DefaultBrowser)+ effective := runtimekit.ResolveEffectiveBrowser(cfg)+ browserID := effective.IDif _, ok := browsers.Get(browserID); !ok {return nil // unknown provider — let the normal path report it}- if override := strings.TrimSpace(cfg.BrowserBinary); override != "" {+ if override := strings.TrimSpace(effective.Binary); override != "" {if info, err := os.Stat(override); err != nil || info.IsDir() {- return fmt.Errorf("configured browser.binary does not point at a usable executable: %s\n"+- " Point it at an existing browser binary, or unset it to use auto-discovery. "++ return fmt.Errorf("configured browser executable does not point at a usable executable: %s\n"++ " Point the active browser config at an existing browser binary, or unset it to use auto-discovery. "+"Run `pinchtab doctor` for details", override)}return nil}- if runtimekit.FindBrowserBinary(browserID) == "" {+ if effective.Binary == "" {return fmt.Errorf("no %s browser found on this machine.\n"+" Install one (e.g. Google Chrome for Testing, or `apt-get install -y chromium` "+- "on Debian/Ubuntu) or set browser.binary in your config.\n"++ "on Debian/Ubuntu) or set a browser binary in your config.\n"+" Run `pinchtab doctor` for the full diagnosis", browserID)}return nildiff --git a/cmd/pinchtab/cmd_cli_runtime_test.go b/cmd/pinchtab/cmd_cli_runtime_test.goindex 29cb63d4..c007eed7 100644--- a/cmd/pinchtab/cmd_cli_runtime_test.go+++ b/cmd/pinchtab/cmd_cli_runtime_test.go@@ -207,8 +207,8 @@ func TestPreflightBrowserBinary(t *testing.T) {if err == nil {t.Fatal("expected error for a missing browser.binary override")}- if !strings.Contains(err.Error(), "browser.binary") || !strings.Contains(err.Error(), "doctor") {- t.Errorf("error should name browser.binary and point at doctor; got: %v", err)+ if !strings.Contains(err.Error(), "browser executable") || !strings.Contains(err.Error(), "doctor") {+ t.Errorf("error should describe the configured browser executable and point at doctor; got: %v", err)}})@@ -221,6 +221,20 @@ func TestPreflightBrowserBinary(t *testing.T) {}})+ t.Run("default target binary passes", func(t *testing.T) {+ if err := preflightBrowserBinary(&config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ Targets: config.BrowserTargetsConfig{+ "only": {+ Provider: config.BrowserCloak,+ Binary: existing,+ },+ },+ }); err != nil {+ t.Errorf("expected nil for an existing default-target binary; got %v", err)+ }+ })+t.Run("external CDP attach skips local binary check", func(t *testing.T) {if err := preflightBrowserBinary(&config.RuntimeConfig{DefaultBrowser: "chrome",diff --git a/cmd/pinchtab/cmd_daemon.go b/cmd/pinchtab/cmd_daemon.goindex 1c13640c..b1ba0362 100644--- a/cmd/pinchtab/cmd_daemon.go+++ b/cmd/pinchtab/cmd_daemon.go@@ -5,6 +5,7 @@ import ("os""github.com/pinchtab/pinchtab/internal/browsers/chrome"+ "github.com/pinchtab/pinchtab/internal/browsers/runtimekit""github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/daemon"@@ -84,15 +85,16 @@ func handleDaemonInstall(manager daemon.Manager) {printDaemonActionError(manager, fmt.Sprintf("daemon install failed: %v", err))}fmt.Println(cli.StyleStdout(cli.SuccessStyle, " [ok] ") + message)- warnPrimaryChromeMacOS(fileCfg)+ warnPrimaryChromeMacOS(loadConfig())printDaemonFollowUp()}// warnPrimaryChromeMacOS surfaces the issue #583 collision at install time:// on macOS, auto-launching the user's daily Google Chrome for headless// automation can stop their normal Chrome from opening a window.-func warnPrimaryChromeMacOS(fileCfg *config.FileConfig) {- if fileCfg == nil || !chrome.ResolvesToPrimaryChromeMacOS(fileCfg.BrowserBinary()) {+func warnPrimaryChromeMacOS(cfg *config.RuntimeConfig) {+ effective := runtimekit.ResolveEffectiveBrowser(cfg)+ if effective.ID != config.BrowserChrome || !chrome.IsPrimaryChromeBinaryMacOS(effective.Binary) {return}fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle,diff --git a/cmd/pinchtab/cmd_mcp_test.go b/cmd/pinchtab/cmd_mcp_test.goindex c8b55ccf..2efc0405 100644--- a/cmd/pinchtab/cmd_mcp_test.go+++ b/cmd/pinchtab/cmd_mcp_test.go@@ -57,6 +57,21 @@ func TestIsServerHealthy_SendsAuthHeader(t *testing.T) {}}+func TestIsServerHealthy_SendsSessionAuthHeader(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Session ses_testtoken" {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ w.WriteHeader(http.StatusOK)+ }))+ defer ts.Close()++ if !isServerHealthy(ts.URL, "ses_testtoken") {+ t.Fatal("expected healthy server with session token to return true")+ }+}+func TestWaitForServer_ImmediatelyHealthy(t *testing.T) {ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)diff --git a/cmd/pinchtab/cmd_server_ensure.go b/cmd/pinchtab/cmd_server_ensure.goindex b351c876..3fc38676 100644--- a/cmd/pinchtab/cmd_server_ensure.go+++ b/cmd/pinchtab/cmd_server_ensure.go@@ -50,8 +50,8 @@ func ensureServerWithAutoStart(baseURL, token, command string, allowAutoStart bofunc isServerHealthy(baseURL, token string) bool {headers := map[string]string{}- if token != "" {- headers["Authorization"] = "Bearer " + token+ if auth := server.AuthorizationHeaderValue(token); auth != "" {+ headers["Authorization"] = auth}status, _, reachable := server.ProbeHealth(baseURL+"/health", 3*time.Second, headers)return reachable && status < 500diff --git a/cmd/pinchtab/root_health.go b/cmd/pinchtab/root_health.goindex 44ffedba..c3c6a9ab 100644--- a/cmd/pinchtab/root_health.go+++ b/cmd/pinchtab/root_health.go@@ -61,8 +61,8 @@ func fetchHealthSnapshot(port string) (*healthSnapshot, healthSnapshotState) {// /health (the unauthenticated probe would just see a protected listener).func fetchHealthSnapshotWithToken(port, token string) (*healthSnapshot, healthSnapshotState) {var headers map[string]string- if strings.TrimSpace(token) != "" {- headers = map[string]string{"Authorization": "Bearer " + token}+ if auth := server.AuthorizationHeaderValue(token); auth != "" {+ headers = map[string]string{"Authorization": auth}}status, body, reachable := server.ProbeHealth(fmt.Sprintf("http://localhost:%s/health", port), 500*time.Millisecond, headers)if !reachable {diff --git a/internal/browsers/chrome/chrome.go b/internal/browsers/chrome/chrome.goindex b84f0204..54c83825 100644--- a/internal/browsers/chrome/chrome.go+++ b/internal/browsers/chrome/chrome.go@@ -116,6 +116,10 @@ func (Browser) Capabilities() browsers.CapabilitySet {)}+func IsPrimaryChromeBinaryMacOS(binary string) bool {+ return runtime.GOOS == "darwin" && strings.TrimSpace(binary) == primaryChromeAppMacOS+}+// ResolvesToPrimaryChromeMacOS reports whether, absent an explicit binary// override, Chrome discovery would launch the user's daily Google Chrome on// macOS — the configuration that triggers the issue #583 LaunchServices@@ -125,7 +129,7 @@ func ResolvesToPrimaryChromeMacOS(binaryOverride string) bool {return false}d := browserprobe.DiscoverBinary(BinaryNames(), CommonPaths(runtime.GOOS))- return d.Found == primaryChromeAppMacOS+ return IsPrimaryChromeBinaryMacOS(d.Found)}func (Browser) DiscoverBinary() browsers.BinaryDiscovery {diff --git a/internal/browsers/runtimekit/runtimekit.go b/internal/browsers/runtimekit/runtimekit.goindex d7efc93f..bb979b67 100644--- a/internal/browsers/runtimekit/runtimekit.go+++ b/internal/browsers/runtimekit/runtimekit.go@@ -17,6 +17,12 @@ type ProviderLaunchPlan struct {Binary string}+type EffectiveBrowser struct {+ ID string+ Binary string+ Config *config.RuntimeConfig+}+func RuntimeProxyConfig(cfg *config.RuntimeConfig) browsers.ProxyConfig {if cfg == nil {return browsers.ProxyConfig{}@@ -92,6 +98,26 @@ func FindBrowserBinary(browserID string) string {return b.DiscoverBinary().Found}+func ResolveEffectiveBrowser(cfg *config.RuntimeConfig) EffectiveBrowser {+ if cfg == nil {+ return EffectiveBrowser{}+ }+ effectiveCfg := cfg+ if resolved, err := config.ResolveDefaultBrowserTarget(cfg); err == nil && resolved != nil && resolved.Config != nil {+ effectiveCfg = resolved.Config+ }+ browserID := config.NormalizeBrowser(effectiveCfg.DefaultBrowser)+ binary := strings.TrimSpace(effectiveCfg.BrowserBinary)+ if binary == "" {+ binary = FindBrowserBinary(browserID)+ }+ return EffectiveBrowser{+ ID: browserID,+ Binary: binary,+ Config: effectiveCfg,+ }+}+func BaseFlagArgs(browserID string, headless bool) []string {args, _, err := browsers.MustGet(browserID).BuildLaunchArgs(browsers.LaunchConfig{Headless: headless})if err != nil {diff --git a/internal/browsers/runtimekit/runtimekit_test.go b/internal/browsers/runtimekit/runtimekit_test.goindex 8c62720d..c2e163d6 100644--- a/internal/browsers/runtimekit/runtimekit_test.go+++ b/internal/browsers/runtimekit/runtimekit_test.go@@ -170,6 +170,28 @@ func TestFindBrowserBinary_UnknownProvider(t *testing.T) {}}+func TestResolveEffectiveBrowser_PromotesDefaultTargetBinary(t *testing.T) {+ cfg := &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ Targets: config.BrowserTargetsConfig{+ "only": {+ Provider: config.BrowserCloak,+ Binary: "/opt/cloak/chrome",+ },+ },+ }+ got := ResolveEffectiveBrowser(cfg)+ if got.ID != config.BrowserCloak {+ t.Fatalf("ID = %q, want %q", got.ID, config.BrowserCloak)+ }+ if got.Binary != "/opt/cloak/chrome" {+ t.Fatalf("Binary = %q, want %q", got.Binary, "/opt/cloak/chrome")+ }+ if got.Config == nil || got.Config.BrowserBinary != "/opt/cloak/chrome" {+ t.Fatalf("resolved config missing target binary: %+v", got.Config)+ }+}+func TestBaseFlagArgs_Chrome(t *testing.T) {args := BaseFlagArgs("chrome", false)if len(args) == 0 {diff --git a/internal/orchestrator/browser_preflight.go b/internal/orchestrator/browser_preflight.goindex 391b31fc..db3aaa8a 100644--- a/internal/orchestrator/browser_preflight.go+++ b/internal/orchestrator/browser_preflight.go@@ -8,7 +8,6 @@ import ("github.com/pinchtab/pinchtab/internal/browsers""github.com/pinchtab/pinchtab/internal/browsers/runtimekit"- "github.com/pinchtab/pinchtab/internal/config")// BrowserUnavailableReason reports whether the request's target browser has no@@ -18,36 +17,36 @@ import (// opaque-503 cold start surfaced by install-UX testing, on the API path as well// as the CLI.//-// It deliberately speaks only to the simple default/single-provider case. An-// explicit per-request browser, a multi-target config, or a CDP attach all fall-// through (return false) so existing behavior and HTTP error mapping are-// unchanged. It mirrors the launch-time resolution in bridge/runtime.InitBrowser-// (explicit browser.binary wins over discovery) so it can't diverge from what-// the instance would actually try to launch.+// It deliberately avoids explicit per-request browser overrides, since those may+// select a different target/provider than the instance's default launch path.+// For the normal implicit path it mirrors the launch-time resolution in+// bridge/runtime.InitBrowser, including default-target promotion, so it can't+// diverge from what the instance would actually try to launch.func (o *Orchestrator) BrowserUnavailableReason(r *http.Request) (string, bool) {if o == nil || o.runtimeCfg == nil {return "", false}- if ExtractRequestedBrowser(r) != "" || len(o.runtimeCfg.Targets) > 0 {+ if ExtractRequestedBrowser(r) != "" {return "", false}if strings.TrimSpace(o.runtimeCfg.CDPAttachURL) != "" {return "", false // attaching to an external CDP endpoint; no local binary needed}- provider := config.NormalizeBrowser(o.runtimeCfg.DefaultBrowser)+ effective := runtimekit.ResolveEffectiveBrowser(o.runtimeCfg)+ provider := effective.IDif _, ok := browsers.Get(provider); !ok {return "", false}- if override := strings.TrimSpace(o.runtimeCfg.BrowserBinary); override != "" {+ if override := strings.TrimSpace(effective.Binary); override != "" {if info, err := os.Stat(override); err != nil || info.IsDir() {- return fmt.Sprintf("configured browser.binary does not point at a usable executable: %s — "+- "set it to a real browser or unset it for auto-discovery (run `pinchtab doctor`)", override), true+ return fmt.Sprintf("configured browser executable does not point at a usable executable: %s — "++ "set the active browser config to a real browser or unset it for auto-discovery (run `pinchtab doctor`)", override), true}return "", false}- if runtimekit.FindBrowserBinary(provider) == "" {+ if effective.Binary == "" {return fmt.Sprintf("no %s browser found on this host — install Chrome/Chromium "+- "(e.g. `apt-get install -y chromium`) or set browser.binary (run `pinchtab doctor`)", provider), true+ "(e.g. `apt-get install -y chromium`) or set a browser binary in config (run `pinchtab doctor`)", provider), true}return "", false}diff --git a/internal/orchestrator/browser_preflight_test.go b/internal/orchestrator/browser_preflight_test.goindex 89c83e5a..bd54e219 100644--- a/internal/orchestrator/browser_preflight_test.go+++ b/internal/orchestrator/browser_preflight_test.go@@ -43,6 +43,21 @@ func TestBrowserUnavailableReason(t *testing.T) {}})+ t.Run("default target binary is available", func(t *testing.T) {+ o := &Orchestrator{runtimeCfg: &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ Targets: config.BrowserTargetsConfig{+ "only": {+ Provider: config.BrowserCloak,+ Binary: existing,+ },+ },+ }}+ if _, unavailable := o.BrowserUnavailableReason(req("/text?url=http://x/")); unavailable {+ t.Error("an existing default-target binary should be available")+ }+ })+t.Run("explicit per-request browser falls through", func(t *testing.T) {o := &Orchestrator{runtimeCfg: &config.RuntimeConfig{DefaultBrowser: "chrome",diff --git a/internal/server/helpers.go b/internal/server/helpers.goindex b62587ea..b57e53c2 100644--- a/internal/server/helpers.go+++ b/internal/server/helpers.go@@ -4,6 +4,7 @@ import ("fmt""io""net/http"+ "strings""time""github.com/pinchtab/pinchtab/internal/httpx"@@ -35,10 +36,21 @@ func ProbeHealth(url string, timeout time.Duration, headers map[string]string) (return resp.StatusCode, b, true}+func AuthorizationHeaderValue(token string) string {+ token = strings.TrimSpace(token)+ if token == "" {+ return ""+ }+ if strings.HasPrefix(token, "ses_") {+ return "Session " + token+ }+ return "Bearer " + token+}+func CheckPinchTabRunning(port, token string) bool {headers := map[string]string{}- if token != "" {- headers["Authorization"] = "Bearer " + token+ if auth := AuthorizationHeaderValue(token); auth != "" {+ headers["Authorization"] = auth}status, _, reachable := ProbeHealth(fmt.Sprintf("http://localhost:%s/health", port), 500*time.Millisecond, headers)return reachable && status == 200@@ -91,8 +103,8 @@ func ShutdownServer(port, token string) error {if err != nil {return fmt.Errorf("build request: %w", err)}- if token != "" {- req.Header.Set("Authorization", "Bearer "+token)+ if auth := AuthorizationHeaderValue(token); auth != "" {+ req.Header.Set("Authorization", auth)}resp, err := client.Do(req)if err != nil {diff --git a/internal/server/helpers_test.go b/internal/server/helpers_test.goindex 925e45fa..de6d30cf 100644--- a/internal/server/helpers_test.go+++ b/internal/server/helpers_test.go@@ -6,6 +6,26 @@ import ("github.com/pinchtab/pinchtab/internal/routes")+func TestAuthorizationHeaderValue(t *testing.T) {+ tests := []struct {+ name string+ token string+ want string+ }{+ {name: "empty", token: "", want: ""},+ {name: "bearer token", token: "server-token", want: "Bearer server-token"},+ {name: "session token", token: "ses_token123", want: "Session ses_token123"},+ {name: "trimmed session token", token: " ses_token123 ", want: "Session ses_token123"},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := AuthorizationHeaderValue(tt.token); got != tt.want {+ t.Fatalf("AuthorizationHeaderValue(%q) = %q, want %q", tt.token, got, tt.want)+ }+ })+ }+}+// TestDefaultProxyShorthandsAreCatalogRoutes guards against the default-proxy// allowlist drifting from the shared route catalog: every forwarded route must// be a real catalog route (or the management GET /tabs handled separately), so a