Skip to content

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

fix: refuse an action whose ref carries a superseded snapshot vocabulary token (PIN-084)

Luigi Agostia997e33c7215
diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.go
index 25c56b6b..48111032 100644
--- a/internal/bridge/action_request.go
+++ b/internal/bridge/action_request.go
@@ -151,6 +151,8 @@ type ActionRequest struct {
// browsers. Recorded on route metadata but does not change actual
// routing yet.
Browser string `json:"browser,omitempty"`
+
+ Vocab string `json:"vocab,omitempty"`
}
type actionRequestAlias ActionRequest
diff --git a/internal/bridge/bridge_types.go b/internal/bridge/bridge_types.go
index 4639f7bd..5b410867 100644
--- a/internal/bridge/bridge_types.go
+++ b/internal/bridge/bridge_types.go
@@ -74,6 +74,10 @@ func (c *RefCache) Lookup(ref string) (RefTarget, bool) {
return RefTarget{}, false
}
+func MintVocabToken() string {
+ return mintDomEpoch()
+}
+
func RefTargetsFromNodes(nodes []A11yNode) map[string]RefTarget {
targets := make(map[string]RefTarget, len(nodes))
for _, node := range nodes {
diff --git a/internal/handlers/action_execution.go b/internal/handlers/action_execution.go
index d8f3bd14..51db2c68 100644
--- a/internal/handlers/action_execution.go
+++ b/internal/handlers/action_execution.go
@@ -457,9 +457,10 @@ func (h *Handlers) refreshRefCache(ctx context.Context, tabID string) {
flat, refs := bridge.BuildSnapshot(nodes, bridge.FilterInteractive, -1)
_ = bridge.EnrichA11yNodesWithDOMMetadata(ctx, flat)
h.Bridge.SetRefCache(tabID, &bridge.RefCache{
- Refs: refs,
- Targets: bridge.RefTargetsFromNodes(flat),
- Nodes: flat,
+ Refs: refs,
+ Targets: bridge.RefTargetsFromNodes(flat),
+ Nodes: flat,
+ DomEpoch: bridge.MintVocabToken(),
})
}
diff --git a/internal/handlers/action_vocab_test.go b/internal/handlers/action_vocab_test.go
new file mode 100644
index 00000000..9d87f2a3
--- /dev/null
+++ b/internal/handlers/action_vocab_test.go
@@ -0,0 +1,243 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type vocabMockBridge struct {
+ mockBridge
+ refCache *bridge.RefCache
+ executeCalled bool
+}
+
+func (m *vocabMockBridge) GetRefCache(string) *bridge.RefCache { return m.refCache }
+
+func (m *vocabMockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {
+ m.executeCalled = true
+ return map[string]any{"success": true}, nil
+}
+
+func newVocabHandlers(cacheToken string) (*Handlers, *vocabMockBridge) {
+ mb := &vocabMockBridge{
+ mockBridge: mockBridge{availableActions: []string{bridge.ActionClick}},
+ }
+ if cacheToken != "" {
+ mb.refCache = &bridge.RefCache{DomEpoch: cacheToken, Refs: map[string]int64{"e1": 42}}
+ }
+ return New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil), mb
+}
+
+func postVocabAction(h *Handlers, body string, header string) (*httptest.ResponseRecorder, map[string]any) {
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", "/action", strings.NewReader(body))
+ if header != "" {
+ req.Header.Set(vocabHeader, header)
+ }
+ h.HandleAction(w, req)
+ var out map[string]any
+ _ = json.Unmarshal(w.Body.Bytes(), &out)
+ return w, out
+}
+
+// A ref carrying a token from an earlier snapshot, while the tab's current vocabulary is a
+// different token, is the exact silent-wrong-click case: today it resolved e1 positionally
+// against whichever snapshot ran last and reported success. It must now be refused loudly,
+// before any node is touched, with its own code.
+func TestARefFromASupersededVocabularyIsRefusedBeforeAnyNodeIsTouched(t *testing.T) {
+ h, mb := newVocabHandlers("current")
+ w, body := postVocabAction(h, `{"kind":"click","ref":"e1","tabId":"tab1","vocab":"stale"}`, "")
+
+ if w.Code != 409 {
+ t.Fatalf("status = %d, want 409 — a ref minted under a superseded vocabulary must be refused, not resolved positionally: %s", w.Code, w.Body.String())
+ }
+ if body["code"] != vocabSupersededCode {
+ t.Errorf("code = %v, want %q", body["code"], vocabSupersededCode)
+ }
+ if body["retryable"] != true {
+ t.Errorf("retryable = %v, want true — re-snapshotting and retrying with the fresh ref is exactly the fix", body["retryable"])
+ }
+ if mb.executeCalled {
+ t.Error("the action reached ExecuteAction; the refusal must land before any node is touched")
+ }
+}
+
+// The absence half: a ref echoed with the tab's CURRENT token is not the superseded case, so
+// the guard must let it through to resolution rather than being satisfiable by refusing every
+// ref. It is NOT refused with the vocab code (it fails downstream only because the mock cannot
+// resolve e1, which is a different, later refusal).
+func TestARefCarryingTheCurrentVocabularyIsNotRefusedByTheGuard(t *testing.T) {
+ h, mb := newVocabHandlers("current")
+ _, body := postVocabAction(h, `{"kind":"click","ref":"e1","tabId":"tab1","vocab":"current"}`, "")
+
+ if body["code"] == vocabSupersededCode {
+ t.Errorf("a ref used within its own vocabulary was refused as superseded: %v", body)
+ }
+ _ = mb
+}
+
+// Fail-safe permissiveness: an action carrying no token, or one hitting a tab whose cache
+// carries no token, keeps today's behaviour so no existing client breaks. Each is asserted
+// against the same stale/current setup so a guard that refused unconditionally would red here.
+func TestTheGuardIsPermissiveWhenEitherSideHasNoToken(t *testing.T) {
+ cases := []struct {
+ name string
+ cacheToken string
+ body string
+ }{
+ {"no token on the request", "current", `{"kind":"click","ref":"e1","tabId":"tab1"}`},
+ {"no cache at all", "", `{"kind":"click","ref":"e1","tabId":"tab1","vocab":"stale"}`},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ h, _ := newVocabHandlers(tc.cacheToken)
+ _, body := postVocabAction(h, tc.body, "")
+ if body["code"] == vocabSupersededCode {
+ t.Errorf("%s was refused as superseded; the guard must stay permissive when a token is absent", tc.name)
+ }
+ })
+ }
+}
+
+// A stale token on an action that does not resolve through the ref cache — a coordinate click
+// carries its own target — must not be blocked: scoping the guard to ref-targeted actions is
+// what keeps ordinary non-ref flows working after a renumbering publish.
+func TestAStaleTokenDoesNotBlockANonRefAction(t *testing.T) {
+ h, mb := newVocabHandlers("current")
+ w, body := postVocabAction(h, `{"kind":"click","x":10,"y":20,"tabId":"tab1","vocab":"stale"}`, "")
+
+ if body["code"] == vocabSupersededCode {
+ t.Fatalf("a coordinate click was refused as superseded though it never resolves a ref: %v", body)
+ }
+ if !mb.executeCalled {
+ t.Errorf("the non-ref action did not reach ExecuteAction (status %d): %s", w.Code, w.Body.String())
+ }
+}
+
+// The token rides back in a response header, so a client that read it from the header — not
+// the JSON body — echoes it the same way. The guard reads the header when the request carried
+// no explicit field.
+func TestTheGuardReadsTheTokenFromTheRequestHeader(t *testing.T) {
+ h, _ := newVocabHandlers("current")
+ w, body := postVocabAction(h, `{"kind":"click","ref":"e1","tabId":"tab1"}`, "stale")
+ if w.Code != 409 || body["code"] != vocabSupersededCode {
+ t.Errorf("a superseded token sent as a header was not refused: status %d body %s", w.Code, w.Body.String())
+ }
+}
+
+// The GET form: the token is a query parameter, and the unknown-parameter guard must ALLOW
+// it (it is derived from ActionRequest's fields, so `vocab` is accepted with no edit) while
+// still enforcing the mismatch.
+func TestTheGETFormCarriesAndEnforcesTheToken(t *testing.T) {
+ h, _ := newVocabHandlers("current")
+ w := httptest.NewRecorder()
+ h.HandleAction(w, httptest.NewRequest("GET", "/action?kind=click&ref=e1&tabId=tab1&vocab=stale", nil))
+ var body map[string]any
+ _ = json.Unmarshal(w.Body.Bytes(), &body)
+ if w.Code != 409 || body["code"] != vocabSupersededCode {
+ t.Errorf("the GET form did not enforce a superseded token (status %d): %s", w.Code, w.Body.String())
+ }
+}
+
+// Every publish mints a fresh token, so any renumbering publish supersedes the previous one —
+// this is why a same-options republish (the stale-ref retry re-runs the interactive filter)
+// still supersedes, which a hash-of-options token would not.
+func TestEachMintedTokenIsDistinctAndNonEmpty(t *testing.T) {
+ seen := map[string]bool{}
+ for i := 0; i < 64; i++ {
+ tok := bridge.MintVocabToken()
+ if tok == "" {
+ t.Fatal("MintVocabToken returned an empty token; an empty cache token disables the guard")
+ }
+ if seen[tok] {
+ t.Fatalf("MintVocabToken repeated %q; two publishes would share a vocabulary and the guard would miss the supersession", tok)
+ }
+ seen[tok] = true
+ }
+}
+
+// Wiring census: the guard above only refuses when the tab's cached token differs from the
+// request's, so it is inert unless every ref-publishing site actually MINTS and stores a fresh
+// token. This is the browserless proof of criteria one and four — that /snapshot publishes a
+// token and that the annotate and stale-ref-retry paths supersede — since those handlers reach
+// live CDP and cannot be driven by the package mock. Dropping the mint at any site reddens here
+// while leaving the behavioural gate tests green, so this census is load-bearing.
+func TestEveryRefPublishSiteMintsAVocabularyToken(t *testing.T) {
+ for _, tc := range []struct {
+ file string
+ want string
+ why string
+ }{
+ {"snapshot.go", "MintVocabToken", "the /snapshot response is the primary vocabulary a client reads and echoes"},
+ {"screenshot_annotate.go", "MintVocabToken", "the annotate path republishes with a hardcoded interactive filter and must supersede"},
+ {"action_execution.go", "MintVocabToken", "the stale-ref retry refreshes the cache and must supersede a ref minted before it"},
+ } {
+ if !fileCallsSelector(t, tc.file, tc.want) {
+ t.Errorf("%s does not call bridge.%s, so this publish site stores no token and the guard is inert for it — %s", tc.file, tc.want, tc.why)
+ }
+ }
+
+ if !fileMentionsIdent(t, "snapshot.go", "vocabHeader") {
+ t.Error("snapshot.go does not emit the token in a response header, so a client reading a compact/text snapshot cannot obtain it")
+ }
+ if !fileMentionsString(t, "snapshot.go", "vocabularyToken") {
+ t.Error("snapshot.go does not carry the token in its JSON body, so a JSON snapshot consumer cannot echo it")
+ }
+ if !fileMentionsIdent(t, "capture.go", "vocabHeader") {
+ t.Error("capture.go does not emit the token in a response header, so a /capture client cannot obtain it uniformly with /snapshot")
+ }
+}
+
+func parseHandlerFile(t *testing.T, name string) *ast.File {
+ t.Helper()
+ f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0)
+ if err != nil {
+ t.Fatalf("parse %s: %v", name, err)
+ }
+ return f
+}
+
+func fileCallsSelector(t *testing.T, name, sel string) bool {
+ found := false
+ ast.Inspect(parseHandlerFile(t, name), func(n ast.Node) bool {
+ if call, ok := n.(*ast.CallExpr); ok {
+ if se, ok := call.Fun.(*ast.SelectorExpr); ok && se.Sel.Name == sel {
+ found = true
+ }
+ }
+ return true
+ })
+ return found
+}
+
+func fileMentionsIdent(t *testing.T, name, ident string) bool {
+ found := false
+ ast.Inspect(parseHandlerFile(t, name), func(n ast.Node) bool {
+ if id, ok := n.(*ast.Ident); ok && id.Name == ident {
+ found = true
+ }
+ return true
+ })
+ return found
+}
+
+func fileMentionsString(t *testing.T, name, lit string) bool {
+ found := false
+ ast.Inspect(parseHandlerFile(t, name), func(n ast.Node) bool {
+ if bl, ok := n.(*ast.BasicLit); ok && bl.Kind == token.STRING && strings.Trim(bl.Value, "`\"") == lit {
+ found = true
+ }
+ return true
+ })
+ return found
+}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 4e6e7a4e..f8e9cb7f 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -431,6 +431,7 @@ func decodeActionRequest(w http.ResponseWriter, r *http.Request) (bridge.ActionR
d.Bool("hasDelta", &hasDeltaParam)
req.HasDelta = req.HasDelta || hasDeltaParam
req.Browser = q.Get("browser")
+ req.Vocab = q.Get("vocab")
if err := d.Err(); err != nil {
httpx.Error(w, 400, err)
return bridge.ActionRequest{}, false
@@ -446,6 +447,26 @@ func decodeActionRequest(w http.ResponseWriter, r *http.Request) (bridge.ActionR
return req, true
}
+const vocabHeader = "X-PinchTab-Vocab"
+
+const vocabSupersededCode = "vocab_superseded"
+
+func actionTargetsRef(req bridge.ActionRequest) bool {
+ if req.NodeID != 0 {
+ return false
+ }
+ if strings.TrimSpace(req.Ref) != "" {
+ return true
+ }
+ return selector.Parse(req.Selector).Kind == selector.KindRef
+}
+
+func writeVocabSuperseded(w http.ResponseWriter, tabID string) {
+ httpx.ErrorCode(w, http.StatusConflict, vocabSupersededCode,
+ "ref vocabulary superseded: a newer snapshot renumbered this tab's refs, so a ref from the earlier snapshot no longer denotes the node it named — re-snapshot and use the refs from the latest response",
+ true, map[string]any{"tabId": tabID})
+}
+
func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
req, ok := decodeActionRequest(w, r)
if !ok {
@@ -533,6 +554,16 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
h.recordResolvedTab(r, resolvedTabID)
w.Header().Set(activity.HeaderPTTabID, resolvedTabID)
+ if req.Vocab == "" {
+ req.Vocab = r.Header.Get(vocabHeader)
+ }
+ if req.Vocab != "" && actionTargetsRef(req) {
+ if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil && cache.DomEpoch != "" && cache.DomEpoch != req.Vocab {
+ writeVocabSuperseded(w, resolvedTabID)
+ return
+ }
+ }
+
actionTimeout := effectiveCfg.ActionTimeout
if r.Method == http.MethodGet {
if v := r.URL.Query().Get("timeout"); v != "" {
diff --git a/internal/handlers/capture.go b/internal/handlers/capture.go
index 5c535fcf..2a969c69 100644
--- a/internal/handlers/capture.go
+++ b/internal/handlers/capture.go
@@ -172,14 +172,13 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {
return
}
- // Persist the snapshot half to the ref cache with the minted epoch so that
- // follow-up `/click eN` etc. can later opt into an epoch handshake.
h.Bridge.SetRefCache(resolvedTabID, &bridge.RefCache{
Refs: result.Refs,
Targets: bridge.RefTargetsFromNodes(result.Nodes),
Nodes: result.Nodes,
DomEpoch: result.DomEpoch,
})
+ w.Header().Set(vocabHeader, result.DomEpoch)
imageInfo := map[string]any{
"format": result.ImageFormat,
diff --git a/internal/handlers/screenshot_annotate.go b/internal/handlers/screenshot_annotate.go
index 3d579ec3..224d2104 100644
--- a/internal/handlers/screenshot_annotate.go
+++ b/internal/handlers/screenshot_annotate.go
@@ -61,11 +61,11 @@ func (h *Handlers) collectScreenshotAnnotations(
flat, refs = bridge.BuildSnapshot(rawNodes, "", -1)
}
- // Record refs so a subsequent click/fill on `e5` resolves the same node.
h.Bridge.SetRefCache(tabID, &bridge.RefCache{
- Refs: refs,
- Targets: bridge.RefTargetsFromNodes(flat),
- Nodes: flat,
+ Refs: refs,
+ Targets: bridge.RefTargetsFromNodes(flat),
+ Nodes: flat,
+ DomEpoch: bridge.MintVocabToken(),
})
items = make([]cdptk.AnnotationItem, 0, len(flat))
diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.go
index 346b4194..db8d4f25 100644
--- a/internal/handlers/snapshot.go
+++ b/internal/handlers/snapshot.go
@@ -220,11 +220,14 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
}
+ vocab := bridge.MintVocabToken()
h.Bridge.SetRefCache(resolvedTabID, &bridge.RefCache{
- Refs: refs,
- Targets: bridge.RefTargetsFromNodes(flat),
- Nodes: flat,
+ Refs: refs,
+ Targets: bridge.RefTargetsFromNodes(flat),
+ Nodes: flat,
+ DomEpoch: vocab,
})
+ w.Header().Set(vocabHeader, vocab)
h.recordResolvedURL(r, url)
@@ -444,11 +447,12 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(yamlContent)
default:
resp := scopeInfo.attach(map[string]any{
- "url": url,
- "title": title,
- "route": snapChromeRoute,
- "nodes": flat,
- "count": len(flat),
+ "url": url,
+ "title": title,
+ "route": snapChromeRoute,
+ "nodes": flat,
+ "count": len(flat),
+ "vocabularyToken": vocab,
})
if truncated {
resp["truncated"] = true