Skip to content

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

refactor: heldButton restates the button vocabulary as two literal cases with a silent left default, so a fourth button would be accepted everywhere and dispatched as left (PIN-248)

Luigi Agostiaafe035a2bba
diff --git a/internal/bridge/cdpops/pointer.go b/internal/bridge/cdpops/pointer.go
index a4b6d9fe..cb9c2e7b 100644
--- a/internal/bridge/cdpops/pointer.go
+++ b/internal/bridge/cdpops/pointer.go
@@ -23,13 +23,53 @@ const mouseMoveDispatchTimeout = 50 * time.Millisecond
// default; an unrecognised NAME is a caller error, and the two used to share this answer.
const DefaultMouseButton = "left"
-var mouseButtons = []string{DefaultMouseButton, "right", "middle"}
-
-// MouseButtons is the one owner of the button vocabulary. The normalizer, the refusal
-// message and the CLI flag help all derive from it, so a fourth button cannot be accepted
-// in one place and refused in another.
+// mouseButton is one row of the button vocabulary: the name a caller writes, the CDP enum,
+// the "buttons" bitmask that says it is held, and MouseEvent.button for the synthetic DOM
+// fallback. Every fact about a button lives on its row, so a name that validates dispatches
+// correctly BY CONSTRUCTION — the vocabulary used to have one owner for which names exist
+// and hand-written switches for what each name means, so a fourth entry would have passed
+// validation and then been dispatched as left, with a drag pressing one button and moving
+// under another.
+type mouseButton struct {
+ name string
+ enum input.MouseButton
+ held int64
+ jsCode int
+}
+
+var mouseButtonTable = []mouseButton{
+ {name: DefaultMouseButton, enum: input.Left, held: 1, jsCode: 0},
+ {name: "right", enum: input.Right, held: 2, jsCode: 2},
+ {name: "middle", enum: input.Middle, held: 4, jsCode: 1},
+}
+
+// MouseButtons is the button vocabulary, derived from the table rather than maintained
+// beside it. The normalizer, the refusal message and the CLI flag help all read this, so a
+// fourth button cannot be accepted in one place and refused in another.
func MouseButtons() []string {
- return append([]string(nil), mouseButtons...)
+ names := make([]string, 0, len(mouseButtonTable))
+ for _, b := range mouseButtonTable {
+ names = append(names, b.name)
+ }
+ return names
+}
+
+func mouseButtonNamed(name string) (mouseButton, bool) {
+ for _, b := range mouseButtonTable {
+ if b.name == name {
+ return b, true
+ }
+ }
+ return mouseButton{}, false
+}
+
+func mouseButtonForEnum(enum input.MouseButton) (mouseButton, bool) {
+ for _, b := range mouseButtonTable {
+ if b.enum == enum {
+ return b, true
+ }
+ }
+ return mouseButton{}, false
}
// ValidateMouseButton refuses a name that is not a button, naming the ones that are. Empty
@@ -41,22 +81,18 @@ func ValidateMouseButton(button string) error {
if normalized == "" {
return nil
}
- for _, name := range mouseButtons {
- if normalized == name {
- return nil
- }
+ if _, ok := mouseButtonNamed(normalized); ok {
+ return nil
}
- return fmt.Errorf("button %q is not a mouse button; use one of %s", button, strings.Join(mouseButtons, ", "))
+ return fmt.Errorf("button %q is not a mouse button; use one of %s", button, strings.Join(MouseButtons(), ", "))
}
// normalizeMouseButton keeps its permissive default and its plain-string return: by the time
// a value reaches it, ValidateMouseButton has already refused every name that is not here.
func normalizeMouseButton(button string) string {
normalized := strings.ToLower(strings.TrimSpace(button))
- for _, name := range mouseButtons {
- if normalized == name {
- return normalized
- }
+ if _, ok := mouseButtonNamed(normalized); ok {
+ return normalized
}
return DefaultMouseButton
}
@@ -85,13 +121,13 @@ func mousePressReleaseActions(x, y float64, clickCount int) []chromedp.Action {
return []chromedp.Action{
mouseEventAction(map[string]any{
"type": "mousePressed",
- "button": "left",
+ "button": DefaultMouseButton,
"clickCount": clickCount,
"x": x, "y": y,
}),
mouseEventAction(map[string]any{
"type": "mouseReleased",
- "button": "left",
+ "button": DefaultMouseButton,
"clickCount": clickCount,
"x": x, "y": y,
}),
@@ -117,6 +153,10 @@ var (
dispatchRealMouseMoveFunc = dispatchRealMouseMove
dispatchSyntheticMouseMoveFunc = dispatchSyntheticMouseMove
dispatchSyntheticMouseMoveOnNodeFunc = dispatchSyntheticMouseMoveOnNode
+ // dispatchMouseEventFunc joins them so a drag's press payload is observable without a
+ // browser: the button a drag PRESSES and the button its moves HOLD have to be compared
+ // to each other, and only the call site can show they agree.
+ dispatchMouseEventFunc = dispatchMouseEvent
)
func dispatchMouseMove(ctx context.Context, x, y float64, button input.MouseButton, buttons int64) error {
@@ -196,17 +236,22 @@ func dispatchSyntheticMouseMoveOnNode(ctx context.Context, nodeID int64, button
}))
}
+// mouseButtonCode is MouseEvent.button for the synthetic DOM fallback, read off the table.
+// Unlike heldButton, its no-row case has a legitimate caller: a plain move carries
+// input.None, which the DOM encodes as button 0 beside buttons 0. So the zero here is the
+// answer for "nothing pressed", not a stand-in for left.
func mouseButtonCode(button input.MouseButton) int {
- switch button {
- case input.Middle:
- return 1
- case input.Right:
- return 2
- default:
- return 0
+ if row, ok := mouseButtonForEnum(button); ok {
+ return row.jsCode
}
+ return noButtonJSCode
}
+// noButtonJSCode is MouseEvent.button when no button is pressed. It equals left's code
+// because the DOM says so, which is why the two cases must be told apart by their reason
+// rather than by their value.
+const noButtonJSCode = 0
+
func MouseMoveByCoordinate(ctx context.Context, x, y float64) error {
if err := validatePointerCoordinates(x, y); err != nil {
return err
@@ -230,7 +275,7 @@ func MouseDownByCoordinate(ctx context.Context, x, y float64, button string, mod
if err := validatePointerCoordinates(x, y); err != nil {
return err
}
- return dispatchMouseEvent(ctx, map[string]any{
+ return dispatchMouseEventFunc(ctx, map[string]any{
"type": "mousePressed",
"button": normalizeMouseButton(button),
"clickCount": 1,
@@ -244,7 +289,7 @@ func MouseUpByCoordinate(ctx context.Context, x, y float64, button string, modif
if err := validatePointerCoordinates(x, y); err != nil {
return err
}
- return dispatchMouseEvent(ctx, map[string]any{
+ return dispatchMouseEventFunc(ctx, map[string]any{
"type": "mouseReleased",
"button": normalizeMouseButton(button),
"clickCount": 1,
@@ -354,7 +399,7 @@ func DoubleClickByCoordinate(ctx context.Context, x, y float64) error {
chromedp.ActionFunc(func(ctx context.Context) error {
return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
"type": "mousePressed",
- "button": "left",
+ "button": DefaultMouseButton,
"clickCount": 2,
"x": x,
"y": y,
@@ -363,7 +408,7 @@ func DoubleClickByCoordinate(ctx context.Context, x, y float64) error {
chromedp.ActionFunc(func(ctx context.Context) error {
return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
"type": "mouseReleased",
- "button": "left",
+ "button": DefaultMouseButton,
"clickCount": 2,
"x": x,
"y": y,
@@ -395,17 +440,21 @@ func DragByNodeID(ctx context.Context, nodeID int64, dx, dy int, button string)
return DragBetweenPoints(ctx, x, y, x+float64(dx), y+float64(dy), button)
}
-// heldButton maps a button name to the pair Input.dispatchMouseEvent needs while that
-// button is down: the enum for "button" and the bitmask for "buttons".
-func heldButton(button string) (input.MouseButton, int64) {
- switch normalizeMouseButton(button) {
- case "right":
- return input.Right, 2
- case "middle":
- return input.Middle, 4
- default:
- return input.Left, 1
+// heldButton resolves a name to its whole row, so the press payload and the held moves of
+// one drag cannot describe different buttons. It resolves empty-means-default itself rather
+// than borrowing normalizeMouseButton, whose permissive contract answers left for an
+// unrecognised name too — routing through it would have moved the silent fallback rather
+// than removing it. Unspecified is a default; unrecognised is a caller error.
+func heldButton(button string) (mouseButton, error) {
+ name := strings.ToLower(strings.TrimSpace(button))
+ if name == "" {
+ name = DefaultMouseButton
}
+ row, ok := mouseButtonNamed(name)
+ if !ok {
+ return mouseButton{}, fmt.Errorf("button %q is not a mouse button; use one of %s", button, strings.Join(MouseButtons(), ", "))
+ }
+ return row, nil
}
// Chrome starts an HTML5 drag only after sustained movement follows the press, so the
@@ -421,15 +470,17 @@ func DragBetweenPoints(ctx context.Context, x, y, endX, endY float64, button str
if steps > 20 {
steps = 20
}
- held, heldMask := heldButton(button)
- name := normalizeMouseButton(button)
+ held, err := heldButton(button)
+ if err != nil {
+ return err
+ }
if err := dispatchMouseMove(ctx, x, y, input.None, 0); err != nil {
return err
}
- if err := dispatchMouseEvent(ctx, map[string]any{
+ if err := dispatchMouseEventFunc(ctx, map[string]any{
"type": "mousePressed",
- "button": name,
+ "button": held.name,
"clickCount": 1,
"x": x, "y": y,
}); err != nil {
@@ -437,13 +488,13 @@ func DragBetweenPoints(ctx context.Context, x, y, endX, endY float64, button str
}
for i := 1; i <= steps; i++ {
t := float64(i) / float64(steps)
- if err := dispatchMouseMove(ctx, x+t*dx, y+t*dy, held, heldMask); err != nil {
+ if err := dispatchMouseMove(ctx, x+t*dx, y+t*dy, held.enum, held.held); err != nil {
return err
}
}
- return dispatchMouseEvent(ctx, map[string]any{
+ return dispatchMouseEventFunc(ctx, map[string]any{
"type": "mouseReleased",
- "button": name,
+ "button": held.name,
"clickCount": 1,
"x": endX, "y": endY,
})
diff --git a/internal/bridge/cdpops/pointer_test.go b/internal/bridge/cdpops/pointer_test.go
index 0be89c18..6f18a2ed 100644
--- a/internal/bridge/cdpops/pointer_test.go
+++ b/internal/bridge/cdpops/pointer_test.go
@@ -267,3 +267,157 @@ func passesButtonOn(fn *ast.FuncDecl) bool {
})
return found
}
+
+// dragCapture records what one DragBetweenPoints put on the wire, without a browser: the
+// press/release payloads and the button state of every interpolated move.
+type dragCapture struct {
+ pressed []map[string]any
+ moveEnum []input.MouseButton
+ moveMask []int64
+}
+
+func captureDrag(t *testing.T, button string) (*dragCapture, error) {
+ t.Helper()
+ origEvent, origMove := dispatchMouseEventFunc, dispatchRealMouseMoveFunc
+ t.Cleanup(func() {
+ dispatchMouseEventFunc = origEvent
+ dispatchRealMouseMoveFunc = origMove
+ })
+
+ got := &dragCapture{}
+ dispatchMouseEventFunc = func(_ context.Context, payload map[string]any) error {
+ got.pressed = append(got.pressed, payload)
+ return nil
+ }
+ dispatchRealMouseMoveFunc = func(_ context.Context, _, _ float64, b input.MouseButton, mask int64) error {
+ got.moveEnum = append(got.moveEnum, b)
+ got.moveMask = append(got.moveMask, mask)
+ return nil
+ }
+ return got, DragBetweenPoints(context.Background(), 10, 10, 200, 200, button)
+}
+
+// THE ASSERTION THAT WOULD HAVE CAUGHT THE SPLIT, driven at the call site and enumerated
+// over the table rather than over three restated names: a drag used to take its press
+// button from the NAME and its held moves from a hand-written switch, so a fourth entry
+// would have pressed one button and moved under another. Adding a row to the table brings
+// it into this test with no edit here.
+func TestEveryButtonInTheTableIsPressedAndHeldAsItself(t *testing.T) {
+ for _, want := range mouseButtonTable {
+ t.Run(want.name, func(t *testing.T) {
+ got, err := captureDrag(t, want.name)
+ if err != nil {
+ t.Fatalf("DragBetweenPoints(%q): %v", want.name, err)
+ }
+
+ if len(got.pressed) != 2 {
+ t.Fatalf("press/release events = %d, want 2: %v", len(got.pressed), got.pressed)
+ }
+ for _, payload := range got.pressed {
+ if payload["button"] != want.name {
+ t.Errorf("%v carries button %v, want %q", payload["type"], payload["button"], want.name)
+ }
+ }
+
+ if len(got.moveEnum) == 0 {
+ t.Fatal("no interpolated moves were dispatched, so nothing pins what the drag held")
+ }
+ heldMoves := 0
+ for i, enum := range got.moveEnum {
+ if got.moveMask[i] == 0 && enum == input.None {
+ continue // the initial position move, dispatched before the press
+ }
+ heldMoves++
+ if enum != want.enum {
+ t.Errorf("move %d held enum %v, want %v — the press said %q", i, enum, want.enum, want.name)
+ }
+ if got.moveMask[i] != want.held {
+ t.Errorf("move %d held mask %d, want %d", i, got.moveMask[i], want.held)
+ }
+ }
+ if heldMoves == 0 {
+ t.Fatal("every move was button-less, so the held state is unpinned")
+ }
+ })
+ }
+}
+
+// Unspecified means the default; unrecognised is a caller error. The second half is the
+// silent fallback this card removed — heldButton answered left for any name, so a button
+// the validator would have refused still dragged, as left.
+func TestHeldButtonSeparatesUnspecifiedFromUnrecognised(t *testing.T) {
+ for _, unspecified := range []string{"", " ", "\t"} {
+ row, err := heldButton(unspecified)
+ if err != nil {
+ t.Errorf("heldButton(%q) = %v; an unspecified button is the default, not an error", unspecified, err)
+ continue
+ }
+ if row.name != DefaultMouseButton {
+ t.Errorf("heldButton(%q) = %q, want the default %q", unspecified, row.name, DefaultMouseButton)
+ }
+ }
+
+ // Derived, not listed: a name that later joins the table must stop being a fixture
+ // here rather than turning this test into a false alarm about its own staleness.
+ for _, unrecognised := range namesOutsideTheTable("back", "forward", "primary", "LEFTish") {
+ if row, err := heldButton(unrecognised); err == nil {
+ t.Errorf("heldButton(%q) = %+v with no error; an unrecognised name must not be reinterpreted", unrecognised, row)
+ } else if !strings.Contains(err.Error(), strings.Join(MouseButtons(), ", ")) {
+ t.Errorf("heldButton(%q) error = %q; it must name the buttons that do exist", unrecognised, err)
+ }
+ }
+
+ outside := namesOutsideTheTable("back", "forward")
+ if len(outside) == 0 {
+ t.Skip("every candidate name is now a real button, so there is no unrecognised case to drive")
+ }
+ if _, err := captureDrag(t, outside[0]); err == nil {
+ t.Errorf("DragBetweenPoints accepted %q; the drag is where the silent left used to happen", outside[0])
+ }
+}
+
+// namesOutsideTheTable keeps the candidates that are genuinely not buttons.
+func namesOutsideTheTable(candidates ...string) []string {
+ outside := make([]string, 0, len(candidates))
+ for _, candidate := range candidates {
+ if _, ok := mouseButtonNamed(strings.ToLower(strings.TrimSpace(candidate))); !ok {
+ outside = append(outside, candidate)
+ }
+ }
+ return outside
+}
+
+// Every fact about a button is on its row, so the enum, the mask and the JS code cannot be
+// spelled a second time. The masks are the CDP "buttons" bits and must stay distinct powers
+// of two, or two buttons would be indistinguishable while held.
+func TestTheButtonTableIsTheOnlyPlaceAButtonFactIsWritten(t *testing.T) {
+ if len(mouseButtonTable) < 3 {
+ t.Fatalf("table = %+v; a census over fewer than the three documented buttons would pass vacuously", mouseButtonTable)
+ }
+
+ seenName, seenEnum, seenMask := map[string]bool{}, map[input.MouseButton]bool{}, map[int64]bool{}
+ for _, b := range mouseButtonTable {
+ if seenName[b.name] || seenEnum[b.enum] || seenMask[b.held] {
+ t.Errorf("row %+v repeats a name, enum or mask already in the table", b)
+ }
+ seenName[b.name], seenEnum[b.enum], seenMask[b.held] = true, true, true
+ if b.held == 0 || b.held&(b.held-1) != 0 {
+ t.Errorf("row %+v has held mask %d; the CDP buttons field is a bitmask, so each button owns one bit", b, b.held)
+ }
+ if _, ok := mouseButtonForEnum(b.enum); !ok {
+ t.Errorf("row %+v is not reachable by enum, so mouseButtonCode cannot derive its JS code", b)
+ }
+ if code := mouseButtonCode(b.enum); code != b.jsCode {
+ t.Errorf("mouseButtonCode(%v) = %d, want the row's %d", b.enum, code, b.jsCode)
+ }
+ }
+
+ // A move with nothing pressed is not a left click: input.None has no row, and its zero
+ // is the DOM's "no button" rather than a stand-in for left.
+ if _, ok := mouseButtonForEnum(input.None); ok {
+ t.Error("input.None has a table row; it is the absence of a button, not one of them")
+ }
+ if got := mouseButtonCode(input.None); got != noButtonJSCode {
+ t.Errorf("mouseButtonCode(input.None) = %d, want %d", got, noButtonJSCode)
+ }
+}