High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: key the CLI vocab token by the resolved tab id in one bounded 0600 store, not the caller's --tab spelling (PIN-376)
Luigi Agosti8d76ac498b32
diff --git a/internal/cli/actions/actions_snapshot.go b/internal/cli/actions/actions_snapshot.goindex 12cd89f9..3e51d1d9 100644--- a/internal/cli/actions/actions_snapshot.go+++ b/internal/cli/actions/actions_snapshot.go@@ -34,7 +34,7 @@ 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, params.Get("tabId"))+ result := apiclient.DoGetCapturingVocab(client, base, token, "/snapshot", params)apiclient.SuggestNextAction("snapshot", result)}diff --git a/internal/cli/actions/vocab_echo_test.go b/internal/cli/actions/vocab_echo_test.goindex 0f07689c..0b8dd6c6 100644--- a/internal/cli/actions/vocab_echo_test.go+++ b/internal/cli/actions/vocab_echo_test.go@@ -14,6 +14,7 @@ func vocabEchoServer(t *testing.T, token string, lastActionBody *string) *httptet.Helper()srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path == "/snapshot" {+ w.Header().Set("X-PinchTab-Tab-Id", r.URL.Query().Get("tabId"))w.Header().Set("X-PinchTab-Vocab", token)_, _ = w.Write([]byte(`{"status":"ok"}`))returndiff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex c28dff6e..8cb3d063 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -11,41 +11,93 @@ import ("time")-const vocabHeader = "X-PinchTab-Vocab"+const (+ vocabHeader = "X-PinchTab-Vocab"+ vocabTabIDHeader = "X-PinchTab-Tab-Id"+ vocabStoreLimit = 16+)++// vocabEntry pairs a snapshot's vocabulary token with the tab the server+// actually resolved it for, so a later action echoes the token only when it+// targets that same tab.+type vocabEntry struct {+ TabID string `json:"tabId"`+ Token string `json:"token"`+}// DoGetCapturingVocab performs a GET like DoGet and, on success, persists the-// response's vocabulary token for (base, tabKey) so 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, tabKey string) map[string]any {+// 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 {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, tabKey, headers.Get(vocabHeader))+ storeVocabToken(base, headers.Get(vocabTabIDHeader), headers.Get(vocabHeader))return printAndDecode(body)}-// VocabTokenFor returns the last vocabulary token stored for (base, tabKey), or "".-func VocabTokenFor(base, tabKey string) string {- data, err := os.ReadFile(vocabTokenPath(base, tabKey))- if err != nil {+// 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.+func VocabTokenFor(base, tabID string) string {+ if tabID == "" {return ""}- return strings.TrimSpace(string(data))+ for _, e := range loadVocabStore(base) {+ if e.TabID == tabID {+ return e.Token+ }+ }+ return ""}-func storeVocabToken(base, tabKey, token string) {- if token == "" {+func storeVocabToken(base, tabID, token string) {+ if tabID == "" || token == "" {return}- path := vocabTokenPath(base, tabKey)+ entries := loadVocabStore(base)+ kept := entries[:0]+ for _, e := range entries {+ if e.TabID != tabID {+ kept = append(kept, e)+ }+ }+ kept = append(kept, vocabEntry{TabID: tabID, Token: token})+ if len(kept) > vocabStoreLimit {+ kept = kept[len(kept)-vocabStoreLimit:]+ }+ writeVocabStore(base, kept)+}++func loadVocabStore(base string) []vocabEntry {+ data, err := os.ReadFile(vocabStorePath(base))+ if err != nil {+ return nil+ }+ var entries []vocabEntry+ if err := json.Unmarshal(data, &entries); err != nil {+ return nil+ }+ return entries+}++func writeVocabStore(base string, entries []vocabEntry) {+ path := vocabStorePath(base)_ = os.MkdirAll(filepath.Dir(path), 0755)- _ = os.WriteFile(path, []byte(token+"\n"), 0644)+ data, err := json.Marshal(entries)+ if err != nil {+ return+ }+ _ = os.WriteFile(path, data, 0600)}-func vocabTokenPath(base, tabKey string) string {+func vocabStorePath(base string) string {dir := os.Getenv("XDG_STATE_HOME")if dir != "" {dir += "/pinchtab"@@ -54,11 +106,7 @@ func vocabTokenPath(base, tabKey string) string {} else {dir = "/tmp/pinchtab"}- key := tabKey- if key == "" {- key = "default"- }- return filepath.Join(dir, "vocab-"+fileSlug(base)+"-"+fileSlug(key))+ return filepath.Join(dir, "vocab-"+fileSlug(base))}func fileSlug(s string) string {diff --git a/internal/cli/apiclient/vocab_test.go b/internal/cli/apiclient/vocab_test.gonew file mode 100644index 00000000..a365c347--- /dev/null+++ b/internal/cli/apiclient/vocab_test.go@@ -0,0 +1,189 @@+package apiclient_test++import (+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "sync"+ "testing"++ "github.com/pinchtab/pinchtab/internal/cli/actions"+ "github.com/spf13/cobra"+)++// 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.+type vocabServer struct {+ mu sync.Mutex+ current string+ epoch map[string]int+ lastVocab string+ hadVocab bool+ lastPath string+ httpServer *httptest.Server+}++func newVocabServer(current string) *vocabServer {+ s := &vocabServer{current: current, epoch: map[string]int{}}+ s.httpServer = httptest.NewServer(http.HandlerFunc(s.handle))+ return s+}++func (s *vocabServer) tokenFor(tab string) string {+ if s.epoch[tab] == 0 {+ s.epoch[tab] = 1+ }+ return fmt.Sprintf("%s-e%d", tab, s.epoch[tab])+}++func (s *vocabServer) bumpEpoch(tab string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.epoch[tab] == 0 {+ s.epoch[tab] = 1+ }+ 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()++ if r.Method == http.MethodGet && r.URL.Path == "/snapshot" {+ resolved := r.URL.Query().Get("tabId")+ if resolved == "" {+ resolved = s.current+ }+ w.Header().Set("X-PinchTab-Tab-Id", resolved)+ w.Header().Set("X-PinchTab-Vocab", s.tokenFor(resolved))+ _, _ = w.Write([]byte("{}\n"))+ return+ }++ body, _ := io.ReadAll(r.Body)+ var decoded map[string]any+ _ = json.Unmarshal(body, &decoded)+ s.lastPath = r.URL.Path+ s.lastVocab, s.hadVocab = "", false+ if v, ok := decoded["vocab"].(string); ok {+ s.lastVocab, s.hadVocab = v, true+ }+ _, _ = w.Write([]byte(`{"success":true}`))+}++func snapCmd(tab string) *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().String("tab", "", "")+ if tab != "" {+ _ = cmd.Flags().Set("tab", tab)+ }+ return cmd+}++func clickCmd(tab string) *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().String("tab", "", "")+ cmd.Flags().Bool("json", false, "")+ if tab != "" {+ _ = cmd.Flags().Set("tab", tab)+ }+ 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".+func TestExplicitClickSendsTheLatestTokenForItsResolvedTab(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("X"), "")+ srv.bumpEpoch("X")+ actions.Snapshot(client, base, "", snapCmd(""), "")+ 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)+ }+ 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) {+ 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)+ }+}++// AC-3: the per-tab files are replaced by one bounded file per server, written+// 0600, holding at most the N most recent tabs.+func TestVocabStoreIsOneBoundedFilePerServer(t *testing.T) {+ stateHome := t.TempDir()+ t.Setenv("XDG_STATE_HOME", stateHome)+ srv := newVocabServer("")+ defer srv.httpServer.Close()+ base, client := srv.httpServer.URL, srv.httpServer.Client()++ for i := 0; i < 50; i++ {+ actions.Snapshot(client, base, "", snapCmd(fmt.Sprintf("tab-%02d", i)), "")+ }++ files, err := filepath.Glob(filepath.Join(stateHome, "pinchtab", "vocab-*"))+ if err != nil {+ t.Fatal(err)+ }+ if len(files) != 1 {+ t.Fatalf("expected exactly one vocab store file per server, found %d: %v", len(files), files)+ }++ info, err := os.Stat(files[0])+ if err != nil {+ t.Fatal(err)+ }+ if perm := info.Mode().Perm(); perm != 0o600 {+ t.Errorf("vocab store written %o, want 0600 (it holds a capability token on a possibly shared path)", perm)+ }++ data, err := os.ReadFile(files[0])+ if err != nil {+ t.Fatal(err)+ }+ var entries []struct {+ TabID string `json:"tabId"`+ Token string `json:"token"`+ }+ if err := json.Unmarshal(data, &entries); 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))+ }+}