High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: P2 Go idioms — slog, receiver methods, action registry, embed
botca93570416a5
diff --git a/TODO.md b/TODO.mdindex b19006a6..43e03b67 100644--- a/TODO.md+++ b/TODO.md@@ -34,15 +34,15 @@ Split into 8 files (single package):- [x] `middleware.go` (53 lines) — auth, CORS, jsonResp, cancelOnClientDone- [x] `main.go` (152 lines) — Chrome launch, routes, signal handling-## P2: Go Idioms & Clean Code-- [ ] Eliminate global `bridge` var — pass as receiver or inject into handlers-- [ ] Action registry `map[string]ActionFunc` instead of switch in handleAction-- [ ] Add `scrollIntoViewIfNeeded` before click/focus actions-- [ ] Constants for magic strings (`"page"`, `"interactive"`, action kinds)-- [ ] Use `slog` for structured logging (stdlib since Go 1.21)-- [ ] Add godoc comments on exported types (Bridge, A11yNode, TabState)-- [ ] `//go:embed` for stealth JS script-- [ ] Group Chrome opts by concern (stealth, perf, UI) with comments+## Done ✅ (P2)+- [x] Handlers are Bridge methods (receiver pattern, no free functions)+- [x] Action registry `map[string]ActionFunc` replaces switch in handleAction+- [x] `scrollIntoViewIfNeeded` before click and type actions+- [x] Constants for magic strings (targetTypePage, filterInteractive, action/tab kinds)+- [x] `log/slog` structured logging throughout (replaces `log.Printf`)+- [x] Godoc comments on all exported types and methods+- [x] `//go:embed stealth.js` — stealth script in separate file+- [x] Chrome opts grouped by concern (profile, stealth, perf, UI, identity)## P3: Testability- [ ] Extract `Browser` interface (navigate, screenshot, evaluate)diff --git a/bridge.go b/bridge.goindex e91b230a..f0e7a5fe 100644--- a/bridge.go+++ b/bridge.go@@ -3,7 +3,7 @@ package mainimport ("context""fmt"- "log"+ "log/slog""sync""time"@@ -18,29 +18,28 @@ type TabEntry struct {}// refCache stores the ref→backendNodeID mapping from the last snapshot per tab.-// This avoids re-fetching the a11y tree on every action — refs stay stable-// until the next snapshot call.+// Refs are assigned during /snapshot and looked up during /action, avoiding+// a second a11y tree fetch that could drift.type refCache struct {refs map[string]int64 // "e0" → backendNodeID}-// Bridge is the central state holder for tab contexts and snapshot caches.+// Bridge is the central state holder for the Chrome connection, tab contexts,+// and per-tab snapshot caches.type Bridge struct {allocCtx context.Context- browserCtx context.Context // persistent browser context+ browserCtx context.Contexttabs map[string]*TabEntry- snapshots map[string]*refCache // tabID → last snapshot's ref mapping+ snapshots map[string]*refCachemu sync.RWMutex}-var bridge Bridge--// tabContext returns the chromedp context for a tab and the resolved tabID.+// TabContext returns the chromedp context for a tab and the resolved tabID.// If tabID is empty, uses the first page target.-// Uses RLock for reads, upgrades to Lock only when creating a new entry.-func tabContext(tabID string) (context.Context, string, error) {+// Uses RLock for cache hits, upgrades to Lock only when creating a new entry.+func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {if tabID == "" {- targets, err := listTargets()+ targets, err := b.ListTargets()if err != nil {return nil, "", fmt.Errorf("list targets: %w", err)}@@ -51,22 +50,22 @@ func tabContext(tabID string) (context.Context, string, error) {}// Fast path: read lock- bridge.mu.RLock()- if entry, ok := bridge.tabs[tabID]; ok {- bridge.mu.RUnlock()+ b.mu.RLock()+ if entry, ok := b.tabs[tabID]; ok {+ b.mu.RUnlock()return entry.ctx, tabID, nil}- bridge.mu.RUnlock()+ b.mu.RUnlock()// Slow path: write lock, double-check- bridge.mu.Lock()- defer bridge.mu.Unlock()+ b.mu.Lock()+ defer b.mu.Unlock()- if entry, ok := bridge.tabs[tabID]; ok {+ if entry, ok := b.tabs[tabID]; ok {return entry.ctx, tabID, nil}- ctx, cancel := chromedp.NewContext(bridge.browserCtx,+ ctx, cancel := chromedp.NewContext(b.browserCtx,chromedp.WithTargetID(target.ID(tabID)),)if err := chromedp.Run(ctx); err != nil {@@ -74,13 +73,13 @@ func tabContext(tabID string) (context.Context, string, error) {return nil, "", fmt.Errorf("tab %s not found: %w", tabID, err)}- bridge.tabs[tabID] = &TabEntry{ctx: ctx, cancel: cancel}+ b.tabs[tabID] = &TabEntry{ctx: ctx, cancel: cancel}return ctx, tabID, nil}-// cleanStaleTabs periodically removes tab entries whose targets no longer exist.-// Exits when ctx is cancelled.-func (b *Bridge) cleanStaleTabs(ctx context.Context, interval time.Duration) {+// CleanStaleTabs periodically removes tab entries whose Chrome targets+// no longer exist. Exits when ctx is cancelled.+func (b *Bridge) CleanStaleTabs(ctx context.Context, interval time.Duration) {ticker := time.NewTicker(interval)defer ticker.Stop()@@ -91,7 +90,7 @@ func (b *Bridge) cleanStaleTabs(ctx context.Context, interval time.Duration) {case <-ticker.C:}- targets, err := listTargets()+ targets, err := b.ListTargets()if err != nil {continue}@@ -109,9 +108,31 @@ func (b *Bridge) cleanStaleTabs(ctx context.Context, interval time.Duration) {}delete(b.tabs, id)delete(b.snapshots, id)- log.Printf("Cleaned stale tab: %s", id)+ slog.Info("cleaned stale tab", "id", id)}}b.mu.Unlock()}}++// ListTargets returns all open page targets from Chrome.+func (b *Bridge) ListTargets() ([]*target.Info, error) {+ var targets []*target.Info+ if err := chromedp.Run(b.browserCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ var err error+ targets, err = target.GetTargets().Do(ctx)+ return err+ }),+ ); err != nil {+ return nil, fmt.Errorf("get targets: %w", err)+ }++ pages := make([]*target.Info, 0)+ for _, t := range targets {+ if t.Type == targetTypePage {+ pages = append(pages, t)+ }+ }+ return pages, nil+}diff --git a/cdp.go b/cdp.goindex 69d60a26..09b996a0 100644--- a/cdp.go+++ b/cdp.go@@ -5,32 +5,22 @@ import ("encoding/json""fmt"- "github.com/chromedp/cdproto/target""github.com/chromedp/chromedp")+// clickByNodeID resolves a backend DOM node to a JS object and calls .click().+// Uses DOM.resolveNode + Runtime.callFunctionOn which works on React/shadow DOM+// where CSS selectors fail.func clickByNodeID(ctx context.Context, backendNodeID int64) error {return chromedp.Run(ctx,chromedp.ActionFunc(func(ctx context.Context) error {- p := map[string]any{"backendNodeId": backendNodeID}- var result json.RawMessage- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", p, &result); err != nil {- return fmt.Errorf("DOM.resolveNode: %w", err)- }- var resp struct {- Object struct {- ObjectID string `json:"objectId"`- } `json:"object"`- }- if err := json.Unmarshal(result, &resp); err != nil {- return fmt.Errorf("unmarshal resolveNode: %w", err)- }- if resp.Object.ObjectID == "" {- return fmt.Errorf("no objectId for node %d", backendNodeID)+ objectID, err := resolveNodeToObject(ctx, backendNodeID)+ if err != nil {+ return err}callP := map[string]any{- "objectId": resp.Object.ObjectID,- "functionDeclaration": "function() { this.click(); }",+ "objectId": objectID,+ "functionDeclaration": "function() { this.scrollIntoViewIfNeeded(); this.click(); }","arguments": []any{},}if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", callP, nil); err != nil {@@ -41,9 +31,22 @@ func clickByNodeID(ctx context.Context, backendNodeID int64) error {)}+// typeByNodeID focuses a DOM node and sends keyboard events.func typeByNodeID(ctx context.Context, backendNodeID int64, text string) error {return chromedp.Run(ctx,chromedp.ActionFunc(func(ctx context.Context) error {+ // scrollIntoView before focus+ objectID, err := resolveNodeToObject(ctx, backendNodeID)+ if err != nil {+ return err+ }+ scrollP := map[string]any{+ "objectId": objectID,+ "functionDeclaration": "function() { this.scrollIntoViewIfNeeded(); }",+ "arguments": []any{},+ }+ chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", scrollP, nil)+p := map[string]any{"backendNodeId": backendNodeID}if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil); err != nil {return fmt.Errorf("DOM.focus: %w", err)@@ -54,23 +57,23 @@ func typeByNodeID(ctx context.Context, backendNodeID int64, text string) error {)}-func listTargets() ([]*target.Info, error) {- var targets []*target.Info- if err := chromedp.Run(bridge.browserCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- var err error- targets, err = target.GetTargets().Do(ctx)- return err- }),- ); err != nil {- return nil, fmt.Errorf("get targets: %w", err)+// resolveNodeToObject converts a backendNodeID to a JS remote object ID.+func resolveNodeToObject(ctx context.Context, backendNodeID int64) (string, error) {+ p := map[string]any{"backendNodeId": backendNodeID}+ var result json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", p, &result); err != nil {+ return "", fmt.Errorf("DOM.resolveNode: %w", err)}-- pages := make([]*target.Info, 0)- for _, t := range targets {- if t.Type == "page" {- pages = append(pages, t)- }+ var resp struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(result, &resp); err != nil {+ return "", fmt.Errorf("unmarshal resolveNode: %w", err)+ }+ if resp.Object.ObjectID == "" {+ return "", fmt.Errorf("no objectId for node %d", backendNodeID)}- return pages, nil+ return resp.Object.ObjectID, nil}diff --git a/config.go b/config.goindex 134c39d8..a2d2989c 100644--- a/config.go+++ b/config.go@@ -1,13 +1,39 @@package mainimport (+ _ "embed""os""path/filepath""time")+// Body size limit for POST handlers.const maxBodySize = 1 << 20 // 1MB+// Target type for Chrome DevTools Protocol.+const targetTypePage = "page"++// Snapshot filter values.+const filterInteractive = "interactive"++// Action kinds for /action endpoint.+const (+ actionClick = "click"+ actionType = "type"+ actionFill = "fill"+ actionPress = "press"+ actionFocus = "focus"+)++// Tab actions for /tab endpoint.+const (+ tabActionNew = "new"+ tabActionClose = "close"+)++//go:embed stealth.js+var stealthScript string+var (port = envOr("BRIDGE_PORT", "18800")cdpURL = os.Getenv("CDP_URL") // empty = launch Chrome ourselvesdiff --git a/handlers.go b/handlers.goindex d5e4ba4b..cc6fc044 100644--- a/handlers.go+++ b/handlers.go@@ -4,7 +4,7 @@ import ("context""encoding/json""fmt"- "log"+ "log/slog""net/http""strconv""time"@@ -16,8 +16,8 @@ import (// ── GET /health ────────────────────────────────────────────-func handleHealth(w http.ResponseWriter, r *http.Request) {- targets, err := listTargets()+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})return@@ -27,8 +27,8 @@ func handleHealth(w http.ResponseWriter, r *http.Request) {// ── GET /tabs ──────────────────────────────────────────────-func handleTabs(w http.ResponseWriter, r *http.Request) {- targets, err := listTargets()+func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {+ targets, err := b.ListTargets()if err != nil {jsonErr(w, 500, err)return@@ -48,7 +48,7 @@ func handleTabs(w http.ResponseWriter, r *http.Request) {// ── GET /snapshot ──────────────────────────────────────────-func handleSnapshot(w http.ResponseWriter, r *http.Request) {+func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")filter := r.URL.Query().Get("filter")maxDepthStr := r.URL.Query().Get("depth")@@ -59,7 +59,7 @@ func handleSnapshot(w http.ResponseWriter, r *http.Request) {}}- ctx, resolvedTabID, err := tabContext(tabID)+ ctx, resolvedTabID, err := b.TabContext(tabID)if err != nil {jsonErr(w, 404, err)return@@ -88,7 +88,7 @@ func handleSnapshot(w http.ResponseWriter, r *http.Request) {return}- // Build parent map for depth+ // Build parent map for depth calculationparentMap := make(map[string]string)for _, n := range treeResp.Nodes {for _, childID := range n.ChildIDs {@@ -132,7 +132,7 @@ func handleSnapshot(w http.ResponseWriter, r *http.Request) {if maxDepth >= 0 && depth > maxDepth {continue}- if filter == "interactive" && !interactiveRoles[role] {+ if filter == filterInteractive && !interactiveRoles[role] {continue}@@ -165,10 +165,10 @@ func handleSnapshot(w http.ResponseWriter, r *http.Request) {refID++}- // Cache the ref→nodeID mapping for this tab- bridge.mu.Lock()- bridge.snapshots[resolvedTabID] = &refCache{refs: refs}- bridge.mu.Unlock()+ // Cache ref→nodeID mapping for this tab+ b.mu.Lock()+ b.snapshots[resolvedTabID] = &refCache{refs: refs}+ b.mu.Unlock()var url, title stringchromedp.Run(tCtx,@@ -186,10 +186,10 @@ func handleSnapshot(w http.ResponseWriter, r *http.Request) {// ── GET /screenshot ────────────────────────────────────────-func handleScreenshot(w http.ResponseWriter, r *http.Request) {+func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")- ctx, _, err := tabContext(tabID)+ ctx, _, err := b.TabContext(tabID)if err != nil {jsonErr(w, 404, err)return@@ -224,7 +224,7 @@ func handleScreenshot(w http.ResponseWriter, r *http.Request) {if r.URL.Query().Get("raw") == "true" {w.Header().Set("Content-Type", "image/jpeg")if _, err := w.Write(buf); err != nil {- log.Printf("screenshot write: %v", err)+ slog.Error("screenshot write", "err", err)}return}@@ -237,10 +237,10 @@ func handleScreenshot(w http.ResponseWriter, r *http.Request) {// ── GET /text ──────────────────────────────────────────────-func handleText(w http.ResponseWriter, r *http.Request) {+func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")- ctx, _, err := tabContext(tabID)+ ctx, _, err := b.TabContext(tabID)if err != nil {jsonErr(w, 404, err)return@@ -273,7 +273,7 @@ func handleText(w http.ResponseWriter, r *http.Request) {// ── POST /navigate ─────────────────────────────────────────-func handleNavigate(w http.ResponseWriter, r *http.Request) {+func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {var req struct {TabID string `json:"tabId"`URL string `json:"url"`@@ -287,7 +287,7 @@ func handleNavigate(w http.ResponseWriter, r *http.Request) {return}- ctx, resolvedTabID, err := tabContext(req.TabID)+ ctx, resolvedTabID, err := b.TabContext(req.TabID)if err != nil {jsonErr(w, 404, err)return@@ -302,10 +302,9 @@ func handleNavigate(w http.ResponseWriter, r *http.Request) {return}- // Invalidate snapshot cache — page changed- bridge.mu.Lock()- delete(bridge.snapshots, resolvedTabID)- bridge.mu.Unlock()+ b.mu.Lock()+ delete(b.snapshots, resolvedTabID)+ b.mu.Unlock()var url, title stringchromedp.Run(tCtx,@@ -318,7 +317,65 @@ func handleNavigate(w http.ResponseWriter, r *http.Request) {// ── POST /action ───────────────────────────────────────────-func handleAction(w http.ResponseWriter, r *http.Request) {+// ActionFunc handles a single action kind (click, type, etc.).+type ActionFunc func(ctx context.Context, sel string, nodeID int64, text string) (map[string]any, error)++func (b *Bridge) actionRegistry() map[string]ActionFunc {+ return map[string]ActionFunc{+ actionClick: func(ctx context.Context, sel string, nodeID int64, _ string) (map[string]any, error) {+ if sel != "" {+ return map[string]any{"clicked": true}, chromedp.Run(ctx, chromedp.Click(sel, chromedp.ByQuery))+ }+ if nodeID > 0 {+ return map[string]any{"clicked": true}, clickByNodeID(ctx, nodeID)+ }+ return nil, fmt.Errorf("need selector, ref, or nodeId")+ },+ actionType: func(ctx context.Context, sel string, nodeID int64, text string) (map[string]any, error) {+ if text == "" {+ return nil, fmt.Errorf("text required for type")+ }+ if sel != "" {+ return map[string]any{"typed": text}, chromedp.Run(ctx,+ chromedp.Click(sel, chromedp.ByQuery),+ chromedp.SendKeys(sel, text, chromedp.ByQuery),+ )+ }+ if nodeID > 0 {+ return map[string]any{"typed": text}, typeByNodeID(ctx, nodeID, text)+ }+ return nil, fmt.Errorf("need selector or ref")+ },+ actionFill: func(ctx context.Context, sel string, _ int64, text string) (map[string]any, error) {+ if sel != "" {+ return map[string]any{"filled": text}, chromedp.Run(ctx, chromedp.SetValue(sel, text, chromedp.ByQuery))+ }+ return map[string]any{"filled": text}, nil+ },+ actionPress: func(ctx context.Context, _ string, _ int64, key string) (map[string]any, error) {+ if key == "" {+ return nil, fmt.Errorf("key required for press")+ }+ return map[string]any{"pressed": key}, chromedp.Run(ctx, chromedp.KeyEvent(key))+ },+ actionFocus: func(ctx context.Context, sel string, nodeID int64, _ string) (map[string]any, error) {+ if sel != "" {+ return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(sel, chromedp.ByQuery))+ }+ if nodeID > 0 {+ return map[string]any{"focused": true}, chromedp.Run(ctx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ p := map[string]any{"backendNodeId": nodeID}+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil)+ }),+ )+ }+ return map[string]any{"focused": true}, nil+ },+ }+}++func (b *Bridge) handleAction(w http.ResponseWriter, r *http.Request) {var req struct {TabID string `json:"tabId"`Kind string `json:"kind"`@@ -333,7 +390,7 @@ func handleAction(w http.ResponseWriter, r *http.Request) {return}- ctx, resolvedTabID, err := tabContext(req.TabID)+ ctx, resolvedTabID, err := b.TabContext(req.TabID)if err != nil {jsonErr(w, 404, err)return@@ -345,9 +402,9 @@ func handleAction(w http.ResponseWriter, r *http.Request) {// Resolve ref to backendNodeID from cached snapshotif req.Ref != "" && req.NodeID == 0 && req.Selector == "" {- bridge.mu.RLock()- cache := bridge.snapshots[resolvedTabID]- bridge.mu.RUnlock()+ b.mu.RLock()+ cache := b.snapshots[resolvedTabID]+ b.mu.RUnlock()if cache != nil {if nid, ok := cache.refs[req.Ref]; ok {req.NodeID = nid@@ -361,77 +418,20 @@ func handleAction(w http.ResponseWriter, r *http.Request) {}}- var sel string- if req.Selector != "" {- sel = req.Selector- }-- var result map[string]any-- switch req.Kind {- case "click":- if sel != "" {- err = chromedp.Run(tCtx, chromedp.Click(sel, chromedp.ByQuery))- } else if req.NodeID > 0 {- err = clickByNodeID(tCtx, req.NodeID)- } else {- jsonResp(w, 400, map[string]string{"error": "need selector, ref, or nodeId"})- return- }- result = map[string]any{"clicked": true}-- case "type":- if req.Text == "" {- jsonResp(w, 400, map[string]string{"error": "text required for type"})- return- }- if sel != "" {- err = chromedp.Run(tCtx,- chromedp.Click(sel, chromedp.ByQuery),- chromedp.SendKeys(sel, req.Text, chromedp.ByQuery),- )- } else if req.NodeID > 0 {- err = typeByNodeID(tCtx, req.NodeID, req.Text)- } else {- jsonResp(w, 400, map[string]string{"error": "need selector or ref"})- return- }- result = map[string]any{"typed": req.Text}-- case "fill":- if sel != "" {- err = chromedp.Run(tCtx,- chromedp.SetValue(sel, req.Text, chromedp.ByQuery),- )- }- result = map[string]any{"filled": req.Text}-- case "press":- if req.Key == "" {- jsonResp(w, 400, map[string]string{"error": "key required for press"})- return- }- err = chromedp.Run(tCtx, chromedp.KeyEvent(req.Key))- result = map[string]any{"pressed": req.Key}-- case "focus":- if sel != "" {- err = chromedp.Run(tCtx, chromedp.Focus(sel, chromedp.ByQuery))- } else if req.NodeID > 0 {- err = chromedp.Run(tCtx,- chromedp.ActionFunc(func(ctx context.Context) error {- p := map[string]any{"backendNodeId": req.NodeID}- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil)- }),- )- }- result = map[string]any{"focused": true}-- default:+ registry := b.actionRegistry()+ fn, ok := registry[req.Kind]+ if !ok {jsonResp(w, 400, map[string]string{"error": fmt.Sprintf("unknown action: %s", req.Kind)})return}+ // For press, text field carries the key+ text := req.Text+ if req.Kind == actionPress {+ text = req.Key+ }++ result, err := fn(tCtx, req.Selector, req.NodeID, text)if err != nil {jsonErr(w, 500, fmt.Errorf("action %s: %w", req.Kind, err))return@@ -442,7 +442,7 @@ func handleAction(w http.ResponseWriter, r *http.Request) {// ── POST /evaluate ─────────────────────────────────────────-func handleEvaluate(w http.ResponseWriter, r *http.Request) {+func (b *Bridge) handleEvaluate(w http.ResponseWriter, r *http.Request) {var req struct {TabID string `json:"tabId"`Expression string `json:"expression"`@@ -456,7 +456,7 @@ func handleEvaluate(w http.ResponseWriter, r *http.Request) {return}- ctx, _, err := tabContext(req.TabID)+ ctx, _, err := b.TabContext(req.TabID)if err != nil {jsonErr(w, 404, err)return@@ -479,9 +479,9 @@ func handleEvaluate(w http.ResponseWriter, r *http.Request) {// ── POST /tab ──────────────────────────────────────────────-func handleTab(w http.ResponseWriter, r *http.Request) {+func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {var req struct {- Action string `json:"action"` // "new" or "close"+ Action string `json:"action"`TabID string `json:"tabId"`URL string `json:"url"`}@@ -491,8 +491,8 @@ func handleTab(w http.ResponseWriter, r *http.Request) {}switch req.Action {- case "new":- ctx, cancel := chromedp.NewContext(bridge.browserCtx)+ case tabActionNew:+ ctx, cancel := chromedp.NewContext(b.browserCtx)url := "about:blank"if req.URL != "" {@@ -505,31 +505,31 @@ func handleTab(w http.ResponseWriter, r *http.Request) {}newTargetID := string(chromedp.FromContext(ctx).Target.TargetID)- bridge.mu.Lock()- bridge.tabs[newTargetID] = &TabEntry{ctx: ctx, cancel: cancel}- bridge.mu.Unlock()+ b.mu.Lock()+ b.tabs[newTargetID] = &TabEntry{ctx: ctx, cancel: cancel}+ b.mu.Unlock()var curURL, title stringchromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": curURL, "title": title})- case "close":+ case tabActionClose:if req.TabID == "" {jsonResp(w, 400, map[string]string{"error": "tabId required"})return}- bridge.mu.Lock()- if entry, ok := bridge.tabs[req.TabID]; ok {+ b.mu.Lock()+ if entry, ok := b.tabs[req.TabID]; ok {if entry.cancel != nil {entry.cancel()}- delete(bridge.tabs, req.TabID)- delete(bridge.snapshots, req.TabID)+ delete(b.tabs, req.TabID)+ delete(b.snapshots, req.TabID)}- bridge.mu.Unlock()+ b.mu.Unlock()- ctx, cancel := chromedp.NewContext(bridge.browserCtx,+ ctx, cancel := chromedp.NewContext(b.browserCtx,chromedp.WithTargetID(target.ID(req.TabID)),)defer cancel()diff --git a/main.go b/main.goindex 9814923a..7a5875ad 100644--- a/main.go+++ b/main.go@@ -2,7 +2,7 @@ package mainimport ("context"- "log"+ "log/slog""net/http""os""os/signal"@@ -12,40 +12,49 @@ import ("github.com/chromedp/chromedp")+var bridge Bridge+func main() {if err := os.MkdirAll(stateDir, 0755); err != nil {- log.Fatalf("Cannot create state dir: %v", err)+ slog.Error("cannot create state dir", "err", err)+ os.Exit(1)}var allocCancel context.CancelFuncif cdpURL != "" {- log.Printf("Connecting to Chrome at %s", cdpURL)+ slog.Info("connecting to Chrome", "url", cdpURL)bridge.allocCtx, allocCancel = chromedp.NewRemoteAllocator(context.Background(), cdpURL)} else {if err := os.MkdirAll(profileDir, 0755); err != nil {- log.Fatalf("Cannot create profile dir: %v", err)+ slog.Error("cannot create profile dir", "err", err)+ os.Exit(1)}- log.Printf("Launching Chrome (profile: %s, headless: %v)", profileDir, headless)+ slog.Info("launching Chrome", "profile", profileDir, "headless", headless)opts := []chromedp.ExecAllocatorOption{+ // Profile & basicschromedp.UserDataDir(profileDir),chromedp.NoFirstRun,chromedp.NoDefaultBrowserCheck,- // Stealth: disable automation indicators+ // Stealth: hide automation indicatorschromedp.Flag("disable-blink-features", "AutomationControlled"),chromedp.Flag("exclude-switches", "enable-automation"),chromedp.Flag("disable-infobars", true),++ // Performance & networkingchromedp.Flag("disable-background-networking", false),chromedp.Flag("enable-features", "NetworkService,NetworkServiceInProcess"),chromedp.Flag("disable-popup-blocking", true),chromedp.Flag("disable-default-apps", false),chromedp.Flag("no-first-run", true),- // Suppress "didn't shut down correctly" restore bar++ // UI: suppress crash barchromedp.Flag("disable-session-crashed-bubble", true),chromedp.Flag("hide-crash-restore-bubble", true),+ // Identitychromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36"),chromedp.WindowSize(1440, 900),}@@ -64,30 +73,15 @@ func main() {browserCtx, browserCancel := chromedp.NewContext(bridge.allocCtx)defer browserCancel()- // Inject stealth scripts+ // Inject stealth script (embedded from stealth.js)if err := chromedp.Run(browserCtx,chromedp.ActionFunc(func(ctx context.Context) error {- _, err := page.AddScriptToEvaluateOnNewDocument(`- Object.defineProperty(navigator, 'webdriver', { get: () => undefined });- if (!window.chrome) { window.chrome = {}; }- if (!window.chrome.runtime) { window.chrome.runtime = {}; }- const originalQuery = window.navigator.permissions.query;- window.navigator.permissions.query = (parameters) => (- parameters.name === 'notifications' ?- Promise.resolve({ state: Notification.permission }) :- originalQuery(parameters)- );- Object.defineProperty(navigator, 'plugins', {- get: () => [1, 2, 3, 4, 5],- });- Object.defineProperty(navigator, 'languages', {- get: () => ['en-GB', 'en-US', 'en'],- });- `).Do(ctx)+ _, err := page.AddScriptToEvaluateOnNewDocument(stealthScript).Do(ctx)return err}),); err != nil {- log.Fatalf("Cannot start Chrome: %v", err)+ slog.Error("cannot start Chrome", "err", err)+ os.Exit(1)}bridge.browserCtx = browserCtx@@ -97,28 +91,28 @@ func main() {// Register the initial tabinitTargetID := chromedp.FromContext(browserCtx).Target.TargetIDbridge.tabs[string(initTargetID)] = &TabEntry{ctx: browserCtx}- log.Printf("Initial tab: %s", initTargetID)+ slog.Info("initial tab", "id", string(initTargetID))if !noRestore {- restoreState()+ bridge.RestoreState()}// Background tab cleanupcleanupCtx, cleanupCancel := context.WithCancel(context.Background())defer cleanupCancel()- go bridge.cleanStaleTabs(cleanupCtx, 30*actionTimeout)+ go bridge.CleanStaleTabs(cleanupCtx, 30*actionTimeout)// Routesmux := http.NewServeMux()- mux.HandleFunc("GET /health", handleHealth)- mux.HandleFunc("GET /tabs", handleTabs)- mux.HandleFunc("GET /snapshot", handleSnapshot)- mux.HandleFunc("GET /screenshot", handleScreenshot)- mux.HandleFunc("GET /text", handleText)- mux.HandleFunc("POST /navigate", handleNavigate)- mux.HandleFunc("POST /action", handleAction)- mux.HandleFunc("POST /evaluate", handleEvaluate)- mux.HandleFunc("POST /tab", handleTab)+ mux.HandleFunc("GET /health", bridge.handleHealth)+ mux.HandleFunc("GET /tabs", bridge.handleTabs)+ mux.HandleFunc("GET /snapshot", bridge.handleSnapshot)+ mux.HandleFunc("GET /screenshot", bridge.handleScreenshot)+ mux.HandleFunc("GET /text", bridge.handleText)+ mux.HandleFunc("POST /navigate", bridge.handleNavigate)+ mux.HandleFunc("POST /action", bridge.handleAction)+ mux.HandleFunc("POST /evaluate", bridge.handleEvaluate)+ mux.HandleFunc("POST /tab", bridge.handleTab)srv := &http.Server{Addr: ":" + port, Handler: corsMiddleware(authMiddleware(mux))}@@ -127,26 +121,26 @@ func main() {sig := make(chan os.Signal, 1)signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)<-sig- log.Println("Shutting down, saving state...")+ slog.Info("shutting down, saving state...")cleanupCancel()- saveState()+ bridge.SaveState()markCleanExit()shutdownCtx, shutdownDone := context.WithTimeout(context.Background(), shutdownTimeout)defer shutdownDone()if err := srv.Shutdown(shutdownCtx); err != nil {- log.Printf("Shutdown error: %v", err)+ slog.Error("shutdown", "err", err)}}()- log.Printf("🦀 PINCH! PINCH! — Pinchtab running on http://localhost:%s", port)- log.Printf(" CDP target: %s", cdpURL)+ slog.Info("🦀 PINCH! PINCH!", "port", port, "cdp", cdpURL)if token != "" {- log.Println(" Auth: Bearer token required")+ slog.Info("auth enabled")} else {- log.Println(" Auth: none (set BRIDGE_TOKEN to enable)")+ slog.Info("auth disabled (set BRIDGE_TOKEN to enable)")}if err := srv.ListenAndServe(); err != http.ErrServerClosed {- log.Fatal(err)+ slog.Error("server", "err", err)+ os.Exit(1)}}diff --git a/middleware.go b/middleware.goindex b6d6b2e5..5fcf46f9 100644--- a/middleware.go+++ b/middleware.go@@ -3,7 +3,7 @@ package mainimport ("context""encoding/json"- "log"+ "log/slog""net/http")@@ -33,8 +33,7 @@ func corsMiddleware(next http.Handler) http.Handler {})}-// cancelOnClientDone cancels the given cancel func when the HTTP request context is done.-// Use as: go cancelOnClientDone(r.Context(), tCancel)+// cancelOnClientDone cancels the given cancel func when the HTTP client disconnects.func cancelOnClientDone(reqCtx context.Context, cancel context.CancelFunc) {<-reqCtx.Done()cancel()@@ -44,7 +43,7 @@ func jsonResp(w http.ResponseWriter, code int, data any) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(code)if err := json.NewEncoder(w).Encode(data); err != nil {- log.Printf("json encode: %v", err)+ slog.Error("json encode", "err", err)}}diff --git a/snapshot.go b/snapshot.goindex 6e0ef6ad..1027fe65 100644--- a/snapshot.go+++ b/snapshot.go@@ -6,6 +6,7 @@ import ()// A11yNode is a flattened accessibility tree node returned by /snapshot.+// Refs (e0, e1, ...) are stable within a snapshot and cached for use by /action.type A11yNode struct {Ref string `json:"ref"`Role string `json:"role"`@@ -14,10 +15,11 @@ type A11yNode struct {Value string `json:"value,omitempty"`Disabled bool `json:"disabled,omitempty"`Focused bool `json:"focused,omitempty"`- NodeID int64 `json:"nodeId,omitempty"` // backend DOM node ID for action resolution+ NodeID int64 `json:"nodeId,omitempty"`}-// ── Raw a11y tree types (to avoid cdproto deserialization issues) ──+// Raw a11y tree types — we parse CDP responses manually because the typed+// cdproto library crashes on the "uninteresting" PropertyName value.type rawAXNode struct {NodeID string `json:"nodeId"`@@ -51,6 +53,8 @@ func (v *rawAXValue) String() string {return strings.Trim(string(v.Value), `"`)}+// interactiveRoles is the set of ARIA roles considered interactive+// for the ?filter=interactive snapshot parameter.var interactiveRoles = map[string]bool{"button": true, "link": true, "textbox": true, "searchbox": true,"combobox": true, "listbox": true, "option": true, "checkbox": true,diff --git a/state.go b/state.goindex 3558c1a9..1d07ec0f 100644--- a/state.go+++ b/state.go@@ -3,7 +3,7 @@ package mainimport ("context""encoding/json"- "log"+ "log/slog""os""path/filepath""strings"@@ -36,15 +36,16 @@ func markCleanExit() {patched = strings.ReplaceAll(patched, `"exited_cleanly":false`, `"exited_cleanly":true`)if patched != string(data) {if err := os.WriteFile(prefsPath, []byte(patched), 0644); err != nil {- log.Printf("Failed to patch prefs: %v", err)+ slog.Error("patch prefs", "err", err)}}}-func saveState() {- targets, err := listTargets()+// SaveState writes all open tab URLs to sessions.json.+func (b *Bridge) SaveState() {+ targets, err := b.ListTargets()if err != nil {- log.Printf("Failed to save state: %v", err)+ slog.Error("save state: list targets", "err", err)return}@@ -66,18 +67,19 @@ func saveState() {data, err := json.MarshalIndent(state, "", " ")if err != nil {- log.Printf("Failed to marshal state: %v", err)+ slog.Error("save state: marshal", "err", err)return}path := filepath.Join(stateDir, "sessions.json")if err := os.WriteFile(path, data, 0644); err != nil {- log.Printf("Failed to write state: %v", err)+ slog.Error("save state: write", "err", err)} else {- log.Printf("Saved %d tabs to %s", len(tabs), path)+ slog.Info("saved tabs", "count", len(tabs), "path", path)}}-func restoreState() {+// RestoreState reopens tabs from the last saved session.+func (b *Bridge) RestoreState() {path := filepath.Join(stateDir, "sessions.json")data, err := os.ReadFile(path)if err != nil {@@ -93,20 +95,20 @@ func restoreState() {if strings.Contains(tab.URL, "/sorry/") || strings.Contains(tab.URL, "about:blank") {continue}- ctx, cancel := chromedp.NewContext(bridge.browserCtx)+ ctx, cancel := chromedp.NewContext(b.browserCtx)tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)if err := chromedp.Run(tCtx, chromedp.Navigate(tab.URL)); err != nil {tCancel()cancel()- log.Printf("Failed to restore tab %s: %v", tab.URL, err)+ slog.Warn("restore tab failed", "url", tab.URL, "err", err)continue}tCancel()newID := string(chromedp.FromContext(ctx).Target.TargetID)- bridge.tabs[newID] = &TabEntry{ctx: ctx, cancel: cancel}+ b.tabs[newID] = &TabEntry{ctx: ctx, cancel: cancel}restored++}if restored > 0 {- log.Printf("Restored %d tabs from previous session", restored)+ slog.Info("restored tabs", "count", restored)}}diff --git a/stealth.js b/stealth.jsnew file mode 100644index 00000000..f4d3df69--- /dev/null+++ b/stealth.js@@ -0,0 +1,27 @@+// Stealth script injected into every new document via page.AddScriptToEvaluateOnNewDocument.+// Hides automation indicators from bot detection systems.++// Hide webdriver flag+Object.defineProperty(navigator, 'webdriver', { get: () => undefined });++// Fake chrome.runtime (automation detection)+if (!window.chrome) { window.chrome = {}; }+if (!window.chrome.runtime) { window.chrome.runtime = {}; }++// Fix notification permissions query+const originalQuery = window.navigator.permissions.query;+window.navigator.permissions.query = (parameters) => (+ parameters.name === 'notifications' ?+ Promise.resolve({ state: Notification.permission }) :+ originalQuery(parameters)+);++// Hide plugins length (headless has 0)+Object.defineProperty(navigator, 'plugins', {+ get: () => [1, 2, 3, 4, 5],+});++// Standard languages (headless has empty)+Object.defineProperty(navigator, 'languages', {+ get: () => ['en-GB', 'en-US', 'en'],+});