High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: click coordinates are read from page-controllable geometry (PIN-063)
Luigi Agosti70972dfa730a
diff --git a/internal/bridge/cdpops/frame_dom.go b/internal/bridge/cdpops/frame_dom.goindex 101d346c..19d668ea 100644--- a/internal/bridge/cdpops/frame_dom.go+++ b/internal/bridge/cdpops/frame_dom.go@@ -4,12 +4,89 @@ import ("context""encoding/json""fmt"+ "strings""github.com/chromedp/chromedp""github.com/pinchtab/pinchtab/internal/runtimetypes")+// IsolatedNodeObjectID converts a backend node id to a JS object handle in the+// top frame's isolated world. DOM.resolveNode without an executionContextId+// hands back a main-world object, so every Runtime.callFunctionOn against it+// runs where page script can redefine the DOM methods it calls.+//+// A handle from any frame's isolated world reaches a node in another+// same-process frame, and a bare backend node id does not carry its own frame,+// so the top frame's world is used. Never falls back to the main world: a+// caller that cannot obtain an isolated context gets an error.+//+// JS invoked on the returned handle must not read ambient globals. The handle+// lives in the world it was resolved into, not necessarily the node's frame, so+// `window` and `document` there are the top frame's. Derive them from the node+// via ownerDocument/defaultView instead.+func IsolatedNodeObjectID(ctx context.Context, backendNodeID int64) (string, error) {+ execID, err := topFrameIsolatedContextID(ctx)+ if err != nil {+ return "", err+ }++ var raw json.RawMessage+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": backendNodeID,+ "executionContextId": execID,+ }, &raw)+ })); err != nil {+ return "", fmt.Errorf("resolve node: %w", err)+ }++ var parsed struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(raw, &parsed); err != nil {+ return "", err+ }+ if strings.TrimSpace(parsed.Object.ObjectID) == "" {+ return "", fmt.Errorf("resolve node: backend node %d not found", backendNodeID)+ }+ return parsed.Object.ObjectID, nil+}++func topFrameIsolatedContextID(ctx context.Context) (int64, error) {+ var raw json.RawMessage+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Page.getFrameTree", nil, &raw)+ })); err != nil {+ return 0, fmt.Errorf("resolve top frame: %w", err)+ }++ var tree struct {+ FrameTree struct {+ Frame struct {+ ID string `json:"id"`+ } `json:"frame"`+ } `json:"frameTree"`+ }+ if err := json.Unmarshal(raw, &tree); err != nil {+ return 0, err+ }+ if tree.FrameTree.Frame.ID == "" {+ return 0, fmt.Errorf("resolve top frame: frame id is empty")+ }++ execID, err := FrameExecutionContextID(ctx, tree.FrameTree.Frame.ID)+ if err != nil {+ return 0, err+ }+ if execID == 0 {+ return 0, fmt.Errorf("frame %q has no isolated execution context", tree.FrameTree.Frame.ID)+ }+ return execID, nil+}+// FrameExecutionContextID returns a Runtime.executionContextId that evaluates// in the given frame's document. Returns (0, nil) when frameID is empty so// callers can fall back to the default top-level context without branching.diff --git a/internal/bridge/cdpops/validation.go b/internal/bridge/cdpops/validation.goindex 385b40d3..568ad414 100644--- a/internal/bridge/cdpops/validation.go+++ b/internal/bridge/cdpops/validation.go@@ -38,37 +38,28 @@ func PointerPointForNode(ctx context.Context, backendNodeID int64, requireTopMosreturn 0, 0, fmt.Errorf("scroll into view: %w", err)}- var resolveResult json.RawMessage- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{- "backendNodeId": backendNodeID,- }, &resolveResult)- })); err != nil {- return 0, 0, fmt.Errorf("resolve node: %w", err)- }-- var resolved struct {- Object struct {- ObjectID string `json:"objectId"`- } `json:"object"`- }- if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ objectID, err := IsolatedNodeObjectID(ctx, backendNodeID)+ if err != nil {return 0, 0, err}- if strings.TrimSpace(resolved.Object.ObjectID) == "" {- return 0, 0, fmt.Errorf("resolve node: backend node %d not found", backendNodeID)- }+ // view/doc come from the node, never from the ambient globals. In the main+ // world those globals were the node's own frame; in an isolated world the+ // handle carries no such guarantee, and reading them there would compute the+ // style, the frame walk, the viewport bounds and the occlusion hit-test+ // against the top frame for a node that lives in an iframe.const probeJS = `function() {+ const view = (this.ownerDocument && this.ownerDocument.defaultView) || window;+ const doc = this.ownerDocument || document;const r = this.getBoundingClientRect();- const style = window.getComputedStyle(this);+ const style = view.getComputedStyle(this);const localX = r.left + (r.width / 2);const localY = r.top + (r.height / 2);let x = localX;let y = localY;- let topWindow = window;+ let topWindow = view;try {- let current = window;+ let current = view;while (current && current.parent && current !== current.parent) {const frameEl = current.frameElement;if (!frameEl) {@@ -85,15 +76,15 @@ func PointerPointForNode(ctx context.Context, backendNodeID int64, requireTopMos// the frame-local coordinates and let higher layers decide whether that// target is safely actionable.}- const viewportWidth = topWindow && topWindow.innerWidth ? topWindow.innerWidth : window.innerWidth;- const viewportHeight = topWindow && topWindow.innerHeight ? topWindow.innerHeight : window.innerHeight;+ const viewportWidth = topWindow && topWindow.innerWidth ? topWindow.innerWidth : view.innerWidth;+ const viewportHeight = topWindow && topWindow.innerHeight ? topWindow.innerHeight : view.innerHeight;const inViewport = x >= 0 && y >= 0 && x <= viewportWidth && y <= viewportHeight;const visible = !!style && style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity || '1') > 0;const pointerEvent = style ? String(style.pointerEvents || '') : '';let occluded = false;let topTag = '';- if (localX >= 0 && localY >= 0 && localX <= window.innerWidth && localY <= window.innerHeight) {- const top = document.elementFromPoint(localX, localY);+ if (localX >= 0 && localY >= 0 && localX <= view.innerWidth && localY <= view.innerHeight) {+ const top = doc.elementFromPoint(localX, localY);if (top) {topTag = String(top.tagName || '').toLowerCase();const related = top === this || this.contains(top) || top.contains(this);@@ -117,7 +108,7 @@ func PointerPointForNode(ctx context.Context, backendNodeID int64, requireTopMosif err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{"functionDeclaration": probeJS,- "objectId": resolved.Object.ObjectID,+ "objectId": objectID,"returnByValue": true,}, &probeRaw)})); err != nil {diff --git a/internal/bridge/isolated_world_test.go b/internal/bridge/isolated_world_test.goindex b3515927..4eb14a85 100644--- a/internal/bridge/isolated_world_test.go+++ b/internal/bridge/isolated_world_test.go@@ -179,7 +179,6 @@ var mainWorldResolvers = map[string]string{"internal/bridge/cdpops/element_ops.go": "element ops act on an already-chosen node","internal/bridge/cdpops/frame_dom.go": "callFunctionOn helper for an already-chosen node","internal/bridge/cdpops/pointer.go": "pointer actions act on an already-chosen node",- "internal/bridge/cdpops/validation.go": "post-action validation reads an already-chosen node","internal/bridge/cdpops/geometry.go": "click-point geometry for an already-chosen node",}diff --git a/internal/bridge/pointer_isolated_test.go b/internal/bridge/pointer_isolated_test.gonew file mode 100644index 00000000..4a0617aa--- /dev/null+++ b/internal/bridge/pointer_isolated_test.go@@ -0,0 +1,177 @@+package bridge++import (+ "context"+ "encoding/base64"+ "errors"+ "testing"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/bridge/cdpops"+ "github.com/pinchtab/pinchtab/internal/testbrowser"+)++func newPointerFixture(t *testing.T, html string) context.Context {+ t.Helper()+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(+ chromedp.DefaultExecAllocatorOptions[:],+ chromedp.ExecPath(testbrowser.Path(t)),+ chromedp.UserDataDir(t.TempDir()),+ chromedp.Flag("headless", true),+ chromedp.Flag("no-sandbox", true),+ )...)+ ctx, cancelBrowser := chromedp.NewContext(alloc)+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)+ t.Cleanup(func() {+ cancelTimeout()+ cancelBrowser()+ cancelAlloc()+ })++ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))+ if err := chromedp.Run(ctx,+ chromedp.Navigate(dataURL),+ chromedp.WaitVisible("#target", chromedp.ByID),+ ); err != nil {+ t.Fatal(err)+ }+ return ctx+}++// The page forges both methods the probe reads. getBoundingClientRect moves the+// element's reported box far from where it renders, and getComputedStyle would+// let the page fake visibility or pointer-events. In the main world the probe+// believes them and the synthetic click lands wherever the page said.+const pointerHijackHTML = `<body style="margin:0">+<button id="target" style="position:absolute;left:40px;top:60px;width:120px;height:40px">Accept</button>+<script>+Element.prototype.getBoundingClientRect = function () {+ return {x: 700, y: 500, left: 700, top: 500, right: 800, bottom: 540, width: 100, height: 40};+};+const realGCS = window.getComputedStyle;+window.getComputedStyle = function (el) {+ const s = realGCS.call(window, el);+ return new Proxy(s, {get: (t, k) => (k === 'pointerEvents' ? 'auto' : Reflect.get(t, k))});+};+</script>+</body>`++func TestPointerPointResistsForgedGeometry(t *testing.T) {+ ctx := newPointerFixture(t, pointerHijackHTML)++ nodeID, err := ResolveCSSToNodeID(ctx, "#target")+ if err != nil {+ t.Fatal(err)+ }++ x, y, err := cdpops.PointerPointForNode(ctx, nodeID, false)+ if err != nil {+ t.Fatalf("pointer point: %v", err)+ }++ // The element really renders at (40,60)-(160,100), so its centre is (100,80).+ // The forged rect would put the click at (750,520).+ const wantX, wantY = 100.0, 80.0+ if x != wantX || y != wantY {+ t.Errorf("pointer point = (%.0f,%.0f), want (%.0f,%.0f); page script steered the click", x, y, wantX, wantY)+ }+}++const pointerFrameHTML = `<body style="margin:0">+<div id="target" style="position:absolute;left:0;top:0;width:10px;height:10px"></div>+<iframe id="outer" style="position:absolute;left:120px;top:80px;border:0" width="400" height="300"+ srcdoc="<body style='margin:0'><iframe id='inner' style='position:absolute;left:30px;top:20px;border:0' width='300' height='200' srcdoc="<body style='margin:0'><button id='deep' style='position:absolute;left:25px;top:15px;width:80px;height:30px' onclick='this.dataset.hits=String(Number(this.dataset.hits||0)+1)'>Deep</button></body>"></iframe></body>"></iframe>+</body>`++// The frame-offset walk reads current.frameElement up the chain. It ran in the+// node's own frame before; from an isolated world it must still start there, or+// a nested click lands at frame-local coordinates in the top document.+func TestPointerPointWalksNestedFrameOffsets(t *testing.T) {+ ctx := newPointerFixture(t, pointerFrameHTML)++ deepNodeID := deepFrameNode(t, ctx)++ x, y, err := cdpops.PointerPointForNode(ctx, deepNodeID, false)+ if err != nil {+ t.Fatalf("pointer point: %v", err)+ }++ // 120+30+25 + 80/2 = 215, 80+20+15 + 30/2 = 130.+ const wantX, wantY = 215.0, 130.0+ if x != wantX || y != wantY {+ t.Errorf("nested pointer point = (%.0f,%.0f), want (%.0f,%.0f); frame offsets were not applied", x, y, wantX, wantY)+ }++ if err := ClickByCoordinate(ctx, x, y, 0); err != nil {+ t.Fatalf("click: %v", err)+ }+ var hits int+ if err := cdpops.CallFunctionOnNode(ctx, deepNodeID,+ `function(){ return Number(this.dataset.hits || 0); }`, nil, &hits); err != nil {+ t.Fatal(err)+ }+ if hits != 1 {+ t.Errorf("deep button received %d clicks, want 1 — the coordinate did not land on it", hits)+ }+}++func deepFrameNode(t *testing.T, ctx context.Context) int64 {+ t.Helper()+ var walk func(tree RawFrameTree) []string+ walk = func(tree RawFrameTree) []string {+ ids := []string{tree.Frame.ID}+ for _, child := range tree.ChildFrames {+ ids = append(ids, walk(child)...)+ }+ return ids+ }++ deadline := time.Now().Add(10 * time.Second)+ for {+ tree, err := FetchFrameTree(ctx)+ if err != nil {+ t.Fatal(err)+ }+ for _, frameID := range walk(tree) {+ if nodeID, err := ResolveCSSToNodeIDInFrame(ctx, frameID, "#deep"); err == nil {+ return nodeID+ }+ }+ if time.Now().After(deadline) {+ t.Fatal("nested #deep button never appeared")+ }+ time.Sleep(100 * time.Millisecond)+ }+}++const pointerOcclusionHTML = `<body style="margin:0">+<button id="target" style="position:absolute;left:40px;top:60px;width:120px;height:40px">Accept</button>+<div id="cover" style="position:absolute;left:0;top:0;width:400px;height:300px;background:#000"></div>+</body>`++// requireTopMost is the guard that refuses a click the user could not have made.+// Both of its answers are asserted: an element under an overlay must still be+// refused, and a clear one must still be allowed.+func TestPointerPointOcclusionUnchanged(t *testing.T) {+ ctx := newPointerFixture(t, pointerOcclusionHTML)++ nodeID, err := ResolveCSSToNodeID(ctx, "#target")+ if err != nil {+ t.Fatal(err)+ }++ if _, _, err := cdpops.PointerPointForNode(ctx, nodeID, true); !errors.Is(err, cdpops.ErrElementOccluded) {+ t.Errorf("covered element: err = %v, want ErrElementOccluded", err)+ }+ if _, _, err := cdpops.PointerPointForNode(ctx, nodeID, false); err != nil {+ t.Errorf("covered element without requireTopMost should still resolve: %v", err)+ }++ if err := chromedp.Run(ctx, chromedp.Evaluate(`document.getElementById('cover').remove(), true`, new(bool))); err != nil {+ t.Fatal(err)+ }+ if _, _, err := cdpops.PointerPointForNode(ctx, nodeID, true); err != nil {+ t.Errorf("uncovered element: err = %v, want a clickable point", err)+ }+}