High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: five command groups exit 0 on an unknown subcommand, so a typo'd cache/cookies/session verb silently no-ops and reports success (PIN-117)
Luigi Agostie8204cb156e2
diff --git a/cmd/pinchtab/cmd_daemon.go b/cmd/pinchtab/cmd_daemon.goindex b304e0e3..70d6aa78 100644--- a/cmd/pinchtab/cmd_daemon.go+++ b/cmd/pinchtab/cmd_daemon.go@@ -84,7 +84,7 @@ func dispatchDaemonCommand(subcommand string, jsonOut bool) int {func printDaemonUsage(subcommand string) int {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("unknown daemon command: %s", subcommand)))fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.MutedStyle, "Usage: pinchtab daemon <status|install|start|restart|stop|uninstall>"))- return 2+ return unknownSubcommandExitCode}func isDaemonStatusSubcommand(subcommand string) bool {diff --git a/cmd/pinchtab/cmd_daemon_test.go b/cmd/pinchtab/cmd_daemon_test.goindex 3eef22cb..ca5332f5 100644--- a/cmd/pinchtab/cmd_daemon_test.go+++ b/cmd/pinchtab/cmd_daemon_test.go@@ -188,8 +188,8 @@ func TestDaemonUsageListsStatusForm(t *testing.T) {code = dispatchDaemonCommand("bogus", false)})- if code != 2 {- t.Fatalf("exit code = %d, want 2", code)+ if code != unknownSubcommandExitCode {+ t.Fatalf("exit code = %d, want the one unknown-subcommand code %d used across the CLI", code, unknownSubcommandExitCode)}if !strings.Contains(output, "pinchtab daemon <status|install|start|restart|stop|uninstall>") {t.Fatalf("expected usage line listing status, got %q", output)diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.goindex fed5e3c4..3d47b581 100644--- a/cmd/pinchtab/cmd_mcp.go+++ b/cmd/pinchtab/cmd_mcp.go@@ -13,6 +13,9 @@ var mcpCmd = &cobra.Command{Use: "mcp",Short: "Start the MCP stdio server",Long: "Start the Model Context Protocol stdio server and proxy browser actions to a running PinchTab instance.",+ // No subcommands to mistype, so the group guard cannot reach this one: an unrecognised+ // token here would otherwise start the server and ignore it.+ Args: cobra.NoArgs,Run: func(cmd *cobra.Command, args []string) {cfg := loadConfig()runMCP(cfg)diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.goindex 53518fb6..7cd88c5f 100644--- a/cmd/pinchtab/root.go+++ b/cmd/pinchtab/root.go@@ -54,6 +54,7 @@ func maybeRunWizard() {func Execute() {safelog.InstallDefault()+ installUnknownSubcommandGuard(rootCmd)if err := rootCmd.Execute(); err != nil {fmt.Fprintln(os.Stderr, err)os.Exit(commandExitCode(err))diff --git a/cmd/pinchtab/unknown_subcommand.go b/cmd/pinchtab/unknown_subcommand.gonew file mode 100644index 00000000..dde6aec6--- /dev/null+++ b/cmd/pinchtab/unknown_subcommand.go@@ -0,0 +1,73 @@+package main++import (+ "fmt"+ "sort"+ "strings"++ "github.com/spf13/cobra"+)++// unknownSubcommandExitCode is the one exit code for a typo'd verb anywhere in the CLI.+// It is 1 because that is what cobra's own error path already returns for a top-level+// unknown command, and every other reported error in this CLI exits 1 as well; daemon's+// hand-rolled 2 is what changed to match, not the other way round.+const unknownSubcommandExitCode = 1++// installUnknownSubcommandGuard makes an unrecognised subcommand an error on every group,+// which is what cobra does NOT do: its default argument check only rejects an unknown+// command on the ROOT, so `pinchtab cache clera` fell through to the group — printing help,+// or in the case of a runnable group such as `config` running the group's own action and+// swallowing the arguments — and exited 0. A script cannot tell that from the real verb, so+// `set -e` does not trip and the state it believed it reset was never reset.+//+// The guard is derived from the command tree rather than a list of group names, because a+// hand-written list is exactly how eleven groups came to be missing it. A group that+// declares its own Args is left alone: that declaration is how a parent whose operand is+// data rather than a verb opts out — `tab [id]` focuses a tab, `network <filter>` takes a+// pattern — and it is also the record of that decision.+//+// It must run after every command is registered, so it belongs at Execute rather than in an+// init: registration is spread across many init functions and their order is not a contract.+func installUnknownSubcommandGuard(cmd *cobra.Command) {+ for _, sub := range cmd.Commands() {+ installUnknownSubcommandGuard(sub)+ }+ if !cmd.HasSubCommands() || !cmd.HasParent() || cmd.Args != nil {+ return+ }+ cmd.Args = rejectUnknownSubcommand+ if !cmd.Runnable() {+ // A group with no action of its own never reaches its argument check: cobra returns+ // "print the help" for an unrunnable command BEFORE validating arguments, which is why+ // setting Args alone left `pinchtab cache clera` at exit 0. Printing the help is what+ // the command already did for no arguments, so this keeps that and nothing more.+ cmd.RunE = printGroupHelp+ }+}++func printGroupHelp(cmd *cobra.Command, _ []string) error {+ return cmd.Help()+}++// rejectUnknownSubcommand names the valid verbs in the error itself rather than relying on+// the usage template, which this CLI shortens to a single "run --help" line.+func rejectUnknownSubcommand(cmd *cobra.Command, args []string) error {+ if len(args) == 0 {+ return nil+ }+ message := fmt.Sprintf("unknown command %q for %q\nValid subcommands: %s",+ args[0], cmd.CommandPath(), strings.Join(subcommandNames(cmd), ", "))+ return newCommandExitError(unknownSubcommandExitCode, fmt.Errorf("%s", message))+}++func subcommandNames(cmd *cobra.Command) []string {+ var names []string+ for _, sub := range cmd.Commands() {+ if sub.IsAvailableCommand() {+ names = append(names, sub.Name())+ }+ }+ sort.Strings(names)+ return names+}diff --git a/cmd/pinchtab/unknown_subcommand_test.go b/cmd/pinchtab/unknown_subcommand_test.gonew file mode 100644index 00000000..45b67202--- /dev/null+++ b/cmd/pinchtab/unknown_subcommand_test.go@@ -0,0 +1,208 @@+package main++import (+ "bytes"+ "io"+ "os"+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++// TestMain installs the guard the way Execute does, so every test in this package drives the+// command tree production actually ships rather than the pre-guard one.+func TestMain(m *testing.M) {+ installUnknownSubcommandGuard(rootCmd)+ os.Exit(m.Run())+}++// operandNotAVerb records the parents whose first argument is DATA, not a subcommand, with+// what that data is. They opt out by declaring their own Args — this table is the reason,+// and it fails both ways: a parent that stops taking an operand must leave, and a parent+// that starts accepting an unknown verb must be added deliberately.+var operandNotAVerb = map[string]string{+ "pinchtab tab": "the argument is a tab ID to focus, so an unknown token is a 404 from the server rather than a typo'd verb",+ "pinchtab network": "the argument is a URL filter for the network log",+}++// A typo'd verb must not read as success: these are state-changing commands that live in+// setup and teardown scripts, so exit 0 means `set -e` does not trip and the state the+// script believed it reset was never reset. The census walks the command TREE rather than a+// list of group names, because a hand-written list is how eleven groups came to be missing+// this in the first place.+func TestEveryCommandGroupRejectsAnUnknownSubcommand(t *testing.T) {+ groups := commandGroups(rootCmd)+ if len(groups) < 15 {+ t.Fatalf("found only %d command groups, so this census is not walking the command tree", len(groups))+ }++ for _, group := range groups {+ path := group.CommandPath()+ // A nil validator is cobra's default, which accepts anything below the root — the very+ // state this guard exists to leave behind, so it must read as acceptance, not a panic.+ var err error+ if group.Args != nil {+ err = group.Args(group, []string{"zzz-not-a-subcommand"})+ }++ if reason, exempt := operandNotAVerb[path]; exempt {+ if err != nil {+ t.Errorf("%s rejected its operand; it takes one because %s", path, reason)+ }+ continue+ }++ if err == nil {+ t.Errorf("%s accepts an unknown subcommand, so a typo there exits 0 and a script reads it as success", path)+ continue+ }+ if got := commandExitCode(err); got != unknownSubcommandExitCode {+ t.Errorf("%s unknown-subcommand exit code = %d, want %d everywhere so callers can branch on it", path, got, unknownSubcommandExitCode)+ }+ if !strings.Contains(err.Error(), "zzz-not-a-subcommand") {+ t.Errorf("%s refusal = %q, want it to name the token that was not understood", path, err)+ }+ for _, name := range subcommandNames(group) {+ if !strings.Contains(err.Error(), name) {+ t.Errorf("%s refusal = %q, want it to name the valid subcommand %q", path, err, name)+ }+ }+ // The argument check is only reached on a runnable command: cobra answers "print the+ // help" for an unrunnable one before validating anything, which is why setting Args+ // alone left the groups with no action of their own at exit 0.+ if !group.Runnable() {+ t.Errorf("%s is not runnable, so cobra never reaches its argument check", path)+ }+ }++ for path := range operandNotAVerb {+ if findGroup(groups, path) == nil {+ t.Errorf("%s is recorded as taking an operand but is no longer a group; drop the entry", path)+ }+ }+}++// The guard must not shadow the verbs it protects: every registered subcommand still has to+// resolve to itself rather than to its parent's refusal.+func TestEveryValidSubcommandStillResolves(t *testing.T) {+ checked := 0+ for _, group := range commandGroups(rootCmd) {+ for _, sub := range group.Commands() {+ if !sub.IsAvailableCommand() {+ continue+ }+ path := append(commandPathArgs(group), sub.Name())+ found, _, err := rootCmd.Find(path)+ if err != nil {+ t.Errorf("Find(%v) error = %v", path, err)+ continue+ }+ if found != sub {+ t.Errorf("Find(%v) resolved to %s, want the subcommand itself", path, found.CommandPath())+ }+ checked+++ }+ }+ if checked < 40 {+ t.Fatalf("only checked %d subcommands, so this absence assertion is not covering the tree", checked)+ }+}++// Zero arguments is not a typo: a group invoked bare still prints its help and exits 0, the+// behaviour a human relies on to discover the verbs.+func TestABareGroupStillPrintsItsHelpAndSucceeds(t *testing.T) {+ out, err := runRootArgs(t, "cache")+ if err != nil {+ t.Fatalf("`pinchtab cache` error = %v, want the group help and exit 0", err)+ }+ if !strings.Contains(out, "clear") || !strings.Contains(out, "status") {+ t.Errorf("`pinchtab cache` output = %q, want the group help listing its subcommands", out)+ }+}++// One exit code for the whole CLI, measured at all three places that produce it: cobra's+// top-level error, a group refusal, and daemon's hand-rolled dispatch, which used to answer+// 2 and is the one this card changed.+func TestUnknownSubcommandExitsWithOneCodeEverywhere(t *testing.T) {+ if _, err := runRootArgs(t, "zzz-not-a-command"); err == nil {+ t.Fatal("a top-level unknown command must be an error")+ } else if got := commandExitCode(err); got != unknownSubcommandExitCode {+ t.Errorf("top-level unknown command exit code = %d, want %d", got, unknownSubcommandExitCode)+ }++ if _, err := runRootArgs(t, "cache", "clera"); err == nil {+ t.Fatal("a group's unknown subcommand must be an error")+ } else if got := commandExitCode(err); got != unknownSubcommandExitCode {+ t.Errorf("group unknown subcommand exit code = %d, want %d", got, unknownSubcommandExitCode)+ }++ if got := dispatchDaemonCommand("zzz-not-a-subcommand", false); got != unknownSubcommandExitCode {+ t.Errorf("daemon unknown subcommand exit code = %d, want %d", got, unknownSubcommandExitCode)+ }+}++// The guard lives at Execute because the command tree is only complete there. A test that+// installs it itself proves the walk works, not that the binary runs it.+func TestExecuteInstallsTheGuard(t *testing.T) {+ src, err := os.ReadFile("root.go")+ if err != nil {+ t.Fatal(err)+ }+ body := string(src)+ install := strings.Index(body, "installUnknownSubcommandGuard(rootCmd)")+ execute := strings.Index(body, "rootCmd.Execute()")+ if install < 0 {+ t.Fatal("Execute no longer installs the unknown-subcommand guard, so every group is back to exit 0")+ }+ if execute < install {+ t.Error("the guard is installed after rootCmd.Execute, which is too late to matter")+ }+}++func commandGroups(root *cobra.Command) []*cobra.Command {+ var groups []*cobra.Command+ var walk func(cmd *cobra.Command)+ walk = func(cmd *cobra.Command) {+ if cmd.HasSubCommands() && cmd.HasParent() {+ groups = append(groups, cmd)+ }+ for _, sub := range cmd.Commands() {+ walk(sub)+ }+ }+ walk(root)+ return groups+}++func findGroup(groups []*cobra.Command, path string) *cobra.Command {+ for _, group := range groups {+ if group.CommandPath() == path {+ return group+ }+ }+ return nil+}++// commandPathArgs is the argv that reaches a command, which is its command path without the+// binary name — Find wants the arguments, not the display string.+func commandPathArgs(cmd *cobra.Command) []string {+ return strings.Fields(cmd.CommandPath())[1:]+}++func runRootArgs(t *testing.T, args ...string) (string, error) {+ t.Helper()++ var out bytes.Buffer+ t.Cleanup(func() {+ rootCmd.SetArgs(nil)+ rootCmd.SetOut(nil)+ rootCmd.SetErr(nil)+ })+ rootCmd.SetArgs(args)+ rootCmd.SetOut(&out)+ rootCmd.SetErr(io.Discard)++ err := rootCmd.Execute()+ return out.String(), err+}diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 887bbb04..ce7feb9c 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -87,6 +87,17 @@ pinchtab network # GET 200 https://...**For scripts**: Always use `--json` when piping or parsing programmatically. Human-readable output may change between versions. JSON is the stable contract.+## Exit Codes++A mistyped verb is an error everywhere: an unrecognised command or subcommand exits `1` and+names the valid subcommands, at the top level and inside every group. `pinchtab cache clera`+does not share an exit code with `pinchtab cache clear`, so `set -e` and `&&` chains stop on+a typo instead of continuing as though the state had been reset.++Two commands take an argument rather than a subcommand and are unaffected: `pinchtab tab+<id>` focuses a tab, and `pinchtab network <filter>` filters the network log. An unknown+value there is data the server rejects, not a typo the CLI can catch.+## Core Commands| Command | Purpose |