High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: implicit CLI actions echo the current tab's vocab token tagged X-PinchTab-Vocab-Tab, and the server enforces the epoch check only for the resolved tab (PIN-376)
Luigi Agosti9414a571bd9d
diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.goindex 48322d51..5a9c9378 100644--- a/internal/cli/actions/actions_element.go+++ b/internal/cli/actions/actions_element.go@@ -122,8 +122,12 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.C}if _, ok := body["vocab"]; !ok {- if tok := apiclient.VocabTokenFor(base, tabID); tok != "" {+ if vocabTab, tok := apiclient.VocabForAction(base, tabID); tok != "" {body["vocab"] = tok+ if headers == nil {+ headers = map[string]string{}+ }+ headers[apiclient.VocabTabHeader] = vocabTab}}diff --git a/internal/cli/actions/actions_snapshot.go b/internal/cli/actions/actions_snapshot.goindex 3e51d1d9..865d211f 100644--- a/internal/cli/actions/actions_snapshot.go+++ b/internal/cli/actions/actions_snapshot.go@@ -34,7 +34,8 @@ func Snapshot(client *http.Client, base, token string, cmd *cobra.Command, selecif v, _ := cmd.Flags().GetString("tab"); v != "" {params.Set("tabId", v)}- result := apiclient.DoGetCapturingVocab(client, base, token, "/snapshot", params)+ implicit := params.Get("tabId") == ""+ result := apiclient.DoGetCapturingVocab(client, base, token, "/snapshot", params, implicit)apiclient.SuggestNextAction("snapshot", result)}diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex 8cb3d063..d5ae2c2f 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -14,7 +14,11 @@ import (const (vocabHeader = "X-PinchTab-Vocab"vocabTabIDHeader = "X-PinchTab-Tab-Id"- vocabStoreLimit = 16+ // VocabTabHeader tells the server which tab the echoed token belongs to, so it+ // enforces the epoch check only when the action resolves that same tab and+ // ignores a token left over from a tab the current pointer has since moved off.+ VocabTabHeader = "X-PinchTab-Vocab-Tab"+ vocabStoreLimit = 16)// vocabEntry pairs a snapshot's vocabulary token with the tab the server@@ -25,45 +29,66 @@ type vocabEntry struct {Token string `json:"token"`}+// vocabStore is one server's token records plus the tab the last implicit+// snapshot resolved, so an implicit action can echo that tab's token and tag it.+type vocabStore struct {+ Current string `json:"current"`+ Entries []vocabEntry `json:"entries"`+}+// DoGetCapturingVocab performs a GET like DoGet and, on success, persists the// response's vocabulary token keyed by the tab the server resolved (the-// X-PinchTab-Tab-Id header), not by how the caller spelled --tab. A later action-// on that tab echoes it and a ref renumbered by an intervening snapshot is-// refused rather than mis-resolved. The token is delivered as a response header-// so it survives every snapshot format, including the compact text the CLI-// defaults to.-func DoGetCapturingVocab(client *http.Client, base, token, path string, params url.Values) map[string]any {+// X-PinchTab-Tab-Id header), not by how the caller spelled --tab. When the+// snapshot was implicit (no --tab), the resolved tab also becomes the store's+// current pointer, so a later implicit action echoes that tab's token. The token+// is delivered as a response header so it survives every snapshot format,+// including the compact text the CLI defaults to.+func DoGetCapturingVocab(client *http.Client, base, token, path string, params url.Values, implicit bool) map[string]any {var headers http.Headerr := request{method: "GET", url: buildURL(base, path, params), respHeaders: &headers}status, body := mustRequest(client, token, r)exitOnAPIError(r, status, body)- storeVocabToken(base, headers.Get(vocabTabIDHeader), headers.Get(vocabHeader))+ storeVocabToken(base, headers.Get(vocabTabIDHeader), headers.Get(vocabHeader), implicit)return printAndDecode(body)}-// VocabTokenFor returns the token stored for a resolved tab id, or "". An empty-// tabID (an implicit action, whose target the CLI cannot know before the server-// resolves it) returns "", so the caller omits the token rather than echoing one-// belonging to whatever tab was current at the last snapshot.+// VocabForAction returns the tab id to tag and the token to echo for an action.+// An explicit --tab X uses X's own record; an implicit action uses the current+// pointer's tab. The returned tab is sent as VocabTabHeader so the server can+// ignore the token when the action resolves a different tab.+func VocabForAction(base, requestedTab string) (vocabTab, token string) {+ store := loadVocabStore(base)+ tab := requestedTab+ if tab == "" {+ tab = store.Current+ }+ if tab == "" {+ return "", ""+ }+ for _, e := range store.Entries {+ if e.TabID == tab {+ return tab, e.Token+ }+ }+ return tab, ""+}++// VocabTokenFor returns the token stored for a resolved tab id, or "".func VocabTokenFor(base, tabID string) string {if tabID == "" {return ""}- for _, e := range loadVocabStore(base) {- if e.TabID == tabID {- return e.Token- }- }- return ""+ _, token := VocabForAction(base, tabID)+ return token}-func storeVocabToken(base, tabID, token string) {+func storeVocabToken(base, tabID, token string, implicit bool) {if tabID == "" || token == "" {return}- entries := loadVocabStore(base)- kept := entries[:0]- for _, e := range entries {+ store := loadVocabStore(base)+ kept := store.Entries[:0]+ for _, e := range store.Entries {if e.TabID != tabID {kept = append(kept, e)}@@ -72,25 +97,29 @@ func storeVocabToken(base, tabID, token string) {if len(kept) > vocabStoreLimit {kept = kept[len(kept)-vocabStoreLimit:]}- writeVocabStore(base, kept)+ store.Entries = kept+ if implicit {+ store.Current = tabID+ }+ writeVocabStore(base, store)}-func loadVocabStore(base string) []vocabEntry {+func loadVocabStore(base string) vocabStore {data, err := os.ReadFile(vocabStorePath(base))if err != nil {- return nil+ return vocabStore{}}- var entries []vocabEntry- if err := json.Unmarshal(data, &entries); err != nil {- return nil+ var store vocabStore+ if err := json.Unmarshal(data, &store); err != nil {+ return vocabStore{}}- return entries+ return store}-func writeVocabStore(base string, entries []vocabEntry) {+func writeVocabStore(base string, store vocabStore) {path := vocabStorePath(base)_ = os.MkdirAll(filepath.Dir(path), 0755)- data, err := json.Marshal(entries)+ data, err := json.Marshal(store)if err != nil {return}diff --git a/internal/cli/apiclient/vocab_test.go b/internal/cli/apiclient/vocab_test.goindex a365c347..a5961c19 100644--- a/internal/cli/apiclient/vocab_test.go+++ b/internal/cli/apiclient/vocab_test.go@@ -16,16 +16,17 @@ import ()// vocabServer mints a distinct vocabulary token per (tab, epoch) and records the-// token each action echoes, so a test can assert which snapshot's token a later-// action sent — the whole point of keying the token store by resolved tab.+// token and tab tag each action echoes, so a test can assert which snapshot's+// token a later action sent and which tab it claimed it for.type vocabServer struct {- mu sync.Mutex- current string- epoch map[string]int- lastVocab string- hadVocab bool- lastPath string- httpServer *httptest.Server+ mu sync.Mutex+ current string+ epoch map[string]int+ lastVocab string+ lastVocabTab string+ hadVocab bool+ lastPath string+ httpServer *httptest.Server}func newVocabServer(current string) *vocabServer {@@ -50,12 +51,6 @@ func (s *vocabServer) bumpEpoch(tab string) {s.epoch[tab]++}-func (s *vocabServer) setCurrent(tab string) {- s.mu.Lock()- defer s.mu.Unlock()- s.current = tab-}-func (s *vocabServer) handle(w http.ResponseWriter, r *http.Request) {s.mu.Lock()defer s.mu.Unlock()@@ -79,6 +74,7 @@ func (s *vocabServer) handle(w http.ResponseWriter, r *http.Request) {if v, ok := decoded["vocab"].(string); ok {s.lastVocab, s.hadVocab = v, true}+ s.lastVocabTab = r.Header.Get("X-PinchTab-Vocab-Tab")_, _ = w.Write([]byte(`{"success":true}`))}@@ -101,10 +97,10 @@ func clickCmd(tab string) *cobra.Command {return cmd}-// AC-1: an explicit action echoes the token of the snapshot that resolved the-// SAME tab, even when that snapshot was implicit. On HEAD the click reads the-// slot keyed by the "--tab X" spelling (T1) and misses the implicit snapshot's-// T2 stored under "default".+// AC-1 / row (c): an explicit action echoes the token of the snapshot that+// resolved the SAME tab, tagged with that tab, even when that snapshot was+// implicit. On the pre-fix commit the click read the slot keyed by the "--tab X"+// spelling (T1) and missed the implicit snapshot's T2.func TestExplicitClickSendsTheLatestTokenForItsResolvedTab(t *testing.T) {t.Setenv("XDG_STATE_HOME", t.TempDir())srv := newVocabServer("X")@@ -117,34 +113,39 @@ func TestExplicitClickSendsTheLatestTokenForItsResolvedTab(t *testing.T) {actions.Action(client, base, "", "click", "e5", clickCmd("X"))if srv.lastVocab != "X-e2" {- t.Fatalf("click sent vocab %q (hadVocab=%v), want the current token X-e2; a stale token here is the false 409 this fixes", srv.lastVocab, srv.hadVocab)+ t.Fatalf("click sent vocab %q (hadVocab=%v), want the current token X-e2", srv.lastVocab, srv.hadVocab)+ }+ if srv.lastVocabTab != "X" {+ t.Fatalf("click tagged the token for tab %q, want X", srv.lastVocabTab)}if srv.lastPath != "/tabs/X/action" {t.Fatalf("click went to %q, want /tabs/X/action", srv.lastPath)}}-// AC-2 (mirror): an implicit snapshot resolves the current tab X; the current-// tab then moves to Y; an implicit click must not echo X's token, because the-// CLI cannot know it will resolve Y. On HEAD the click reads the shared-// "default" slot and sends X's token against Y.-func TestImplicitClickDoesNotSendAPriorTabsToken(t *testing.T) {+// The implicit flow keeps its protection: after an implicit snapshot resolves the+// current tab, an implicit click echoes that tab's token, tagged with it, so the+// server can refuse a superseded ref. The pre-fix (omit) commit sent no token+// here, which is the silent-wrong-click regression this restores.+func TestImplicitClickSendsTheCurrentTabsTaggedToken(t *testing.T) {t.Setenv("XDG_STATE_HOME", t.TempDir())srv := newVocabServer("X")defer srv.httpServer.Close()base, client := srv.httpServer.URL, srv.httpServer.Client()actions.Snapshot(client, base, "", snapCmd(""), "")- srv.setCurrent("Y")actions.Action(client, base, "", "click", "e5", clickCmd(""))- if srv.hadVocab {- t.Fatalf("implicit click sent vocab %q; it must omit the token when it cannot know the resolved tab", srv.lastVocab)+ if !srv.hadVocab {+ t.Fatal("implicit click sent no token; the common snap-then-click flow lost its supersession protection")+ }+ if srv.lastVocab != "X-e1" || srv.lastVocabTab != "X" {+ t.Fatalf("implicit click sent vocab %q tagged %q, want X-e1 tagged X", srv.lastVocab, srv.lastVocabTab)}}// AC-3: the per-tab files are replaced by one bounded file per server, written-// 0600, holding at most the N most recent tabs.+// 0600, holding at most the N most recent tabs plus the current pointer.func TestVocabStoreIsOneBoundedFilePerServer(t *testing.T) {stateHome := t.TempDir()t.Setenv("XDG_STATE_HOME", stateHome)@@ -176,14 +177,17 @@ func TestVocabStoreIsOneBoundedFilePerServer(t *testing.T) {if err != nil {t.Fatal(err)}- var entries []struct {- TabID string `json:"tabId"`- Token string `json:"token"`+ var store struct {+ Current string `json:"current"`+ Entries []struct {+ TabID string `json:"tabId"`+ Token string `json:"token"`+ } `json:"entries"`}- if err := json.Unmarshal(data, &entries); err != nil {+ if err := json.Unmarshal(data, &store); err != nil {t.Fatalf("vocab store is not the bounded JSON map: %v\n%s", err, data)}- if len(entries) == 0 || len(entries) > 16 {- t.Fatalf("store holds %d entries after 50 snapshots, want 1..16", len(entries))+ if len(store.Entries) == 0 || len(store.Entries) > 16 {+ t.Fatalf("store holds %d entries after 50 snapshots, want 1..16", len(store.Entries))}}diff --git a/internal/handlers/action_vocab_test.go b/internal/handlers/action_vocab_test.goindex 4f107d33..523ef1f9 100644--- a/internal/handlers/action_vocab_test.go+++ b/internal/handlers/action_vocab_test.go@@ -124,6 +124,42 @@ func TestAStaleTokenDoesNotBlockANonRefAction(t *testing.T) {}}+// A token tagged (X-PinchTab-Vocab-Tab) for the tab the action resolves is enforced: a+// superseded token on the resolved tab is still refused, so the implicit snap-then-click+// flow keeps its supersession protection.+func TestATokenTaggedForTheResolvedTabIsEnforced(t *testing.T) {+ h, mb := newVocabHandlers("current")+ w := httptest.NewRecorder()+ req := httptest.NewRequest("POST", "/action", strings.NewReader(`{"kind":"click","ref":"e1","tabId":"tab1","vocab":"stale"}`))+ req.Header.Set(vocabTabHeader, "tab1")+ h.HandleAction(w, req)+ var body map[string]any+ _ = json.Unmarshal(w.Body.Bytes(), &body)+ if w.Code != 409 || body["code"] != vocabSupersededCode {+ t.Fatalf("a superseded token tagged for the resolved tab was not refused: status %d body %s", w.Code, w.Body.String())+ }+ if mb.executeCalled {+ t.Error("the refusal must land before ExecuteAction")+ }+}++// A token tagged for a DIFFERENT tab than the action resolves is ignored, not refused: the+// current pointer moved off the snapshotted tab, and a false supersession there is the+// mirror-case regression the tag exists to kill. Pre-fix the server ignored the tag and+// refused this with a 409.+func TestATokenTaggedForADifferentTabIsIgnored(t *testing.T) {+ h, _ := newVocabHandlers("current")+ w := httptest.NewRecorder()+ req := httptest.NewRequest("POST", "/action", strings.NewReader(`{"kind":"click","ref":"e1","tabId":"tab1","vocab":"stale"}`))+ req.Header.Set(vocabTabHeader, "other-tab")+ h.HandleAction(w, req)+ var body map[string]any+ _ = json.Unmarshal(w.Body.Bytes(), &body)+ if body["code"] == vocabSupersededCode {+ t.Errorf("a token tagged for another tab produced a false supersession: %v", body)+ }+}+// 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.diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 059acf7f..e1d6787c 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -417,8 +417,18 @@ func decodeActionRequest(w http.ResponseWriter, r *http.Request) (bridge.ActionRconst vocabHeader = "X-PinchTab-Vocab"+// vocabTabHeader names the tab the echoed token belongs to. The epoch check runs+// only when it is empty (a legacy client that cannot tag) or equals the resolved+// tab; a token tagged for a different tab is ignored, so a stale current pointer+// after the tab moved proceeds instead of a false supersession.+const vocabTabHeader = "X-PinchTab-Vocab-Tab"+const vocabSupersededCode = "vocab_superseded"+func vocabTabMatches(vocabTab, resolvedTabID string) bool {+ return vocabTab == "" || vocabTab == resolvedTabID+}+func actionTargetsRef(req bridge.ActionRequest) bool {if req.NodeID != 0 {return false@@ -510,7 +520,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {if req.Vocab == "" {req.Vocab = r.Header.Get(vocabHeader)}- if req.Vocab != "" && actionTargetsRef(req) {+ if req.Vocab != "" && actionTargetsRef(req) && vocabTabMatches(r.Header.Get(vocabTabHeader), resolvedTabID) {if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil && cache.DomEpoch != "" && cache.DomEpoch != req.Vocab {writeVocabSuperseded(w, resolvedTabID)return