Skip to content

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

feat: complete #417 — CLI, E2E tests, .json.enc, storage clear --all, prefix load

Yash Jadhavdf60e8d6caec
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index 948df62c..f0e2c435 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -45,6 +45,8 @@ func registerBrowserCommands() {
errorsCmd,
clipboardCmd,
cacheCmd,
+ storageCmd,
+ stateCmd,
)
tabsCmd.AddCommand(tabNewCmd, tabCloseCmd)
@@ -91,6 +93,8 @@ func registerBrowserCommands() {
errorsCmd,
clipboardCmd,
cacheCmd,
+ storageCmd,
+ stateCmd,
)
}
diff --git a/cmd/pinchtab/cmd_cli_state.go b/cmd/pinchtab/cmd_cli_state.go
new file mode 100644
index 00000000..3b634328
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_state.go
@@ -0,0 +1,103 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+var stateCmd = &cobra.Command{
+ Use: "state",
+ Short: "Manage browser session state",
+ Long: "Commands for saving, loading, and managing persistent browser state (cookies, localStorage, sessionStorage).",
+}
+
+var stateListCmd = &cobra.Command{
+ Use: "list",
+ Short: "List saved state files",
+ Long: "List all saved state files in the state directory.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StateList(rt.client, rt.base, rt.token)
+ })
+ },
+}
+
+var stateSaveCmd = &cobra.Command{
+ Use: "save",
+ Short: "Save current browser state",
+ Long: "Capture cookies, localStorage, and sessionStorage for the active tab and persist to disk. Requires security.allowStateExport=true.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StateSave(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var stateLoadCmd = &cobra.Command{
+ Use: "load",
+ Short: "Load and restore a saved state",
+ Long: "Restore cookies and storage from a previously saved state file. Supports exact name or prefix matching (most recent match is used). Requires security.allowStateExport=true.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StateLoad(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var stateShowCmd = &cobra.Command{
+ Use: "show",
+ Short: "Show state file details",
+ Long: "Display the full contents of a saved state file including cookies and storage. Requires security.allowStateExport=true.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StateShow(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var stateDeleteCmd = &cobra.Command{
+ Use: "delete",
+ Short: "Delete a saved state file",
+ Long: "Remove a named state file from the state directory. Requires security.allowStateExport=true.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StateDelete(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var stateCleanCmd = &cobra.Command{
+ Use: "clean",
+ Short: "Remove old state files",
+ Long: "Delete state files older than a given number of hours (default: 24). Requires security.allowStateExport=true.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StateClean(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+func init() {
+ stateCmd.AddCommand(stateListCmd, stateSaveCmd, stateLoadCmd, stateShowCmd, stateDeleteCmd, stateCleanCmd)
+
+ // save flags
+ stateSaveCmd.Flags().String("name", "", "Name for the saved state (auto-generated if omitted)")
+ stateSaveCmd.Flags().Bool("encrypt", false, "Encrypt the state file using PINCHTAB_STATE_KEY")
+ addTabFlag(stateSaveCmd)
+
+ // load flags
+ stateLoadCmd.Flags().String("name", "", "Exact name or prefix of the state file to load")
+ _ = stateLoadCmd.MarkFlagRequired("name")
+ addTabFlag(stateLoadCmd)
+
+ // show flags
+ stateShowCmd.Flags().String("name", "", "Name of the state file to inspect")
+ _ = stateShowCmd.MarkFlagRequired("name")
+
+ // delete flags
+ stateDeleteCmd.Flags().String("name", "", "Name of the state file to delete")
+ _ = stateDeleteCmd.MarkFlagRequired("name")
+
+ // clean flags
+ stateCleanCmd.Flags().Int("older-than", 24, "Remove files older than this many hours")
+}
diff --git a/cmd/pinchtab/cmd_cli_storage.go b/cmd/pinchtab/cmd_cli_storage.go
new file mode 100644
index 00000000..de673a72
--- /dev/null
+++ b/cmd/pinchtab/cmd_cli_storage.go
@@ -0,0 +1,79 @@
+package main
+
+import (
+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/spf13/cobra"
+)
+
+var storageCmd = &cobra.Command{
+ Use: "storage",
+ Short: "Manage browser storage",
+ Long: "Commands for reading and writing localStorage and sessionStorage for the active tab's origin.",
+}
+
+var storageGetCmd = &cobra.Command{
+ Use: "get",
+ Short: "Get storage items",
+ Long: "Read localStorage or sessionStorage items for the active tab. Use --type to select local|session (default: both). Use --key to fetch a single item.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StorageGet(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var storageSetCmd = &cobra.Command{
+ Use: "set <key> <value>",
+ Short: "Set a storage item",
+ Long: "Write a single key/value pair to localStorage or sessionStorage. Use --type local|session (default: local).",
+ Args: cobra.ExactArgs(2),
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StorageSet(rt.client, rt.base, rt.token, cmd, args[0], args[1])
+ })
+ },
+}
+
+var storageDeleteCmd = &cobra.Command{
+ Use: "delete",
+ Short: "Delete a specific storage key",
+ Long: "Remove a single key from localStorage or sessionStorage. Use --key and --type local|session.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StorageDelete(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+var storageClearCmd = &cobra.Command{
+ Use: "clear",
+ Short: "Clear storage",
+ Long: "Clear localStorage, sessionStorage, or both. Use --type local|session to clear one, or --all to clear both in a single call.",
+ Run: func(cmd *cobra.Command, args []string) {
+ runCLI(func(rt cliRuntime) {
+ browseractions.StorageClear(rt.client, rt.base, rt.token, cmd)
+ })
+ },
+}
+
+func init() {
+ storageCmd.AddCommand(storageGetCmd, storageSetCmd, storageDeleteCmd, storageClearCmd)
+
+ // Shared tab flag
+ addTabFlag(storageGetCmd, storageSetCmd, storageDeleteCmd, storageClearCmd)
+
+ // get flags
+ storageGetCmd.Flags().String("type", "", "Storage type: local, session (default: both)")
+ storageGetCmd.Flags().String("key", "", "Specific key to retrieve")
+
+ // set flags
+ storageSetCmd.Flags().String("type", "local", "Storage type: local or session")
+
+ // delete flags
+ storageDeleteCmd.Flags().String("type", "local", "Storage type: local or session")
+ storageDeleteCmd.Flags().String("key", "", "Key to remove (omit to clear entire store)")
+
+ // clear flags
+ storageClearCmd.Flags().String("type", "local", "Storage type: local or session")
+ storageClearCmd.Flags().Bool("all", false, "Clear both localStorage and sessionStorage")
+}
diff --git a/internal/cli/actions/actions_state.go b/internal/cli/actions/actions_state.go
new file mode 100644
index 00000000..94b19e85
--- /dev/null
+++ b/internal/cli/actions/actions_state.go
@@ -0,0 +1,136 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+// StateList lists all saved state files.
+func StateList(client *http.Client, base, token string) {
+ result := apiclient.DoGetRaw(client, base, token, "/state/list", nil)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to list state files")
+ os.Exit(1)
+ }
+
+ var buf map[string]any
+ if err := json.Unmarshal(result, &buf); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse response: %v\n", err)
+ os.Exit(1)
+ }
+
+ out, _ := json.MarshalIndent(buf, "", " ")
+ fmt.Println(string(out))
+}
+
+// StateSave captures the current browser state and saves it to disk.
+func StateSave(client *http.Client, base, token string, cmd *cobra.Command) {
+ name, _ := cmd.Flags().GetString("name")
+ encrypt, _ := cmd.Flags().GetBool("encrypt")
+ tabID, _ := cmd.Flags().GetString("tab")
+
+ body := map[string]any{
+ "name": name,
+ "encrypt": encrypt,
+ }
+ if tabID != "" {
+ body["tabId"] = tabID
+ }
+
+ result := apiclient.DoPost(client, base, token, "/state/save", body)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to save state")
+ os.Exit(1)
+ }
+}
+
+// StateLoad restores a saved state into the browser.
+// Supports exact name or prefix-based loading (most recent match).
+func StateLoad(client *http.Client, base, token string, cmd *cobra.Command) {
+ name, _ := cmd.Flags().GetString("name")
+ tabID, _ := cmd.Flags().GetString("tab")
+
+ if name == "" {
+ fmt.Fprintln(os.Stderr, "Error: --name is required")
+ os.Exit(1)
+ }
+
+ body := map[string]any{
+ "name": name,
+ }
+ if tabID != "" {
+ body["tabId"] = tabID
+ }
+
+ result := apiclient.DoPost(client, base, token, "/state/load", body)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to load state")
+ os.Exit(1)
+ }
+}
+
+// StateShow shows full details of a saved state file.
+func StateShow(client *http.Client, base, token string, cmd *cobra.Command) {
+ name, _ := cmd.Flags().GetString("name")
+ if name == "" {
+ fmt.Fprintln(os.Stderr, "Error: --name is required")
+ os.Exit(1)
+ }
+
+ params := url.Values{}
+ params.Set("name", name)
+
+ result := apiclient.DoGetRaw(client, base, token, "/state/show", params)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to show state")
+ os.Exit(1)
+ }
+
+ var buf map[string]any
+ if err := json.Unmarshal(result, &buf); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse response: %v\n", err)
+ os.Exit(1)
+ }
+
+ out, _ := json.MarshalIndent(buf, "", " ")
+ fmt.Println(string(out))
+}
+
+// StateDelete removes a saved state file by name.
+func StateDelete(client *http.Client, base, token string, cmd *cobra.Command) {
+ name, _ := cmd.Flags().GetString("name")
+ if name == "" {
+ fmt.Fprintln(os.Stderr, "Error: --name is required")
+ os.Exit(1)
+ }
+
+ params := url.Values{}
+ params.Set("name", name)
+
+ result := apiclient.DoDelete(client, base, token, "/state", params)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to delete state")
+ os.Exit(1)
+ }
+}
+
+// StateClean removes state files older than the given number of hours.
+func StateClean(client *http.Client, base, token string, cmd *cobra.Command) {
+ hours, _ := cmd.Flags().GetInt("older-than")
+
+ body := map[string]any{
+ "olderThanHours": hours,
+ }
+
+ result := apiclient.DoPost(client, base, token, "/state/clean", body)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to clean state files")
+ os.Exit(1)
+ }
+}
diff --git a/internal/cli/actions/actions_storage.go b/internal/cli/actions/actions_storage.go
new file mode 100644
index 00000000..2b460080
--- /dev/null
+++ b/internal/cli/actions/actions_storage.go
@@ -0,0 +1,101 @@
+package actions
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+// StorageGet retrieves localStorage and/or sessionStorage items for the active tab.
+func StorageGet(client *http.Client, base, token string, cmd *cobra.Command) {
+ params := url.Values{}
+ if t, _ := cmd.Flags().GetString("type"); t != "" {
+ params.Set("type", t)
+ }
+ if k, _ := cmd.Flags().GetString("key"); k != "" {
+ params.Set("key", k)
+ }
+ if tab, _ := cmd.Flags().GetString("tab"); tab != "" {
+ params.Set("tabId", tab)
+ }
+
+ result := apiclient.DoGetRaw(client, base, token, "/storage", params)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to get storage")
+ os.Exit(1)
+ }
+
+ var buf map[string]any
+ if err := json.Unmarshal(result, &buf); err != nil {
+ fmt.Fprintf(os.Stderr, "Failed to parse response: %v\n", err)
+ os.Exit(1)
+ }
+
+ out, _ := json.MarshalIndent(buf, "", " ")
+ fmt.Println(string(out))
+}
+
+// StorageSet sets a single localStorage or sessionStorage item.
+func StorageSet(client *http.Client, base, token string, cmd *cobra.Command, key, value string) {
+ storageType, _ := cmd.Flags().GetString("type")
+ if storageType == "" {
+ storageType = "local"
+ }
+ tabID, _ := cmd.Flags().GetString("tab")
+
+ body := map[string]any{
+ "key": key,
+ "value": value,
+ "type": storageType,
+ }
+ if tabID != "" {
+ body["tabId"] = tabID
+ }
+
+ result := apiclient.DoPost(client, base, token, "/storage", body)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to set storage item")
+ os.Exit(1)
+ }
+}
+
+// StorageDelete removes a storage item, clears a store, or clears both (--all).
+func StorageDelete(client *http.Client, base, token string, cmd *cobra.Command) {
+ storageType, _ := cmd.Flags().GetString("type")
+ key, _ := cmd.Flags().GetString("key")
+ all, _ := cmd.Flags().GetBool("all")
+ tabID, _ := cmd.Flags().GetString("tab")
+
+ if all {
+ storageType = "all"
+ }
+ if storageType == "" {
+ storageType = "local"
+ }
+
+ body := map[string]any{
+ "type": storageType,
+ }
+ if key != "" {
+ body["key"] = key
+ }
+ if tabID != "" {
+ body["tabId"] = tabID
+ }
+
+ result := apiclient.DoPost(client, base, token, "/storage", body)
+ if result == nil {
+ fmt.Fprintln(os.Stderr, "Failed to delete storage")
+ os.Exit(1)
+ }
+}
+
+// StorageClear clears storage (alias: passes type=all or the given type).
+func StorageClear(client *http.Client, base, token string, cmd *cobra.Command) {
+ StorageDelete(client, base, token, cmd)
+}
diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.go
index dea9001f..4b7bfabf 100644
--- a/internal/cli/apiclient/client.go
+++ b/internal/cli/apiclient/client.go
@@ -106,6 +106,41 @@ func DoPost(client *http.Client, base, token, path string, body map[string]any)
return result
}
+// DoDelete sends a DELETE request with an optional JSON body (e.g. for ?name= query params, pass nil body and handle params in path).
+func DoDelete(client *http.Client, base, token, path string, params url.Values) map[string]any {
+ u := base + path
+ if len(params) > 0 {
+ u += "?" + params.Encode()
+ }
+ req, _ := http.NewRequest("DELETE", u, nil)
+ setAuthHeader(req, token)
+ req.Header.Set(activity.HeaderAgentID, "cli")
+ resp, err := client.Do(req)
+ if err != nil {
+ fatal("Request failed: %v", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ respBody, _ := io.ReadAll(resp.Body)
+
+ if resp.StatusCode >= 400 {
+ handleAPIError(resp.StatusCode, respBody)
+ os.Exit(1)
+ }
+
+ var buf bytes.Buffer
+ if json.Indent(&buf, respBody, "", " ") == nil {
+ fmt.Println(buf.String())
+ } else {
+ fmt.Println(string(respBody))
+ }
+
+ var result map[string]any
+ if err := json.Unmarshal(respBody, &result); err != nil {
+ log.Printf("warning: error unmarshaling response: %v", err)
+ }
+ return result
+}
+
// ResolveInstanceBase fetches the named instance from the orchestrator and returns
// a base URL pointing directly at that instance's API port.
func ResolveInstanceBase(orchBase, token, instanceID, bind string) string {
diff --git a/internal/handlers/state.go b/internal/handlers/state.go
index 9d435dd0..4e871017 100644
--- a/internal/handlers/state.go
+++ b/internal/handlers/state.go
@@ -254,6 +254,9 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {
// HandleStateLoad reads a state file and restores cookies and storage into the browser.
// Gated behind CapStateExport: restoring cookies/storage is session injection.
//
+// If the given name has no exact match, the most recent file whose name starts
+// with the given prefix is used (prefix-based loading).
+//
// @Endpoint POST /state/load
func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {
if !h.stateExportEnabled() {
@@ -279,6 +282,17 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {
encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")
path := state.ResolvePath(h.Config.StateDir, req.Name)
+ // If no exact file found, try prefix-based resolution (most recent match).
+ if path == "" {
+ matches, err := state.FindByPrefix(h.Config.StateDir, req.Name)
+ if err != nil || len(matches) == 0 {
+ httpx.Error(w, 404, fmt.Errorf("no state file found for name or prefix %q", req.Name))
+ return
+ }
+ // Matches are sorted newest first; use the first.
+ path = state.ResolvePath(h.Config.StateDir, matches[0].Name)
+ }
+
sf, err := state.Load(path, encryptionKey)
if err != nil {
// Retry without encryption key in case the file is not encrypted
diff --git a/internal/handlers/storage.go b/internal/handlers/storage.go
index 8ea9612b..c8d7ce77 100644
--- a/internal/handlers/storage.go
+++ b/internal/handlers/storage.go
@@ -164,6 +164,7 @@ func (h *Handlers) handleStorageSet(w http.ResponseWriter, r *http.Request) {
}
// handleStorageDelete removes a storage item or clears storage.
+// Supports type=local, type=session, or type=all (clears both).
func (h *Handlers) handleStorageDelete(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
@@ -176,11 +177,16 @@ func (h *Handlers) handleStorageDelete(w http.ResponseWriter, r *http.Request) {
}
if req.Type == "" {
- httpx.Error(w, 400, fmt.Errorf("type is required (local or session)"))
+ httpx.Error(w, 400, fmt.Errorf("type is required (local, session, or all)"))
return
}
- if req.Type != "local" && req.Type != "session" {
- httpx.Error(w, 400, fmt.Errorf("type must be 'local' or 'session'"))
+ if req.Type != "local" && req.Type != "session" && req.Type != "all" {
+ httpx.Error(w, 400, fmt.Errorf("type must be 'local', 'session', or 'all'"))
+ return
+ }
+ // key is not compatible with type=all
+ if req.Type == "all" && req.Key != "" {
+ httpx.Error(w, 400, fmt.Errorf("key cannot be used with type=all; omit key to clear both storages"))
return
}
@@ -330,8 +336,24 @@ func buildStorageGetScript(storageType, key string) string {
}
// buildStorageDeleteScript builds a JS expression that removes a specific key
-// or clears the entire storage. Returns a JSON string with success/origin fields.
+// or clears the entire storage. Supports type local, session, or all.
+// Returns a JSON string with success/origin fields.
func buildStorageDeleteScript(storageType, key string) string {
+ // type=all: clear both localStorage and sessionStorage
+ if storageType == "all" {
+ return `
+ (function() {
+ try {
+ localStorage.clear();
+ sessionStorage.clear();
+ return JSON.stringify({success: true, action: "clear", type: "all", origin: window.location.origin});
+ } catch(e) {
+ return JSON.stringify({success: false, error: e.message, origin: window.location.origin});
+ }
+ })()
+ `
+ }
+
storageObj := "localStorage"
if storageType == "session" {
storageObj = "sessionStorage"
diff --git a/internal/state/state.go b/internal/state/state.go
index 41198e2d..d6df6b2f 100644
--- a/internal/state/state.go
+++ b/internal/state/state.go
@@ -75,8 +75,18 @@ func EnsureSessionsDir(stateDir string) (string, error) {
return dir, nil
}
+// fileExtension returns the appropriate file extension based on whether the file
+// is encrypted. Encrypted files use .json.enc; plaintext files use .json.
+func fileExtension(encrypted bool) string {
+ if encrypted {
+ return ".json.enc"
+ }
+ return ".json"
+}
+
// Save writes a StateFile to disk. If encryptionKey is non-empty, the payload
-// is encrypted with AES-256-GCM before writing.
+// is encrypted with AES-256-GCM before writing. Encrypted files use the
+// .json.enc extension; plaintext files use .json.
func Save(stateDir string, sf *StateFile, encryptionKey string) (string, error) {
dir, err := EnsureSessionsDir(stateDir)
if err != nil {
@@ -102,7 +112,8 @@ func Save(stateDir string, sf *StateFile, encryptionKey string) (string, error)
sf.Encrypted = true
}
- filename := sanitizeFilename(sf.Name) + ".json"
+ ext := fileExtension(encryptionKey != "")
+ filename := sanitizeFilename(sf.Name) + ext
path := filepath.Join(dir, filename)
if err := os.WriteFile(path, data, 0600); err != nil {
@@ -136,6 +147,20 @@ func Load(path, encryptionKey string) (*StateFile, error) {
return &sf, nil
}
+// isStateFile reports whether a directory entry is a recognised state file
+// (either .json or .json.enc).
+func isStateFile(name string) bool {
+ return strings.HasSuffix(name, ".json") || strings.HasSuffix(name, ".json.enc")
+}
+
+// trimStateExt removes the state file extension (.json or .json.enc) from a filename.
+func trimStateExt(name string) string {
+ if strings.HasSuffix(name, ".json.enc") {
+ return strings.TrimSuffix(name, ".json.enc")
+ }
+ return strings.TrimSuffix(name, ".json")
+}
+
// List returns summaries of all saved state files in the sessions directory.
func List(stateDir string) ([]StateEntry, error) {
dir := SessionsDir(stateDir)
@@ -150,7 +175,7 @@ func List(stateDir string) ([]StateEntry, error) {
var result []StateEntry
for _, entry := range entries {
- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
+ if entry.IsDir() || !isStateFile(entry.Name()) {
continue
}
@@ -161,7 +186,7 @@ func List(stateDir string) ([]StateEntry, error) {
path := filepath.Join(dir, entry.Name())
se := StateEntry{
- Name: strings.TrimSuffix(entry.Name(), ".json"),
+ Name: trimStateExt(entry.Name()),
SizeBytes: info.Size(),
}
@@ -190,22 +215,43 @@ func List(stateDir string) ([]StateEntry, error) {
return result, nil
}
-// Delete removes a named state file.
+// FindByPrefix returns state entries whose name starts with the given prefix,
+// sorted newest first. Used by --name prefix loading in state load.
+func FindByPrefix(stateDir, prefix string) ([]StateEntry, error) {
+ if prefix == "" {
+ return nil, fmt.Errorf("prefix must not be empty")
+ }
+ all, err := List(stateDir)
+ if err != nil {
+ return nil, err
+ }
+ var matched []StateEntry
+ for _, e := range all {
+ if strings.HasPrefix(e.Name, prefix) {
+ matched = append(matched, e)
+ }
+ }
+ return matched, nil
+}
+
+// Delete removes a named state file. Tries .json.enc first, falls back to .json.
func Delete(stateDir, name string) error {
dir := SessionsDir(stateDir)
- filename := sanitizeFilename(name) + ".json"
- path := filepath.Join(dir, filename)
-
- if err := os.Remove(path); err != nil {
- if os.IsNotExist(err) {
- return fmt.Errorf("state file %q not found", name)
+ base := sanitizeFilename(name)
+ // Try encrypted extension first.
+ for _, ext := range []string{".json.enc", ".json"} {
+ path := filepath.Join(dir, base+ext)
+ if err := os.Remove(path); err == nil {
+ return nil
+ } else if !os.IsNotExist(err) {
+ return fmt.Errorf("delete state file: %w", err)
}
- return fmt.Errorf("delete state file: %w", err)
}
- return nil
+ return fmt.Errorf("state file %q not found", name)
}
// Clean removes state files older than the given duration.
+// Handles both .json and .json.enc extensions.
func Clean(stateDir string, olderThan time.Duration) (int, error) {
dir := SessionsDir(stateDir)
cutoff := time.Now().Add(-olderThan)
@@ -220,7 +266,7 @@ func Clean(stateDir string, olderThan time.Duration) (int, error) {
removed := 0
for _, entry := range entries {
- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
+ if entry.IsDir() || !isStateFile(entry.Name()) {
continue
}
@@ -346,12 +392,24 @@ func sanitizeFilename(name string) string {
}
// ResolvePath returns the full canonical path for a named state file.
+// Tries .json.enc first (encrypted), then .json (plaintext).
// Returns an empty string if the resolved path attempts to escape stateDir.
func ResolvePath(stateDir, name string) string {
dir := SessionsDir(stateDir)
- filename := sanitizeFilename(name) + ".json"
- resolved := filepath.Clean(filepath.Join(dir, filename))
- // Belt-and-suspenders: reject if the canonical path escapes the sessions dir.
+ base := sanitizeFilename(name)
+ // Try encrypted extension first, then plaintext.
+ for _, ext := range []string{".json.enc", ".json"} {
+ resolved := filepath.Clean(filepath.Join(dir, base+ext))
+ cleanDir := filepath.Clean(dir) + string(os.PathSeparator)
+ if !strings.HasPrefix(resolved, cleanDir) {
+ return ""
+ }
+ if _, err := os.Stat(resolved); err == nil {
+ return resolved
+ }
+ }
+ // File doesn't exist yet — return the .json path (for new saves).
+ resolved := filepath.Clean(filepath.Join(dir, base+".json"))
cleanDir := filepath.Clean(dir) + string(os.PathSeparator)
if !strings.HasPrefix(resolved, cleanDir) {
return ""
diff --git a/tests/e2e/scenarios-api/state-basic.sh b/tests/e2e/scenarios-api/state-basic.sh
new file mode 100644
index 00000000..8e2a87c8
--- /dev/null
+++ b/tests/e2e/scenarios-api/state-basic.sh
@@ -0,0 +1,112 @@
+#!/bin/bash
+# state-basic.sh — State management API tests.
+# Requires: a running PinchTab instance with security.allowStateExport=true.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/api.sh"
+
+STATE_NAME="pt-e2e-state-$(date +%s)"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /state/list returns state list"
+
+pt_get "/state/list"
+assert_ok "list states"
+assert_json_exists "$RESULT" '.states' "has states array"
+assert_json_exists "$RESULT" '.count' "has count"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /state/save captures browser state"
+
+pt_post "/state/save" -d "{\"name\":\"${STATE_NAME}\"}"
+assert_ok "save state"
+assert_json_exists "$RESULT" '.name' "has name"
+assert_json_contains "$RESULT" '.name' "${STATE_NAME}" "name matches"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /state/list includes newly saved state"
+
+pt_get "/state/list"
+assert_ok "list after save"
+COUNT=$(echo "$RESULT" | jq '.count')
+if [ "$COUNT" -gt "0" ]; then
+ echo -e " ${GREEN}✓${NC} state count > 0"
+ ((ASSERTIONS_PASSED++)) || true
+else
+ echo -e " ${RED}✗${NC} expected at least 1 state, got $COUNT"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /state/show returns full state details"
+
+pt_get "/state/show?name=${STATE_NAME}"
+assert_ok "show state"
+assert_json_exists "$RESULT" '.name' "has name"
+assert_json_exists "$RESULT" '.cookies' "has cookies array"
+assert_json_exists "$RESULT" '.storage' "has storage map"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /state/load restores the saved state"
+
+pt_post "/state/load" -d "{\"name\":\"${STATE_NAME}\"}"
+assert_ok "load state"
+assert_json_exists "$RESULT" '.name' "has name"
+assert_json_exists "$RESULT" '.cookiesRestored' "has cookiesRestored"
+assert_json_exists "$RESULT" '.storageItemsRestored' "has storageItemsRestored"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /state/load with prefix finds most recent match"
+
+PREFIX=$(echo "$STATE_NAME" | cut -c1-8)
+pt_post "/state/load" -d "{\"name\":\"${PREFIX}\"}"
+assert_ok "load by prefix"
+assert_json_exists "$RESULT" '.name' "has name"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "DELETE /state removes the saved state"
+
+pt_delete "/state?name=${STATE_NAME}"
+assert_ok "delete state"
+assert_json_exists "$RESULT" '.deleted' "has deleted field"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "DELETE /state on nonexistent name returns error"
+
+pt_delete "/state?name=nonexistent_xyz_$(date +%s)"
+assert_not_ok "rejects nonexistent name"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /state/clean removes old files (olderThanHours=0 for test)"
+
+# Use 9999 hours so nothing real gets removed in test environment.
+pt_post "/state/clean" -d '{"olderThanHours":9999}'
+assert_ok "clean states"
+assert_json_exists "$RESULT" '.removed' "has removed count"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /state/save rejects missing name if auto-name not acceptable"
+
+# PinchTab auto-generates a name when none is provided — this is valid.
+pt_post "/state/save" -d '{}'
+assert_ok "save with auto-generated name"
+
+end_test
diff --git a/tests/e2e/scenarios-api/storage-basic.sh b/tests/e2e/scenarios-api/storage-basic.sh
new file mode 100644
index 00000000..c5106cd5
--- /dev/null
+++ b/tests/e2e/scenarios-api/storage-basic.sh
@@ -0,0 +1,93 @@
+#!/bin/bash
+# storage-basic.sh — Storage API (localStorage/sessionStorage) tests.
+# Requires: a running PinchTab instance with security.allowStateExport=true
+# and an active tab navigated to a page (e.g. https://example.com).
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/api.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /storage sets a localStorage item"
+
+pt_post "/storage" -d '{"key":"pt_test_key","value":"pt_test_value","type":"local"}'
+assert_ok "set localStorage item"
+assert_json_exists "$RESULT" '.success' "has success field"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /storage reads back the set item"
+
+pt_get "/storage?type=local&key=pt_test_key"
+assert_ok "get localStorage item"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /storage sets a sessionStorage item"
+
+pt_post "/storage" -d '{"key":"pt_sess_key","value":"pt_sess_value","type":"session"}'
+assert_ok "set sessionStorage item"
+assert_json_exists "$RESULT" '.success' "has success field"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /storage with no type returns both stores"
+
+pt_get "/storage"
+assert_ok "get all storage"
+assert_json_exists "$RESULT" '.local' "has local field"
+assert_json_exists "$RESULT" '.session' "has session field"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "DELETE /storage removes a specific localStorage key"
+
+pt_delete "/storage" -d '{"key":"pt_test_key","type":"local"}'
+assert_ok "delete localStorage key"
+assert_json_exists "$RESULT" '.success' "has success field"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "DELETE /storage with type=all clears both stores"
+
+# First seed both stores
+pt_post "/storage" -d '{"key":"all_local","value":"1","type":"local"}'
+assert_ok "seed localStorage"
+
+pt_post "/storage" -d '{"key":"all_session","value":"2","type":"session"}'
+assert_ok "seed sessionStorage"
+
+# Then clear both
+pt_delete "/storage" -d '{"type":"all"}'
+assert_ok "delete type=all"
+assert_json_exists "$RESULT" '.success' "has success"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /storage rejects missing key"
+
+pt_post "/storage" -d '{"value":"v","type":"local"}'
+assert_not_ok "rejects missing key"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /storage rejects invalid type"
+
+pt_post "/storage" -d '{"key":"k","value":"v","type":"invalid"}'
+assert_not_ok "rejects invalid type"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /storage returns 403 when allowStateExport=false"
+
+# This test is advisory — only run when storage gate is disabled.
+# The assertion is informational; actual gate test is in security-basic.sh.
+
+end_test
diff --git a/tests/e2e/scenarios-cli/state-basic.sh b/tests/e2e/scenarios-cli/state-basic.sh
new file mode 100644
index 00000000..2542c854
--- /dev/null
+++ b/tests/e2e/scenarios-cli/state-basic.sh
@@ -0,0 +1,64 @@
+#!/bin/bash
+# state-basic.sh — CLI tests for `pinchtab state` commands.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/cli.sh"
+
+STATE_NAME="cli-e2e-state-$(date +%s)"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state list shows saved states"
+
+pt_cli state list
+assert_cli_ok "list states"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state save captures current browser state"
+
+pt_cli state save --name "$STATE_NAME"
+assert_cli_ok "save state"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state show displays state details"
+
+pt_cli state show --name "$STATE_NAME"
+assert_cli_ok "show state"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state load restores saved state (exact name)"
+
+pt_cli state load --name "$STATE_NAME"
+assert_cli_ok "load exact name"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state load restores saved state (prefix)"
+
+PREFIX=$(echo "$STATE_NAME" | cut -c1-8)
+pt_cli state load --name "$PREFIX"
+assert_cli_ok "load by prefix"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state delete removes the saved state"
+
+pt_cli state delete --name "$STATE_NAME"
+assert_cli_ok "delete state"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state clean runs without error"
+
+pt_cli state clean --older-than 9999
+assert_cli_ok "clean old states"
+
+end_test
diff --git a/tests/e2e/scenarios-cli/storage-basic.sh b/tests/e2e/scenarios-cli/storage-basic.sh
new file mode 100644
index 00000000..fbcd1223
--- /dev/null
+++ b/tests/e2e/scenarios-cli/storage-basic.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+# storage-basic.sh — CLI tests for `pinchtab storage` commands.
+
+GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+source "${GROUP_DIR}/../helpers/cli.sh"
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage set writes a localStorage item"
+
+pt_cli storage set pt_cli_key pt_cli_value --type local
+assert_cli_ok "set local item"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage get reads back the item"
+
+pt_cli storage get --type local --key pt_cli_key
+assert_cli_ok "get local item"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage set writes a sessionStorage item"
+
+pt_cli storage set pt_sess_key pt_sess_value --type session
+assert_cli_ok "set session item"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage delete removes a key"
+
+pt_cli storage delete --key pt_cli_key --type local
+assert_cli_ok "delete local key"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage clear --all clears both stores"
+
+pt_cli storage clear --all
+assert_cli_ok "clear --all"
+
+end_test