High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: an unrecognised --button name is silently reinterpreted as left, so a misspelled right-button action succeeds as a left-button one (PIN-232)
Luigi Agostie95a23a4994e
diff --git a/cmd/pinchtab/cmd_cli_button_test.go b/cmd/pinchtab/cmd_cli_button_test.gonew file mode 100644index 00000000..636d4264--- /dev/null+++ b/cmd/pinchtab/cmd_cli_button_test.go@@ -0,0 +1,84 @@+package main++import (+ "strings"+ "testing"++ bridgecdpops "github.com/pinchtab/pinchtab/internal/bridge/cdpops"+ "github.com/spf13/cobra"+)++// buttonCommands is derived from the tree rather than hand-listed: every command that+// registers --button must refuse an unknown one locally, so a fourth command gaining the flag+// is covered on arrival.+func buttonCommands(t *testing.T) []*cobra.Command {+ t.Helper()++ var found []*cobra.Command+ var walk func(cmd *cobra.Command)+ walk = func(cmd *cobra.Command) {+ if cmd.Flags().Lookup("button") != nil {+ found = append(found, cmd)+ }+ for _, sub := range cmd.Commands() {+ walk(sub)+ }+ }+ walk(rootCmd)++ if len(found) < 3 {+ t.Fatalf("found %d commands with --button, so this census is not walking the command tree", len(found))+ }+ return found+}++// The local refusal is a fast path for a typo — better than a server round trip — and it must+// not be the only guard, which the HTTP-side test covers.+func TestEveryButtonFlagRefusesAnUnknownNameLocally(t *testing.T) {+ for _, cmd := range buttonCommands(t) {+ path := cmd.CommandPath()+ if cmd.PreRunE == nil {+ t.Errorf("%s registers --button with no local check, so a typo costs a server round trip to discover", path)+ continue+ }++ if err := cmd.Flags().Set("button", "rihgt"); err != nil {+ t.Fatal(err)+ }+ err := cmd.PreRunE(cmd, nil)+ if err == nil {+ t.Errorf("%s accepted a misspelled button", path)+ } else if !strings.Contains(err.Error(), "rihgt") {+ t.Errorf("%s refusal = %v, want it to name what was sent", path, err)+ }++ for _, valid := range append(bridgecdpops.MouseButtons(), "RIGHT", " middle ") {+ if err := cmd.Flags().Set("button", valid); err != nil {+ t.Fatal(err)+ }+ if err := cmd.PreRunE(cmd, nil); err != nil {+ t.Errorf("%s refused %q: %v", path, valid, err)+ }+ }++ if err := cmd.Flags().Set("button", bridgecdpops.DefaultMouseButton); err != nil {+ t.Fatal(err)+ }+ }+}++// The help text and the default both come from the vocabulary owner, so the next button is+// not documented in one place and refused in another.+func TestEveryButtonFlagDerivesItsHelpFromTheVocabulary(t *testing.T) {+ for _, cmd := range buttonCommands(t) {+ flag := cmd.Flags().Lookup("button")+ if flag.DefValue != bridgecdpops.DefaultMouseButton {+ t.Errorf("%s --button default = %q, want the vocabulary's own default %q", cmd.CommandPath(), flag.DefValue, bridgecdpops.DefaultMouseButton)+ }+ for _, name := range bridgecdpops.MouseButtons() {+ if !strings.Contains(flag.Usage, name) {+ t.Errorf("%s --button help = %q, want it to name %q", cmd.CommandPath(), flag.Usage, name)+ }+ }+ }+}diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex 594d9081..aedd8cc5 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -6,6 +6,7 @@ import ("time""github.com/pinchtab/pinchtab/internal/bridge"+ bridgecdpops "github.com/pinchtab/pinchtab/internal/bridge/cdpops""github.com/spf13/cobra")@@ -82,10 +83,10 @@ func configureBrowserFlags() {addPointerActionFlags(mouseMoveCmd, bridge.ActionMouseMove)addPointerActionFlags(mouseDownCmd, bridge.ActionMouseDown)- mouseDownCmd.Flags().String("button", "left", "Mouse button: left, right, middle")+ addMouseButtonFlag(mouseDownCmd)addPointerActionFlags(mouseUpCmd, bridge.ActionMouseUp)- mouseUpCmd.Flags().String("button", "left", "Mouse button: left, right, middle")+ addMouseButtonFlag(mouseUpCmd)addPointerActionFlags(mouseWheelCmd, bridge.ActionMouseWheel)@@ -97,7 +98,7 @@ func configureBrowserFlags() {scrollCmd.Flags().Int("dy", 0, "Vertical scroll in pixels (negative scrolls up)")scrollCmd.Flags().Int("dx", 0, "Horizontal scroll in pixels (negative scrolls left)")- dragCmd.Flags().String("button", "left", "Mouse button: left, right, middle")+ addMouseButtonFlag(dragCmd)dragCmd.Flags().Int("drag-x", 0, "Horizontal pixel offset for single-step drag action")dragCmd.Flags().Int("drag-y", 0, "Vertical pixel offset for single-step drag action")@@ -500,3 +501,23 @@ func addPostActionFlags(cmd *cobra.Command, verb string, withText bool) {cmd.Flags().Bool("text", false, "Output page text after "+verb+" (for verification)")}}++// addMouseButtonFlag registers --button and the local refusal together, so the help text,+// the default and the accepted set all come from the one vocabulary owner rather than being+// spelled out per command. The refusal is a fast path for a typo, NOT the guard: the HTTP+// body is validated server-side because the CLI is not the only client.+func addMouseButtonFlag(cmd *cobra.Command) {+ cmd.Flags().String("button", bridgecdpops.DefaultMouseButton,+ "Mouse button: "+strings.Join(bridgecdpops.MouseButtons(), ", "))+ previous := cmd.PreRunE+ cmd.PreRunE = func(c *cobra.Command, args []string) error {+ button, _ := c.Flags().GetString("button")+ if err := bridgecdpops.ValidateMouseButton(button); err != nil {+ return err+ }+ if previous != nil {+ return previous(c, args)+ }+ return nil+ }+}diff --git a/docs/reference/mouse.md b/docs/reference/mouse.mdindex 0418752e..fdf97cb4 100644--- a/docs/reference/mouse.md+++ b/docs/reference/mouse.md@@ -54,7 +54,12 @@ Notes:sustained movement follows the press, so a single jump fires no `dragstart` at all.Assembling a drag yourself out of `mouse move`/`mouse down`/`mouse up` has that problem:use `drag` for anything with a `draggable` source.-- `button` supports `left`, `right`, and `middle`.+- `button` supports `left`, `right`, and `middle`. Any other name is refused — the CLI+ refuses it before sending, and the HTTP action body answers 400 naming the three. Omitting+ `button` still means `left`; that is a default, whereas a name the server does not know+ used to be reinterpreted as `left` and reported as success. The DOM's `primary` and+ `secondary` are refused rather than mapped, since `primary` happens to mean left while+ `secondary` would not.- Pointer move uses a bounded CDP `mouseMoved` dispatch first. If headless Chromium stalls that dispatch, PinchTab falls back to DOM mouse events so hover and mouse-move flows remain responsive.## HTTP APIdiff --git a/internal/bridge/action_button_test.go b/internal/bridge/action_button_test.gonew file mode 100644index 00000000..25cdd608--- /dev/null+++ b/internal/bridge/action_button_test.go@@ -0,0 +1,76 @@+package bridge++import (+ "context"+ "strings"+ "testing"++ bridgecdpops "github.com/pinchtab/pinchtab/internal/bridge/cdpops"+)++// The validator is not gated on the action kind, so every kind that can carry a button is+// covered without a list anyone has to maintain — including one nobody thought of. These+// kinds are the ones the CLI and the pointer helpers actually pass a button for.+func TestValidateButtonActionRefusesAnUnknownNameForEveryKind(t *testing.T) {+ for _, kind := range []string{ActionMouseDown, ActionMouseUp, ActionDrag, ActionClick, ActionDoubleClick, "a-kind-nobody-listed"} {+ err := ValidateButtonAction(kind, ActionRequest{Kind: kind, Button: "rihgt"})+ if err == nil {+ t.Errorf("%s accepted a misspelled button, so it dispatches left and reports success", kind)+ continue+ }+ if !strings.Contains(err.Error(), "rihgt") {+ t.Errorf("%s refusal = %v, want it to name what the caller sent", kind, err)+ }++ for _, ok := range append(bridgecdpops.MouseButtons(), "", "RIGHT", " right ") {+ if err := ValidateButtonAction(kind, ActionRequest{Kind: kind, Button: ok}); err != nil {+ t.Errorf("%s refused %q: %v", kind, ok, err)+ }+ }+ }+}++// ExecuteAction is the second enforcement point: the handler refuses first with a 400, but a+// caller reaching the bridge directly must not get the silent left-click either.+func TestExecuteActionRefusesAnUnknownButtonBeforeDispatch(t *testing.T) {+ dispatched := false+ b := &Bridge{Actions: map[string]ActionFunc{+ ActionMouseDown: func(ctx context.Context, req ActionRequest) (map[string]any, error) {+ dispatched = true+ return map[string]any{"down": true}, nil+ },+ }}++ _, err := b.ExecuteAction(context.Background(), ActionMouseDown, ActionRequest{Button: "secondary"})++ if err == nil {+ t.Fatal("ExecuteAction accepted an unknown button")+ }+ if dispatched {+ t.Error("the action ran before the button was validated, so the refusal came too late to prevent the wrong click")+ }+ for _, name := range bridgecdpops.MouseButtons() {+ if !strings.Contains(err.Error(), name) {+ t.Errorf("refusal = %v, want it to name the valid button %q", err, name)+ }+ }+}++func TestExecuteActionStillDispatchesTheValidButtons(t *testing.T) {+ for _, button := range append(bridgecdpops.MouseButtons(), "", "RIGHT", " middle ") {+ dispatched := false+ b := &Bridge{Actions: map[string]ActionFunc{+ ActionMouseDown: func(ctx context.Context, req ActionRequest) (map[string]any, error) {+ dispatched = true+ return map[string]any{"down": true}, nil+ },+ }}++ if _, err := b.ExecuteAction(context.Background(), ActionMouseDown, ActionRequest{Button: button}); err != nil {+ t.Errorf("button %q was refused: %v", button, err)+ }+ if !dispatched {+ t.Errorf("button %q did not reach the action", button)+ }+ }+}diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.goindex ca009124..b7623fd7 100644--- a/internal/bridge/action_request.go+++ b/internal/bridge/action_request.go@@ -6,6 +6,8 @@ import ("fmt""log/slog""strings"++ bridgecdpops "github.com/pinchtab/pinchtab/internal/bridge/cdpops")type ActionFunc func(ctx context.Context, req ActionRequest) (map[string]any, error)@@ -259,6 +261,16 @@ func ValidateFillAction(kind string, req ActionRequest) error {return nil}+// ValidateButtonAction refuses a button name no pointer action can honour. It is not gated+// on the action kind, deliberately: the button is normalized inside cdpops for every action+// that dispatches a press, so a kind list here would have to be kept in step with that set+// and would leave any kind nobody thought of accepting a misspelling silently. An+// unrecognised name reached CDP as "left", so a mistyped right-click performed a left-click+// and reported success.+func ValidateButtonAction(kind string, req ActionRequest) error {+ return bridgecdpops.ValidateMouseButton(req.Button)+}+func hasJSONKey(raw map[string]json.RawMessage, key string) bool {_, ok := raw[key]return ok@@ -276,6 +288,9 @@ func (b *Bridge) ExecuteAction(ctx context.Context, kind string, req ActionRequeif err := ValidateFillAction(kind, req); err != nil {return nil, err}+ if err := ValidateButtonAction(kind, req); err != nil {+ return nil, err+ }if kind == ActionClick && b.effectiveHumanize(req) && strings.TrimSpace(req.Mode) != "" {return nil, fmt.Errorf("mode and humanize are mutually exclusive")}diff --git a/internal/bridge/cdpops/pointer.go b/internal/bridge/cdpops/pointer.goindex ebe581dc..a4b6d9fe 100644--- a/internal/bridge/cdpops/pointer.go+++ b/internal/bridge/cdpops/pointer.go@@ -19,15 +19,46 @@ import (// stay responsive.const mouseMoveDispatchTimeout = 50 * time.Millisecond+// DefaultMouseButton is what an unspecified button means. An unspecified button is a+// 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.+func MouseButtons() []string {+ return append([]string(nil), mouseButtons...)+}++// ValidateMouseButton refuses a name that is not a button, naming the ones that are. Empty+// and whitespace-only stay valid: that is the default, not forgiveness. The DOM's own+// vocabulary is refused rather than mapped — "primary" happens to mean left, so mapping it+// would look right while "secondary" silently became left, and PinchTab documents neither.+func ValidateMouseButton(button string) error {+ normalized := strings.ToLower(strings.TrimSpace(button))+ if normalized == "" {+ return nil+ }+ for _, name := range mouseButtons {+ if normalized == name {+ return nil+ }+ }+ 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 {- switch strings.ToLower(strings.TrimSpace(button)) {- case "right":- return "right"- case "middle":- return "middle"- default:- return "left"+ normalized := strings.ToLower(strings.TrimSpace(button))+ for _, name := range mouseButtons {+ if normalized == name {+ return normalized+ }}+ return DefaultMouseButton}func validatePointerCoordinates(x, y float64) error {diff --git a/internal/bridge/cdpops/pointer_test.go b/internal/bridge/cdpops/pointer_test.goindex 5e2723c7..0be89c18 100644--- a/internal/bridge/cdpops/pointer_test.go+++ b/internal/bridge/cdpops/pointer_test.go@@ -3,6 +3,11 @@ package cdpopsimport ("context""errors"+ "go/ast"+ "go/parser"+ "go/token"+ "os"+ "strings""testing""github.com/chromedp/cdproto/input"@@ -117,3 +122,148 @@ func TestDispatchMouseMoveToNodeFallsBackToSyntheticNodeMove(t *testing.T) {t.Fatal("expected synthetic node fallback to run")}}++// An unspecified button is a default; an unrecognised NAME is a caller error. Those two+// shared one answer, so a mistyped right-click dispatched a left-click and reported success.+func TestValidateMouseButtonSeparatesUnspecifiedFromUnrecognised(t *testing.T) {+ for _, tc := range []struct {+ in string+ wantErr bool+ why string+ }{+ {in: "", why: "unspecified is the default, not an error — refusing it would break every caller that never named one"},+ {in: " ", why: "whitespace-only is still unspecified"},+ {in: "left"},+ {in: "right"},+ {in: "middle"},+ {in: "RIGHT", why: "case tolerance is worth keeping"},+ {in: " right ", why: "surrounding whitespace is worth keeping"},+ {in: "rihgt", wantErr: true, why: "a misspelling used to dispatch left"},+ {in: "primary", wantErr: true, why: "the DOM vocabulary is refused, not mapped: primary happens to mean left, which is what made this class look harmless"},+ {in: "secondary", wantErr: true, why: "the case primary hides — mapping the DOM names would silently make this left"},+ {in: "0", wantErr: true, why: "a numeric button is not this vocabulary"},+ } {+ err := ValidateMouseButton(tc.in)+ if tc.wantErr && err == nil {+ t.Errorf("ValidateMouseButton(%q) accepted it; %s", tc.in, tc.why)+ continue+ }+ if !tc.wantErr && err != nil {+ t.Errorf("ValidateMouseButton(%q) = %v; %s", tc.in, err, tc.why)+ continue+ }+ if tc.wantErr {+ for _, name := range MouseButtons() {+ if !strings.Contains(err.Error(), name) {+ t.Errorf("ValidateMouseButton(%q) = %v, want it to name the valid button %q", tc.in, err, name)+ }+ }+ }+ }+}++// One vocabulary owner: the normalizer accepts exactly what MouseButtons lists and the+// refusal names exactly that list, so a fourth button added there cannot be accepted in one+// place and refused in another.+func TestTheButtonVocabularyHasOneOwner(t *testing.T) {+ buttons := MouseButtons()+ if len(buttons) < 3 {+ t.Fatalf("MouseButtons() = %v, want at least the three this CLI documents", buttons)+ }+ for _, name := range buttons {+ if err := ValidateMouseButton(name); err != nil {+ t.Errorf("%q is listed as a button but refused: %v", name, err)+ }+ if got := normalizeMouseButton(name); got != name {+ t.Errorf("normalizeMouseButton(%q) = %q; a listed button must survive normalization", name, got)+ }+ }+ if got := normalizeMouseButton(""); got != DefaultMouseButton {+ t.Errorf("normalizeMouseButton(\"\") = %q, want the default %q", got, DefaultMouseButton)+ }+}++// Derived from the callers rather than a hand-listed set: every exported entry point taking+// a button must route it through the normalizer, so none reaches CDP with a raw caller+// string. Adding an entry point that forgets is what this catches.+func TestEveryButtonTakingEntryPointNormalizesIt(t *testing.T) {+ source, err := os.ReadFile("pointer.go")+ if err != nil {+ t.Fatal(err)+ }+ fset := token.NewFileSet()+ file, err := parser.ParseFile(fset, "pointer.go", source, 0)+ if err != nil {+ t.Fatal(err)+ }++ checked := 0+ for _, decl := range file.Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok || fn.Body == nil || !takesAButton(fn) {+ continue+ }+ if fn.Name.Name == "normalizeMouseButton" || fn.Name.Name == "ValidateMouseButton" {+ continue+ }+ checked+++ if !callsNormalizer(fn) && !passesButtonOn(fn) {+ t.Errorf("%s takes a button and neither normalizes it nor passes it to something that does, so a caller string reaches CDP raw", fn.Name.Name)+ }+ }+ if checked < 4 {+ t.Fatalf("found only %d button-taking functions in pointer.go; this census is not reading the callers", checked)+ }+}++func takesAButton(fn *ast.FuncDecl) bool {+ if fn.Type.Params == nil {+ return false+ }+ for _, param := range fn.Type.Params.List {+ ident, ok := param.Type.(*ast.Ident)+ if !ok || ident.Name != "string" {+ continue+ }+ for _, name := range param.Names {+ if name.Name == "button" {+ return true+ }+ }+ }+ return false+}++func callsNormalizer(fn *ast.FuncDecl) bool {+ found := false+ ast.Inspect(fn.Body, func(node ast.Node) bool {+ call, ok := node.(*ast.CallExpr)+ if !ok {+ return true+ }+ if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == "normalizeMouseButton" {+ found = true+ }+ return true+ })+ return found+}++// A wrapper that hands the button to another button-taking helper is covered by that+// helper's own normalization, so it counts.+func passesButtonOn(fn *ast.FuncDecl) bool {+ found := false+ ast.Inspect(fn.Body, func(node ast.Node) bool {+ call, ok := node.(*ast.CallExpr)+ if !ok {+ return true+ }+ for _, arg := range call.Args {+ if ident, ok := arg.(*ast.Ident); ok && ident.Name == "button" {+ found = true+ }+ }+ return true+ })+ return found+}diff --git a/internal/handlers/action_button_test.go b/internal/handlers/action_button_test.gonew file mode 100644index 00000000..56bc685a--- /dev/null+++ b/internal/handlers/action_button_test.go@@ -0,0 +1,59 @@+package handlers++import (+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ bridgecdpops "github.com/pinchtab/pinchtab/internal/bridge/cdpops"+ "github.com/pinchtab/pinchtab/internal/config"+)++// The CLI is not the only client: the query-parameter path accepts anything a caller sends,+// so the HTTP body has to be refused server-side rather than relying on the local flag check.+// This is the surface where an unknown button previously became a left-button action with a+// 200 and no reason.+func TestTheActionEndpointRefusesAnUnknownButtonWith400(t *testing.T) {+ h := New(&mockBridge{availableActions: []string{bridge.ActionMouseDown}}, &config.RuntimeConfig{}, nil, nil, nil)++ for _, tc := range []struct{ name, body string }{+ {name: "misspelling", body: `{"kind":"mouse-down","button":"rihgt","tabId":"tab1"}`},+ {name: "the DOM vocabulary", body: `{"kind":"mouse-down","button":"secondary","tabId":"tab1"}`},+ {name: "numeric", body: `{"kind":"mouse-down","button":"0","tabId":"tab1"}`},+ } {+ w := httptest.NewRecorder()+ h.HandleAction(w, httptest.NewRequest("POST", "/action", strings.NewReader(tc.body)))++ if w.Code != 400 {+ t.Errorf("%s: status = %d, want 400; a button nothing can honour must not reach the browser", tc.name, w.Code)+ continue+ }+ for _, name := range bridgecdpops.MouseButtons() {+ if !strings.Contains(w.Body.String(), name) {+ t.Errorf("%s: body = %s, want it to name the valid button %q", tc.name, w.Body.String(), name)+ }+ }+ }+}++// The pair assertion: refusing unknown names is satisfiable by refusing everything, which+// would break every caller that never named a button.+func TestTheActionEndpointStillAcceptsTheValidButtonsAndTheDefault(t *testing.T) {+ h := New(&mockBridge{availableActions: []string{bridge.ActionMouseDown}}, &config.RuntimeConfig{}, nil, nil, nil)++ for _, button := range append(bridgecdpops.MouseButtons(), "RIGHT", " middle ") {+ body := `{"kind":"mouse-down","button":"` + button + `","tabId":"tab1"}`+ w := httptest.NewRecorder()+ h.HandleAction(w, httptest.NewRequest("POST", "/action", strings.NewReader(body)))+ if w.Code == 400 {+ t.Errorf("button %q was refused: %s", button, w.Body.String())+ }+ }++ w := httptest.NewRecorder()+ h.HandleAction(w, httptest.NewRequest("POST", "/action", strings.NewReader(`{"kind":"mouse-down","tabId":"tab1"}`)))+ if w.Code == 400 {+ t.Errorf("an unspecified button was refused: %s", w.Body.String())+ }+}diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex d276204c..69e8cd39 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -271,6 +271,10 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {httpx.ErrorCode(w, http.StatusBadRequest, "missing_fill_text", err.Error(), false, nil)return}+ if err := bridge.ValidateButtonAction(req.Kind, req); err != nil {+ httpx.ErrorCode(w, http.StatusBadRequest, "invalid_mouse_button", err.Error(), false, nil)+ return+ }h.recordActionRequest(r, req)if available := h.Bridge.AvailableActions(); len(available) > 0 {known := false