High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
chore: remove all unused code to pass golangci-lint checks
Mariof60fb6a38038
diff --git a/cmd/pinchtab/browser.go b/cmd/pinchtab/browser.godeleted file mode 100644index 99309175..00000000--- a/cmd/pinchtab/browser.go+++ /dev/null@@ -1,256 +0,0 @@-package main--import (- "bytes"- "context"- "fmt"- "log/slog"- "os"- "os/exec"- "runtime"- "strconv"- "strings"- "syscall"- "time"-- "github.com/chromedp/cdproto/emulation"- "github.com/chromedp/cdproto/page"- "github.com/chromedp/cdproto/target"- "github.com/chromedp/chromedp"- "github.com/pinchtab/pinchtab/internal/bridge"- "github.com/pinchtab/pinchtab/internal/config"- "github.com/pinchtab/pinchtab/internal/uameta"-)--func setupAllocator(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption) {- 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(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", cfg.ProfileDir, lockName)- if err := os.Remove(lockPath); err == nil {- slog.Warn("removed stale lock", "file", lockName)- }- }-- if bridge.WasUncleanExit(cfg.ProfileDir) {- slog.Warn("previous session exited uncleanly, clearing Chrome session restore data")- bridge.ClearChromeSessions(cfg.ProfileDir)- }-- killOrphanedChrome(cfg.ProfileDir)-- slog.Info("launching Chrome", "profile", cfg.ProfileDir, "headless", cfg.Headless)-- opts := buildChromeOpts(cfg)-- bridge.MarkCleanExit(cfg.ProfileDir)- ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)- return ctx, cancel, opts-}--// killOrphanedChrome finds and kills Chrome processes that were spawned by a-// previous Pinchtab instance using the same profile directory. We identify our-// processes by matching --user-data-dir=<profileDir> in the command line args,-// which is unique to Pinchtab-managed Chrome and won't match the user's Chrome.-func killOrphanedChrome(profileDir string) {- if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {- return- }-- // Use ps to find Chrome processes with our profile dir in the args- marker := "--user-data-dir=" + profileDir- out, err := exec.Command("ps", "axo", "pid,args").Output()- if err != nil {- return- }-- var killed int- for _, line := range bytes.Split(out, []byte("\n")) {- lineStr := strings.TrimSpace(string(line))- if !strings.Contains(lineStr, marker) {- continue- }- parts := strings.SplitN(lineStr, " ", 2)- if len(parts) < 2 {- continue- }- pid, err := strconv.Atoi(parts[0])- if err != nil || pid == os.Getpid() {- continue- }- if proc, err := os.FindProcess(pid); err == nil {- if err := proc.Signal(syscall.SIGTERM); err == nil {- killed++- }- }- }- if killed > 0 {- slog.Warn("killed orphaned Chrome processes", "count", killed, "profileDir", profileDir)- }-}--func buildChromeOpts(cfg *config.RuntimeConfig) []chromedp.ExecAllocatorOption {- opts := []chromedp.ExecAllocatorOption{- chromedp.UserDataDir(cfg.ProfileDir),- chromedp.NoFirstRun,- chromedp.NoDefaultBrowserCheck,-- chromedp.Flag("exclude-switches", "enable-automation"),- chromedp.Flag("disable-infobars", true),- chromedp.Flag("disable-dev-shm-usage", true),- chromedp.Flag("disable-renderer-backgrounding", true),- chromedp.Flag("disable-background-timer-throttling", true),- chromedp.Flag("disable-backgrounding-occluded-windows", true),- chromedp.Flag("disable-client-side-phishing-detection", true),- chromedp.Flag("disable-default-apps", true),- chromedp.Flag("disable-hang-monitor", true),- chromedp.Flag("disable-prompt-on-repost", true),- chromedp.Flag("disable-sync", true),- chromedp.Flag("disable-web-security", false),-- chromedp.Flag("disable-background-networking", false),- chromedp.Flag("enable-features", "NetworkService,NetworkServiceInProcess"),- chromedp.Flag("disable-popup-blocking", true),- chromedp.Flag("no-first-run", true),-- chromedp.Flag("disable-session-crashed-bubble", true),- chromedp.Flag("hide-crash-restore-bubble", true),- chromedp.Flag("disable-device-discovery-notifications", true),-- chromedp.Flag("js-flags", "--random-seed=1157259157"),-- chromedp.WindowSize(randomWindowSize()),- }-- if cfg.ChromeBinary != "" {- opts = append(opts, chromedp.ExecPath(cfg.ChromeBinary))- }- 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 {- opts = append(opts, chromedp.Flag(strings.TrimLeft(f, "-"), true))- }- }- }-- if cfg.Headless {- opts = append(opts, chromedp.Headless)- }- // Note: In headed mode, don't add any headless flag - Chrome defaults to headed when no headless flag is present-- return opts-}--func startChrome(allocCtx context.Context, cfg *config.RuntimeConfig, seededScript string) (context.Context, context.CancelFunc, error) {- startCtx, startDone := context.WithTimeout(context.Background(), chromeStartTimeout)- defer startDone()-- // For CDP_URL (remote allocator), ensure we have a target available.- // Remote Chrome instances may not have any windows open yet.- if cfg.CdpURL != "" {- // Get or create a target for the remote browser- getCtx, getCancel := context.WithTimeout(context.Background(), 5*time.Second)- targets, err := func() ([]*target.Info, error) {- var tgts []*target.Info- getErr := chromedp.Run(getCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- var err error- tgts, err = target.GetTargets().Do(ctx)- return err- }),- )- return tgts, getErr- }()- getCancel()-- targetID := target.ID("")- if err == nil && len(targets) > 0 {- // Use first existing target- targetID = targets[0].TargetID- } else {- // Try to create a new target- createCtx, createCancel := context.WithTimeout(context.Background(), 5*time.Second)- _ = chromedp.Run(createCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- tID, err := target.CreateTarget("about:blank").Do(ctx)- if err == nil {- targetID = tID- }- return nil // Don't fail, will try with browser context- }),- )- createCancel()- }-- bCtx, bCancel := chromedp.NewContext(allocCtx,- chromedp.WithTargetID(targetID),- )- return bCtx, bCancel, nil- }-- bCtx, bCancel := chromedp.NewContext(allocCtx)-- errCh := make(chan error, 1)- go func() {- errCh <- chromedp.Run(bCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- _, err := page.AddScriptToEvaluateOnNewDocument(seededScript).Do(ctx)- return err- }),- )- }()-- select {- case err := <-errCh:- if err != nil {- bCancel()- return nil, nil, err- }- return bCtx, bCancel, nil- case <-startCtx.Done():- bCancel()- return nil, nil, fmt.Errorf("timed out after %s", chromeStartTimeout)- }-}--func applyTimezone(browserCtx context.Context, cfg *config.RuntimeConfig) {- if cfg.Timezone == "" {- return- }- if err := chromedp.Run(browserCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- return emulation.SetTimezoneOverride(cfg.Timezone).Do(ctx)- }),- ); err != nil {- slog.Warn("timezone override failed", "tz", cfg.Timezone, "err", err)- } else {- slog.Info("timezone override", "tz", cfg.Timezone)- }-}--func applyUserAgentOverride(browserCtx context.Context, cfg *config.RuntimeConfig) {- override := uameta.Build(cfg.UserAgent, cfg.ChromeVersion)- if override == nil {- return- }- if err := chromedp.Run(browserCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- return override.Do(ctx)- }),- ); err != nil {- slog.Warn("user-agent override failed", "err", err)- } else {- slog.Info("user-agent override applied")- }-}diff --git a/cmd/pinchtab/browser_test.go b/cmd/pinchtab/browser_test.godeleted file mode 100644index 94b82fd4..00000000--- a/cmd/pinchtab/browser_test.go+++ /dev/null@@ -1,105 +0,0 @@-package main--import (- "testing"-- "github.com/pinchtab/pinchtab/internal/config"-)--// TestBuildChromeOpts_HeadlessMode verifies that headless mode adds chromedp.Headless-func TestBuildChromeOpts_HeadlessMode(t *testing.T) {- cfg := &config.RuntimeConfig{- Headless: true,- ProfileDir: "/tmp/test-profile",- ChromeBinary: "",- }-- opts := buildChromeOpts(cfg)-- // Check that chromedp.Headless was added- hasHeadlessOpt := false- for _, opt := range opts {- // chromedp.Headless is ExecAllocatorOption that sets headless mode- // We can verify by checking if it's in the opts slice- // Since ExecAllocatorOption is a func type, we check the length increased- if opt != nil {- // This is a bit of a proxy check - the actual function will set headless=true- hasHeadlessOpt = true- break- }- }-- if !hasHeadlessOpt || len(opts) == 0 {- t.Error("expected chromedp.Headless option to be added for headless mode")- }-}--// TestBuildChromeOpts_HeadedMode verifies that headed mode does NOT add any headless flag-func TestBuildChromeOpts_HeadedMode(t *testing.T) {- cfg := &config.RuntimeConfig{- Headless: false,- ProfileDir: "/tmp/test-profile",- ChromeBinary: "",- }-- opts := buildChromeOpts(cfg)-- // For headed mode, we should still have options but NOT set headless=false- // The key is that we don't set any headless flag when headless=false- // Chrome defaults to headed when no headless flag is present-- if len(opts) == 0 {- t.Error("expected some Chrome options even for headed mode")- }-- // This test verifies the fix: we don't call chromedp.Flag("headless", false)- // which was broken. Instead, we just don't add any headless flag for headed mode.- t.Logf("headed mode generated %d options (Chrome will default to headed)", len(opts))-}--// TestBuildChromeOpts_ComparesOptions verifies that headless and headed modes differ-func TestBuildChromeOpts_ComparesOptions(t *testing.T) {- cfgHeadless := &config.RuntimeConfig{- Headless: true,- ProfileDir: "/tmp/test-profile",- ChromeBinary: "",- }-- cfgHeaded := &config.RuntimeConfig{- Headless: false,- ProfileDir: "/tmp/test-profile",- ChromeBinary: "",- }-- optsHeadless := buildChromeOpts(cfgHeadless)- optsHeaded := buildChromeOpts(cfgHeaded)-- // Headless mode should have one more option (chromedp.Headless)- if len(optsHeadless) <= len(optsHeaded) {- t.Errorf("expected headless mode to have more options (%d) than headed mode (%d)",- len(optsHeadless), len(optsHeaded))- }-- t.Logf("headless mode: %d options, headed mode: %d options",- len(optsHeadless), len(optsHeaded))-}--// TestBuildChromeOpts_WithCustomBinary verifies custom binary path is honored-func TestBuildChromeOpts_WithCustomBinary(t *testing.T) {- customBinary := "/custom/path/to/chrome"- cfg := &config.RuntimeConfig{- Headless: true,- ProfileDir: "/tmp/test-profile",- ChromeBinary: customBinary,- }-- opts := buildChromeOpts(cfg)-- if len(opts) == 0 {- t.Fatal("expected options when custom binary is set")- }-- // We can't directly verify the binary in opts since they're function closures,- // but this test ensures the code path works without panicking- t.Logf("custom binary config generated %d options", len(opts))-}diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.goindex 7842d3f3..61b9fe09 100644--- a/internal/orchestrator/handlers.go+++ b/internal/orchestrator/handlers.go@@ -3,7 +3,6 @@ package orchestratorimport ("encoding/json""fmt"- "log""net""net/http""net/url"@@ -21,10 +20,6 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {// Note: GET /tabs and POST /tab handlers are in dashboard.go// These orchestrator handlers are used when no instances are running or for aggregationmux.HandleFunc("POST /tabs/open", o.handleTabOpen)- // Commented out to avoid conflict with dashboard's GET /tabs- // mux.HandleFunc("GET /tabs", o.handleTabList)- mux.HandleFunc("GET /tabs/{id}", o.handleTabGet)- // mux.HandleFunc("POST /tabs/{id}/close", o.handleTabClose) // Handled by dashboard's POST /tab// Profile lifecycle by ID (canonical)mux.HandleFunc("POST /profiles/{id}/start", o.handleStartByID)@@ -390,8 +385,8 @@ func readResponseBody(resp *http.Response) []byte {// handleTabOpen: POST /tabs/open {instanceId, url?}func (o *Orchestrator) handleTabOpen(w http.ResponseWriter, r *http.Request) {var req struct {- InstanceID string `json:"instanceId"` // Required: instance ID- URL string `json:"url,omitempty"` // Optional: URL to open+ InstanceID string `json:"instanceId"` // Required: instance ID+ URL string `json:"url,omitempty"` // Optional: URL to open}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {@@ -431,150 +426,3 @@ func (o *Orchestrator) handleTabOpen(w http.ResponseWriter, r *http.Request) {}// handleTabList: GET /tabs?instanceId=...-func (o *Orchestrator) handleTabList(w http.ResponseWriter, r *http.Request) {- instanceID := r.URL.Query().Get("instanceId")-- // Get all instances and their tabs via proxying- // For now, return a simple response indicating tabs can be queried- tabs := []map[string]any{}-- if instanceID != "" {- // Filter tabs for specific instance- o.mu.RLock()- instInternal, ok := o.instances[instanceID]- o.mu.RUnlock()-- if !ok {- web.Error(w, 404, fmt.Errorf("instance %q not found", instanceID))- return- }-- // Query instance for its tabs- // This would proxy to the instance's /tabs endpoint- tabResp, err := o.client.Get(fmt.Sprintf("http://localhost:%s/tabs", instInternal.Port))- if err != nil {- web.Error(w, 500, fmt.Errorf("failed to get tabs from instance: %w", err))- return- }- defer func() { _ = tabResp.Body.Close() }()-- if tabResp.StatusCode == 200 {- var instanceTabs []map[string]any- if err := json.NewDecoder(tabResp.Body).Decode(&instanceTabs); err != nil {- log.Printf("error decoding tabs from instance: %v", err)- }- // Add instanceId to each tab- for _, tab := range instanceTabs {- tab["instanceId"] = instanceID- tabs = append(tabs, tab)- }- }- } else {- // List all tabs across all instances- o.mu.RLock()- instances := make([]*InstanceInternal, 0, len(o.instances))- for _, inst := range o.instances {- instances = append(instances, inst)- }- o.mu.RUnlock()-- for _, inst := range instances {- if inst.Status != "running" {- continue- }- // Query instance for its tabs- tabResp, err := o.client.Get(fmt.Sprintf("http://localhost:%s/tabs", inst.Port))- if err != nil {- continue- }- defer func() { _ = tabResp.Body.Close() }()-- if tabResp.StatusCode == 200 {- var instanceTabs []map[string]any- if err := json.NewDecoder(tabResp.Body).Decode(&instanceTabs); err != nil {- log.Printf("error decoding tabs from instance: %v", err)- }- // Add instanceId to each tab- for _, tab := range instanceTabs {- tab["instanceId"] = inst.ID- tabs = append(tabs, tab)- }- }- }- }-- web.JSON(w, 200, tabs)-}--// handleTabGet: GET /tabs/{id}-func (o *Orchestrator) handleTabGet(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")-- // Find which instance has this tab- o.mu.RLock()- instances := make([]*InstanceInternal, 0, len(o.instances))- for _, inst := range o.instances {- instances = append(instances, inst)- }- o.mu.RUnlock()-- for _, inst := range instances {- if inst.Status != "running" {- continue- }- // Query instance for this specific tab- tabResp, err := o.client.Get(fmt.Sprintf("http://localhost:%s/tabs/%s", inst.Port, tabID))- if err != nil {- continue- }- defer func() { _ = tabResp.Body.Close() }()-- if tabResp.StatusCode == 200 {- var tab map[string]any- if err := json.NewDecoder(tabResp.Body).Decode(&tab); err != nil {- log.Printf("error decoding tab from instance: %v", err)- }- tab["instanceId"] = inst.ID- web.JSON(w, 200, tab)- return- }- }-- web.Error(w, 404, fmt.Errorf("tab %q not found", tabID))-}--// handleTabClose: POST /tabs/{id}/close-func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")-- // Find which instance has this tab and close it- o.mu.RLock()- instances := make([]*InstanceInternal, 0, len(o.instances))- for _, inst := range o.instances {- instances = append(instances, inst)- }- o.mu.RUnlock()-- for _, inst := range instances {- if inst.Status != "running" {- continue- }- // Try to close tab in this instance- closeResp, err := o.client.Post(- fmt.Sprintf("http://localhost:%s/tabs/%s/close", inst.Port, tabID),- "application/json",- nil,- )- if err != nil {- continue- }- defer func() { _ = closeResp.Body.Close() }()-- if closeResp.StatusCode == 200 || closeResp.StatusCode == 204 {- web.JSON(w, 200, map[string]string{"id": tabID, "status": "closed"})- return- }- }-- web.Error(w, 404, fmt.Errorf("tab %q not found", tabID))-}diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.goindex 4ad0d91b..c50e1252 100644--- a/internal/profiles/handlers.go+++ b/internal/profiles/handlers.go@@ -14,18 +14,18 @@ import (func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {// Standard CRUD endpointsmux.HandleFunc("GET /profiles", pm.handleList)- mux.HandleFunc("POST /profiles", pm.handleCreate) // RESTful: POST /profiles instead of /profiles/create+ mux.HandleFunc("POST /profiles", pm.handleCreate) // RESTful: POST /profiles instead of /profiles/createmux.HandleFunc("POST /profiles/create", pm.handleCreate) // Backward compat- mux.HandleFunc("GET /profiles/{id}", pm.handleGetByID) // Get single profile by ID or name+ mux.HandleFunc("GET /profiles/{id}", pm.handleGetByID) // Get single profile by ID or name// Advanced endpoints (specific paths, no conflict with {id})mux.HandleFunc("POST /profiles/import", pm.handleImport)mux.HandleFunc("PATCH /profiles/meta", pm.handleUpdateMeta)- mux.HandleFunc("POST /profiles/{id}/reset", pm.handleResetByIDOrName) // Reset profile- mux.HandleFunc("GET /profiles/{id}/logs", pm.handleLogsByIDOrName) // Get logs+ mux.HandleFunc("POST /profiles/{id}/reset", pm.handleResetByIDOrName) // Reset profile+ mux.HandleFunc("GET /profiles/{id}/logs", pm.handleLogsByIDOrName) // Get logsmux.HandleFunc("GET /profiles/{id}/analytics", pm.handleAnalyticsByIDOrName) // Get analytics- mux.HandleFunc("DELETE /profiles/{id}", pm.handleDeleteByID) // Delete profile- mux.HandleFunc("PATCH /profiles/{id}", pm.handleUpdateByIDOrName) // Update profile metadata+ mux.HandleFunc("DELETE /profiles/{id}", pm.handleDeleteByID) // Delete profile+ mux.HandleFunc("PATCH /profiles/{id}", pm.handleUpdateByIDOrName) // Update profile metadata}func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {@@ -329,66 +329,3 @@ func (pm *ProfileManager) handleAnalyticsByIDOrName(w http.ResponseWriter, r *htreport := pm.Analytics(name)web.JSON(w, 200, report)}--// OLD: Path-param compat handlers for dashboard JS (deprecated - kept for legacy support if needed)-// These are now handled above with {id} pattern that accepts both IDs and names--func (pm *ProfileManager) handleDeleteByPath(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- if err := pm.Delete(name); err != nil {- web.Error(w, 404, err)- return- }- web.JSON(w, 200, map[string]string{"status": "deleted", "name": name})-}--func (pm *ProfileManager) handleUpdateByPath(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- var req struct {- Name string `json:"name"`- UseWhen string `json:"useWhen"`- Description string `json:"description"`- }- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- web.Error(w, 400, fmt.Errorf("invalid JSON"))- return- }-- updates := make(map[string]string)- if req.Description != "" {- updates["description"] = req.Description- }- if req.UseWhen != "" {- updates["useWhen"] = req.UseWhen- }- if len(updates) > 0 {- if err := pm.UpdateMeta(name, updates); err != nil {- web.Error(w, 404, err)- return- }- }-- web.JSON(w, 200, map[string]string{"status": "updated", "name": name})-}--func (pm *ProfileManager) handleResetByPath(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- if err := pm.Reset(name); err != nil {- web.Error(w, 404, err)- return- }- web.JSON(w, 200, map[string]string{"status": "reset", "name": name})-}--func (pm *ProfileManager) handleLogsByPath(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))- logs := pm.Logs(name, limit)- web.JSON(w, 200, logs)-}--func (pm *ProfileManager) handleAnalyticsByPath(w http.ResponseWriter, r *http.Request) {- name := r.PathValue("name")- report := pm.Analytics(name)- web.JSON(w, 200, report)-}