High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(cli): keep config token prose off stdout and fail loudly without a clipboard
Luigi Agosti2fab0fce83ae
diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.goindex 905b2fce..320cc0d5 100644--- a/cmd/pinchtab/cmd_config.go+++ b/cmd/pinchtab/cmd_config.go@@ -58,14 +58,19 @@ func init() {}configSchemaCmd.Flags().Bool("print", false, "Print the bundled schema JSON instead of the schema URL")configCmd.AddCommand(configSchemaCmd)- configCmd.AddCommand(&cobra.Command{+ configTokenCmd := &cobra.Command{Use: "token",Short: "Copy the API token to clipboard",- Long: "Copies the configured server.token to the system clipboard. The token is never printed to stdout.",+ Long: "Copies the configured server.token to the system clipboard. Nothing is printed to stdout " ++ "unless you pass --stdout, which prints the token and nothing else so it can be captured " ++ "with $(...) on a host with no clipboard tool.",Run: func(cmd *cobra.Command, args []string) {- handleConfigTokenCopy()+ toStdout, _ := cmd.Flags().GetBool("stdout")+ handleConfigTokenCopy(toStdout)},- })+ }+ configTokenCmd.Flags().Bool("stdout", false, "Print the token to stdout instead of copying it to the clipboard")+ configCmd.AddCommand(configTokenCmd)configCmd.AddCommand(&cobra.Command{Use: "get <path>",Short: "Get a config value (e.g., server.port)",diff --git a/cmd/pinchtab/cmd_config_actions.go b/cmd/pinchtab/cmd_config_actions.goindex 9b125cdc..f27264e4 100644--- a/cmd/pinchtab/cmd_config_actions.go+++ b/cmd/pinchtab/cmd_config_actions.go@@ -13,25 +13,39 @@ import ("github.com/pinchtab/pinchtab/internal/server")-func handleConfigTokenCopy() {+func handleConfigTokenCopy(toStdout bool) {cfg := loadLocalConfig()- if err := copyConfigToken(cfg.Token); err != nil {+ if err := emitConfigToken(cfg.Token, toStdout); err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))os.Exit(1)}}-func copyConfigToken(token string) error {- if strings.TrimSpace(token) == "" {+// emitConfigToken puts the token where the caller asked for it. Every human+// message goes to stderr: stdout is the machine channel, so+// TOKEN=$(pinchtab config token) captures the token or nothing, never prose+// that would then be sent as a bearer credential.+//+// A clipboard failure is an error, not a notice. It used to print and return+// nil, so on the headless hosts where agents actually run the command exited 0+// having done nothing and named no other way to get the token.+func emitConfigToken(token string, toStdout bool) error {+ token = strings.TrimSpace(token)+ if token == "" {return fmt.Errorf("server token is empty")}- if err := copyToClipboard(token); err == nil {- fmt.Println(cli.StyleStdout(cli.SuccessStyle, "Token copied to clipboard."))+ if toStdout {+ fmt.Println(token)return nil}- fmt.Println(cli.StyleStdout(cli.WarningStyle, "Clipboard unavailable; token not shown for safety."))+ if err := copyToClipboard(token); err != nil {+ return fmt.Errorf("clipboard unavailable (%v); run `pinchtab config token --stdout` to print it, or read server.token from %s",+ err, workflow.CurrentConfigPath())+ }++ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.SuccessStyle, "Token copied to clipboard."))return nil}diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.goindex 0af9a350..ad091704 100644--- a/cmd/pinchtab/cmd_config_test.go+++ b/cmd/pinchtab/cmd_config_test.go@@ -63,20 +63,25 @@ func TestClipboardCommands(t *testing.T) {}}-func TestCopyConfigTokenDoesNotPrintTokenWhenClipboardUnavailable(t *testing.T) {+func TestEmitConfigTokenFailsLoudlyWhenClipboardUnavailable(t *testing.T) {t.Setenv("PATH", "")- output := captureStdout(t, func() {- if err := copyConfigToken("very-secret-token-value"); err != nil {- t.Fatalf("copyConfigToken() error = %v", err)- }+ var err error+ stdout, _ := captureStdoutStderr(t, func() {+ err = emitConfigToken("very-secret-token-value", false)})- if strings.Contains(output, "very-secret-token-value") {- t.Fatalf("expected token to stay hidden, got %q", output)+ if err == nil {+ t.Fatal("emitConfigToken() returned nil with no clipboard available; the command would exit 0 having done nothing")}- if !strings.Contains(output, "token not shown for safety") {- t.Fatalf("expected safe fallback message, got %q", output)+ if strings.Contains(err.Error(), "very-secret-token-value") {+ t.Errorf("the failure message leaks the token: %v", err)+ }+ if !strings.Contains(err.Error(), "--stdout") {+ t.Errorf("the failure names no supported way to get the token on a headless host: %v", err)+ }+ if stdout != "" {+ t.Errorf("stdout = %q, want empty; a caller capturing $(...) must not receive prose", stdout)}}@@ -298,18 +303,21 @@ func TestConfigTokenSubcommandCopiesToClipboard(t *testing.T) {rootCmd.SetArgs(nil)})- output := captureStdout(t, func() {+ stdout, stderr := captureStdoutStderr(t, func() {rootCmd.SetArgs([]string{"config", "token"})if err := rootCmd.Execute(); err != nil {t.Fatalf("Execute() error = %v", err)}})- if strings.Contains(output, "test-token-for-clipboard") {- t.Fatalf("expected token to stay hidden, got %q", output)+ if strings.Contains(stdout+stderr, "test-token-for-clipboard") {+ t.Fatalf("expected token to stay hidden, got stdout=%q stderr=%q", stdout, stderr)+ }+ if stdout != "" {+ t.Fatalf("stdout = %q, want empty; the human message belongs on stderr so $(...) captures nothing", stdout)}- if !strings.Contains(output, "Token copied to clipboard") {- t.Fatalf("expected clipboard success message, got %q", output)+ if !strings.Contains(stderr, "Token copied to clipboard") {+ t.Fatalf("expected clipboard success message on stderr, got %q", stderr)}}@@ -389,8 +397,8 @@ func TestConfigSchemaSubcommandPrintsBundledSchema(t *testing.T) {}}-func TestCopyConfigTokenReturnsErrorWhenEmpty(t *testing.T) {- err := copyConfigToken("")+func TestEmitConfigTokenReturnsErrorWhenEmpty(t *testing.T) {+ err := emitConfigToken("", false)if err == nil {t.Fatal("expected error for empty token")}diff --git a/cmd/pinchtab/cmd_config_token_test.go b/cmd/pinchtab/cmd_config_token_test.gonew file mode 100644index 00000000..a5bc6dff--- /dev/null+++ b/cmd/pinchtab/cmd_config_token_test.go@@ -0,0 +1,124 @@+package main++import (+ "context"+ "os"+ "os/exec"+ "strings"+ "testing"+)++// stubClipboard makes copyToClipboard succeed or fail on demand, so the two+// halves of `config token` can be exercised without a real clipboard tool.+func stubClipboard(t *testing.T, available bool) {+ t.Helper()+ originalLookPath, originalExecCommand := clipboardLookPath, clipboardExecCommand+ if available {+ clipboardLookPath = func(name string) (string, error) { return name, nil }+ clipboardExecCommand = func(ctx context.Context, _ string, _ ...string) *exec.Cmd {+ return exec.CommandContext(ctx, os.Args[0], "-test.run=^$")+ }+ } else {+ clipboardLookPath = func(name string) (string, error) { return "", exec.ErrNotFound }+ }+ t.Cleanup(func() {+ clipboardLookPath, clipboardExecCommand = originalLookPath, originalExecCommand+ })+}++// stdout is the machine channel: TOKEN=$(pinchtab config token) has to capture+// the token or nothing. Prose there is captured verbatim and then sent as a+// bearer credential, which the server rejects as bad_token with no hint that+// the value was an English sentence.+func TestConfigTokenKeepsStdoutFreeOfHumanText(t *testing.T) {+ const token = "tok-abcdef0123456789"++ for _, tc := range []struct {+ name string+ clipboardWorks bool+ toStdout bool+ wantErr bool+ wantStdout string+ wantStderrHasText bool+ }{+ {+ name: "clipboard success says so on stderr only",+ clipboardWorks: true,+ wantStdout: "",+ wantStderrHasText: true,+ },+ {+ name: "clipboard unavailable says so on stderr only",+ clipboardWorks: false,+ wantErr: true,+ wantStdout: "",+ wantStderrHasText: false,+ },+ {+ name: "explicit --stdout emits the token and nothing else",+ clipboardWorks: false,+ toStdout: true,+ wantStdout: token + "\n",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ stubClipboard(t, tc.clipboardWorks)++ var err error+ stdout, stderr := captureStdoutStderr(t, func() {+ err = emitConfigToken(token, tc.toStdout)+ })++ if tc.wantErr != (err != nil) {+ t.Fatalf("error = %v, wantErr = %v", err, tc.wantErr)+ }+ if stdout != tc.wantStdout {+ t.Errorf("stdout = %q, want %q", stdout, tc.wantStdout)+ }+ if tc.wantStderrHasText && strings.TrimSpace(stderr) == "" {+ t.Errorf("stderr is empty; the human message has to go somewhere")+ }+ if !tc.toStdout && strings.Contains(stdout+stderr, token) {+ t.Errorf("the token leaked without --stdout:\n stdout=%q\n stderr=%q", stdout, stderr)+ }+ })+ }+}++// Whatever the clipboard does, a capture must never come back holding prose.+func TestCapturingConfigTokenNeverYieldsProse(t *testing.T) {+ const token = "tok-abcdef0123456789"++ for _, clipboardWorks := range []bool{true, false} {+ stubClipboard(t, clipboardWorks)+ stdout, _ := captureStdoutStderr(t, func() {+ _ = emitConfigToken(token, false)+ })+ captured := strings.TrimSpace(stdout)+ if captured != "" && captured != token {+ t.Errorf("clipboardWorks=%v: $(...) would capture %q — neither the token nor nothing", clipboardWorks, captured)+ }+ }+}++// AC-4: the advice the CLI gives on a protected listener has to work in the+// script the reader is standing in.+func TestProtectedListenerHintPointsAtACapturableCommand(t *testing.T) {+ hints, _ := nextStepsForState(healthSnapshotProtected)+ if len(hints) == 0 {+ t.Fatal("the protected-listener state offers no next steps")+ }++ var tokenHint string+ for _, hint := range hints {+ if strings.Contains(hint.Command, "config token") {+ tokenHint = hint.Command+ }+ }+ if tokenHint == "" {+ t.Fatal("the protected-listener hints no longer mention config token; a reader locked out by a token is not told how to get one")+ }+ if !strings.Contains(tokenHint, "--stdout") {+ t.Errorf("hint %q sends the reader to a command whose stdout is empty, so the $(...) they run captures nothing", tokenHint)+ }+}diff --git a/cmd/pinchtab/root_status.go b/cmd/pinchtab/root_status.goindex ce35413d..92b76622 100644--- a/cmd/pinchtab/root_status.go+++ b/cmd/pinchtab/root_status.go@@ -49,7 +49,7 @@ func nextStepsForState(state healthSnapshotState) ([]cli.CommandHint, int) {return cli.NextStepsRunningHints, 64case healthSnapshotProtected:return []cli.CommandHint{- {Command: "pinchtab config token", Comment: "# copy configured API token"},+ {Command: "pinchtab config token --stdout", Comment: "# print the API token (capture with $(...))"},{Command: "pinchtab health --json", Comment: "# retry health with the current token"},{Command: "pinchtab config show", Comment: "# inspect configured port and token"},}, 44diff --git a/docs/commands.md b/docs/commands.mdindex 86459222..32c1dc28 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -388,6 +388,7 @@ pinchtab config # Interactive config overview/editorpinchtab config init # Create a default config filepinchtab config show # Print effective runtime configpinchtab config token # Copy server.token to the clipboard without printing it+pinchtab config token --stdout # Print server.token to stdout (headless hosts, $(...) capture)pinchtab config path # Print config file pathpinchtab config validate # Validate the current config filepinchtab config get <path> # Read one file-config valuediff --git a/docs/guides/mcp-agents.md b/docs/guides/mcp-agents.mdindex a0f107cb..48f33ffb 100644--- a/docs/guides/mcp-agents.md+++ b/docs/guides/mcp-agents.md@@ -119,7 +119,7 @@ config's `server.token` off the machine:PINCHTAB_TOKEN=<that-host-token> pinchtab --server http://remote:9867 mcp```-`PINCHTAB_TOKEN` comes from `server.token` in your PinchTab config file — that is the credential for your LOCAL server, not for a remote one. To copy the current token without printing it to stdout, run `pinchtab config token`.+`PINCHTAB_TOKEN` comes from `server.token` in your PinchTab config file — that is the credential for your LOCAL server, not for a remote one. To copy the current token without printing it to stdout, run `pinchtab config token`. On a host with no clipboard tool — CI, Docker, headless Linux — use `PINCHTAB_TOKEN=$(pinchtab config token --stdout)`, which prints the token and nothing else.## Typical Agent Workflowdiff --git a/docs/guides/security.md b/docs/guides/security.mdindex 66b6ec67..46e1051e 100644--- a/docs/guides/security.md+++ b/docs/guides/security.md@@ -164,7 +164,7 @@ Recommended practice:pinchtab config init```-The dashboard Settings page does not expose or rotate `server.token`. Use `pinchtab config token` to copy the current token, or let `pinchtab security` restore or create one if `server.token` is empty.+The dashboard Settings page does not expose or rotate `server.token`. Use `pinchtab config token` to copy the current token (or `pinchtab config token --stdout` to print it where there is no clipboard), or let `pinchtab security` restore or create one if `server.token` is empty.If you are calling the API manually:diff --git a/docs/reference/config.md b/docs/reference/config.mdindex 47fd2aa2..b567a273 100644--- a/docs/reference/config.md+++ b/docs/reference/config.md@@ -71,15 +71,20 @@ The Security section also includes `security.trustLoopbackProxy` as `Trust Loopb### `pinchtab config token`-Copies the configured `server.token` to the system clipboard without printing it-to stdout.+Copies the configured `server.token` to the system clipboard. Nothing is written+to stdout, so a shell capture returns empty rather than a message.```bash-pinchtab config token+pinchtab config token # copy to clipboard; status goes to stderr+TOKEN=$(pinchtab config token --stdout) # print the token and nothing else```-If clipboard access is unavailable, the command reports that safely and still-does not print the token.+`--stdout` is the supported way to read the token on a host with no clipboard+tool. Without it the token is never printed.++If clipboard access is unavailable the command exits non-zero and names both+`--stdout` and the config file path on stderr, so a script sees the failure+instead of a success that copied nothing.### `pinchtab config path`