Skip to content

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

fix: --server redirects the destination but the credential stays ambient, so pointing the CLI at any host sends the local config's server.token to it in cleartext (PIN-247)

Luigi Agostia338f0e8e1eb
diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.go
index fe58ed69..9a88965c 100644
--- a/cmd/pinchtab/cmd_cli_runtime.go
+++ b/cmd/pinchtab/cmd_cli_runtime.go
@@ -2,7 +2,9 @@ package main
import (
"fmt"
+ "net"
"net/http"
+ "net/url"
"os"
"strings"
"time"
@@ -102,10 +104,11 @@ func preflightBrowserBinary(cfg *config.RuntimeConfig) error {
}
func newCLIRuntime(cfg *config.RuntimeConfig) cliRuntime {
+ base := resolveCLIBase(cfg)
return cliRuntime{
client: newCLIHTTPClient(resolveCLIAgentID()),
- base: resolveCLIBase(cfg),
- token: resolveCLIToken(cfg),
+ base: base,
+ token: tokenForBaseOrExit(cfg, base),
}
}
@@ -146,7 +149,12 @@ func resolveDefaultCLIBase(cfg *config.RuntimeConfig) string {
// freshness window. Same target, same credential, or the probe cannot self-heal.
var resolveTabStateEndpoint = func() (base, token string) {
cfg := config.Load()
- return resolveBaseURL(resolveDefaultCLIBase(cfg)), resolveCLIToken(cfg)
+ base = resolveBaseURL(resolveDefaultCLIBase(cfg))
+ token, err := resolveCLIToken(cfg, base)
+ if err != nil {
+ return base, ""
+ }
+ return base, token
}
// resolveBaseURL returns the server base URL from flag/env/default.
@@ -168,19 +176,55 @@ func canAutoStartServerForCLI(cfg *config.RuntimeConfig, baseURL string) bool {
return strings.TrimRight(baseURL, "/") == resolveDefaultCLIBase(cfg)
}
-func resolveCLIToken(cfg *config.RuntimeConfig) string {
+// resolveCLIToken is the ONE owner pairing a credential with its destination.
+// The config file's server.token is a secret for the LOCAL server: it is only
+// ever sent to a loopback base, so a typo'd or hostile --server host cannot
+// receive it — an explicit env credential travels anywhere the caller says.
+func resolveCLIToken(cfg *config.RuntimeConfig, base string) (string, error) {
if s := os.Getenv("PINCHTAB_SESSION"); s != "" {
apiclient.UseTokenSource("the PINCHTAB_SESSION environment variable")
- return s
+ return s, nil
}
if t := os.Getenv("PINCHTAB_TOKEN"); t != "" {
apiclient.UseTokenSource("the PINCHTAB_TOKEN environment variable")
- return t
+ return t, nil
+ }
+ if !loopbackBase(base) {
+ return "", fmt.Errorf("refusing to send the local config's server.token to %s: set PINCHTAB_TOKEN (or PINCHTAB_SESSION) with the credential for that host", base)
}
if cfg.Token != "" {
apiclient.UseTokenSource("server.token in " + cliTokenConfigPath())
}
- return cfg.Token
+ return cfg.Token, nil
+}
+
+// tokenForBaseOrExit is the terminal wrapper for command paths: the refusal
+// happens here, before any client or request exists.
+func tokenForBaseOrExit(cfg *config.RuntimeConfig, base string) string {
+ token, err := resolveCLIToken(cfg, base)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "pinchtab: %v\n", err)
+ osExit(1)
+ }
+ return token
+}
+
+var osExit = os.Exit
+
+func loopbackBase(base string) bool {
+ u, err := url.Parse(base)
+ if err != nil {
+ return false
+ }
+ host := u.Hostname()
+ if host == "" {
+ return false
+ }
+ if strings.EqualFold(host, "localhost") {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
}
func cliTokenConfigPath() string {
diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.go
index b57503ce..57c27b13 100644
--- a/cmd/pinchtab/cmd_mcp.go
+++ b/cmd/pinchtab/cmd_mcp.go
@@ -31,7 +31,7 @@ func init() {
func runMCP(cfg *config.RuntimeConfig) {
baseURL := resolveCLIBase(cfg)
- token := resolveCLIToken(cfg)
+ token := tokenForBaseOrExit(cfg, baseURL)
if err := ensureServerForCLI(cfg, baseURL, token, "mcp"); err != nil {
fmt.Fprintf(os.Stderr, "mcp: %v\n", err)
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
index 92bd6277..02f822fc 100644
--- a/cmd/pinchtab/cmd_security.go
+++ b/cmd/pinchtab/cmd_security.go
@@ -53,7 +53,11 @@ func printEnforcedDriftWarning(cfg *config.RuntimeConfig) {
if cfg == nil {
return
}
- snap, state := fetchHealthSnapshotWithToken(cfg.Port, resolveCLIToken(cfg))
+ localToken, err := resolveCLIToken(cfg, resolveDefaultCLIBase(cfg))
+ if err != nil {
+ return
+ }
+ snap, state := fetchHealthSnapshotWithToken(cfg.Port, localToken)
if state != healthSnapshotRunning || snap == nil || !snap.RestartRequired {
return
}
diff --git a/cmd/pinchtab/remote_token_guard_test.go b/cmd/pinchtab/remote_token_guard_test.go
new file mode 100644
index 00000000..091d920a
--- /dev/null
+++ b/cmd/pinchtab/remote_token_guard_test.go
@@ -0,0 +1,155 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type exitPanic struct{ code int }
+
+func interceptExit(t *testing.T) {
+ t.Helper()
+ orig := osExit
+ osExit = func(code int) { panic(exitPanic{code}) }
+ t.Cleanup(func() { osExit = orig })
+}
+
+func expectRefusalExit(t *testing.T, fn func()) string {
+ t.Helper()
+ return captureStderr(t, func() {
+ defer func() {
+ if r := recover(); r == nil {
+ t.Errorf("the path completed without refusing")
+ } else if _, ok := r.(exitPanic); !ok {
+ panic(r)
+ }
+ }()
+ fn()
+ })
+}
+
+// failOnAnyRequest listens on loopback while the CLI is pointed at the SAME port via
+// 0.0.0.0, which the predicate classifies as non-loopback but the OS routes locally —
+// so a guard that fails to refuse produces an observable request instead of a timeout.
+func failOnAnyRequest(t *testing.T) string {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Errorf("a request reached the host: %s %s Authorization=%q — the refusal must happen before anything is sent", r.Method, r.URL.Path, r.Header.Get("Authorization"))
+ }))
+ t.Cleanup(srv.Close)
+ u, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return "http://0.0.0.0:" + u.Port()
+}
+
+func clearCredentialEnv(t *testing.T) {
+ t.Helper()
+ t.Setenv("PINCHTAB_SESSION", "")
+ t.Setenv("PINCHTAB_TOKEN", "")
+ t.Setenv("PINCHTAB_AGENT_ID", "")
+}
+
+func TestARemoteServerWithNoEnvCredentialRefusesBeforeAnyRequest(t *testing.T) {
+ clearCredentialEnv(t)
+ remote := failOnAnyRequest(t)
+ t.Setenv("PINCHTAB_SERVER", remote)
+ interceptExit(t)
+ cfg := &config.RuntimeConfig{Port: "9867", Token: "local-secret"}
+
+ stderr := expectRefusalExit(t, func() { newCLIRuntime(cfg) })
+
+ for _, want := range []string{remote, "PINCHTAB_TOKEN", "server.token"} {
+ if !strings.Contains(stderr, want) {
+ t.Errorf("refusal %q does not name %q; a typo'd host must be visible in the message", stderr, want)
+ }
+ }
+ if strings.Contains(stderr, "local-secret") {
+ t.Errorf("refusal %q echoes the secret it protects", stderr)
+ }
+}
+
+func TestTheMCPPathRefusesARemoteHostWithoutACredential(t *testing.T) {
+ clearCredentialEnv(t)
+ remote := failOnAnyRequest(t)
+ t.Setenv("PINCHTAB_SERVER", remote)
+ interceptExit(t)
+ cfg := &config.RuntimeConfig{Port: "9867", Token: "local-secret"}
+
+ stderr := expectRefusalExit(t, func() { runMCP(cfg) })
+
+ if !strings.Contains(stderr, remote) || !strings.Contains(stderr, "PINCHTAB_TOKEN") {
+ t.Errorf("mcp refusal %q must name the host and PINCHTAB_TOKEN — this is the flow docs/mcp.md recommends", stderr)
+ }
+}
+
+func TestTheTabProbeNeverSendsTheConfigTokenToARemoteHost(t *testing.T) {
+ clearCredentialEnv(t)
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ if err := os.WriteFile(configPath, []byte(`{"server":{"token":"local-secret"}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ t.Setenv("PINCHTAB_SERVER", "http://203.0.113.9:9867")
+ if base, token := resolveTabStateEndpoint(); token != "" {
+ t.Errorf("probe endpoint %s carries token %q; the probe must degrade to unauthenticated rather than leak the config secret", base, token)
+ }
+
+ t.Setenv("PINCHTAB_SERVER", "http://127.0.0.1:19999")
+ if _, token := resolveTabStateEndpoint(); token != "local-secret" {
+ t.Errorf("loopback probe token = %q, want the config token; the guard must not break the local probe", token)
+ }
+}
+
+func TestTheConfigTokenStillServesEveryLoopbackShape(t *testing.T) {
+ clearCredentialEnv(t)
+ cfg := &config.RuntimeConfig{Port: "9867", Token: "local-secret"}
+
+ for name, base := range map[string]string{
+ "the default base": "http://127.0.0.1:9867",
+ "loopback on another port": "http://127.0.0.1:9999",
+ "localhost by name": "http://localhost:9868",
+ "ipv6 loopback": "http://[::1]:9867",
+ "other 127/8 loopback": "http://127.0.0.2:9867",
+ } {
+ t.Run(name, func(t *testing.T) {
+ token, err := resolveCLIToken(cfg, base)
+ if err != nil || token != "local-secret" {
+ t.Fatalf("token = %q, err = %v; a loopback destination keeps today's behaviour exactly", token, err)
+ }
+ })
+ }
+}
+
+func TestAnEnvCredentialTravelsToAnyHost(t *testing.T) {
+ clearCredentialEnv(t)
+ t.Setenv("PINCHTAB_TOKEN", "remote-secret")
+ cfg := &config.RuntimeConfig{Port: "9867", Token: "local-secret"}
+
+ token, err := resolveCLIToken(cfg, "http://203.0.113.9:9867")
+ if err != nil || token != "remote-secret" {
+ t.Fatalf("token = %q, err = %v; an explicit env credential is the deliberate way to authenticate to a named host", token, err)
+ }
+}
+
+func TestSubcommandHelpListsTheGlobalFlags(t *testing.T) {
+ target, _, err := rootCmd.Find([]string{"tabs"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ usage := target.UsageString()
+ for _, want := range []string{"Global Flags", "--server", "--agent-id"} {
+ if !strings.Contains(usage, want) {
+ t.Errorf("`pinchtab tabs --help` output lacks %q; --server redirects every command and must be discoverable from the command being run\n%s", want, usage)
+ }
+ }
+}
diff --git a/docs/architecture/mcp.md b/docs/architecture/mcp.md
index 0527c351..f7762815 100644
--- a/docs/architecture/mcp.md
+++ b/docs/architecture/mcp.md
@@ -16,7 +16,7 @@ flowchart LR
Key design decisions:
- **No direct Chrome dependency** — the MCP process has no CDP connection. All browser work is delegated to the PinchTab instance.
-- **Any deployment works** — use `--server` flag to point at a local server, Docker container, or remote host.
+- **Any deployment works** — use `--server` flag to point at a local server, Docker container, or remote host; a non-loopback host needs its own credential in `PINCHTAB_TOKEN` (e.g. `PINCHTAB_TOKEN=<token> pinchtab --server http://remote:9867 mcp`), since the local config's `server.token` is never sent off the machine.
- **Stateless protocol layer** — the MCP server holds no browser state itself; it is purely a translation adapter.
## Transport
diff --git a/docs/commands.md b/docs/commands.md
index b5cd1be2..96f0dd17 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -354,11 +354,13 @@ pinchtab security down # Apply documented guards-down preset
The root command supports:
```bash
-pinchtab --server http://host:9867 <command>
+PINCHTAB_TOKEN=<that-host-token> pinchtab --server http://host:9867 <command>
pinchtab --help
pinchtab --version
```
+A non-loopback `--server` host requires its credential in `PINCHTAB_TOKEN` (or `PINCHTAB_SESSION`) on the same command — the CLI refuses to send the local config's `server.token` off the machine.
+
Commands with `--tab` currently include:
- `nav`
diff --git a/docs/mcp.md b/docs/mcp.md
index 3bccf9fd..caa95af8 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -73,10 +73,10 @@ The MCP server communicates over stdio using JSON-RPC, which is the standard MCP
| --- | --- |
| `PINCHTAB_TOKEN` | Auth token for secured servers |
-For remote servers, use the root `--server` flag:
+For remote servers, use the root `--server` flag with that host's credential — a non-loopback host requires `PINCHTAB_TOKEN` (or `PINCHTAB_SESSION`), since the CLI refuses to send the local config's `server.token` off the machine:
```bash
-pinchtab --server http://remote:9867 mcp
+PINCHTAB_TOKEN=<that-host-token> pinchtab --server http://remote:9867 mcp
```
## Available Tools
diff --git a/internal/cli/styles.go b/internal/cli/styles.go
index a627a548..0b563618 100644
--- a/internal/cli/styles.go
+++ b/internal/cli/styles.go
@@ -70,6 +70,10 @@ func SetupUsage(root *cobra.Command) {
%s:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}
{{end}}
+{{if .HasAvailableInheritedFlags}}
+%s:
+{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}
+{{end}}
{{if .HasExample}}
%s:
{{.Example}}
@@ -80,6 +84,7 @@ func SetupUsage(root *cobra.Command) {
cmdStyle("{{rpad .Name .NamePadding}}"),
cmdStyle("{{rpad .Name .NamePadding}}"),
headerStyle("Flags"),
+ headerStyle("Global Flags"),
headerStyle("Examples")))
}