Skip to content

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

fix: resolve dialog-scoped selector and clip nodes in the isolated world, not the main world (PIN-045)

Luigi Agosti2797fc1c3c08
diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.go
index 1237e621..62c3f681 100644
--- a/internal/bridge/action_resolve.go
+++ b/internal/bridge/action_resolve.go
@@ -46,25 +46,76 @@ func frameExecutionContextID(ctx context.Context, frameID string) (int64, error)
return bridgecdpops.FrameExecutionContextID(ctx, frameID)
}
-func frameDocumentObjectID(ctx context.Context, frameID string) (string, error) {
- // Selector and modal discovery run in an isolated world so page script cannot
- // hide or redirect targets by replacing DOM methods in the main world.
+// isolatedExecutionContextID returns the isolated world's execution context for
+// frameID, or for the top frame when frameID is empty. Selector and modal
+// discovery run there so page script cannot hide or redirect targets by
+// replacing DOM methods in the main world. It never returns a usable zero: a
+// caller that cannot get an isolated context gets an error, not the main world.
+func isolatedExecutionContextID(ctx context.Context, frameID string) (int64, error) {
if frameID == "" {
frameTree, err := FetchFrameTree(ctx)
if err != nil {
- return "", fmt.Errorf("resolve top frame: %w", err)
+ return 0, fmt.Errorf("resolve top frame: %w", err)
}
frameID = frameTree.Frame.ID
if frameID == "" {
- return "", fmt.Errorf("resolve top frame: frame id is empty")
+ return 0, fmt.Errorf("resolve top frame: frame id is empty")
}
}
execID, err := frameExecutionContextID(ctx, frameID)
if err != nil {
- return "", err
+ return 0, err
}
if execID == 0 {
- return "", fmt.Errorf("frame %q has no isolated execution context", frameID)
+ return 0, fmt.Errorf("frame %q has no isolated execution context", frameID)
+ }
+ return execID, nil
+}
+
+// IsolatedNodeObjectID converts a backend node id to a JS object handle in the
+// isolated world. DOM.resolveNode without an executionContextId hands back a
+// main-world object, and every Runtime.callFunctionOn against it then runs where
+// page script can redefine the DOM methods it uses — so a scoped selector or a
+// clip origin could be steered by the page it is inspecting.
+//
+// The isolated world is per-frame but a handle from any frame's world reaches a
+// node in another same-process frame, so the top frame's world is used rather
+// than the node's own: a bare backend node id does not carry its frame, and
+// DOM.describeNode reports frameId only for frame owner elements.
+func IsolatedNodeObjectID(ctx context.Context, backendNodeID int64) (string, error) {
+ execID, err := isolatedExecutionContextID(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 "", err
+ }
+
+ var parsed struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(raw, &parsed); err != nil {
+ return "", err
+ }
+ if parsed.Object.ObjectID == "" {
+ return "", fmt.Errorf("backend node %d is no longer attached", backendNodeID)
+ }
+ return parsed.Object.ObjectID, nil
+}
+
+func frameDocumentObjectID(ctx context.Context, frameID string) (string, error) {
+ execID, err := isolatedExecutionContextID(ctx, frameID)
+ if err != nil {
+ return "", err
}
params := map[string]any{
@@ -291,31 +342,14 @@ func TopmostModalNodeID(ctx context.Context, frameID string) (int64, bool, error
// resolveNodeWithinBackendNode invokes functionDeclaration with the scope
// element as `this` and converts the returned DOM object to a backend node ID.
func resolveNodeWithinBackendNode(ctx context.Context, scopeBackendNodeID int64, functionDeclaration string, args []map[string]any) (int64, error) {
- var scopeResult json.RawMessage
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
- "backendNodeId": scopeBackendNodeID,
- }, &scopeResult)
- }))
+ scopeObjectID, err := IsolatedNodeObjectID(ctx, scopeBackendNodeID)
if err != nil {
return 0, fmt.Errorf("resolve scope node: %w", err)
}
- var scope struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(scopeResult, &scope); err != nil {
- return 0, err
- }
- if scope.Object.ObjectID == "" {
- return 0, fmt.Errorf("dialog scope is no longer attached")
- }
-
params := map[string]any{
"functionDeclaration": functionDeclaration,
- "objectId": scope.Object.ObjectID,
+ "objectId": scopeObjectID,
"returnByValue": false,
}
if len(args) > 0 {
@@ -360,38 +394,17 @@ func BackendNodeWithinScope(ctx context.Context, scopeBackendNodeID, targetBacke
return false, nil
}
- resolve := func(ctx context.Context, backendNodeID int64) (string, error) {
- var raw json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
- "backendNodeId": backendNodeID,
- }, &raw); err != nil {
- return "", err
- }
- var parsed struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(raw, &parsed); err != nil {
- return "", err
- }
- if parsed.Object.ObjectID == "" {
- return "", fmt.Errorf("backend node %d is no longer attached", backendNodeID)
- }
- return parsed.Object.ObjectID, nil
+ scopeObjectID, err := IsolatedNodeObjectID(ctx, scopeBackendNodeID)
+ if err != nil {
+ return false, fmt.Errorf("resolve scope node: %w", err)
+ }
+ targetObjectID, err := IsolatedNodeObjectID(ctx, targetBackendNodeID)
+ if err != nil {
+ return false, fmt.Errorf("resolve target node: %w", err)
}
var contains bool
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- scopeObjectID, err := resolve(ctx, scopeBackendNodeID)
- if err != nil {
- return fmt.Errorf("resolve scope node: %w", err)
- }
- targetObjectID, err := resolve(ctx, targetBackendNodeID)
- if err != nil {
- return fmt.Errorf("resolve target node: %w", err)
- }
-
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
var raw json.RawMessage
if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
"functionDeclaration": `function(target) {
diff --git a/internal/bridge/isolated_world_test.go b/internal/bridge/isolated_world_test.go
new file mode 100644
index 00000000..cbf2b237
--- /dev/null
+++ b/internal/bridge/isolated_world_test.go
@@ -0,0 +1,216 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/selector"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+)
+
+// The page attempts the substitution the isolated world exists to prevent. Every
+// redefinition is real page script, not a mock: querySelectorAll and matches are
+// what the scoped selector resolver calls, and getBoundingClientRect is what the
+// clip builder calls. In the main world all three answer the attacker.
+const hijackFixtureHTML = `<body>
+<div id="dlg" role="dialog" aria-modal="true" style="position:fixed;inset:20px;background:#fff">
+<button id="real">Confirm</button>
+<button id="decoy">Decoy</button>
+</div>
+<script>
+(() => {
+ const decoy = document.getElementById('decoy');
+ const realQSA = Element.prototype.querySelectorAll;
+ Element.prototype.querySelectorAll = function () { return [decoy]; };
+ Element.prototype.matches = function () { return true; };
+ Element.prototype.getBoundingClientRect = function () {
+ return {x: 999, y: 999, left: 999, top: 999, right: 1099, bottom: 1049, width: 100, height: 50};
+ };
+ window.__realQSA = realQSA;
+})();
+</script>
+</body>`
+
+func newHijackFixture(t *testing.T) 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(hijackFixtureHTML))
+ if err := chromedp.Run(ctx,
+ chromedp.Navigate(dataURL),
+ chromedp.WaitVisible("#real", chromedp.ByID),
+ ); err != nil {
+ t.Fatal(err)
+ }
+ return ctx
+}
+
+// nodeDescription names what a backend node id actually is, so a failure reads
+// "button#decoy" rather than two opaque numbers.
+func nodeDescription(t *testing.T, ctx context.Context, backendNodeID int64) string {
+ t.Helper()
+ objectID, err := IsolatedNodeObjectID(ctx, backendNodeID)
+ if err != nil {
+ t.Fatalf("describe node %d: %v", backendNodeID, err)
+ }
+ var call struct {
+ Result struct {
+ Value string `json:"value"`
+ } `json:"result"`
+ }
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": `function(){ return this.tagName.toLowerCase() + (this.id ? "#" + this.id : ""); }`,
+ "objectId": objectID,
+ "returnByValue": true,
+ }, &call)
+ })); err != nil {
+ t.Fatalf("describe node %d: %v", backendNodeID, err)
+ }
+ return call.Result.Value
+}
+
+// The page redefines the very methods the dialog-scoped resolver calls. A
+// main-world resolution hands back whatever they return; an isolated-world one
+// never sees them.
+func TestDialogScopedSelectorResistsMainWorldSubstitution(t *testing.T) {
+ ctx := newHijackFixture(t)
+
+ dialogNodeID, open, err := TopmostModalNodeID(ctx, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !open {
+ t.Fatal("fixture dialog was not detected")
+ }
+
+ got, err := ResolveUnifiedSelectorWithinNode(ctx, selector.Parse("css:#real"), nil, dialogNodeID)
+ if err != nil {
+ t.Fatalf("scoped resolve: %v", err)
+ }
+ if desc := nodeDescription(t, ctx, got); desc != "button#real" {
+ t.Errorf("dialog-scoped css:#real resolved to %s; page script steered the resolution", desc)
+ }
+}
+
+// getBoundingClientRect is redefined to report a rectangle far from the element.
+// If the clip is built in the main world the capture is aimed at the attacker's
+// coordinates instead of the element's.
+func TestScreenshotClipResistsMainWorldSubstitution(t *testing.T) {
+ ctx := newHijackFixture(t)
+
+ nodeID, err := ResolveCSSToNodeID(ctx, "#real")
+ if err != nil {
+ t.Fatal(err)
+ }
+ clip, err := ScreenshotClipForNode(ctx, nodeID)
+ if err != nil {
+ t.Fatalf("clip: %v", err)
+ }
+
+ // The forged rect is the one value the page can produce; anything else means
+ // the read happened somewhere the page could not reach.
+ if clip.X == 999 || clip.Y == 999 || (clip.Width == 100 && clip.Height == 50) {
+ t.Errorf("clip %+v matches the rectangle page script forged; the origin was read in the main world", clip)
+ }
+ if clip.Width <= 0 || clip.Height <= 0 {
+ t.Errorf("clip %+v has no area", clip)
+ }
+}
+
+// The boundary must fail closed. If no isolated context can be obtained the
+// resolution has to error — falling back to a main-world handle would leave the
+// hole open with every test above still green.
+func TestIsolatedNodeObjectIDFailsClosedWithoutContext(t *testing.T) {
+ ctx := newHijackFixture(t)
+
+ nodeID, err := ResolveCSSToNodeID(ctx, "#real")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // A cancelled context cannot create an isolated world, which is the closest
+ // reachable stand-in for a frame that cannot supply one.
+ dead, cancel := context.WithCancel(ctx)
+ cancel()
+
+ if objectID, err := IsolatedNodeObjectID(dead, nodeID); err == nil {
+ t.Fatalf("resolution succeeded with object %q when no isolated context was obtainable; it must not fall back to the main world", objectID)
+ }
+}
+
+// mainWorldResolvers is the boundary as it actually stands, as data. These files
+// still resolve a bare backend node id, so their Runtime.callFunctionOn work runs
+// in the main world. They are the OPERATION paths — what is done to a node once
+// chosen — which this change deliberately does not cover; extending the boundary
+// across the action layer is a larger question with its own risk profile.
+//
+// The resolution paths, which decide WHICH element is acted on, are not here:
+// that is the whole claim, and this table is what keeps the claim honest. A new
+// unprotected site appearing, or one of these being fixed without updating the
+// list, both fail here.
+var mainWorldResolvers = map[string]string{
+ "action_form.go": "form fill operates on an already-chosen field",
+ "semantic_metadata.go": "metadata enrichment reads an already-chosen node",
+ "tab_auto_switch.go": "tab switching acts on an already-chosen target",
+}
+
+func TestIsolatedWorldBoundaryCensus(t *testing.T) {
+ entries, err := os.ReadDir(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ found := map[string]bool{}
+ checked := 0
+ for _, entry := range entries {
+ name := entry.Name()
+ if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ raw, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, block := range strings.Split(string(raw), `"DOM.resolveNode"`)[1:] {
+ checked++
+ head := block
+ if len(head) > 200 {
+ head = head[:200]
+ }
+ if strings.Contains(head, "executionContextId") {
+ continue
+ }
+ found[name] = true
+ if _, known := mainWorldResolvers[name]; !known {
+ t.Errorf("%s resolves a node without an isolated executionContextId and is not a recorded operation path:\n%s", name, head)
+ }
+ }
+ }
+ if checked == 0 {
+ t.Fatal("no DOM.resolveNode call found in the package — this census is checking nothing")
+ }
+ for name, why := range mainWorldResolvers {
+ if !found[name] {
+ t.Errorf("%s no longer resolves in the main world (%s); remove it from mainWorldResolvers so the recorded boundary stays true", name, why)
+ }
+ }
+}
diff --git a/internal/bridge/screenshot.go b/internal/bridge/screenshot.go
index 98bcdd50..c8b8063d 100644
--- a/internal/bridge/screenshot.go
+++ b/internal/bridge/screenshot.go
@@ -241,33 +241,24 @@ func ScreenshotClipForNode(ctx context.Context, nodeID int64) (*ScreenshotClip,
return nil, 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": nodeID,
- }, &resolveResult)
- })); err != nil {
+ // Isolated world: boxFn reads getBoundingClientRect, so a main-world handle
+ // would let the page steer the clip origin by redefining it.
+ objectID, err := IsolatedNodeObjectID(ctx, nodeID)
+ if err != nil {
return nil, 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 {
- return nil, fmt.Errorf("parse resolved node: %w", err)
- }
- if resolved.Object.ObjectID == "" {
- return nil, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)
- }
-
+ // The frame walk starts from the NODE's own view, not the ambient `window`.
+ // An isolated-world handle runs in the world it was resolved into, which is
+ // not necessarily the node's frame, and a bare `window` there is the wrong
+ // frame's — its frameElement chain is empty and every frame offset is lost.
const boxFn = `function() {
+ const view = (this.ownerDocument && this.ownerDocument.defaultView) || window;
const rect = this.getBoundingClientRect();
- let x = rect.left + (window.scrollX || window.pageXOffset || 0);
- let y = rect.top + (window.scrollY || window.pageYOffset || 0);
+ let x = rect.left + (view.scrollX || view.pageXOffset || 0);
+ let y = rect.top + (view.scrollY || view.pageYOffset || 0);
try {
- let current = window;
+ let current = view;
while (current && current.parent && current !== current.parent) {
const frameEl = current.frameElement;
if (!frameEl) {
@@ -290,7 +281,7 @@ func ScreenshotClipForNode(ctx context.Context, nodeID int64) (*ScreenshotClip,
if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
"functionDeclaration": boxFn,
- "objectId": resolved.Object.ObjectID,
+ "objectId": objectID,
"returnByValue": true,
}, &callResult)
})); err != nil {