Skip to content

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

fix: the CLI collapses missing_token and bad_token into one 'Error 401: unauthorized', dropping the code the server sends, and there is no --token flag to pair with --server (PIN-210)

Luigi Agosti6b186e0590b4
diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.go
index c7e5a8b3..fe58ed69 100644
--- a/cmd/pinchtab/cmd_cli_runtime.go
+++ b/cmd/pinchtab/cmd_cli_runtime.go
@@ -10,6 +10,7 @@ import (
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/browsers"
"github.com/pinchtab/pinchtab/internal/browsers/runtimekit"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
"github.com/pinchtab/pinchtab/internal/cli/output"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/spf13/cobra"
@@ -160,15 +161,6 @@ func resolveBaseURL(defaultBase string) string {
return defaultBase
}
-// resolveToken returns the auth token from env vars (session takes precedence).
-// Shared by both the full CLI runtime path and the lightweight tab probe.
-func resolveToken() string {
- if s := os.Getenv("PINCHTAB_SESSION"); s != "" {
- return s
- }
- return os.Getenv("PINCHTAB_TOKEN")
-}
-
func canAutoStartServerForCLI(cfg *config.RuntimeConfig, baseURL string) bool {
if serverURL != "" || os.Getenv("PINCHTAB_SERVER") != "" {
return false
@@ -177,12 +169,27 @@ func canAutoStartServerForCLI(cfg *config.RuntimeConfig, baseURL string) bool {
}
func resolveCLIToken(cfg *config.RuntimeConfig) string {
- if t := resolveToken(); t != "" {
+ if s := os.Getenv("PINCHTAB_SESSION"); s != "" {
+ apiclient.UseTokenSource("the PINCHTAB_SESSION environment variable")
+ return s
+ }
+ if t := os.Getenv("PINCHTAB_TOKEN"); t != "" {
+ apiclient.UseTokenSource("the PINCHTAB_TOKEN environment variable")
return t
}
+ if cfg.Token != "" {
+ apiclient.UseTokenSource("server.token in " + cliTokenConfigPath())
+ }
return cfg.Token
}
+func cliTokenConfigPath() string {
+ if p := strings.TrimSpace(os.Getenv("PINCHTAB_CONFIG")); p != "" {
+ return p
+ }
+ return config.DefaultConfigPath()
+}
+
func resolveCLIAgentID() string {
if trimmed := strings.TrimSpace(cliAgentID); trimmed != "" {
return trimmed
diff --git a/internal/cli/apiclient/apierror.go b/internal/cli/apiclient/apierror.go
index 1f49af56..1cab812c 100644
--- a/internal/cli/apiclient/apierror.go
+++ b/internal/cli/apiclient/apierror.go
@@ -145,9 +145,12 @@ func renderAPIErrorBody(statusCode int, body []byte) string {
}
var b strings.Builder
- if errResp.Error != "" {
+ switch {
+ case errResp.Error != "" && errResp.Code != "" && errResp.Code != errResp.Error:
+ fmt.Fprintf(&b, "Error %d: %s (%s)\n", statusCode, errResp.Error, errResp.Code)
+ case errResp.Error != "":
fmt.Fprintf(&b, "Error %d: %s\n", statusCode, errResp.Error)
- } else {
+ default:
fmt.Fprintf(&b, "Error %d: %s\n", statusCode, string(body))
}
@@ -156,10 +159,30 @@ func renderAPIErrorBody(statusCode int, body []byte) string {
line, _ := errResp.Details["remedy"].(string)
b.WriteString(renderGuidance(hint, remedy.Remedy(line)))
}
+ b.WriteString(renderGuidance(rejectedTokenProvenance(statusCode, errResp.Code), remedy.None))
b.WriteString(renderGuidance(staleTabAdvice(statusCode, body)))
return b.String()
}
+// TokenSource is where the credential the CLI just sent came from — resolved at
+// the moment of resolution, recorded as data so rendering an error performs no
+// I/O. The zero value asks for nothing.
+var tokenSource string
+
+// UseTokenSource records the provenance of the token the following requests
+// carry (an env var name, or the config file path the token was read from).
+func UseTokenSource(source string) { tokenSource = source }
+
+// rejectedTokenProvenance names where a rejected credential came from. That
+// single sentence is the fix in the common remote case: the CLI silently sent
+// the LOCAL machine's token to the host --server pointed at.
+func rejectedTokenProvenance(statusCode int, code string) string {
+ if statusCode != http.StatusUnauthorized || code != "bad_token" || tokenSource == "" {
+ return ""
+ }
+ return fmt.Sprintf("the rejected token came from %s", tokenSource)
+}
+
// renderGuidance is the ONE writer of both guidance slots, so a second producer cannot
// print prose into the line a caller reads as executable. Either half may be absent.
func renderGuidance(hint string, r remedy.Remedy) string {
diff --git a/internal/cli/apiclient/apierror_test.go b/internal/cli/apiclient/apierror_test.go
index 73f66d26..95a1f9a9 100644
--- a/internal/cli/apiclient/apierror_test.go
+++ b/internal/cli/apiclient/apierror_test.go
@@ -14,6 +14,8 @@ import (
"path/filepath"
"strings"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/httpx"
)
func TestIsRouteNotFound(t *testing.T) {
@@ -341,3 +343,47 @@ func TestAFailedClearingSaysNothing(t *testing.T) {
t.Fatalf("precondition: the path was removable after all, so this test proves nothing: %v", err)
}
}
+
+func wireUnauthorizedBody(t *testing.T, code, presented string) []byte {
+ t.Helper()
+ w := httptest.NewRecorder()
+ httpx.Unauthorized(w, code, presented)
+ return w.Body.Bytes()
+}
+
+func TestThe401CasesRenderDistinctMessagesWithTheirCodes(t *testing.T) {
+ missing := renderAPIErrorBody(401, wireUnauthorizedBody(t, httpx.CodeMissingToken, ""))
+ bad := renderAPIErrorBody(401, wireUnauthorizedBody(t, httpx.CodeBadToken, "deadbeef"))
+
+ if !strings.Contains(missing, "(missing_token)") || !strings.Contains(missing, "PINCHTAB_TOKEN") {
+ t.Errorf("missing-token render = %q, want the code surfaced and PINCHTAB_TOKEN named", missing)
+ }
+ if !strings.Contains(bad, "(bad_token)") || !strings.Contains(bad, "--server") {
+ t.Errorf("bad-token render = %q, want the code surfaced and the remote cue", bad)
+ }
+ if missing == bad {
+ t.Errorf("both 401 cases render identically: %q — the collapse this card removes", missing)
+ }
+}
+
+func TestACodedErrorWithNoDetailsSurfacesItsCode(t *testing.T) {
+ got := renderAPIErrorBody(400, []byte(`{"error":"invalid button \"rihgt\"","code":"invalid_mouse_button"}`))
+ if !strings.Contains(got, "(invalid_mouse_button)") {
+ t.Errorf("render = %q; a coded error with no details drops the one machine-readable field the server sent", got)
+ }
+}
+
+func TestARejectedTokenNamesItsSource(t *testing.T) {
+ UseTokenSource("the PINCHTAB_TOKEN environment variable")
+ t.Cleanup(func() { UseTokenSource("") })
+
+ bad := renderAPIErrorBody(401, wireUnauthorizedBody(t, httpx.CodeBadToken, "deadbeef"))
+ if !strings.Contains(bad, "the rejected token came from the PINCHTAB_TOKEN environment variable") {
+ t.Errorf("bad-token render = %q, want the credential's provenance named", bad)
+ }
+
+ missing := renderAPIErrorBody(401, wireUnauthorizedBody(t, httpx.CodeMissingToken, ""))
+ if strings.Contains(missing, "came from") {
+ t.Errorf("missing-token render = %q names a provenance for a credential that was never sent", missing)
+ }
+}
diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.go
index a35c3018..f77ca297 100644
--- a/internal/dashboard/auth_api.go
+++ b/internal/dashboard/auth_api.go
@@ -77,8 +77,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
a.loginLimiter.RecordFailure(clientIP)
}
authn.AuditWarn(r, "auth.login_failed", "reason", "missing_token")
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
- httpx.ErrorCode(w, http.StatusUnauthorized, "missing_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeMissingToken, "")
return
}
@@ -97,8 +96,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
}
authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))
authn.AuditWarn(r, "auth.login_failed", "reason", "bad_token")
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
- httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeBadToken, provided)
return
}
@@ -165,20 +163,17 @@ func (a *AuthAPI) HandleElevate(w http.ResponseWriter, r *http.Request) {
provided := strings.TrimSpace(req.Token)
if provided == "" {
authn.AuditWarn(r, "auth.elevation_failed", "reason", "missing_token")
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
- httpx.ErrorCode(w, http.StatusUnauthorized, "missing_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeMissingToken, "")
return
}
if subtle.ConstantTimeCompare([]byte(provided), []byte(token)) != 1 {
authn.AuditWarn(r, "auth.elevation_failed", "reason", "bad_token")
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
- httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeBadToken, provided)
return
}
if !a.sessions.Elevate(creds.Value, token) {
authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
- httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeBadToken, "")
return
}
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index 174295b2..2609eb72 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -98,8 +98,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersess
creds := authn.CredentialsFromRequest(r)
if creds.Value == "" {
authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)
- httpx.ErrorCode(w, 401, "missing_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeMissingToken, "")
return
}
@@ -136,8 +135,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersess
case authn.MethodHeader:
if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {
authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
- httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeBadToken, creds.Value)
return
}
case authn.MethodCookie:
@@ -149,8 +147,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersess
}
if sessions == nil || !sessions.Validate(creds.Value, token) {
authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
- httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeBadToken, "")
return
}
if !cookieAuthAllowed(r) {
@@ -166,8 +163,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersess
}
default:
authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))
- w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)
- httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)
+ httpx.Unauthorized(w, httpx.CodeBadToken, creds.Value)
return
}
next.ServeHTTP(w, r)
diff --git a/internal/httpx/unauthorized.go b/internal/httpx/unauthorized.go
new file mode 100644
index 00000000..cd84fc64
--- /dev/null
+++ b/internal/httpx/unauthorized.go
@@ -0,0 +1,41 @@
+package httpx
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/session"
+)
+
+const (
+ CodeMissingToken = "missing_token"
+ CodeBadToken = "bad_token"
+)
+
+// Unauthorized is the one producer of the bearer 401 pair — the WWW-Authenticate
+// header and the coded body — for every missing_token/bad_token site. presented
+// is the credential the caller actually sent under the Bearer scheme, when one
+// was sent as a header value; it selects the wrong-scheme guidance and is never
+// echoed back.
+func Unauthorized(w http.ResponseWriter, code, presented string) {
+ w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer realm=%q, error=%q", "pinchtab", code))
+ ErrorCode(w, http.StatusUnauthorized, code, "unauthorized", false, map[string]any{
+ "hint": UnauthorizedHint(code, presented),
+ })
+}
+
+// UnauthorizedHint derives the guidance from what is known: a bearer value
+// carrying the agent-session prefix is unambiguously a session token under the
+// wrong scheme, an empty credential wants PINCHTAB_TOKEN named, and a rejected
+// one wants the it-belongs-to-another-host cue. No remedy anywhere: a
+// credential's value is a secret the product cannot spell into a runnable line.
+func UnauthorizedHint(code, presented string) string {
+ if strings.HasPrefix(strings.TrimSpace(presented), session.IDPrefix) {
+ return "that looks like an agent session token; send it as 'Authorization: Session <token>', not Bearer"
+ }
+ if code == CodeMissingToken {
+ return "no credential was sent; set PINCHTAB_TOKEN — it pairs with a remote destination on one line: PINCHTAB_TOKEN=<token> pinchtab --server <url> ..."
+ }
+ return "this host rejected the token; when targeting a remote server with --server, the token must belong to that host — otherwise the CLI sends PINCHTAB_TOKEN or the local config's server.token"
+}
diff --git a/internal/httpx/unauthorized_test.go b/internal/httpx/unauthorized_test.go
new file mode 100644
index 00000000..49a36c0f
--- /dev/null
+++ b/internal/httpx/unauthorized_test.go
@@ -0,0 +1,74 @@
+package httpx
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestUnauthorizedDistinguishesItsThreeCases(t *testing.T) {
+ hints := map[string]string{}
+ for _, tc := range []struct {
+ name string
+ code string
+ presented string
+ wantSays string
+ }{
+ {name: "missing token", code: CodeMissingToken, presented: "", wantSays: "PINCHTAB_TOKEN"},
+ {name: "bad token", code: CodeBadToken, presented: "deadbeef", wantSays: "--server"},
+ {name: "session token under the bearer scheme", code: CodeBadToken, presented: "ses_0123456789abcdef", wantSays: "Authorization: Session"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ Unauthorized(w, tc.code, tc.presented)
+
+ if w.Code != 401 {
+ t.Fatalf("status = %d, want 401", w.Code)
+ }
+ wantHeader := `Bearer realm="pinchtab", error="` + tc.code + `"`
+ if got := w.Header().Get("WWW-Authenticate"); got != wantHeader {
+ t.Errorf("WWW-Authenticate = %q, want %q", got, wantHeader)
+ }
+
+ var body struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ Details struct {
+ Hint string `json:"hint"`
+ } `json:"details"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body.Code != tc.code || body.Error != "unauthorized" {
+ t.Errorf("body code=%q error=%q, want %q/unauthorized", body.Code, body.Error, tc.code)
+ }
+ if !strings.Contains(body.Details.Hint, tc.wantSays) {
+ t.Errorf("hint = %q, want it to carry %q", body.Details.Hint, tc.wantSays)
+ }
+ if strings.Contains(body.Details.Hint, "deadbeef") || strings.Contains(body.Details.Hint, "ses_0123456789abcdef") {
+ t.Errorf("hint = %q echoes the presented credential", body.Details.Hint)
+ }
+ hints[tc.name] = body.Details.Hint
+
+ var raw map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
+ t.Fatal(err)
+ }
+ if details, ok := raw["details"].(map[string]any); ok {
+ if _, hasRemedy := details["remedy"]; hasRemedy {
+ t.Error("a 401 carries a remedy; no credential guidance can be a runnable line, the value is a secret only the operator has")
+ }
+ }
+ })
+ }
+
+ seen := map[string]string{}
+ for name, hint := range hints {
+ if other, dup := seen[hint]; dup {
+ t.Errorf("%q and %q share one hint %q; the whole point is that the cases say different things", name, other, hint)
+ }
+ seen[hint] = name
+ }
+}
diff --git a/skills/pinchtab/references/env.md b/skills/pinchtab/references/env.md
index 8727901d..ab3b312d 100644
--- a/skills/pinchtab/references/env.md
+++ b/skills/pinchtab/references/env.md
@@ -13,13 +13,15 @@ For agent workflows, most runtime behavior should be configured through `config.
## Targeting remote servers
-Use the `--server` CLI flag instead of environment variables:
+Use the `--server` CLI flag instead of environment variables, and pair it with that host's credential — without one, the CLI falls back to `PINCHTAB_TOKEN` or the local config's `server.token`, which the remote host rejects as `bad_token`:
```bash
-pinchtab --server http://192.168.1.50:9867 snap
-pinchtab --server https://pinchtab.com snap
+PINCHTAB_TOKEN=<that-host-token> pinchtab --server http://192.168.1.50:9867 snap
+PINCHTAB_TOKEN=<that-host-token> pinchtab --server https://pinchtab.com snap
```
+There is deliberately no `--token` flag: a credential in argv is visible to every user on the host via the process list and lands in shell history, so the env-var form is the supported pairing.
+
## What is intentionally not listed
- Browser tuning should generally live in `config.json`, not in ad hoc env vars.