High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add configurable port ranges for instance allocation
Marioa0b527e0dff9
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.goindex f06c77e1..f3ec8b77 100644--- a/cmd/pinchtab/cmd_dashboard.go+++ b/cmd/pinchtab/cmd_dashboard.go@@ -42,6 +42,7 @@ func runDashboard(cfg *config.RuntimeConfig) {dash := dashboard.NewDashboard(nil)orch := orchestrator.NewOrchestrator(profilesDir)orch.SetProfileManager(profMgr)+ orch.SetPortRange(cfg.InstancePortStart, cfg.InstancePortEnd)dash.SetInstanceLister(orch)mux := http.NewServeMux()diff --git a/internal/config/config.go b/internal/config/config.goindex 8c133749..0c491e0c 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -11,29 +11,31 @@ import ()type RuntimeConfig struct {- Bind string- Port string- CdpURL string- Token string- StateDir string- Headless bool- NoRestore bool- ProfileDir string- ChromeVersion string- Timezone string- BlockImages bool- BlockMedia bool- BlockAds bool- MaxTabs int- ChromeBinary string- ChromeExtraFlags string- UserAgent string- NoAnimations bool- StealthLevel string- ActionTimeout time.Duration- NavigateTimeout time.Duration- ShutdownTimeout time.Duration- WaitNavDelay time.Duration+ Bind string+ Port string+ InstancePortStart int // Starting port for instances (default 9868)+ InstancePortEnd int // Ending port for instances (default 9968)+ CdpURL string+ Token string+ StateDir string+ Headless bool+ NoRestore bool+ ProfileDir string+ ChromeVersion string+ Timezone string+ BlockImages bool+ BlockMedia bool+ BlockAds bool+ MaxTabs int+ ChromeBinary string+ ChromeExtraFlags string+ UserAgent string+ NoAnimations bool+ StealthLevel string+ ActionTimeout time.Duration+ NavigateTimeout time.Duration+ ShutdownTimeout time.Duration+ WaitNavDelay time.Duration}func envOr(key, fallback string) string {@@ -80,43 +82,47 @@ func (c *RuntimeConfig) ListenAddr() string {}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,omitempty"`- NoRestore bool `json:"noRestore"`- MaxTabs *int `json:"maxTabs,omitempty"`- TimeoutSec int `json:"timeoutSec,omitempty"`- NavigateSec int `json:"navigateSec,omitempty"`+ Port string `json:"port"`+ InstancePortStart *int `json:"instancePortStart,omitempty"`+ InstancePortEnd *int `json:"instancePortEnd,omitempty"`+ CdpURL string `json:"cdpUrl,omitempty"`+ Token string `json:"token,omitempty"`+ StateDir string `json:"stateDir"`+ ProfileDir string `json:"profileDir"`+ Headless *bool `json:"headless,omitempty"`+ NoRestore bool `json:"noRestore"`+ MaxTabs *int `json:"maxTabs,omitempty"`+ TimeoutSec int `json:"timeoutSec,omitempty"`+ NavigateSec int `json:"navigateSec,omitempty"`}func Load() *RuntimeConfig {cfg := &RuntimeConfig{- Bind: envOr("BRIDGE_BIND", "127.0.0.1"),- 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",- BlockAds: envBoolOr("BRIDGE_BLOCK_ADS", false),- MaxTabs: envIntOr("BRIDGE_MAX_TABS", 20),- ChromeBinary: os.Getenv("CHROME_BINARY"),- ChromeExtraFlags: os.Getenv("CHROME_FLAGS"),- UserAgent: os.Getenv("BRIDGE_USER_AGENT"),- 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,+ Bind: envOr("BRIDGE_BIND", "127.0.0.1"),+ Port: envOr("BRIDGE_PORT", "9867"),+ InstancePortStart: envIntOr("INSTANCE_PORT_START", 9868),+ InstancePortEnd: envIntOr("INSTANCE_PORT_END", 9968),+ 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",+ BlockAds: envBoolOr("BRIDGE_BLOCK_ADS", false),+ MaxTabs: envIntOr("BRIDGE_MAX_TABS", 20),+ ChromeBinary: os.Getenv("CHROME_BINARY"),+ ChromeExtraFlags: os.Getenv("CHROME_FLAGS"),+ UserAgent: os.Getenv("BRIDGE_USER_AGENT"),+ 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,}configPath := envOr("BRIDGE_CONFIG", filepath.Join(homeDir(), ".pinchtab", "config.json"))@@ -134,6 +140,12 @@ func Load() *RuntimeConfig {if fc.Port != "" && os.Getenv("BRIDGE_PORT") == "" {cfg.Port = fc.Port}+ if fc.InstancePortStart != nil && os.Getenv("INSTANCE_PORT_START") == "" {+ cfg.InstancePortStart = *fc.InstancePortStart+ }+ if fc.InstancePortEnd != nil && os.Getenv("INSTANCE_PORT_END") == "" {+ cfg.InstancePortEnd = *fc.InstancePortEnd+ }if fc.CdpURL != "" && os.Getenv("CDP_URL") == "" {cfg.CdpURL = fc.CdpURL}@@ -167,14 +179,18 @@ func Load() *RuntimeConfig {func DefaultFileConfig() FileConfig {h := true+ start := 9868+ end := 9968return FileConfig{- Port: "9867",- StateDir: filepath.Join(homeDir(), ".pinchtab"),- ProfileDir: filepath.Join(homeDir(), ".pinchtab", "chrome-profile"),- Headless: &h,- NoRestore: false,- TimeoutSec: 15,- NavigateSec: 30,+ Port: "9867",+ InstancePortStart: &start,+ InstancePortEnd: &end,+ StateDir: filepath.Join(homeDir(), ".pinchtab"),+ ProfileDir: filepath.Join(homeDir(), ".pinchtab", "chrome-profile"),+ Headless: &h,+ NoRestore: false,+ TimeoutSec: 15,+ NavigateSec: 30,}}diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex 40f46fb4..29713e6b 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -25,6 +25,7 @@ type Orchestrator struct {mu sync.RWMutexclient *http.ClientchildAuthToken string+ portAllocator *PortAllocator}type InstanceInternal struct {@@ -67,20 +68,27 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator}}- return &Orchestrator{+ orch := &Orchestrator{instances: make(map[string]*InstanceInternal),baseDir: baseDir,binary: binary,runner: runner,client: &http.Client{Timeout: 3 * time.Second},childAuthToken: os.Getenv("BRIDGE_TOKEN"),+ portAllocator: NewPortAllocator(9868, 9968),}+ return orch}func (o *Orchestrator) SetProfileManager(pm *profiles.ProfileManager) {o.profiles = pm}+// SetPortRange configures the port allocation range+func (o *Orchestrator) SetPortRange(start, end int) {+ o.portAllocator = NewPortAllocator(start, end)+}+func installStableBinary(src, dst string) error {in, err := os.Open(src)if err != nil {diff --git a/internal/orchestrator/ports.go b/internal/orchestrator/ports.gonew file mode 100644index 00000000..9c6f96f6--- /dev/null+++ b/internal/orchestrator/ports.go@@ -0,0 +1,113 @@+package orchestrator++import (+ "fmt"+ "log/slog"+ "net"+ "sync"+)++// PortAllocator manages allocation of ports for instances within a configured range+type PortAllocator struct {+ mu sync.Mutex+ start int+ end int+ allocated map[int]bool // tracks which ports are allocated+ nextCandidate int+}++// NewPortAllocator creates a new port allocator for the given range+func NewPortAllocator(start, end int) *PortAllocator {+ if start < 1 || end < 1 || start > end {+ slog.Error("invalid port range", "start", start, "end", end)+ // Default to a safe range if invalid+ start = 9868+ end = 9968+ }++ return &PortAllocator{+ start: start,+ end: end,+ allocated: make(map[int]bool),+ nextCandidate: start,+ }+}++// AllocatePort finds and allocates the next available port in the range+// Returns error if no ports are available+func (pa *PortAllocator) AllocatePort() (int, error) {+ pa.mu.Lock()+ defer pa.mu.Unlock()++ attempts := 0+ maxAttempts := pa.end - pa.start + 1++ for attempts < maxAttempts {+ candidate := pa.nextCandidate++ // Wrap around to start if we've reached the end+ if candidate > pa.end {+ pa.nextCandidate = pa.start+ candidate = pa.start+ }++ pa.nextCandidate = candidate + 1++ // Skip if already allocated+ if pa.allocated[candidate] {+ attempts+++ continue+ }++ // Check if port is available (not in use by other processes)+ if isPortAvailableInt(candidate) {+ pa.allocated[candidate] = true+ slog.Debug("allocated port", "port", candidate)+ return candidate, nil+ }++ attempts+++ }++ return 0, fmt.Errorf("no available ports in range %d-%d", pa.start, pa.end)+}++// ReleasePort marks a port as no longer allocated+func (pa *PortAllocator) ReleasePort(port int) {+ pa.mu.Lock()+ defer pa.mu.Unlock()++ delete(pa.allocated, port)+ slog.Debug("released port", "port", port)+}++// IsAllocated returns whether a port is currently allocated+func (pa *PortAllocator) IsAllocated(port int) bool {+ pa.mu.Lock()+ defer pa.mu.Unlock()++ return pa.allocated[port]+}++// AllocatedPorts returns a copy of all allocated port numbers+func (pa *PortAllocator) AllocatedPorts() []int {+ pa.mu.Lock()+ defer pa.mu.Unlock()++ ports := make([]int, 0, len(pa.allocated))+ for port := range pa.allocated {+ ports = append(ports, port)+ }+ return ports+}++// isPortAvailableInt checks if a port (as int) is available for binding+func isPortAvailableInt(port int) bool {+ addr := fmt.Sprintf("127.0.0.1:%d", port)+ listener, err := net.Listen("tcp", addr)+ if err != nil {+ return false+ }+ listener.Close()+ return true+}