Skip to content

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

feat: add POST /instances/attach endpoint

Bosch581beab7a428
diff --git a/internal/api/types/types.go b/internal/api/types/types.go
index 4b455f19..0c6342d5 100644
--- a/internal/api/types/types.go
+++ b/internal/api/types/types.go
@@ -37,6 +37,8 @@ type Instance struct {
Status string `json:"status"` // starting/running/stopping/stopped/error
StartTime time.Time `json:"startTime"`
Error string `json:"error,omitempty"`
+ Attached bool `json:"attached"` // True if attached to external Chrome
+ CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for attached instances)
}
// Agent represents a connected AI agent.
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index da3d754c..2b136732 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -127,6 +127,8 @@ type Instance struct {
Status string `json:"status"` // Status: starting/running/stopping/stopped/error
StartTime time.Time `json:"startTime"` // When instance was created
Error string `json:"error,omitempty"` // Error message if status=error
+ Attached bool `json:"attached"` // True if attached to external Chrome (not launched)
+ CdpURL string `json:"cdpUrl,omitempty"` // CDP WebSocket URL (for attached instances)
}
type InstanceTab struct {
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index ee8b777c..5c483999 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -19,6 +19,7 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /instances/metrics", o.handleAllMetrics)
mux.HandleFunc("POST /instances/start", o.handleStartInstance)
mux.HandleFunc("POST /instances/launch", o.handleLaunchByName)
+ mux.HandleFunc("POST /instances/attach", o.handleAttachInstance)
mux.HandleFunc("POST /instances/{id}/start", o.handleStartByInstanceID)
mux.HandleFunc("POST /instances/{id}/stop", o.handleStopByInstanceID)
mux.HandleFunc("GET /instances/{id}/logs", o.handleLogsByID)
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index cde93f69..2228746a 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -182,3 +182,83 @@ func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Reques
web.JSON(w, 201, inst)
}
+
+func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ CdpURL string `json:"cdpUrl"`
+ Name string `json:"name,omitempty"`
+ }
+
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("invalid JSON"))
+ return
+ }
+
+ if req.CdpURL == "" {
+ web.Error(w, 400, fmt.Errorf("cdpUrl is required"))
+ return
+ }
+
+ // Validate attach is enabled and URL is allowed
+ if err := o.validateAttachURL(req.CdpURL); err != nil {
+ web.Error(w, 403, err)
+ return
+ }
+
+ // Generate name if not provided
+ name := req.Name
+ if name == "" {
+ name = fmt.Sprintf("attached-%d", time.Now().UnixNano())
+ }
+
+ inst, err := o.Attach(name, req.CdpURL)
+ if err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+
+ web.JSON(w, 201, inst)
+}
+
+// validateAttachURL checks if attach is enabled and the CDP URL is allowed.
+func (o *Orchestrator) validateAttachURL(cdpURL string) error {
+ if o.runtimeCfg == nil {
+ return fmt.Errorf("attach not configured")
+ }
+
+ if !o.runtimeCfg.AttachEnabled {
+ return fmt.Errorf("attach is disabled")
+ }
+
+ parsed, err := url.Parse(cdpURL)
+ if err != nil {
+ return fmt.Errorf("invalid cdpUrl: %w", err)
+ }
+
+ // Validate scheme
+ schemeAllowed := false
+ for _, allowed := range o.runtimeCfg.AttachAllowSchemes {
+ if parsed.Scheme == allowed {
+ schemeAllowed = true
+ break
+ }
+ }
+ if !schemeAllowed {
+ return fmt.Errorf("scheme %q not allowed (allowed: %v)", parsed.Scheme, o.runtimeCfg.AttachAllowSchemes)
+ }
+
+ // Validate host
+ host := parsed.Hostname()
+ hostAllowed := false
+ for _, allowed := range o.runtimeCfg.AttachAllowHosts {
+ if host == allowed {
+ hostAllowed = true
+ break
+ }
+ }
+ if !hostAllowed {
+ return fmt.Errorf("host %q not allowed (allowed: %v)", host, o.runtimeCfg.AttachAllowHosts)
+ }
+
+ return nil
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index aca61eaf..479275b4 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -355,6 +355,53 @@ func (o *Orchestrator) writeChildConfig(port, profilePath, instanceStateDir stri
return configPath, nil
}
+// Attach connects to an externally managed Chrome instance via CDP URL.
+// Unlike Launch, this does not start a Chrome process - it only registers
+// the external instance for tracking and proxying.
+func (o *Orchestrator) Attach(name, cdpURL string) (*bridge.Instance, error) {
+ o.mu.Lock()
+
+ // Check for duplicate name
+ for _, inst := range o.instances {
+ if inst.ProfileName == name && instanceIsActive(inst) {
+ o.mu.Unlock()
+ return nil, fmt.Errorf("instance with name %q already exists", name)
+ }
+ }
+ o.mu.Unlock()
+
+ // Generate IDs (use name as pseudo-profile)
+ profileID := o.idMgr.ProfileID(name)
+ instanceID := o.idMgr.InstanceID(profileID, name)
+
+ inst := &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: instanceID,
+ ProfileID: profileID,
+ ProfileName: name,
+ Status: "running",
+ StartTime: time.Now(),
+ Attached: true,
+ CdpURL: cdpURL,
+ },
+ URL: cdpURL,
+ }
+
+ o.mu.Lock()
+ o.instances[instanceID] = inst
+ o.mu.Unlock()
+
+ slog.Info("attached to external Chrome", "id", instanceID, "name", name, "cdpUrl", cdpURL)
+
+ // Emit event
+ o.emitEvent("instance.attached", &inst.Instance)
+
+ // Sync to instance manager if available
+ o.syncInstanceToManager(&inst.Instance)
+
+ return &inst.Instance, nil
+}
+
func (o *Orchestrator) Stop(id string) error {
o.mu.Lock()
inst, ok := o.instances[id]
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index 2e8853d0..fdea2d59 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -180,3 +180,51 @@ func findSubstring(s, substr string) bool {
}
return false
}
+
+func TestOrchestrator_Attach(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ cdpURL := "ws://localhost:9222/devtools/browser/abc123"
+ inst, err := o.Attach("my-external-chrome", cdpURL)
+ if err != nil {
+ t.Fatalf("Attach failed: %v", err)
+ }
+
+ if !inst.Attached {
+ t.Error("expected Attached to be true")
+ }
+ if inst.CdpURL != cdpURL {
+ t.Errorf("expected CdpURL %q, got %q", cdpURL, inst.CdpURL)
+ }
+ if inst.Status != "running" {
+ t.Errorf("expected status running, got %s", inst.Status)
+ }
+ if inst.ProfileName != "my-external-chrome" {
+ t.Errorf("expected ProfileName %q, got %q", "my-external-chrome", inst.ProfileName)
+ }
+
+ // Check it appears in list
+ list := o.List()
+ if len(list) != 1 {
+ t.Fatalf("expected 1 instance in list, got %d", len(list))
+ }
+ if !list[0].Attached {
+ t.Error("instance in list should have Attached=true")
+ }
+}
+
+func TestOrchestrator_Attach_DuplicateName(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ _, err := o.Attach("chrome1", "ws://localhost:9222/a")
+ if err != nil {
+ t.Fatalf("First attach failed: %v", err)
+ }
+
+ _, err = o.Attach("chrome1", "ws://localhost:9222/b")
+ if err == nil {
+ t.Error("expected error when attaching duplicate name")
+ }
+}