High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: implement Storage & State Management API (#417)
Yash Jadhav293461a56138
diff --git a/docs/endpoints.md b/docs/endpoints.mdindex 3331bca6..527fc4c8 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -227,6 +227,78 @@ Notes:- clipboard endpoints are gated by `security.allowClipboard`- upload uses a JSON body with `selector` and `files`+## Storage++```text+GET /storage+POST /storage+DELETE /storage+GET /tabs/{id}/storage+POST /tabs/{id}/storage+DELETE /tabs/{id}/storage+```++Storage is captured only for the current origin (active tab). Multi-origin storage is not supported.++GET query parameters:++- `type` — `local`, `session`, or empty (both)+- `key` — optional, specific key to retrieve+- `tabId` — optional tab identifier++POST body fields:++- `key` — required+- `value` — required+- `type` — `local` or `session` (required)+- `tabId` — optional++DELETE body fields:++- `type` — `local` or `session` (required)+- `key` — optional (if omitted, clears entire storage)+- `tabId` — optional++## State Management++```text+GET /state/list+GET /state/show+POST /state/save+POST /state/load+DELETE /state+POST /state/clean+```++State management saves and restores browser state (cookies, localStorage, sessionStorage, metadata) to disk.++Notes:++- `POST /state/save` and `GET /state/show` are gated by `security.allowStateExport`+- state files are stored in `{stateDir}/sessions/` with `0600` permissions+- optional AES-256-GCM encryption via `PINCHTAB_STATE_KEY` environment variable+- storage is captured only for the current origin (active tab)++`POST /state/save` body fields:++- `name` — state file name+- `encrypt` — optional, encrypt the state file+- `tabId` — optional tab identifier+- `metadata` — optional additional metadata++`POST /state/load` body fields:++- `name` — state file name (required)+- `tabId` — optional tab identifier++`DELETE /state` query parameters:++- `name` — state file name (required)++`POST /state/clean` body fields:++- `olderThanHours` — optional (default: 24)+## Wait, Network, Dialog, Console, And Errors```text@@ -418,6 +490,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`+- `/state/save` and `/state/show` -> `security.allowStateExport`## Error Response Formatdiff --git a/internal/config/config_file.go b/internal/config/config_file.goindex f5e8b74b..9c1afe83 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -26,6 +26,7 @@ func DefaultFileConfig() FileConfig {downloadMaxBytes := DefaultDownloadMaxBytesallowUpload := falseallowClipboard := false+ allowStateExport := falseenableActionGuards := trueuploadMaxRequestBytes := DefaultUploadMaxRequestBytesuploadMaxFiles := DefaultUploadMaxFiles@@ -67,6 +68,7 @@ func DefaultFileConfig() FileConfig {DownloadMaxBytes: &downloadMaxBytes,AllowUpload: &allowUpload,AllowClipboard: &allowClipboard,+ AllowStateExport: &allowStateExport,EnableActionGuards: &enableActionGuards,UploadMaxRequestBytes: &uploadMaxRequestBytes,UploadMaxFiles: &uploadMaxFiles,@@ -193,6 +195,7 @@ type securityConfigJSON struct {DownloadMaxBytes *int `json:"downloadMaxBytes"`AllowUpload *bool `json:"allowUpload"`AllowClipboard *bool `json:"allowClipboard"`+ AllowStateExport *bool `json:"allowStateExport"`EnableActionGuards *bool `json:"enableActionGuards"`UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes"`UploadMaxFiles *int `json:"uploadMaxFiles"`@@ -345,6 +348,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {DownloadMaxBytes: fc.Security.DownloadMaxBytes,AllowUpload: fc.Security.AllowUpload,AllowClipboard: fc.Security.AllowClipboard,+ AllowStateExport: fc.Security.AllowStateExport,EnableActionGuards: fc.Security.EnableActionGuards,UploadMaxRequestBytes: fc.Security.UploadMaxRequestBytes,UploadMaxFiles: fc.Security.UploadMaxFiles,@@ -453,6 +457,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {downloadMaxBytes := cfg.EffectiveDownloadMaxBytes()allowUpload := cfg.AllowUploadallowClipboard := cfg.AllowClipboard+ allowStateExport := cfg.AllowStateExportenableActionGuards := cfg.EnableActionGuardsuploadMaxRequestBytes := cfg.EffectiveUploadMaxRequestBytes()uploadMaxFiles := cfg.EffectiveUploadMaxFiles()@@ -528,6 +533,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {DownloadMaxBytes: &downloadMaxBytes,AllowUpload: &allowUpload,AllowClipboard: &allowClipboard,+ AllowStateExport: &allowStateExport,EnableActionGuards: &enableActionGuards,UploadMaxRequestBytes: &uploadMaxRequestBytes,UploadMaxFiles: &uploadMaxFiles,diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 161ff118..c17cf541 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -28,6 +28,8 @@ func Load() *RuntimeConfig {DownloadAllowedDomains: nil,DownloadMaxBytes: DefaultDownloadMaxBytes,AllowUpload: false,+ AllowClipboard: false,+ AllowStateExport: false,EnableActionGuards: true,UploadMaxRequestBytes: DefaultUploadMaxRequestBytes,UploadMaxFiles: DefaultUploadMaxFiles,@@ -237,6 +239,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.Security.AllowClipboard != nil {cfg.AllowClipboard = *fc.Security.AllowClipboard}+ if fc.Security.AllowStateExport != nil {+ cfg.AllowStateExport = *fc.Security.AllowStateExport+ }if fc.Security.EnableActionGuards != nil {cfg.EnableActionGuards = *fc.Security.EnableActionGuards}diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 9f969eec..956dd274 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -24,6 +24,7 @@ type RuntimeConfig struct {DownloadMaxBytes intAllowUpload boolAllowClipboard bool+ AllowStateExport boolEnableActionGuards bool // Enable bridge-level stale/navigation guard checks around actionsUploadMaxRequestBytes intUploadMaxFiles int@@ -255,6 +256,7 @@ type SecurityConfig struct {DownloadMaxBytes *int `json:"downloadMaxBytes,omitempty"`AllowUpload *bool `json:"allowUpload,omitempty"`AllowClipboard *bool `json:"allowClipboard,omitempty"`+ AllowStateExport *bool `json:"allowStateExport,omitempty"`EnableActionGuards *bool `json:"enableActionGuards,omitempty"`UploadMaxRequestBytes *int `json:"uploadMaxRequestBytes,omitempty"`UploadMaxFiles *int `json:"uploadMaxFiles,omitempty"`diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex d511ffd3..75f9c86d 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -219,6 +219,19 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /cache/clear", h.HandleCacheClear)mux.HandleFunc("GET /cache/status", h.HandleCacheStatus)+ // Storage (current origin only)+ mux.HandleFunc("GET /storage", h.HandleStorage)+ mux.HandleFunc("POST /storage", h.HandleStorage)+ mux.HandleFunc("DELETE /storage", h.HandleStorage)++ // State management+ mux.HandleFunc("GET /state/list", h.HandleStateList)+ mux.HandleFunc("GET /state/show", h.HandleStateShow)+ mux.HandleFunc("POST /state/save", h.HandleStateSave)+ mux.HandleFunc("POST /state/load", h.HandleStateLoad)+ mux.HandleFunc("DELETE /state", h.HandleStateDelete)+ mux.HandleFunc("POST /state/clean", h.HandleStateClean)+if h.Profiles != nil {h.Profiles.RegisterHandlers(mux)}diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.goindex 55cbb068..103e03d6 100644--- a/internal/handlers/openapi.go+++ b/internal/handlers/openapi.go@@ -72,6 +72,25 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {"description": security["screencast"].Message,"x-pinchtab-enabled": security["screencast"].Enabled,}},+ "/storage": map[string]any{+ "get": map[string]any{"summary": "Get localStorage/sessionStorage items (current origin only)"},+ "post": map[string]any{"summary": "Set a storage item"},+ "delete": map[string]any{"summary": "Delete storage items or clear storage"},+ },+ "/state/list": map[string]any{"get": map[string]any{"summary": "List saved state files"}},+ "/state/load": map[string]any{"post": map[string]any{"summary": "Load and restore browser state"}},+ "/state/clean": map[string]any{"post": map[string]any{"summary": "Clean old state files"}},+ "/state": map[string]any{"delete": map[string]any{"summary": "Delete a saved state file"}},+ "/state/show": map[string]any{"get": map[string]any{+ "summary": "Show state file details",+ "description": security["stateExport"].Message,+ "x-pinchtab-enabled": security["stateExport"].Enabled,+ }},+ "/state/save": map[string]any{"post": map[string]any{+ "summary": "Save browser state (cookies, storage, metadata)",+ "description": security["stateExport"].Message,+ "x-pinchtab-enabled": security["stateExport"].Enabled,+ }},},})}diff --git a/internal/handlers/security.go b/internal/handlers/security.goindex 0ba32f7c..ccfd3d5c 100644--- a/internal/handlers/security.go+++ b/internal/handlers/security.go@@ -63,5 +63,11 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {Message: httpx.DisabledEndpointMessage("clipboard", "security.allowClipboard"),Paths: []string{"GET /clipboard/read", "POST /clipboard/write", "POST /clipboard/copy", "GET /clipboard/paste"},},+ "stateExport": {+ Enabled: h.stateExportEnabled(),+ Setting: "security.allowStateExport",+ Message: httpx.DisabledEndpointMessage("stateExport", "security.allowStateExport"),+ Paths: []string{"POST /state/save", "GET /state/show"},+ },}}diff --git a/internal/handlers/state.go b/internal/handlers/state.gonew file mode 100644index 00000000..d9a3c536--- /dev/null+++ b/internal/handlers/state.go@@ -0,0 +1,430 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "log/slog"+ "net/http"+ "os"+ "path/filepath"+ "time"++ "github.com/chromedp/cdproto/network"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/state"+)++func (h *Handlers) stateExportEnabled() bool {+ return h != nil && h.Config != nil && h.Config.AllowStateExport+}++// HandleStateList lists all saved state files.+//+// @Endpoint GET /state/list+func (h *Handlers) HandleStateList(w http.ResponseWriter, r *http.Request) {+ entries, err := state.List(h.Config.StateDir)+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("list states: %w", err))+ return+ }++ httpx.JSON(w, 200, map[string]any{+ "states": entries,+ "count": len(entries),+ })+}++// HandleStateShow returns the full contents of a saved state file.+// Gated behind CapStateExport (security.allowStateExport).+//+// @Endpoint GET /state/show+func (h *Handlers) HandleStateShow(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+ }++ name := r.URL.Query().Get("name")+ if name == "" {+ httpx.Error(w, 400, fmt.Errorf("name query parameter is required"))+ return+ }++ encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")+ path := state.ResolvePath(h.Config.StateDir, name)++ sf, err := state.Load(path, encryptionKey)+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("load state: %w", err))+ return+ }++ httpx.JSON(w, 200, sf)+}++type stateSaveRequest struct {+ Name string `json:"name"`+ Encrypt bool `json:"encrypt"`+ TabID string `json:"tabId"`+ Metadata map[string]interface{} `json:"metadata"`+}++// HandleStateSave captures the current browser state (cookies, storage, metadata)+// and writes it to disk. Gated behind CapStateExport (security.allowStateExport).+// Storage is captured only for the current origin (active tab).+//+// @Endpoint POST /state/save+func (h *Handlers) HandleStateSave(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+ }++ var req stateSaveRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ encryptionKey := ""+ if req.Encrypt {+ encryptionKey = os.Getenv("PINCHTAB_STATE_KEY")+ if err := state.ValidateEncryptionKey(encryptionKey); err != nil {+ httpx.Error(w, 400, fmt.Errorf("encryption key required: set PINCHTAB_STATE_KEY environment variable"))+ return+ }+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 30*time.Second)+ defer tCancel()++ // Step 1: Get all cookies+ var cookies []*network.Cookie+ if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {+ var err error+ cookies, err = network.GetCookies().Do(ctx)+ return err+ })); err != nil {+ httpx.Error(w, 500, fmt.Errorf("get cookies: %w", err))+ return+ }++ // Step 2: Get storage and metadata via JS evaluation+ storageScript := `+ (function() {+ try {+ var localEntries = {};+ for (var i = 0; i < localStorage.length; i++) {+ var k = localStorage.key(i);+ localEntries[k] = localStorage.getItem(k);+ }+ var sessionEntries = {};+ for (var i = 0; i < sessionStorage.length; i++) {+ var k = sessionStorage.key(i);+ sessionEntries[k] = sessionStorage.getItem(k);+ }+ return JSON.stringify({+ local: localEntries,+ session: sessionEntries,+ url: window.location.href,+ origin: window.location.origin,+ userAgent: navigator.userAgent+ });+ } catch(e) {+ return JSON.stringify({+ error: e.message,+ local: {},+ session: {},+ url: window.location.href,+ origin: window.location.origin,+ userAgent: navigator.userAgent+ });+ }+ })()+ `++ var storageJSON string+ if err := chromedp.Run(tCtx, chromedp.Evaluate(storageScript, &storageJSON)); err != nil {+ httpx.Error(w, 500, fmt.Errorf("evaluate storage: %w", err))+ return+ }++ var storageResult struct {+ Local map[string]string `json:"local"`+ Session map[string]string `json:"session"`+ URL string `json:"url"`+ Origin string `json:"origin"`+ UserAgent string `json:"userAgent"`+ Error string `json:"error"`+ }+ if err := json.Unmarshal([]byte(storageJSON), &storageResult); err != nil {+ httpx.Error(w, 500, fmt.Errorf("parse storage result: %w", err))+ return+ }++ // Build state file+ stateCookies := make([]state.Cookie, len(cookies))+ for i, c := range cookies {+ stateCookies[i] = state.Cookie{+ Name: c.Name,+ Value: c.Value,+ Domain: c.Domain,+ Path: c.Path,+ Secure: c.Secure,+ HTTPOnly: c.HTTPOnly,+ SameSite: c.SameSite.String(),+ Expires: c.Expires,+ }+ }++ if storageResult.Local == nil {+ storageResult.Local = map[string]string{}+ }+ if storageResult.Session == nil {+ storageResult.Session = map[string]string{}+ }++ origins := []string{}+ if storageResult.Origin != "" {+ origins = append(origins, storageResult.Origin)+ }++ metadata := map[string]interface{}{+ "url": storageResult.URL,+ "origin": storageResult.Origin,+ "userAgent": storageResult.UserAgent,+ }+ // Merge user-provided metadata+ for k, v := range req.Metadata {+ metadata[k] = v+ }++ sf := &state.StateFile{+ Name: req.Name,+ SavedAt: time.Now(),+ Origins: origins,+ Cookies: stateCookies,+ Storage: map[string]state.OriginStorage{+ storageResult.Origin: {+ Local: storageResult.Local,+ Session: storageResult.Session,+ },+ },+ Metadata: metadata,+ }++ path, err := state.Save(h.Config.StateDir, sf, encryptionKey)+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("save state: %w", err))+ return+ }++ slog.Info("state saved",+ "name", sf.Name,+ "path", path,+ "cookies", len(stateCookies),+ "origin", storageResult.Origin,+ "encrypted", req.Encrypt,+ "tabId", resolvedTabID,+ "remoteAddr", r.RemoteAddr,+ )++ httpx.JSON(w, 200, map[string]any{+ "name": sf.Name,+ "path": path,+ "cookies": len(stateCookies),+ "origins": origins,+ "encrypted": req.Encrypt,+ })+}++// HandleStateLoad reads a state file and restores cookies and storage.+//+// @Endpoint POST /state/load+func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {+ var req struct {+ Name string `json:"name"`+ TabID string `json:"tabId"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.Name == "" {+ httpx.Error(w, 400, fmt.Errorf("name is required"))+ return+ }++ encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")+ path := state.ResolvePath(h.Config.StateDir, req.Name)++ sf, err := state.Load(path, encryptionKey)+ if err != nil {+ // Retry without encryption key in case the file is not encrypted+ sf, err = state.Load(path, "")+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("load state: %w", err))+ return+ }+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 30*time.Second)+ defer tCancel()++ // Step 1: Restore cookies+ cookiesRestored := 0+ if len(sf.Cookies) > 0 {+ if err := chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {+ for _, c := range sf.Cookies {+ params := network.SetCookie(c.Name, c.Value).+ WithDomain(c.Domain).+ WithPath(c.Path).+ WithSecure(c.Secure).+ WithHTTPOnly(c.HTTPOnly)++ if c.SameSite != "" {+ var sameSite network.CookieSameSite+ switch c.SameSite {+ case "Strict":+ sameSite = network.CookieSameSiteStrict+ case "Lax":+ sameSite = network.CookieSameSiteLax+ case "None":+ sameSite = network.CookieSameSiteNone+ }+ if sameSite != "" {+ params = params.WithSameSite(sameSite)+ }+ }++ if err := chromedp.Run(tCtx, params); err == nil {+ cookiesRestored+++ }+ }+ return nil+ })); err != nil {+ httpx.Error(w, 500, fmt.Errorf("restore cookies: %w", err))+ return+ }+ }++ // Step 2: Restore storage for each origin+ storageRestored := 0+ for _, originStorage := range sf.Storage {+ // Build JS to restore localStorage+ for k, v := range originStorage.Local {+ keyJSON, _ := json.Marshal(k)+ valueJSON, _ := json.Marshal(v)+ script := fmt.Sprintf(`localStorage.setItem(%s, %s)`, string(keyJSON), string(valueJSON))+ if err := chromedp.Run(tCtx, chromedp.Evaluate(script, nil)); err == nil {+ storageRestored+++ }+ }++ // Build JS to restore sessionStorage+ for k, v := range originStorage.Session {+ keyJSON, _ := json.Marshal(k)+ valueJSON, _ := json.Marshal(v)+ script := fmt.Sprintf(`sessionStorage.setItem(%s, %s)`, string(keyJSON), string(valueJSON))+ if err := chromedp.Run(tCtx, chromedp.Evaluate(script, nil)); err == nil {+ storageRestored+++ }+ }+ }++ slog.Info("state loaded",+ "name", req.Name,+ "path", path,+ "cookiesRestored", cookiesRestored,+ "storageItemsRestored", storageRestored,+ "tabId", resolvedTabID,+ "remoteAddr", r.RemoteAddr,+ )++ httpx.JSON(w, 200, map[string]any{+ "name": req.Name,+ "cookiesRestored": cookiesRestored,+ "storageItemsRestored": storageRestored,+ "origins": sf.Origins,+ })+}++// HandleStateDelete removes a saved state file.+//+// @Endpoint DELETE /state+func (h *Handlers) HandleStateDelete(w http.ResponseWriter, r *http.Request) {+ name := r.URL.Query().Get("name")+ if name == "" {+ httpx.Error(w, 400, fmt.Errorf("name query parameter is required"))+ return+ }++ if err := state.Delete(h.Config.StateDir, name); err != nil {+ httpx.Error(w, 500, fmt.Errorf("delete state: %w", err))+ return+ }++ slog.Info("state deleted",+ "name", name,+ "remoteAddr", r.RemoteAddr,+ )++ httpx.JSON(w, 200, map[string]any{+ "deleted": name,+ })+}++// HandleStateClean removes state files older than a given duration.+//+// @Endpoint POST /state/clean+func (h *Handlers) HandleStateClean(w http.ResponseWriter, r *http.Request) {+ var req struct {+ OlderThanHours int `json:"olderThanHours"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.OlderThanHours <= 0 {+ req.OlderThanHours = 24+ }++ duration := time.Duration(req.OlderThanHours) * time.Hour+ removed, err := state.Clean(h.Config.StateDir, duration)+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("clean states: %w", err))+ return+ }++ slog.Info("state clean",+ "olderThanHours", req.OlderThanHours,+ "removed", removed,+ "remoteAddr", r.RemoteAddr,+ )++ httpx.JSON(w, 200, map[string]any{+ "removed": removed,+ "olderThanHours": req.OlderThanHours,+ "sessionsDir": filepath.Base(state.SessionsDir(h.Config.StateDir)),+ })+}diff --git a/internal/handlers/storage.go b/internal/handlers/storage.gonew file mode 100644index 00000000..55c7dbaa--- /dev/null+++ b/internal/handlers/storage.go@@ -0,0 +1,357 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "log/slog"+ "net/http"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++// HandleStorage dispatches to the appropriate storage operation based on HTTP method.+// Storage is captured only for the current origin (active tab).+//+// GET /storage — retrieve storage items+// POST /storage — set a storage item+// DELETE /storage — remove storage items or clear storage+func (h *Handlers) HandleStorage(w http.ResponseWriter, r *http.Request) {+ switch r.Method {+ case http.MethodGet:+ h.handleStorageGet(w, r)+ case http.MethodPost:+ h.handleStorageSet(w, r)+ case http.MethodDelete:+ h.handleStorageDelete(w, r)+ default:+ httpx.Error(w, http.StatusMethodNotAllowed, fmt.Errorf("method %s not allowed", r.Method))+ }+}++// handleStorageGet retrieves localStorage and/or sessionStorage items.+//+// Query params:+// - type: "local", "session", or "" (both)+// - key: optional specific key to retrieve+func (h *Handlers) handleStorageGet(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ storageType := r.URL.Query().Get("type")+ key := r.URL.Query().Get("key")++ ctx, resolvedTabID, err := h.tabContext(r, tabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)+ defer tCancel()++ script := buildStorageGetScript(storageType, key)++ var resultJSON string+ if err := chromedp.Run(tCtx, chromedp.Evaluate(script, &resultJSON)); err != nil {+ httpx.Error(w, 500, fmt.Errorf("evaluate storage get: %w", err))+ return+ }++ var result map[string]interface{}+ if err := json.Unmarshal([]byte(resultJSON), &result); err != nil {+ httpx.Error(w, 500, fmt.Errorf("parse storage result: %w", err))+ return+ }++ slog.Info("storage: get",+ "type", storageType,+ "key", key,+ "tabId", resolvedTabID,+ "remoteAddr", r.RemoteAddr,+ )++ httpx.JSON(w, 200, result)+}++type storageSetRequest struct {+ TabID string `json:"tabId"`+ Key string `json:"key"`+ Value string `json:"value"`+ Type string `json:"type"`+}++// handleStorageSet sets a single storage item.+func (h *Handlers) handleStorageSet(w http.ResponseWriter, r *http.Request) {+ var req storageSetRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.Key == "" {+ httpx.Error(w, 400, fmt.Errorf("key is required"))+ return+ }+ if req.Type == "" {+ httpx.Error(w, 400, fmt.Errorf("type is required (local or session)"))+ return+ }+ if req.Type != "local" && req.Type != "session" {+ httpx.Error(w, 400, fmt.Errorf("type must be 'local' or 'session'"))+ return+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)+ defer tCancel()++ storageObj := "localStorage"+ if req.Type == "session" {+ storageObj = "sessionStorage"+ }++ keyJSON, _ := json.Marshal(req.Key)+ valueJSON, _ := json.Marshal(req.Value)++ script := fmt.Sprintf(`+ try {+ %s.setItem(%s, %s);+ JSON.stringify({success: true, origin: window.location.origin});+ } catch(e) {+ JSON.stringify({success: false, error: e.message, origin: window.location.origin});+ }+ `, storageObj, string(keyJSON), string(valueJSON))++ var resultJSON string+ if err := chromedp.Run(tCtx, chromedp.Evaluate(script, &resultJSON)); err != nil {+ httpx.Error(w, 500, fmt.Errorf("evaluate storage set: %w", err))+ return+ }++ var result map[string]interface{}+ if err := json.Unmarshal([]byte(resultJSON), &result); err != nil {+ httpx.Error(w, 500, fmt.Errorf("parse storage set result: %w", err))+ return+ }++ slog.Info("storage: set",+ "type", req.Type,+ "key", req.Key,+ "tabId", resolvedTabID,+ "remoteAddr", r.RemoteAddr,+ )++ httpx.JSON(w, 200, result)+}++// handleStorageDelete removes a storage item or clears storage.+func (h *Handlers) handleStorageDelete(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ Key string `json:"key"`+ Type string `json:"type"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.Type == "" {+ httpx.Error(w, 400, fmt.Errorf("type is required (local or session)"))+ return+ }+ if req.Type != "local" && req.Type != "session" {+ httpx.Error(w, 400, fmt.Errorf("type must be 'local' or 'session'"))+ return+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)+ defer tCancel()++ script := buildStorageDeleteScript(req.Type, req.Key)++ var resultJSON string+ if err := chromedp.Run(tCtx, chromedp.Evaluate(script, &resultJSON)); err != nil {+ httpx.Error(w, 500, fmt.Errorf("evaluate storage delete: %w", err))+ return+ }++ var result map[string]interface{}+ if err := json.Unmarshal([]byte(resultJSON), &result); err != nil {+ httpx.Error(w, 500, fmt.Errorf("parse storage delete result: %w", err))+ return+ }++ slog.Info("storage: delete",+ "type", req.Type,+ "key", req.Key,+ "tabId", resolvedTabID,+ "remoteAddr", r.RemoteAddr,+ )++ httpx.JSON(w, 200, result)+}++// buildStorageGetScript builds a JS expression that reads from localStorage+// and/or sessionStorage. Returns a JSON string with local/session/origin fields.+func buildStorageGetScript(storageType, key string) string {+ if key != "" {+ keyJSON, _ := json.Marshal(key)+ switch storageType {+ case "local":+ return fmt.Sprintf(`+ (function() {+ try {+ var v = localStorage.getItem(%s);+ return JSON.stringify({+ local: v !== null ? [{key: %s, value: v}] : [],+ session: [],+ origin: window.location.origin+ });+ } catch(e) {+ return JSON.stringify({error: e.message, local: [], session: [], origin: window.location.origin});+ }+ })()+ `, string(keyJSON), string(keyJSON))+ case "session":+ return fmt.Sprintf(`+ (function() {+ try {+ var v = sessionStorage.getItem(%s);+ return JSON.stringify({+ local: [],+ session: v !== null ? [{key: %s, value: v}] : [],+ origin: window.location.origin+ });+ } catch(e) {+ return JSON.stringify({error: e.message, local: [], session: [], origin: window.location.origin});+ }+ })()+ `, string(keyJSON), string(keyJSON))+ default:+ return fmt.Sprintf(`+ (function() {+ try {+ var lv = localStorage.getItem(%s);+ var sv = sessionStorage.getItem(%s);+ return JSON.stringify({+ local: lv !== null ? [{key: %s, value: lv}] : [],+ session: sv !== null ? [{key: %s, value: sv}] : [],+ origin: window.location.origin+ });+ } catch(e) {+ return JSON.stringify({error: e.message, local: [], session: [], origin: window.location.origin});+ }+ })()+ `, string(keyJSON), string(keyJSON), string(keyJSON), string(keyJSON))+ }+ }++ // No key specified: return all items+ getAllScript := func(storageObj string) string {+ return fmt.Sprintf(`+ (function() {+ var items = [];+ try {+ for (var i = 0; i < %s.length; i++) {+ var k = %s.key(i);+ items.push({key: k, value: %s.getItem(k)});+ }+ } catch(e) {}+ return items;+ })()+ `, storageObj, storageObj, storageObj)+ }++ switch storageType {+ case "local":+ return fmt.Sprintf(`+ (function() {+ try {+ var local = %s;+ return JSON.stringify({local: local, session: [], origin: window.location.origin});+ } catch(e) {+ return JSON.stringify({error: e.message, local: [], session: [], origin: window.location.origin});+ }+ })()+ `, getAllScript("localStorage"))+ case "session":+ return fmt.Sprintf(`+ (function() {+ try {+ var session = %s;+ return JSON.stringify({local: [], session: session, origin: window.location.origin});+ } catch(e) {+ return JSON.stringify({error: e.message, local: [], session: [], origin: window.location.origin});+ }+ })()+ `, getAllScript("sessionStorage"))+ default:+ return fmt.Sprintf(`+ (function() {+ try {+ var local = %s;+ var session = %s;+ return JSON.stringify({local: local, session: session, origin: window.location.origin});+ } catch(e) {+ return JSON.stringify({error: e.message, local: [], session: [], origin: window.location.origin});+ }+ })()+ `, getAllScript("localStorage"), getAllScript("sessionStorage"))+ }+}++// buildStorageDeleteScript builds a JS expression that removes a specific key+// or clears the entire storage. Returns a JSON string with success/origin fields.+func buildStorageDeleteScript(storageType, key string) string {+ storageObj := "localStorage"+ if storageType == "session" {+ storageObj = "sessionStorage"+ }++ if key != "" {+ keyJSON, _ := json.Marshal(key)+ return fmt.Sprintf(`+ (function() {+ try {+ %s.removeItem(%s);+ return JSON.stringify({success: true, action: "removeItem", key: %s, origin: window.location.origin});+ } catch(e) {+ return JSON.stringify({success: false, error: e.message, origin: window.location.origin});+ }+ })()+ `, storageObj, string(keyJSON), string(keyJSON))+ }++ return fmt.Sprintf(`+ (function() {+ try {+ %s.clear();+ return JSON.stringify({success: true, action: "clear", origin: window.location.origin});+ } catch(e) {+ return JSON.stringify({success: false, error: e.message, origin: window.location.origin});+ }+ })()+ `, storageObj)+}diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex 396c5317..7438bb08 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -219,6 +219,10 @@ func (o *Orchestrator) AllowsUpload() bool {return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowUpload}+func (o *Orchestrator) AllowsStateExport() bool {+ return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowStateExport+}+func (o *Orchestrator) SetPortRange(start, end int) {o.portAllocator = NewPortAllocator(start, end)}diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 4fbd0043..b2984c54 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -10,12 +10,13 @@ import "fmt"type Capability stringconst (- CapNone Capability = ""- CapEvaluate Capability = "evaluate"- CapMacro Capability = "macro"- CapScreencast Capability = "screencast"- CapDownload Capability = "download"- CapUpload Capability = "upload"+ CapNone Capability = ""+ CapEvaluate Capability = "evaluate"+ CapMacro Capability = "macro"+ CapScreencast Capability = "screencast"+ CapDownload Capability = "download"+ CapUpload Capability = "upload"+ CapStateExport Capability = "stateExport")// Endpoint describes a single API route.@@ -108,6 +109,17 @@ var coreEndpoints = []Endpoint{{"POST", "/cache/clear", "Clear browser cache", CapNone, false},{"GET", "/cache/status", "Cache status", CapNone, false},+ // Storage (current origin only)+ {"GET", "/storage", "Get storage items", CapNone, true},+ {"POST", "/storage", "Set storage item", CapNone, true},+ {"DELETE", "/storage", "Delete storage items", CapNone, true},++ // State management+ {"GET", "/state/list", "List saved states", CapNone, false},+ {"POST", "/state/load", "Load browser state", CapNone, false},+ {"DELETE", "/state", "Delete saved state", CapNone, false},+ {"POST", "/state/clean", "Clean old state files", CapNone, false},+// Capability-gated{"POST", "/evaluate", "Run JavaScript in page", CapEvaluate, true},{"POST", "/macro", "Macro action pipeline", CapMacro, false},@@ -115,6 +127,8 @@ var coreEndpoints = []Endpoint{{"POST", "/upload", "Upload file to file input", CapUpload, true},{"GET", "/screencast", "Live tab frame stream", CapScreencast, false},{"GET", "/screencast/tabs", "List tabs available for screencast", CapScreencast, false},+ {"GET", "/state/show", "Show state details", CapStateExport, false},+ {"POST", "/state/save", "Save browser state", CapStateExport, false},}// Core returns a copy of the canonical endpoint list.diff --git a/internal/state/state.go b/internal/state/state.gonew file mode 100644index 00000000..d24f950f--- /dev/null+++ b/internal/state/state.go@@ -0,0 +1,336 @@+// Package state manages browser state persistence (cookies, storage, metadata)+// independently from the handler layer. State files are saved to the configured+// sessions directory with optional AES-256-GCM encryption.+package state++import (+ "crypto/aes"+ "crypto/cipher"+ "crypto/rand"+ "crypto/sha256"+ "encoding/json"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "sort"+ "strings"+ "time"+)++// Version is the current state file format version.+const Version = 1++// StateFile represents a saved browser session state.+type StateFile struct {+ Version int `json:"version"`+ Name string `json:"name"`+ SavedAt time.Time `json:"savedAt"`+ Origins []string `json:"origins"`+ Cookies []Cookie `json:"cookies"`+ Storage map[string]OriginStorage `json:"storage"`+ Metadata map[string]interface{} `json:"metadata"`+ Encrypted bool `json:"encrypted"`+}++// OriginStorage holds localStorage and sessionStorage key-value pairs+// for a single origin.+type OriginStorage struct {+ Local map[string]string `json:"local"`+ Session map[string]string `json:"session"`+}++// Cookie mirrors the essential fields from a CDP network cookie.+type Cookie struct {+ Name string `json:"name"`+ Value string `json:"value"`+ Domain string `json:"domain"`+ Path string `json:"path"`+ Secure bool `json:"secure"`+ HTTPOnly bool `json:"httpOnly"`+ SameSite string `json:"sameSite"`+ Expires float64 `json:"expires,omitempty"`+}++// StateEntry is a summary of a saved state file (for listing).+type StateEntry struct {+ Name string `json:"name"`+ SavedAt time.Time `json:"savedAt"`+ Origins []string `json:"origins"`+ Encrypted bool `json:"encrypted"`+ SizeBytes int64 `json:"sizeBytes"`+}++// SessionsDir returns the resolved sessions directory path.+func SessionsDir(stateDir string) string {+ return filepath.Join(stateDir, "sessions")+}++// EnsureSessionsDir creates the sessions directory if it does not exist.+func EnsureSessionsDir(stateDir string) (string, error) {+ dir := SessionsDir(stateDir)+ if err := os.MkdirAll(dir, 0700); err != nil {+ return "", fmt.Errorf("create sessions dir: %w", err)+ }+ return dir, nil+}++// Save writes a StateFile to disk. If encryptionKey is non-empty, the payload+// is encrypted with AES-256-GCM before writing.+func Save(stateDir string, sf *StateFile, encryptionKey string) (string, error) {+ dir, err := EnsureSessionsDir(stateDir)+ if err != nil {+ return "", err+ }++ sf.Version = Version+ if sf.Name == "" {+ sf.Name = fmt.Sprintf("state-%d", time.Now().Unix())+ }++ data, err := json.MarshalIndent(sf, "", " ")+ if err != nil {+ return "", fmt.Errorf("marshal state: %w", err)+ }++ if encryptionKey != "" {+ encrypted, encErr := Encrypt(data, encryptionKey)+ if encErr != nil {+ return "", fmt.Errorf("encrypt state: %w", encErr)+ }+ data = encrypted+ sf.Encrypted = true+ }++ filename := sanitizeFilename(sf.Name) + ".json"+ path := filepath.Join(dir, filename)++ if err := os.WriteFile(path, data, 0600); err != nil {+ return "", fmt.Errorf("write state file: %w", err)+ }++ return path, nil+}++// Load reads a StateFile from disk. If encryptionKey is non-empty, the file+// is decrypted before parsing.+func Load(path, encryptionKey string) (*StateFile, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("read state file: %w", err)+ }++ if encryptionKey != "" {+ decrypted, decErr := Decrypt(data, encryptionKey)+ if decErr != nil {+ return nil, fmt.Errorf("decrypt state file: %w", decErr)+ }+ data = decrypted+ }++ var sf StateFile+ if err := json.Unmarshal(data, &sf); err != nil {+ return nil, fmt.Errorf("parse state file: %w", err)+ }++ return &sf, nil+}++// List returns summaries of all saved state files in the sessions directory.+func List(stateDir string) ([]StateEntry, error) {+ dir := SessionsDir(stateDir)++ entries, err := os.ReadDir(dir)+ if err != nil {+ if os.IsNotExist(err) {+ return []StateEntry{}, nil+ }+ return nil, fmt.Errorf("read sessions dir: %w", err)+ }++ var result []StateEntry+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {+ continue+ }++ info, err := entry.Info()+ if err != nil {+ continue+ }++ path := filepath.Join(dir, entry.Name())+ se := StateEntry{+ Name: strings.TrimSuffix(entry.Name(), ".json"),+ SizeBytes: info.Size(),+ }++ // Try to read metadata without full decryption+ data, readErr := os.ReadFile(path)+ if readErr == nil {+ var probe struct {+ SavedAt time.Time `json:"savedAt"`+ Origins []string `json:"origins"`+ Encrypted bool `json:"encrypted"`+ }+ if json.Unmarshal(data, &probe) == nil {+ se.SavedAt = probe.SavedAt+ se.Origins = probe.Origins+ se.Encrypted = probe.Encrypted+ }+ }++ result = append(result, se)+ }++ sort.Slice(result, func(i, j int) bool {+ return result[i].SavedAt.After(result[j].SavedAt)+ })++ return result, nil+}++// Delete removes a named state file.+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)+ }+ return fmt.Errorf("delete state file: %w", err)+ }+ return nil+}++// Clean removes state files older than the given duration.+func Clean(stateDir string, olderThan time.Duration) (int, error) {+ dir := SessionsDir(stateDir)+ cutoff := time.Now().Add(-olderThan)++ entries, err := os.ReadDir(dir)+ if err != nil {+ if os.IsNotExist(err) {+ return 0, nil+ }+ return 0, fmt.Errorf("read sessions dir: %w", err)+ }++ removed := 0+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {+ continue+ }++ info, err := entry.Info()+ if err != nil {+ continue+ }++ if info.ModTime().Before(cutoff) {+ path := filepath.Join(dir, entry.Name())+ if os.Remove(path) == nil {+ removed+++ }+ }+ }++ return removed, nil+}++// Encrypt encrypts plaintext using AES-256-GCM. The key is derived by+// SHA-256 hashing the passphrase to ensure a 32-byte key.+func Encrypt(plaintext []byte, passphrase string) ([]byte, error) {+ if passphrase == "" {+ return nil, fmt.Errorf("encryption key required")+ }++ key := deriveKey(passphrase)++ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, fmt.Errorf("create cipher: %w", err)+ }++ gcm, err := cipher.NewGCM(block)+ if err != nil {+ return nil, fmt.Errorf("create GCM: %w", err)+ }++ nonce := make([]byte, gcm.NonceSize())+ if _, err := io.ReadFull(rand.Reader, nonce); err != nil {+ return nil, fmt.Errorf("generate nonce: %w", err)+ }++ return gcm.Seal(nonce, nonce, plaintext, nil), nil+}++// Decrypt decrypts ciphertext encrypted with Encrypt.+func Decrypt(ciphertext []byte, passphrase string) ([]byte, error) {+ if passphrase == "" {+ return nil, fmt.Errorf("encryption key required")+ }++ key := deriveKey(passphrase)++ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, fmt.Errorf("create cipher: %w", err)+ }++ gcm, err := cipher.NewGCM(block)+ if err != nil {+ return nil, fmt.Errorf("create GCM: %w", err)+ }++ nonceSize := gcm.NonceSize()+ if len(ciphertext) < nonceSize {+ return nil, fmt.Errorf("ciphertext too short")+ }++ nonce, ct := ciphertext[:nonceSize], ciphertext[nonceSize:]+ plaintext, err := gcm.Open(nil, nonce, ct, nil)+ if err != nil {+ return nil, fmt.Errorf("decrypt: %w", err)+ }++ return plaintext, nil+}++// 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 nil+}++// deriveKey produces a 32-byte AES-256 key from an arbitrary passphrase.+func deriveKey(passphrase string) []byte {+ hash := sha256.Sum256([]byte(passphrase))+ return hash[:]+}++// sanitizeFilename strips path separators and problematic characters.+func sanitizeFilename(name string) string {+ name = filepath.Base(name)+ name = strings.Map(func(r rune) rune {+ if r == '/' || r == '\\' || r == ':' || r == '*' || r == '?' || r == '"' || r == '<' || r == '>' || r == '|' {+ return '_'+ }+ return r+ }, name)+ if name == "" || name == "." || name == ".." {+ return "state"+ }+ return name+}++// ResolvePath returns the full path for a named state file.+func ResolvePath(stateDir, name string) string {+ dir := SessionsDir(stateDir)+ filename := sanitizeFilename(name) + ".json"+ return filepath.Join(dir, filename)+}diff --git a/internal/state/state_test.go b/internal/state/state_test.gonew file mode 100644index 00000000..2e328357--- /dev/null+++ b/internal/state/state_test.go@@ -0,0 +1,314 @@+package state++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+ "time"+)++func TestSaveLoadRoundTrip(t *testing.T) {+ dir := t.TempDir()++ sf := &StateFile{+ Name: "test-session",+ SavedAt: time.Now().Truncate(time.Second),+ Origins: []string{"https://example.com"},+ Cookies: []Cookie{+ {Name: "sid", Value: "abc123", Domain: "example.com", Path: "/", Secure: true},+ },+ Storage: map[string]OriginStorage{+ "https://example.com": {+ Local: map[string]string{"theme": "dark"},+ Session: map[string]string{"token": "xyz"},+ },+ },+ Metadata: map[string]interface{}{+ "url": "https://example.com/page",+ "origin": "https://example.com",+ "userAgent": "Chrome/120",+ },+ }++ path, err := Save(dir, sf, "")+ if err != nil {+ t.Fatalf("Save: %v", err)+ }++ loaded, err := Load(path, "")+ if err != nil {+ t.Fatalf("Load: %v", err)+ }++ if loaded.Name != sf.Name {+ t.Errorf("name = %q, want %q", loaded.Name, sf.Name)+ }+ if len(loaded.Cookies) != 1 {+ t.Errorf("cookies count = %d, want 1", len(loaded.Cookies))+ }+ if loaded.Cookies[0].Name != "sid" {+ t.Errorf("cookie name = %q, want %q", loaded.Cookies[0].Name, "sid")+ }+ if len(loaded.Storage) != 1 {+ t.Errorf("storage origins = %d, want 1", len(loaded.Storage))+ }+ origin := loaded.Storage["https://example.com"]+ if origin.Local["theme"] != "dark" {+ t.Errorf("localStorage theme = %q, want %q", origin.Local["theme"], "dark")+ }+ if origin.Session["token"] != "xyz" {+ t.Errorf("sessionStorage token = %q, want %q", origin.Session["token"], "xyz")+ }+}++func TestSaveLoadEncrypted(t *testing.T) {+ dir := t.TempDir()+ key := "my-secret-passphrase"++ sf := &StateFile{+ Name: "encrypted-session",+ SavedAt: time.Now().Truncate(time.Second),+ Origins: []string{"https://secure.example.com"},+ Cookies: []Cookie{+ {Name: "auth", Value: "secret", Domain: "secure.example.com"},+ },+ Storage: map[string]OriginStorage{},+ Metadata: map[string]interface{}{+ "url": "https://secure.example.com",+ },+ }++ path, err := Save(dir, sf, key)+ if err != nil {+ t.Fatalf("Save encrypted: %v", err)+ }++ // Verify the file is not plain JSON+ raw, _ := os.ReadFile(path)+ var probe map[string]interface{}+ if json.Unmarshal(raw, &probe) == nil {+ // If it parses as JSON, encryption might not have worked+ // But note: Save writes encrypted bytes, not a JSON wrapper+ if _, ok := probe["name"]; ok {+ t.Error("encrypted file appears to be plain JSON")+ }+ }++ // Load with correct key+ loaded, err := Load(path, key)+ if err != nil {+ t.Fatalf("Load encrypted: %v", err)+ }+ if loaded.Name != sf.Name {+ t.Errorf("name = %q, want %q", loaded.Name, sf.Name)+ }++ // Load with wrong key should fail+ _, err = Load(path, "wrong-key")+ if err == nil {+ t.Error("Load with wrong key should fail")+ }+}++func TestEncryptDecrypt(t *testing.T) {+ plaintext := []byte("hello, world!")+ key := "test-key-123"++ ct, err := Encrypt(plaintext, key)+ if err != nil {+ t.Fatalf("Encrypt: %v", err)+ }++ pt, err := Decrypt(ct, key)+ if err != nil {+ t.Fatalf("Decrypt: %v", err)+ }++ if string(pt) != string(plaintext) {+ t.Errorf("decrypted = %q, want %q", pt, plaintext)+ }+}++func TestEncryptEmptyKey(t *testing.T) {+ _, err := Encrypt([]byte("data"), "")+ if err == nil {+ t.Error("Encrypt with empty key should fail")+ }++ _, err = Decrypt([]byte("data"), "")+ if err == nil {+ t.Error("Decrypt with empty key should fail")+ }+}++func TestValidateEncryptionKey(t *testing.T) {+ if err := ValidateEncryptionKey("valid-key"); err != nil {+ t.Errorf("valid key should pass: %v", err)+ }+ if err := ValidateEncryptionKey(""); err == nil {+ t.Error("empty key should fail")+ }+}++func TestListEmpty(t *testing.T) {+ dir := t.TempDir()++ entries, err := List(dir)+ if err != nil {+ t.Fatalf("List empty: %v", err)+ }+ if len(entries) != 0 {+ t.Errorf("entries = %d, want 0", len(entries))+ }+}++func TestListNonExistent(t *testing.T) {+ entries, err := List(filepath.Join(t.TempDir(), "nonexistent"))+ if err != nil {+ t.Fatalf("List nonexistent: %v", err)+ }+ if len(entries) != 0 {+ t.Errorf("entries = %d, want 0", len(entries))+ }+}++func TestListAfterSave(t *testing.T) {+ dir := t.TempDir()++ sf := &StateFile{+ Name: "list-test",+ SavedAt: time.Now(),+ Origins: []string{"https://example.com"},+ Storage: map[string]OriginStorage{},+ }+ if _, err := Save(dir, sf, ""); err != nil {+ t.Fatalf("Save: %v", err)+ }++ entries, err := List(dir)+ if err != nil {+ t.Fatalf("List: %v", err)+ }+ if len(entries) != 1 {+ t.Fatalf("entries = %d, want 1", len(entries))+ }+ if entries[0].Name != "list-test" {+ t.Errorf("name = %q, want %q", entries[0].Name, "list-test")+ }+}++func TestDelete(t *testing.T) {+ dir := t.TempDir()++ sf := &StateFile{+ Name: "delete-test",+ SavedAt: time.Now(),+ Storage: map[string]OriginStorage{},+ }+ if _, err := Save(dir, sf, ""); err != nil {+ t.Fatalf("Save: %v", err)+ }++ if err := Delete(dir, "delete-test"); err != nil {+ t.Fatalf("Delete: %v", err)+ }++ entries, _ := List(dir)+ if len(entries) != 0 {+ t.Error("state file should be deleted")+ }+}++func TestDeleteNotFound(t *testing.T) {+ dir := t.TempDir()+ if err := Delete(dir, "nonexistent"); err == nil {+ t.Error("delete nonexistent should fail")+ }+}++func TestClean(t *testing.T) {+ dir := t.TempDir()+ sessDir, _ := EnsureSessionsDir(dir)++ // Create a state file with old modification time+ old := &StateFile{Name: "old", SavedAt: time.Now().Add(-48 * time.Hour), Storage: map[string]OriginStorage{}}+ data, _ := json.Marshal(old)+ oldPath := filepath.Join(sessDir, "old.json")+ if err := os.WriteFile(oldPath, data, 0600); err != nil {+ t.Fatal(err)+ }+ oldTime := time.Now().Add(-48 * time.Hour)+ os.Chtimes(oldPath, oldTime, oldTime)++ // Create a recent state file+ recent := &StateFile{Name: "recent", SavedAt: time.Now(), Storage: map[string]OriginStorage{}}+ if _, err := Save(dir, recent, ""); err != nil {+ t.Fatal(err)+ }++ removed, err := Clean(dir, 24*time.Hour)+ if err != nil {+ t.Fatalf("Clean: %v", err)+ }+ if removed != 1 {+ t.Errorf("removed = %d, want 1", removed)+ }++ entries, _ := List(dir)+ if len(entries) != 1 {+ t.Errorf("remaining = %d, want 1", len(entries))+ }+}++func TestSanitizeFilename(t *testing.T) {+ tests := []struct {+ input, want string+ }{+ {"simple", "simple"},+ {"with spaces", "with spaces"},+ {"path/traversal", "traversal"},+ {"..\\evil", "evil"},+ {"", "state"},+ {".", "state"},+ {"..", "state"},+ {"file:name", "file_name"},+ {"file*name?", "file_name_"},+ }+ for _, tt := range tests {+ got := sanitizeFilename(tt.input)+ if got != tt.want {+ t.Errorf("sanitizeFilename(%q) = %q, want %q", tt.input, got, tt.want)+ }+ }+}++func TestEmptyStorage(t *testing.T) {+ dir := t.TempDir()++ sf := &StateFile{+ Name: "empty-storage",+ SavedAt: time.Now(),+ Origins: []string{},+ Cookies: []Cookie{},+ Storage: map[string]OriginStorage{},+ Metadata: map[string]interface{}{},+ }++ path, err := Save(dir, sf, "")+ if err != nil {+ t.Fatalf("Save: %v", err)+ }++ loaded, err := Load(path, "")+ if err != nil {+ t.Fatalf("Load: %v", err)+ }++ if len(loaded.Cookies) != 0 {+ t.Errorf("cookies = %d, want 0", len(loaded.Cookies))+ }+ if len(loaded.Storage) != 0 {+ t.Errorf("storage = %d, want 0", len(loaded.Storage))+ }+}diff --git a/internal/strategy/routes.go b/internal/strategy/routes.goindex b7090465..e3e66219 100644--- a/internal/strategy/routes.go+++ b/internal/strategy/routes.go@@ -20,6 +20,8 @@ func capabilityEnabled(orch *orchestrator.Orchestrator, cap routes.Capability) breturn orch.AllowsDownload()case routes.CapUpload:return orch.AllowsUpload()+ case routes.CapStateExport:+ return orch.AllowsStateExport()default:return false}@@ -38,6 +40,8 @@ func capabilitySetting(cap routes.Capability) (feature, setting, code string) {return "download", "security.allowDownload", "download_disabled"case routes.CapUpload:return "upload", "security.allowUpload", "upload_disabled"+ case routes.CapStateExport:+ return "stateExport", "security.allowStateExport", "state_export_disabled"default:return string(cap), "security.allow" + string(cap), string(cap) + "_disabled"}