Skip to content

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

fix(snapshot): reject invalid cost controls and report the query params the server ignores

Luigi Agostif91948c31911
diff --git a/docs/endpoints.md b/docs/endpoints.md
index c4987bc5..7ed4934e 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -165,6 +165,25 @@ POST /tabs/{id}/evaluate
`GET /action` decodes a subset of the action fields and refuses, with `400` naming the field, any parameter it cannot express rather than silently dropping it — so a modifier chord, a drag, `waitNav` or `humanize` must be sent as `POST /action` with a JSON body. A parameter the action request does not declare at all is refused the same way, with a `did you mean` hint for a near miss, so `?modifers=8` or `?Modifiers=8` no longer dispatches a plain click and answers `200`. The accepted set is the action request's own fields plus the parameters only the GET form carries, which today is `timeout` — a per-request action timeout in seconds, clamped to 0–60, that the POST form sends in its body instead. Cache-busters and stray parameters must be dropped from the URL.
+`GET /snapshot` validates its cost controls the same way but resolves the unknown-parameter
+question differently, and the difference is deliberate. A bad VALUE is refused with a `400`
+naming the accepted set: `format` is `json`, `compact`, `text` or `yaml`; `filter` is `all`
+or `interactive`; `maxTokens` is a positive whole number; `depth` is a whole number `>= -1`.
+`format` and `filter` are compared case- and whitespace-insensitively, so `INTERACTIVE` and
+`" interactive "` select the interactive subset — each previously fell through to the whole
+tree, because the comparison was an exact string match, and every one of these controls used
+to fail toward the *more expensive* answer without telling the caller.
+
+An unknown parameter NAME is reported rather than refused: `ignoredParams` on JSON and YAML
+responses, an `# ignored params: ...` line on `compact` and `text` ones. `/action` can
+refuse because its parameter set is the action request's own fields, and a caller sending
+something else has genuinely asked for a behaviour that will not happen. `/snapshot` is a
+read that newer clients call with parameters older servers have not learned yet, so
+refusing would break version skew in the direction it normally occurs, while the disclosure
+still ends the silence — which is what mattered, since the `quick` CLI command sent
+`compact=true` for a long time, a parameter `/snapshot` has never read, and received the
+JSON snapshot instead of the compact one it was written to request.
+
`GET /visible` (and `pinchtab visible <ref>`) answers CSS rendered-ness — `display`, `visibility`, `opacity`, and a laid-out box with non-zero size. Scroll position is not an input: an element far below the fold, or scrolled past, still reports `visible: true`. On-screen-ness is the response's `onScreen` field, which shares the capture snapshot's viewport-intersection predicate (see [reference/capture.md](reference/capture.md)); `onScreen` is omitted when the element could not be measured — absent means unknown, never "no".
Action kinds currently include:
diff --git a/internal/cli/actions/actions_quick.go b/internal/cli/actions/actions_quick.go
index 0a847966..80959435 100644
--- a/internal/cli/actions/actions_quick.go
+++ b/internal/cli/actions/actions_quick.go
@@ -29,7 +29,7 @@ func Quick(client *http.Client, base, token string, args []string) {
snapParams := url.Values{}
snapParams.Set("filter", "interactive")
- snapParams.Set("compact", "true")
+ snapParams.Set("format", "compact")
apiclient.DoGet(client, base, token, "/snapshot", snapParams)
if title, ok := navResult["title"].(string); ok {
diff --git a/internal/cli/actions/actions_quick_test.go b/internal/cli/actions/actions_quick_test.go
new file mode 100644
index 00000000..664b4c94
--- /dev/null
+++ b/internal/cli/actions/actions_quick_test.go
@@ -0,0 +1,70 @@
+package actions
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/handlers"
+)
+
+// captureSnapshotQuery runs a CLI action against a stub server and returns the query it
+// actually sent to /snapshot. Asserting on the emitted request rather than on the source is
+// the point: `compact=true` read as a perfectly sensible line of code for as long as it
+// survived, and only the wire shows that the server was never asked for a compact snapshot.
+func captureSnapshotQuery(t *testing.T, run func(client *http.Client, base string)) url.Values {
+ t.Helper()
+
+ var got url.Values
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/snapshot" {
+ got = r.URL.Query()
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ _, _ = w.Write([]byte("e1:button\n"))
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"title":"probe","url":"http://example.test/"}`))
+ }))
+ defer server.Close()
+
+ run(server.Client(), server.URL)
+ if got == nil {
+ t.Fatal("the action never called /snapshot")
+ }
+ return got
+}
+
+func TestQuickAsksForTheCompactSnapshotItIntendedTo(t *testing.T) {
+ got := captureSnapshotQuery(t, func(client *http.Client, base string) {
+ Quick(client, base, "", []string{"http://example.test/"})
+ })
+
+ if format := got.Get("format"); format != "compact" {
+ t.Errorf("format = %q, want compact; `quick` was written to request the compact snapshot and sent an unread `compact=true` instead, so it always got the JSON one", format)
+ }
+ if filter := got.Get("filter"); filter != "interactive" {
+ t.Errorf("filter = %q, want interactive", filter)
+ }
+ if got.Has("compact") {
+ t.Errorf("still sending the parameter the server does not read: %v", got)
+ }
+}
+
+// The general form of the same bug: any parameter the CLI sends that the server does not
+// read is a flag that silently does nothing. Running the server's own validator over the
+// emitted query catches the next one without anybody having to notice it.
+func TestQuickSendsOnlyParametersTheServerHonours(t *testing.T) {
+ got := captureSnapshotQuery(t, func(client *http.Client, base string) {
+ Quick(client, base, "", []string{"http://example.test/"})
+ })
+
+ controls, err := handlers.ParseSnapshotCostControls(got)
+ if err != nil {
+ t.Fatalf("the server would reject the query this CLI action sends: %v", err)
+ }
+ if len(controls.Ignored) > 0 {
+ t.Errorf("the server ignores %v of the parameters this action sends, so those flags do nothing", controls.Ignored)
+ }
+}
diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.go
index 73d31757..4529c6e7 100644
--- a/internal/handlers/snapshot.go
+++ b/internal/handlers/snapshot.go
@@ -7,7 +7,6 @@ import (
"net/http"
"os"
"path/filepath"
- "strconv"
"strings"
"time"
@@ -26,11 +25,9 @@ import (
//
// @Param tabId string query Tab ID (required)
// @Param filter string query Filter type: "interactive" for clickable/inputs only, "all" for everything (optional, default: "all")
-// @Param interactive bool query Alias for filter=interactive (optional)
-// @Param compact bool query Compact output (shorter ref names) (optional, default: false)
// @Param depth int query Max nesting depth (optional, default: -1 for full tree)
-// @Param text bool query Include text content (optional, default: true)
-// @Param format string query Output format: "json" or "yaml" (optional, default: "json")
+// @Param maxTokens int query Token budget for the response (optional, positive)
+// @Param format string query Output format: "json", "compact", "text" or "yaml" (optional, default: "json")
// @Param diff bool query Include diff with previous snapshot (optional, default: false)
// @Param output string query Write to file instead of response (optional)
//
@@ -48,7 +45,7 @@ import (
//
// @Example curl compact:
//
-// curl "http://localhost:9867/snapshot?tabId=abc123&filter=interactive&compact=true"
+// curl "http://localhost:9867/snapshot?tabId=abc123&filter=interactive&format=compact"
//
// @Example cli:
//
@@ -59,8 +56,32 @@ import (
// import requests
// r = requests.get("http://localhost:9867/snapshot", params={"tabId": "abc123", "filter": "interactive"})
// tree = r.json()
+//
+// attachIgnoredParams reports the query parameters the server did not read. A caller that
+// mistypes a flag otherwise gets a plausible-looking answer to a question it did not ask —
+// which is exactly how `compact=true` survived in the CLI for as long as it did.
+func attachIgnoredParams(data map[string]any, ignored []string) map[string]any {
+ if len(ignored) > 0 {
+ data["ignoredParams"] = ignored
+ }
+ return data
+}
+
+// writeIgnoredParamsComment is the same disclosure for the plain-text formats, in the
+// comment shape those responses already use for hints.
+func writeIgnoredParamsComment(w http.ResponseWriter, ignored []string) {
+ if len(ignored) > 0 {
+ _, _ = fmt.Fprintf(w, "# ignored params: %s\n", strings.Join(ignored, ", "))
+ }
+}
+
func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
- filter := r.URL.Query().Get("filter")
+ controls, err := ParseSnapshotCostControls(r.URL.Query())
+ if err != nil {
+ httpx.Error(w, 400, err)
+ return
+ }
+ filter := controls.Filter
tabID := r.URL.Query().Get("tabId")
effectiveCfg, snapChromeRoute, ok := h.resolveReadRouting(w, r, tabID, "snapshot", browsers.ShapeStaticSnapshot)
@@ -73,25 +94,13 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
doDiff := r.URL.Query().Get("diff") == "true"
- format := r.URL.Query().Get("format")
+ format := controls.Format
output := r.URL.Query().Get("output")
outputPath := r.URL.Query().Get("path")
selector := r.URL.Query().Get("selector")
- maxTokensStr := r.URL.Query().Get("maxTokens")
reqNoAnim := r.URL.Query().Get("noAnimations") == "true"
- maxDepthStr := r.URL.Query().Get("depth")
- maxDepth := -1
- if maxDepthStr != "" {
- if d, err := strconv.Atoi(maxDepthStr); err == nil {
- maxDepth = d
- }
- }
- maxTokens := -1
- if maxTokensStr != "" {
- if t, err := strconv.Atoi(maxTokensStr); err == nil && t > 0 {
- maxTokens = t
- }
- }
+ maxDepth := controls.MaxDepth
+ maxTokens := controls.MaxTokens
resolvedTabID, tCtx, cancel, ok := h.resolveReadContext(w, r, tabID, effectiveCfg.ActionTimeout)
if !ok {
@@ -341,12 +350,12 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
}
- httpx.JSON(w, 200, map[string]any{
+ httpx.JSON(w, 200, attachIgnoredParams(map[string]any{
"path": filePath,
"size": len(content),
"format": format,
"timestamp": timestamp,
- })
+ }, controls.Ignored))
return
}
@@ -363,6 +372,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, " (truncated to ~%d tokens)", maxTokens)
}
_, _ = w.Write([]byte("\n"))
+ writeIgnoredParamsComment(w, controls.Ignored)
content := bridge.FormatSnapshotCompactDiff(flat, added, changed, removed)
if wrapContent {
content = h.IDPIGuard.WrapContent(content, url)
@@ -371,7 +381,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
return
}
- httpx.JSON(w, 200, scopeInfo.attach(map[string]any{
+ httpx.JSON(w, 200, attachIgnoredParams(scopeInfo.attach(map[string]any{
"url": url,
"title": title,
"route": snapChromeRoute,
@@ -385,7 +395,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
"removed": len(removed),
"total": len(flat),
},
- }))
+ }), controls.Ignored))
return
}
@@ -401,6 +411,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
if scopedEmptyHint != "" {
_, _ = fmt.Fprintf(w, "# hint: %s\n", scopedEmptyHint)
}
+ writeIgnoredParamsComment(w, controls.Ignored)
content := bridge.FormatSnapshotCompact(flat)
if wrapContent {
content = h.IDPIGuard.WrapContent(content, url)
@@ -413,6 +424,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
if scopedEmptyHint != "" {
_, _ = fmt.Fprintf(w, "# hint: %s\n", scopedEmptyHint)
}
+ writeIgnoredParamsComment(w, controls.Ignored)
_, _ = w.Write([]byte("\n"))
content := bridge.FormatSnapshotText(flat)
if wrapContent {
@@ -429,6 +441,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
if scopedEmptyHint != "" {
data["hint"] = scopedEmptyHint
}
+ attachIgnoredParams(data, controls.Ignored)
yamlContent, err := yaml.Marshal(data)
if err != nil {
httpx.Error(w, 500, fmt.Errorf("marshal yaml: %w", err))
@@ -453,6 +466,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
if scopedEmptyHint != "" {
resp["hint"] = scopedEmptyHint
}
+ attachIgnoredParams(resp, controls.Ignored)
if idpiResult.Threat {
resp["idpiWarning"] = idpiResult.Reason
}
diff --git a/internal/handlers/snapshot_params.go b/internal/handlers/snapshot_params.go
new file mode 100644
index 00000000..a57774fc
--- /dev/null
+++ b/internal/handlers/snapshot_params.go
@@ -0,0 +1,132 @@
+package handlers
+
+import (
+ "fmt"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+// snapshotFormats are the output formats /snapshot can produce. An empty format means
+// json, so it is not listed separately in the error text a caller sees.
+var snapshotFormats = []string{"json", "compact", "text", "yaml"}
+
+// snapshotFilters are the node subsets /snapshot can return. "all" and the empty string
+// both mean the whole tree; bridge.FilterInteractive is the only value that narrows it.
+var snapshotFilters = []string{"all", bridge.FilterInteractive}
+
+// snapshotKnownParams is every query parameter HandleSnapshot reads. A parameter absent
+// from this set is reported back to the caller rather than rejected: rejecting would break
+// version skew in the direction it normally happens — a newer client sending a parameter an
+// older server has not learned yet — and the value here is diagnostic, not enforcement.
+var snapshotKnownParams = map[string]bool{
+ "tabId": true,
+ // browser is read by the routing prelude rather than by HandleSnapshot itself, which
+ // is precisely why it has to be listed: a parameter the request path consumes
+ // somewhere else still gets reported as ignored if this set only covers one file.
+ "browser": true,
+ "filter": true,
+ "format": true,
+ "depth": true,
+ "maxTokens": true,
+ "diff": true,
+ "noAnimations": true,
+ "selector": true,
+ "output": true,
+ "path": true,
+}
+
+// SnapshotCostControls is the validated form of the parameters that decide what a snapshot
+// costs. Every field is already normalised, so the handler compares values it produced
+// rather than strings the caller typed.
+type SnapshotCostControls struct {
+ // Format is one of snapshotFormats, never empty.
+ Format string
+ // Filter is bridge.FilterInteractive or "" for the whole tree.
+ Filter string
+ // MaxTokens is -1 when the caller set no budget.
+ MaxTokens int
+ // MaxDepth is -1 when the caller set no depth limit.
+ MaxDepth int
+ // Ignored names the query parameters the server does not read, sorted. Returned to the
+ // caller so a mistyped flag is visible rather than silently doing nothing.
+ Ignored []string
+}
+
+// ParseSnapshotCostControls validates the cost controls and refuses to guess. Each of them
+// used to fail OPEN toward the expensive answer — an unrecognised format fell through to
+// json, a mis-cased filter returned the whole tree instead of the interactive subset, an
+// unparseable budget or depth was dropped entirely — so a caller that mistyped its own cost
+// control was not told, just charged more.
+func ParseSnapshotCostControls(q url.Values) (SnapshotCostControls, error) {
+ controls := SnapshotCostControls{Format: "json", MaxTokens: -1, MaxDepth: -1}
+
+ format := normalizeParam(q.Get("format"))
+ if format != "" {
+ if !acceptsValue(snapshotFormats, format) {
+ return controls, fmt.Errorf("format must be one of %s (got %q)", joinQuoted(snapshotFormats), q.Get("format"))
+ }
+ controls.Format = format
+ }
+
+ filter := normalizeParam(q.Get("filter"))
+ if filter != "" {
+ if !acceptsValue(snapshotFilters, filter) {
+ return controls, fmt.Errorf("filter must be one of %s (got %q)", joinQuoted(snapshotFilters), q.Get("filter"))
+ }
+ if filter == bridge.FilterInteractive {
+ controls.Filter = filter
+ }
+ }
+
+ if raw := strings.TrimSpace(q.Get("maxTokens")); raw != "" {
+ value, err := strconv.Atoi(raw)
+ if err != nil || value <= 0 {
+ return controls, fmt.Errorf("maxTokens must be a positive whole number (got %q)", q.Get("maxTokens"))
+ }
+ controls.MaxTokens = value
+ }
+
+ if raw := strings.TrimSpace(q.Get("depth")); raw != "" {
+ value, err := strconv.Atoi(raw)
+ if err != nil || value < -1 {
+ return controls, fmt.Errorf("depth must be a whole number >= -1, where -1 means no limit (got %q)", q.Get("depth"))
+ }
+ controls.MaxDepth = value
+ }
+
+ for name := range q {
+ if !snapshotKnownParams[name] {
+ controls.Ignored = append(controls.Ignored, name)
+ }
+ }
+ sort.Strings(controls.Ignored)
+
+ return controls, nil
+}
+
+// normalizeParam is the one place a caller's spelling is reconciled with ours, so `format`
+// and `filter` cannot end up comparing differently-normalised strings.
+func normalizeParam(v string) string {
+ return strings.ToLower(strings.TrimSpace(v))
+}
+
+func acceptsValue(values []string, want string) bool {
+ for _, v := range values {
+ if v == want {
+ return true
+ }
+ }
+ return false
+}
+
+func joinQuoted(values []string) string {
+ quoted := make([]string, 0, len(values))
+ for _, v := range values {
+ quoted = append(quoted, strconv.Quote(v))
+ }
+ return strings.Join(quoted, ", ")
+}
diff --git a/internal/handlers/snapshot_params_test.go b/internal/handlers/snapshot_params_test.go
new file mode 100644
index 00000000..a64b768c
--- /dev/null
+++ b/internal/handlers/snapshot_params_test.go
@@ -0,0 +1,244 @@
+package handlers
+
+import (
+ "net/url"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func parseQuery(t *testing.T, raw string) (SnapshotCostControls, error) {
+ t.Helper()
+ q, err := url.ParseQuery(raw)
+ if err != nil {
+ t.Fatalf("bad probe query %q: %v", raw, err)
+ }
+ return ParseSnapshotCostControls(q)
+}
+
+// Every cost control used to fail OPEN toward the expensive answer: an unrecognised format
+// fell through to json, a mis-cased filter returned the whole tree instead of the
+// interactive subset, and an unparseable budget or depth was dropped. A caller that
+// mistyped its own cost control was not told, only charged more.
+func TestInvalidCostControlsAreRejectedRatherThanIgnored(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ query string
+ wantNamed []string
+ }{
+ {
+ name: "unknown format does not silently become json",
+ query: "format=compct",
+ wantNamed: []string{"json", "compact", "text", "yaml"},
+ },
+ {
+ name: "format that is a real word but not ours",
+ query: "format=xml",
+ wantNamed: []string{"compact"},
+ },
+ {
+ name: "unknown filter does not silently become the whole tree",
+ query: "filter=interactives",
+ wantNamed: []string{"all", "interactive"},
+ },
+ {
+ name: "unparseable maxTokens does not silently drop the budget",
+ query: "maxTokens=lots",
+ wantNamed: []string{"positive"},
+ },
+ {
+ name: "zero maxTokens is not a budget",
+ query: "maxTokens=0",
+ wantNamed: []string{"positive"},
+ },
+ {
+ name: "negative maxTokens is not a budget",
+ query: "maxTokens=-5",
+ wantNamed: []string{"positive"},
+ },
+ {
+ name: "unparseable depth does not silently drop the limit",
+ query: "depth=deep",
+ wantNamed: []string{"-1"},
+ },
+ {
+ name: "depth below the no-limit sentinel is meaningless",
+ query: "depth=-2",
+ wantNamed: []string{"-1"},
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := parseQuery(t, tc.query)
+ if err == nil {
+ t.Fatalf("%s was accepted; the caller gets an answer to a question it did not ask", tc.query)
+ }
+ for _, want := range tc.wantNamed {
+ if !strings.Contains(err.Error(), want) {
+ t.Errorf("the rejection does not name %q, so the caller cannot tell what to send instead: %v", want, err)
+ }
+ }
+ // The rejection has to quote what was actually sent, or a caller with a
+ // generated query cannot find which value was wrong.
+ sent := strings.SplitN(tc.query, "=", 2)[1]
+ if !strings.Contains(err.Error(), sent) {
+ t.Errorf("the rejection does not quote the offending value %q: %v", sent, err)
+ }
+ })
+ }
+}
+
+// A single capital letter used to turn an interactive snapshot into a full-tree one.
+func TestFormatAndFilterAreCaseAndWhitespaceInsensitive(t *testing.T) {
+ for _, query := range []string{
+ "format=COMPACT&filter=INTERACTIVE",
+ "format=Compact&filter=Interactive",
+ "format=+compact+&filter=+interactive+",
+ "format=%09compact%0A&filter=%20interactive%20",
+ } {
+ t.Run(query, func(t *testing.T) {
+ got, err := parseQuery(t, query)
+ if err != nil {
+ t.Fatalf("rejected a value that differs only in case or spacing: %v", err)
+ }
+ if got.Format != "compact" {
+ t.Errorf("format = %q, want compact", got.Format)
+ }
+ if got.Filter != bridge.FilterInteractive {
+ t.Errorf("filter = %q, want %q — a mis-cased filter used to return the whole tree", got.Filter, bridge.FilterInteractive)
+ }
+ })
+ }
+}
+
+func TestCostControlDefaultsWhenUnset(t *testing.T) {
+ got, err := parseQuery(t, "tabId=abc")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Format != "json" {
+ t.Errorf("format = %q, want json", got.Format)
+ }
+ if got.Filter != "" {
+ t.Errorf("filter = %q, want the whole tree", got.Filter)
+ }
+ if got.MaxTokens != -1 || got.MaxDepth != -1 {
+ t.Errorf("maxTokens = %d, depth = %d, want -1 for both", got.MaxTokens, got.MaxDepth)
+ }
+ if len(got.Ignored) != 0 {
+ t.Errorf("ignored = %v, want none", got.Ignored)
+ }
+}
+
+// "all" is the documented spelling of the default and has to be accepted explicitly, not
+// merely tolerated by falling through the unknown-filter branch.
+func TestFilterAllIsTheWholeTree(t *testing.T) {
+ got, err := parseQuery(t, "filter=all")
+ if err != nil {
+ t.Fatalf("filter=all was rejected: %v", err)
+ }
+ if got.Filter != "" {
+ t.Errorf("filter = %q, want the whole tree", got.Filter)
+ }
+}
+
+// The decision on this card: unknown NAMES are reported, not rejected, so version skew in
+// the normal direction — a newer client sending a parameter an older server has not learned
+// — keeps working while a typo stops being invisible.
+func TestUnknownParamsAreReportedNotRejected(t *testing.T) {
+ got, err := parseQuery(t, "tabId=abc&compact=true&interactive=true&format=compact")
+ if err != nil {
+ t.Fatalf("an unknown parameter was rejected; version skew would break: %v", err)
+ }
+ if want := []string{"compact", "interactive"}; !equalStrings(got.Ignored, want) {
+ t.Errorf("ignored = %v, want %v — this is the disclosure that would have caught `compact=true` in the CLI", got.Ignored, want)
+ }
+ if got.Format != "compact" {
+ t.Errorf("format = %q, want the valid parameter still honoured", got.Format)
+ }
+}
+
+// The failure this guard exists for is a parameter the request path DOES read being
+// reported as ignored: `browser` is consumed by the routing prelude rather than by
+// HandleSnapshot, so a known-params set derived from one file alone gets it wrong and every
+// browser-routed call grows a false disclosure.
+func TestParamsTheRequestPathReadsAreNotReportedAsIgnored(t *testing.T) {
+ got, err := parseQuery(t, "tabId=abc&browser=chrome&filter=interactive&format=compact&depth=3&maxTokens=500&diff=true&noAnimations=true&selector=%23main&output=file&path=out.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got.Ignored) != 0 {
+ t.Errorf("ignored = %v, but every one of those is read on the snapshot request path", got.Ignored)
+ }
+}
+
+var queryGetPattern = regexp.MustCompile(`Query\(\)\.Get\("([^"]+)"\)`)
+
+// snapshotPathSources are the files whose Query().Get calls can run for a /snapshot
+// request. Listed rather than derived because the call graph decides membership.
+var snapshotPathSources = []string{"snapshot.go", "read_prelude.go"}
+
+// notOnTheSnapshotPath are parameters those files read from a function /snapshot never
+// calls. They belong OUT of snapshotKnownParams: /snapshot genuinely ignores them, so
+// reporting them back is the correct answer rather than a false disclosure. Checked in
+// both directions below, because an exemption for something the source no longer reads is
+// how a guard quietly stops guarding.
+var notOnTheSnapshotPath = map[string]string{
+ "frameId": "read by resolveTargetFrameID, which /inspect and /text call and HandleSnapshot does not; /snapshot scopes frames from tab state instead",
+}
+
+// A hand-maintained allowlist drifts the moment a parameter is added, and it drifts
+// SILENTLY — the only symptom is a caller told its valid parameter was ignored. This reads
+// the parameters straight out of the source instead of trusting the list to have kept up.
+func TestKnownParamsCoversEveryParamTheHandlerReads(t *testing.T) {
+ var missing []string
+ seen := 0
+ exemptionsUsed := map[string]bool{}
+ for _, name := range snapshotPathSources {
+ body, err := os.ReadFile(filepath.Join(".", name))
+ if err != nil {
+ t.Fatalf("cannot read %s, so this guard would check nothing: %v", name, err)
+ }
+ for _, match := range queryGetPattern.FindAllStringSubmatch(string(body), -1) {
+ seen++
+ param := match[1]
+ if _, exempt := notOnTheSnapshotPath[param]; exempt {
+ exemptionsUsed[param] = true
+ continue
+ }
+ if !snapshotKnownParams[param] {
+ missing = append(missing, name+": "+param)
+ }
+ }
+ }
+ if seen < len(snapshotPathSources) {
+ t.Fatalf("found %d query reads across %v; the scan matched almost nothing and would pass vacuously", seen, snapshotPathSources)
+ }
+ if len(missing) > 0 {
+ t.Errorf("these parameters are read on the snapshot request path but are absent from snapshotKnownParams, so a caller sending them is wrongly told they were ignored:\n %s",
+ strings.Join(missing, "\n "))
+ }
+ for param, why := range notOnTheSnapshotPath {
+ if !exemptionsUsed[param] {
+ t.Errorf("%q is exempted (%s) but no longer read by %v; drop the exemption, or re-point it, rather than leaving it to excuse nothing", param, why, snapshotPathSources)
+ }
+ if snapshotKnownParams[param] {
+ t.Errorf("%q is both exempted and listed as known; one of the two is wrong", param)
+ }
+ }
+}
+
+func equalStrings(got, want []string) bool {
+ if len(got) != len(want) {
+ return false
+ }
+ for i := range got {
+ if got[i] != want[i] {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/mcp/handlers_navigation_format_test.go b/internal/mcp/handlers_navigation_format_test.go
new file mode 100644
index 00000000..509a5c91
--- /dev/null
+++ b/internal/mcp/handlers_navigation_format_test.go
@@ -0,0 +1,41 @@
+package mcp
+
+import (
+ "net/url"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/handlers"
+)
+
+// normalizeSnapshotFormat used to be the only place a bad format was caught, so the
+// guarantee reached MCP callers and nobody else. The HTTP handler enforces it now, which
+// makes this layer an early, friendlier rejection rather than the enforcement — and that
+// only holds while the two agree on what is valid. A format MCP accepts and the handler
+// rejects would turn a clear tool error into a 400 from underneath.
+func TestMCPAcceptsOnlyFormatsTheHandlerAlsoAccepts(t *testing.T) {
+ for _, candidate := range []string{"compact", "text", "json", "yaml", " TEXT ", "xml", "compct", ""} {
+ normalized, mcpErr := normalizeSnapshotFormat(candidate)
+ if mcpErr != nil {
+ continue
+ }
+ if _, err := handlers.ParseSnapshotCostControls(url.Values{"format": {normalized}}); err != nil {
+ t.Errorf("MCP accepts format %q (as %q) but the handler rejects it: %v", candidate, normalized, err)
+ }
+ }
+}
+
+// The inverse is deliberately NOT required: the handler serves json and yaml, which the MCP
+// tools do not offer. This pins that the narrowing is the only difference, so a future
+// format added to the handler does not quietly become unreachable from MCP by accident.
+func TestMCPNarrowsTheHandlerRatherThanDivergingFromIt(t *testing.T) {
+ for _, format := range []string{"compact", "text"} {
+ if _, err := normalizeSnapshotFormat(format); err != nil {
+ t.Errorf("MCP rejects %q, which its own tools document: %v", format, err)
+ }
+ }
+ for _, handlerOnly := range []string{"json", "yaml"} {
+ if _, err := normalizeSnapshotFormat(handlerOnly); err == nil {
+ t.Errorf("MCP now accepts %q; if that is intended, the tool schema and this test both need updating", handlerOnly)
+ }
+ }
+}