Skip to content

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

fix: complete storage & state management (issue #417)

Luigi Agostidc36feb05ea5
diff --git a/cmd/pinchtab/cmd_cli_state.go b/cmd/pinchtab/cmd_cli_state.go
index 3b634328..de810c16 100644
--- a/cmd/pinchtab/cmd_cli_state.go
+++ b/cmd/pinchtab/cmd_cli_state.go
@@ -82,7 +82,7 @@ func init() {
// 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")
+ stateSaveCmd.Flags().Bool("encrypt", false, "Encrypt the state file (requires security.stateEncryptionKey in config)")
addTabFlag(stateSaveCmd)
// load flags
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 90881b5a..80b52073 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -293,9 +293,9 @@ State management saves and restores browser state (cookies, localStorage, sessio
Notes:
-- `/storage`, `/tabs/{id}/storage`, `GET /state/show`, `POST /state/save`, `POST /state/load`, `DELETE /state`, and `POST /state/clean` are gated by `security.allowStateExport`
+- All state and storage endpoints are gated by `security.allowStateExport`: `/storage`, `/tabs/{id}/storage`, `GET /state/list`, `GET /state/show`, `POST /state/save`, `POST /state/load`, `DELETE /state`, and `POST /state/clean`
- state files are stored in `{stateDir}/sessions/` with `0600` permissions
-- optional AES-256-GCM encryption via `PINCHTAB_STATE_KEY` environment variable
+- optional AES-256-GCM encryption via `security.stateEncryptionKey` config setting
- storage is captured only for the current origin (active tab)
`POST /state/save` body fields:
@@ -510,7 +510,7 @@ These gates are not ordinary feature toggles. Enabling them is a documented, non
- clipboard routes -> `security.allowClipboard`
- attach routes -> `security.attach`
- screencast routes -> `security.allowScreencast`
-- storage routes and the full state-management family (`/state/show`, `/state/save`, `/state/load`, `DELETE /state`, `POST /state/clean`) -> `security.allowStateExport`
+- storage routes (`/storage`, `/tabs/{id}/storage`) and the full state-management family (`/state/list`, `/state/show`, `/state/save`, `/state/load`, `DELETE /state`, `POST /state/clean`) -> `security.allowStateExport`
## Error Response Format
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index c1d04991..ba941e61 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -214,6 +214,7 @@ type securityConfigJSON struct {
AllowUpload *bool `json:"allowUpload"`
AllowClipboard *bool `json:"allowClipboard"`
AllowStateExport *bool `json:"allowStateExport"`
+ StateEncryptionKey *string `json:"stateEncryptionKey"`
EnableActionGuards *bool `json:"enableActionGuards"`
UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes"`
UploadMaxFiles *int `json:"uploadMaxFiles"`
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 700e419f..7c5ffeaa 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -30,6 +30,7 @@ func Load() *RuntimeConfig {
AllowUpload: false,
AllowClipboard: false,
AllowStateExport: false,
+ StateEncryptionKey: "",
EnableActionGuards: true,
UploadMaxRequestBytes: DefaultUploadMaxRequestBytes,
UploadMaxFiles: DefaultUploadMaxFiles,
@@ -247,6 +248,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
if fc.Security.AllowStateExport != nil {
cfg.AllowStateExport = *fc.Security.AllowStateExport
}
+ if fc.Security.StateEncryptionKey != nil {
+ cfg.StateEncryptionKey = *fc.Security.StateEncryptionKey
+ }
if fc.Security.EnableActionGuards != nil {
cfg.EnableActionGuards = *fc.Security.EnableActionGuards
}
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index 915b03cf..3c675ad0 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -27,7 +27,8 @@ type RuntimeConfig struct {
AllowUpload bool
AllowClipboard bool
AllowStateExport bool
- EnableActionGuards bool // Enable bridge-level stale/navigation guard checks around actions
+ StateEncryptionKey string // Key for encrypting state files (AES-256-GCM)
+ EnableActionGuards bool // Enable bridge-level stale/navigation guard checks around actions
UploadMaxRequestBytes int
UploadMaxFiles int
UploadMaxFileBytes int
@@ -273,6 +274,7 @@ type SecurityConfig struct {
AllowUpload *bool `json:"allowUpload,omitempty"`
AllowClipboard *bool `json:"allowClipboard,omitempty"`
AllowStateExport *bool `json:"allowStateExport,omitempty"`
+ StateEncryptionKey *string `json:"stateEncryptionKey,omitempty"`
EnableActionGuards *bool `json:"enableActionGuards,omitempty"`
UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes,omitempty"`
UploadMaxFiles *int `json:"uploadMaxFiles,omitempty"`
diff --git a/internal/daemon/bootstrap_test.go b/internal/daemon/bootstrap_test.go
index 3bab7c63..0f4a2476 100644
--- a/internal/daemon/bootstrap_test.go
+++ b/internal/daemon/bootstrap_test.go
@@ -11,7 +11,6 @@ func TestEnsureConfigCreatesDefaultConfig(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
t.Setenv("PINCHTAB_CONFIG", configPath)
t.Setenv("PINCHTAB_TOKEN", "")
- t.Setenv("PINCHTAB_BIND", "")
gotPath, cfg, status, err := EnsureConfig(false)
if err != nil {
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 9da296ad..d005a470 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -232,6 +232,9 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("GET /storage", h.HandleStorage)
mux.HandleFunc("POST /storage", h.HandleStorage)
mux.HandleFunc("DELETE /storage", h.HandleStorage)
+ mux.HandleFunc("GET /tabs/{id}/storage", h.HandleTabStorageGet)
+ mux.HandleFunc("POST /tabs/{id}/storage", h.HandleTabStorageSet)
+ mux.HandleFunc("DELETE /tabs/{id}/storage", h.HandleTabStorageDelete)
// State management
mux.HandleFunc("GET /state/list", h.HandleStateList)
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index 0971d273..36742671 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -89,8 +89,29 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
"x-pinchtab-enabled": security["stateExport"].Enabled,
},
},
- "/state/list": map[string]any{"get": map[string]any{"summary": "List saved state files"}},
+ "/tabs/{id}/storage": map[string]any{
+ "get": map[string]any{
+ "summary": "Get localStorage/sessionStorage items for a specific tab",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ },
+ "post": map[string]any{
+ "summary": "Set a storage item for a specific tab",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ },
+ "delete": map[string]any{
+ "summary": "Delete storage items for a specific tab",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ },
+ },
// CapStateExport-gated endpoints
+ "/state/list": map[string]any{"get": map[string]any{
+ "summary": "List saved state files",
+ "description": security["stateExport"].Message,
+ "x-pinchtab-enabled": security["stateExport"].Enabled,
+ }},
"/state/show": map[string]any{"get": map[string]any{
"summary": "Show state file details",
"description": security["stateExport"].Message,
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index 7bb7ebde..66614ce5 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -70,7 +70,7 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
Paths: []string{
"GET /storage", "POST /storage", "DELETE /storage",
"GET /tabs/{id}/storage", "POST /tabs/{id}/storage", "DELETE /tabs/{id}/storage",
- "GET /state/show", "POST /state/save",
+ "GET /state/list", "GET /state/show", "POST /state/save",
"POST /state/load", "DELETE /state", "POST /state/clean",
},
},
diff --git a/internal/handlers/state.go b/internal/handlers/state.go
index ef496e72..9771d55f 100644
--- a/internal/handlers/state.go
+++ b/internal/handlers/state.go
@@ -21,9 +21,17 @@ func (h *Handlers) stateExportEnabled() bool {
}
// HandleStateList lists all saved state files.
+// Gated behind CapStateExport (security.allowStateExport).
//
// @Endpoint GET /state/list
func (h *Handlers) HandleStateList(w http.ResponseWriter, r *http.Request) {
+ if !h.stateExportEnabled() {
+ httpx.ErrorCode(w, 403, "state_export_disabled", httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"), false, map[string]any{
+ "setting": "security.allowStateExport",
+ })
+ return
+ }
+
entries, err := state.List(h.Config.StateDir)
if err != nil {
httpx.Error(w, 500, fmt.Errorf("list states: %w", err))
@@ -54,7 +62,7 @@ func (h *Handlers) HandleStateShow(w http.ResponseWriter, r *http.Request) {
return
}
- encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")
+ encryptionKey := h.Config.StateEncryptionKey
path := state.ResolvePath(h.Config.StateDir, name)
sf, err := state.Load(path, encryptionKey)
@@ -94,9 +102,9 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {
encryptionKey := ""
if req.Encrypt {
- encryptionKey = os.Getenv("PINCHTAB_STATE_KEY")
+ encryptionKey = h.Config.StateEncryptionKey
if err := state.ValidateEncryptionKey(encryptionKey); err != nil {
- httpx.Error(w, 400, fmt.Errorf("encryption key required: set PINCHTAB_STATE_KEY environment variable"))
+ httpx.Error(w, 400, fmt.Errorf("encryption key required: set security.stateEncryptionKey in config"))
return
}
}
@@ -279,7 +287,7 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {
return
}
- encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")
+ encryptionKey := h.Config.StateEncryptionKey
path := state.ResolvePath(h.Config.StateDir, req.Name)
// ResolvePath returns a constructed path even when the file doesn't exist
diff --git a/internal/handlers/storage.go b/internal/handlers/storage.go
index d74a17ff..b63b52e0 100644
--- a/internal/handlers/storage.go
+++ b/internal/handlers/storage.go
@@ -1,8 +1,10 @@
package handlers
import (
+ "bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -410,3 +412,110 @@ func buildStorageDeleteScript(storageType, key string) string {
})()
`, storageObj)
}
+
+// HandleTabStorageGet retrieves storage items for a tab identified by path ID.
+//
+// @Endpoint GET /tabs/{id}/storage
+func (h *Handlers) HandleTabStorageGet(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ q := r.URL.Query()
+ q.Set("tabId", tabID)
+
+ req := r.Clone(r.Context())
+ u := *r.URL
+ u.RawQuery = q.Encode()
+ req.URL = &u
+
+ h.handleStorageGet(w, req)
+}
+
+// HandleTabStorageSet sets a storage item for a tab identified by path ID.
+//
+// @Endpoint POST /tabs/{id}/storage
+func (h *Handlers) HandleTabStorageSet(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ body := map[string]any{}
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ if rawTabID, ok := body["tabId"]; ok {
+ if provided, ok := rawTabID.(string); !ok || provided == "" {
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
+ return
+ } else if provided != tabID {
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ return
+ }
+ }
+
+ body["tabId"] = tabID
+
+ payload, err := json.Marshal(body)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
+ return
+ }
+
+ req := r.Clone(r.Context())
+ req.Body = io.NopCloser(bytes.NewReader(payload))
+ req.ContentLength = int64(len(payload))
+ req.Header = r.Header.Clone()
+ req.Header.Set("Content-Type", "application/json")
+ h.handleStorageSet(w, req)
+}
+
+// HandleTabStorageDelete deletes storage items for a tab identified by path ID.
+//
+// @Endpoint DELETE /tabs/{id}/storage
+func (h *Handlers) HandleTabStorageDelete(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ httpx.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ body := map[string]any{}
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ if rawTabID, ok := body["tabId"]; ok {
+ if provided, ok := rawTabID.(string); !ok || provided == "" {
+ httpx.Error(w, 400, fmt.Errorf("invalid tabId"))
+ return
+ } else if provided != tabID {
+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ return
+ }
+ }
+
+ body["tabId"] = tabID
+
+ payload, err := json.Marshal(body)
+ if err != nil {
+ httpx.Error(w, 500, fmt.Errorf("encode: %w", err))
+ return
+ }
+
+ req := r.Clone(r.Context())
+ req.Body = io.NopCloser(bytes.NewReader(payload))
+ req.ContentLength = int64(len(payload))
+ req.Header = r.Header.Clone()
+ req.Header.Set("Content-Type", "application/json")
+ h.handleStorageDelete(w, req)
+}
diff --git a/internal/handlers/storage_test.go b/internal/handlers/storage_test.go
index ac022e78..5383e1e3 100644
--- a/internal/handlers/storage_test.go
+++ b/internal/handlers/storage_test.go
@@ -108,6 +108,136 @@ func TestEndpointSecurityState_IncludesStorageMutations(t *testing.T) {
}
}
+func TestHandleTabStorage_StateExportGateDisabled(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: false}, nil, nil, nil)
+
+ tests := []struct {
+ name string
+ method string
+ handler func(http.ResponseWriter, *http.Request)
+ body string
+ }{
+ {name: "tab get blocked", method: http.MethodGet, handler: h.HandleTabStorageGet},
+ {name: "tab post blocked", method: http.MethodPost, handler: h.HandleTabStorageSet, body: `{"key":"k","value":"v","type":"local"}`},
+ {name: "tab delete blocked", method: http.MethodDelete, handler: h.HandleTabStorageDelete, body: `{"type":"all"}`},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var r *http.Request
+ if tc.body != "" {
+ r = httptest.NewRequest(tc.method, "/tabs/tab_abc/storage", bytes.NewReader([]byte(tc.body)))
+ } else {
+ r = httptest.NewRequest(tc.method, "/tabs/tab_abc/storage", nil)
+ }
+ r.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ tc.handler(w, r)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
+func TestHandleTabStorage_StateExportGateEnabled(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: true}, nil, nil, nil)
+ h.evalJS = func(ctx context.Context, expr string, out *string) error {
+ switch {
+ case bytes.Contains([]byte(expr), []byte("setItem")):
+ *out = `{"success":true,"origin":"http://example.com"}`
+ case bytes.Contains([]byte(expr), []byte("clear")) || bytes.Contains([]byte(expr), []byte("removeItem")):
+ *out = `{"success":true,"origin":"http://example.com"}`
+ default:
+ *out = `{"local":[],"session":[],"origin":"http://example.com"}`
+ }
+ return nil
+ }
+
+ tests := []struct {
+ name string
+ method string
+ handler func(http.ResponseWriter, *http.Request)
+ body string
+ }{
+ {name: "tab get allowed", method: http.MethodGet, handler: h.HandleTabStorageGet},
+ {name: "tab post allowed", method: http.MethodPost, handler: h.HandleTabStorageSet, body: `{"key":"k","value":"v","type":"local"}`},
+ {name: "tab delete allowed", method: http.MethodDelete, handler: h.HandleTabStorageDelete, body: `{"type":"all"}`},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var r *http.Request
+ if tc.body != "" {
+ r = httptest.NewRequest(tc.method, "/tabs/tab_abc/storage", bytes.NewReader([]byte(tc.body)))
+ } else {
+ r = httptest.NewRequest(tc.method, "/tabs/tab_abc/storage", nil)
+ }
+ r.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ tc.handler(w, r)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
+func TestHandleTabStorage_MissingTabID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: true}, nil, nil, nil)
+
+ tests := []struct {
+ name string
+ method string
+ handler func(http.ResponseWriter, *http.Request)
+ }{
+ {name: "get missing id", method: http.MethodGet, handler: h.HandleTabStorageGet},
+ {name: "post missing id", method: http.MethodPost, handler: h.HandleTabStorageSet},
+ {name: "delete missing id", method: http.MethodDelete, handler: h.HandleTabStorageDelete},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ r := httptest.NewRequest(tc.method, "/tabs//storage", nil)
+ w := httptest.NewRecorder()
+ tc.handler(w, r)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
+func TestHandleTabStorage_TabIDMismatch(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: true}, nil, nil, nil)
+
+ tests := []struct {
+ name string
+ method string
+ handler func(http.ResponseWriter, *http.Request)
+ body string
+ }{
+ {name: "post tabId mismatch", method: http.MethodPost, handler: h.HandleTabStorageSet, body: `{"tabId":"tab_other","key":"k","value":"v","type":"local"}`},
+ {name: "delete tabId mismatch", method: http.MethodDelete, handler: h.HandleTabStorageDelete, body: `{"tabId":"tab_other","type":"all"}`},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ r := httptest.NewRequest(tc.method, "/tabs/tab_abc/storage", bytes.NewReader([]byte(tc.body)))
+ r.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ tc.handler(w, r)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
+
func TestOpenAPI_StorageModeledOnceWithMethodMetadata(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{AllowStateExport: false}, nil, nil, nil)
w := httptest.NewRecorder()
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index 0df8cf1f..41e433dc 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -85,6 +85,9 @@ func (o *Orchestrator) registerHandlers(mux *http.ServeMux, skipLaunch bool) {
case routes.CapMacro:
enabled = o.AllowsMacro()
feature, setting, code = "macro", "security.allowMacro", "macro_disabled"
+ case routes.CapStateExport:
+ enabled = o.AllowsStateExport()
+ feature, setting, code = "stateExport", "security.allowStateExport", "state_export_disabled"
}
for _, ep := range eps {
registerCapabilityRoute(mux, ep.TabRoute(), enabled, feature, setting, code, o.proxyTabRequest)
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index b41d5e64..9a39d95b 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -113,8 +113,8 @@ var coreEndpoints = []Endpoint{
{"POST", "/storage", "Set storage item", CapStateExport, true},
{"DELETE", "/storage", "Delete storage items", CapStateExport, true},
- // State management — list is read-only summary, ungated.
- {"GET", "/state/list", "List saved states", CapNone, false},
+ // State management
+ {"GET", "/state/list", "List saved states", CapStateExport, false},
// Capability-gated
{"POST", "/evaluate", "Run JavaScript in page", CapEvaluate, true},
diff --git a/internal/state/state.go b/internal/state/state.go
index 993083b7..36c5b614 100644
--- a/internal/state/state.go
+++ b/internal/state/state.go
@@ -389,7 +389,7 @@ func decryptWithKey(ciphertext, key []byte) ([]byte, error) {
// ValidateEncryptionKey checks that the key is non-empty.
func ValidateEncryptionKey(key string) error {
if key == "" {
- return fmt.Errorf("PINCHTAB_STATE_KEY must be set for encrypted state operations")
+ return fmt.Errorf("security.stateEncryptionKey must be set for encrypted state operations")
}
return nil
}
diff --git a/tests/e2e/config/pinchtab-secure.json b/tests/e2e/config/pinchtab-secure.json
index 726c7754..c7ef39ef 100644
--- a/tests/e2e/config/pinchtab-secure.json
+++ b/tests/e2e/config/pinchtab-secure.json
@@ -22,7 +22,7 @@
"allowEvaluate": false,
"allowDownload": false,
"allowUpload": false,
- "allowStateExport": true,
+ "allowStateExport": false,
"allowedDomains": [
"internal-test.invalid",
"fixtures"
diff --git a/tests/e2e/helpers/base.sh b/tests/e2e/helpers/base.sh
index 798de633..fb98a8d8 100644
--- a/tests/e2e/helpers/base.sh
+++ b/tests/e2e/helpers/base.sh
@@ -50,6 +50,7 @@ TESTS_PASSED="${TESTS_PASSED:-0}"
TESTS_FAILED="${TESTS_FAILED:-0}"
ASSERTIONS_PASSED="${ASSERTIONS_PASSED:-0}"
ASSERTIONS_FAILED="${ASSERTIONS_FAILED:-0}"
+ASSERTIONS_SKIPPED="${ASSERTIONS_SKIPPED:-0}"
TEST_START_TIME="${TEST_START_TIME:-0}"
TEST_START_NS="${TEST_START_NS:-0}"
if [ -z "${TEST_RESULTS_INIT:-}" ]; then
diff --git a/tests/e2e/helpers/cli.sh b/tests/e2e/helpers/cli.sh
index cd036978..c40a863d 100644
--- a/tests/e2e/helpers/cli.sh
+++ b/tests/e2e/helpers/cli.sh
@@ -38,7 +38,7 @@ pt() {
rm -f "$tmpout" "$tmperr"
if [ -n "$PT_OUT" ]; then
- echo "$PT_OUT" | head -5
+ head -5 <<< "$PT_OUT" || true
fi
}
diff --git a/tests/e2e/scenarios-api/security-basic.sh b/tests/e2e/scenarios-api/security-basic.sh
index 57e2c7b9..1f08b3e5 100644
--- a/tests/e2e/scenarios-api/security-basic.sh
+++ b/tests/e2e/scenarios-api/security-basic.sh
@@ -34,3 +34,27 @@ pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"
assert_ok "navigate to allowed domain"
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "security: stateExport ALLOWED when enabled"
+
+pt_get /state/list
+assert_ok "state list allowed"
+
+pt_get /storage
+assert_ok "storage get allowed"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "security: tab-scoped storage ALLOWED when stateExport enabled"
+
+pt_get "/tabs"
+TAB_ID=$(echo "$RESULT" | jq -r '.tabs[0].id // empty')
+
+if [ -n "$TAB_ID" ]; then
+ pt_get "/tabs/${TAB_ID}/storage"
+ assert_ok "tab storage get allowed"
+fi
+
+end_test
diff --git a/tests/e2e/scenarios-api/security-full.sh b/tests/e2e/scenarios-api/security-full.sh
index bf04eb3b..b8d72e99 100644
--- a/tests/e2e/scenarios-api/security-full.sh
+++ b/tests/e2e/scenarios-api/security-full.sh
@@ -80,3 +80,43 @@ assert_json_exists "$RESULT" ".code" "has error code"
assert_json_exists "$RESULT" ".error" "has error message"
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "security: stateExport BLOCKED when disabled"
+
+secure_get /state/list
+assert_http_status 403 "state list blocked"
+assert_contains "$RESULT" "state_export_disabled" "correct error code"
+
+secure_get /storage
+assert_http_status 403 "storage get blocked"
+assert_contains "$RESULT" "state_export_disabled" "correct error code"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "security: state save/load BLOCKED when disabled"
+
+secure_post /state/save -d '{"name":"test-blocked"}'
+assert_http_status 403 "state save blocked"
+assert_contains "$RESULT" "state_export_disabled" "correct error code"
+
+secure_post /state/load -d '{"name":"test-blocked"}'
+assert_http_status 403 "state load blocked"
+assert_contains "$RESULT" "state_export_disabled" "correct error code"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "security: tab-scoped storage BLOCKED when stateExport disabled"
+
+secure_get "/tabs"
+TAB_ID=$(echo "$RESULT" | jq -r '.tabs[0].id // empty')
+
+if [ -n "$TAB_ID" ]; then
+ secure_get "/tabs/${TAB_ID}/storage"
+ assert_http_status 403 "tab storage blocked"
+ assert_contains "$RESULT" "state_export_disabled" "correct error code"
+fi
+
+end_test
diff --git a/tests/e2e/scenarios-api/state-basic.sh b/tests/e2e/scenarios-api/state-basic.sh
index 8e2a87c8..e5c49dfd 100644
--- a/tests/e2e/scenarios-api/state-basic.sh
+++ b/tests/e2e/scenarios-api/state-basic.sh
@@ -110,3 +110,57 @@ pt_post "/state/save" -d '{}'
assert_ok "save with auto-generated name"
end_test
+
+# ═══════════════════════════════════════════════════════════════════
+# Encryption tests (require security.stateEncryptionKey in config)
+# ═══════════════════════════════════════════════════════════════════
+
+ENCRYPTED_STATE_NAME="pt-e2e-encrypted-$(date +%s)"
+ENCRYPTED_STATE_CREATED=0
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /state/save with encrypt=true creates encrypted state"
+
+# This test requires stateEncryptionKey to be configured.
+# If not configured, the request will fail with 400.
+pt_post "/state/save" -d "{\"name\":\"${ENCRYPTED_STATE_NAME}\",\"encrypt\":true}"
+
+# Check if encryption key is configured
+if [ "$HTTP_STATUS" -eq 200 ]; then
+ assert_ok "save encrypted state"
+ assert_json_contains "$RESULT" '.encrypted' "true" "encrypted flag set"
+ ENCRYPTED_STATE_CREATED=1
+elif echo "$RESULT" | grep -q "encryption key"; then
+ echo -e " ${YELLOW}⊘${NC} skipped (stateEncryptionKey not configured)"
+ ((ASSERTIONS_SKIPPED++)) || true
+else
+ assert_ok "save encrypted state"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /state/load loads encrypted state"
+
+if [ "$ENCRYPTED_STATE_CREATED" -eq 1 ]; then
+ pt_post "/state/load" -d "{\"name\":\"${ENCRYPTED_STATE_NAME}\"}"
+ assert_ok "load encrypted state"
+else
+ echo -e " ${YELLOW}⊘${NC} skipped (encrypted state not created)"
+ ((ASSERTIONS_SKIPPED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "DELETE /state cleans up encrypted state"
+
+if [ "$ENCRYPTED_STATE_CREATED" -eq 1 ]; then
+ pt_delete "/state?name=${ENCRYPTED_STATE_NAME}"
+ assert_ok "delete encrypted state"
+else
+ echo -e " ${YELLOW}⊘${NC} skipped"
+ ((ASSERTIONS_SKIPPED++)) || true
+fi
+
+end_test
diff --git a/tests/e2e/scenarios-api/storage-basic.sh b/tests/e2e/scenarios-api/storage-basic.sh
index c5106cd5..35133d35 100644
--- a/tests/e2e/scenarios-api/storage-basic.sh
+++ b/tests/e2e/scenarios-api/storage-basic.sh
@@ -6,6 +6,18 @@
GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${GROUP_DIR}/../helpers/api.sh"
+# ═══════════════════════════════════════════════════════════════════
+# Setup: Navigate to a fixture page so storage has a valid origin
+# ═══════════════════════════════════════════════════════════════════
+
+start_test "Setup: navigate to fixture page for storage tests"
+
+pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"
+assert_ok "navigate to fixture"
+sleep 0.5
+
+end_test
+
# ─────────────────────────────────────────────────────────────────
start_test "POST /storage sets a localStorage item"
@@ -91,3 +103,55 @@ start_test "GET /storage returns 403 when allowStateExport=false"
# The assertion is informational; actual gate test is in security-basic.sh.
end_test
+
+# ═══════════════════════════════════════════════════════════════════
+# Tab-scoped storage tests
+# ═══════════════════════════════════════════════════════════════════
+
+# ─────────────────────────────────────────────────────────────────
+start_test "GET /tabs/{id}/storage reads storage for specific tab"
+
+# Get the active tab ID first
+pt_get "/tabs"
+assert_ok "get tabs"
+TAB_ID=$(echo "$RESULT" | jq -r '.tabs[0].id // empty')
+
+if [ -n "$TAB_ID" ]; then
+ pt_get "/tabs/${TAB_ID}/storage"
+ assert_ok "get tab storage"
+ assert_json_exists "$RESULT" '.origin' "has origin field"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /tabs/{id}/storage sets storage for specific tab"
+
+if [ -n "$TAB_ID" ]; then
+ pt_post "/tabs/${TAB_ID}/storage" -d '{"key":"pt_tab_key","value":"pt_tab_value","type":"local"}'
+ assert_ok "set tab localStorage item"
+ assert_json_exists "$RESULT" '.success' "has success field"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "DELETE /tabs/{id}/storage deletes storage for specific tab"
+
+if [ -n "$TAB_ID" ]; then
+ pt_delete "/tabs/${TAB_ID}/storage" -d '{"key":"pt_tab_key","type":"local"}'
+ assert_ok "delete tab localStorage key"
+ assert_json_exists "$RESULT" '.success' "has success field"
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "POST /tabs/{id}/storage rejects mismatched tabId in body"
+
+if [ -n "$TAB_ID" ]; then
+ pt_post "/tabs/${TAB_ID}/storage" -d '{"tabId":"wrong_tab_id","key":"k","value":"v","type":"local"}'
+ assert_not_ok "rejects tabId mismatch"
+fi
+
+end_test
diff --git a/tests/e2e/scenarios-cli/state-basic.sh b/tests/e2e/scenarios-cli/state-basic.sh
index 2542c854..9768d944 100644
--- a/tests/e2e/scenarios-cli/state-basic.sh
+++ b/tests/e2e/scenarios-cli/state-basic.sh
@@ -62,3 +62,57 @@ pt_cli state clean --older-than 9999
assert_cli_ok "clean old states"
end_test
+
+# ═══════════════════════════════════════════════════════════════════
+# Encryption CLI tests (require security.stateEncryptionKey in config)
+# ═══════════════════════════════════════════════════════════════════
+
+ENCRYPTED_CLI_STATE="cli-encrypted-$(date +%s)"
+ENCRYPTED_STATE_CREATED=0
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state save --encrypt creates encrypted state"
+
+# This test requires stateEncryptionKey to be configured.
+pt_cli state save --name "$ENCRYPTED_CLI_STATE" --encrypt
+
+if [ "$PT_CODE" -eq 0 ]; then
+ echo -e " ${GREEN}✓${NC} save encrypted state"
+ ((ASSERTIONS_PASSED++)) || true
+ ENCRYPTED_STATE_CREATED=1
+elif echo "$PT_ERR" | grep -q "encryption key"; then
+ echo -e " ${YELLOW}⊘${NC} skipped (stateEncryptionKey not configured)"
+ ((ASSERTIONS_SKIPPED++)) || true
+else
+ echo -e " ${RED}✗${NC} save encrypted state (exit $PT_CODE)"
+ echo " stderr: $PT_ERR"
+ ((ASSERTIONS_FAILED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state load loads encrypted state"
+
+if [ "${ENCRYPTED_STATE_CREATED}" -eq 1 ]; then
+ pt_cli state load --name "$ENCRYPTED_CLI_STATE"
+ assert_cli_ok "load encrypted state"
+else
+ echo -e " ${YELLOW}⊘${NC} skipped (encrypted state not created)"
+ ((ASSERTIONS_SKIPPED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab state delete cleans up encrypted state"
+
+if [ "${ENCRYPTED_STATE_CREATED}" -eq 1 ]; then
+ pt_cli state delete --name "$ENCRYPTED_CLI_STATE"
+ assert_cli_ok "delete encrypted state"
+else
+ echo -e " ${YELLOW}⊘${NC} skipped"
+ ((ASSERTIONS_SKIPPED++)) || true
+fi
+
+end_test
diff --git a/tests/e2e/scenarios-cli/storage-basic.sh b/tests/e2e/scenarios-cli/storage-basic.sh
index fbcd1223..33766644 100644
--- a/tests/e2e/scenarios-cli/storage-basic.sh
+++ b/tests/e2e/scenarios-cli/storage-basic.sh
@@ -4,6 +4,18 @@
GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${GROUP_DIR}/../helpers/cli.sh"
+# ═══════════════════════════════════════════════════════════════════
+# Setup: Navigate to a fixture page so storage has a valid origin
+# ═══════════════════════════════════════════════════════════════════
+
+start_test "Setup: navigate to fixture page for storage tests"
+
+pt navigate "${FIXTURES_URL}/index.html"
+assert_cli_ok "navigate to fixture"
+sleep 0.5
+
+end_test
+
# ─────────────────────────────────────────────────────────────────
start_test "pinchtab storage set writes a localStorage item"
@@ -43,3 +55,53 @@ pt_cli storage clear --all
assert_cli_ok "clear --all"
end_test
+
+# ═══════════════════════════════════════════════════════════════════
+# Tab-scoped storage CLI tests (using --tab flag)
+# ═══════════════════════════════════════════════════════════════════
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage get --tab reads storage for specific tab"
+
+# Get the actual tab ID from tabs list
+pt_cli tabs list
+TAB_ID=""
+if [ "$PT_CODE" -eq 0 ]; then
+ TAB_ID=$(echo "$PT_OUT" | safe_jq -r '.tabs[0].id // empty' 2>/dev/null)
+fi
+
+if [ -n "$TAB_ID" ] && [ "$TAB_ID" != "null" ]; then
+ pt_cli storage get --tab "$TAB_ID"
+ assert_cli_ok "get storage for tab $TAB_ID"
+else
+ echo -e " ${YELLOW}⊘${NC} skipped (no tab found)"
+ ((ASSERTIONS_SKIPPED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage set --tab writes to specific tab"
+
+if [ -n "$TAB_ID" ] && [ "$TAB_ID" != "null" ]; then
+ pt_cli storage set pt_cli_tab_key pt_cli_tab_value --type local --tab "$TAB_ID"
+ assert_cli_ok "set with --tab"
+else
+ echo -e " ${YELLOW}⊘${NC} skipped (no tab found)"
+ ((ASSERTIONS_SKIPPED++)) || true
+fi
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "pinchtab storage delete --tab removes key from specific tab"
+
+if [ -n "$TAB_ID" ] && [ "$TAB_ID" != "null" ]; then
+ pt_cli storage delete --key pt_cli_tab_key --type local --tab "$TAB_ID"
+ assert_cli_ok "delete with --tab"
+else
+ echo -e " ${YELLOW}⊘${NC} skipped (no tab found)"
+ ((ASSERTIONS_SKIPPED++)) || true
+fi
+
+end_test