Skip to content

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

fix: improving consistency of security locks

Luigi Agostic81c87d50dfa
diff --git a/README.md b/README.md
index 74e383e1..bba03d35 100644
--- a/README.md
+++ b/README.md
@@ -204,13 +204,6 @@ All fields default to `false`/empty — existing behaviour is completely unchang
Full docs at **[pinchtab.com/docs](https://pinchtab.com/docs)**
-- **[Getting Started](https://pinchtab.com/docs/get-started)** — Install and run
-- **[Core Concepts](https://pinchtab.com/docs/core-concepts)** — Instances, profiles, tabs
-- **[Headless vs Headed](https://pinchtab.com/docs/headless-vs-headed)** — Choose the right mode
-- **[API Reference](https://pinchtab.com/docs/api-reference)** — HTTP endpoints
-- **[CLI Reference](https://pinchtab.com/docs/cli-reference)** — Command-line commands
-- **[Configuration](https://pinchtab.com/docs/configuration)** — Config file and runtime settings
-
### MCP (SMCP) integration
An **SMCP plugin** in this repo lets AI agents control PinchTab via the [Model Context Protocol](https://github.com/sanctumos/smcp) (SMCP). One plugin exposes 15 tools (e.g. `pinchtab__navigate`, `pinchtab__snapshot`, `pinchtab__action`). No extra runtime deps (stdlib only). See **[plugins/README.md](plugins/README.md)** for setup (env vars and paths).
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.go
index 6ace4884..b7e2c04b 100644
--- a/cmd/pinchtab/cmd_bridge.go
+++ b/cmd/pinchtab/cmd_bridge.go
@@ -38,9 +38,7 @@ func runBridgeServer(cfg *config.RuntimeConfig) {
})
}
h.RegisterRoutes(mux, doShutdown)
- if cfg.AllowEvaluate && cfg.Token == "" {
- slog.Warn("evaluate endpoint enabled without API token", "hint", "set PINCHTAB_TOKEN for authenticated access")
- }
+ logSecurityWarnings(cfg)
// HTTP server
server := &http.Server{
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 81dd43c6..aba3e415 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -143,9 +143,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
})
handler := handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux)))
- if cfg.AllowEvaluate && cfg.Token == "" {
- slog.Warn("evaluate endpoint enabled without API token", "hint", "set PINCHTAB_TOKEN for authenticated access")
- }
+ logSecurityWarnings(cfg)
srv := &http.Server{
Addr: cfg.Bind + ":" + dashPort,
diff --git a/cmd/pinchtab/security_warnings.go b/cmd/pinchtab/security_warnings.go
new file mode 100644
index 00000000..584211c1
--- /dev/null
+++ b/cmd/pinchtab/security_warnings.go
@@ -0,0 +1,26 @@
+package main
+
+import (
+ "log/slog"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func logSecurityWarnings(cfg *config.RuntimeConfig) {
+ if cfg == nil {
+ return
+ }
+
+ enabled := cfg.EnabledSensitiveEndpoints()
+ if len(enabled) > 0 {
+ slog.Warn("sensitive endpoints enabled", "endpoints", enabled, "hint", "only enable them in trusted environments")
+ }
+
+ if cfg.Token == "" {
+ slog.Warn("api authentication disabled", "hint", "set PINCHTAB_TOKEN to require bearer auth for all endpoints")
+ }
+
+ if len(enabled) > 0 && cfg.Token == "" {
+ slog.Warn("high-risk configuration: sensitive endpoints enabled without API authentication", "endpoints", enabled, "hint", "set PINCHTAB_TOKEN or disable the sensitive endpoints")
+ }
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index d87e6b49..a9a73805 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -72,6 +72,32 @@ type RuntimeConfig struct {
Scheduler SchedulerConfig
}
+// EnabledSensitiveEndpoints returns the names of sensitive endpoint families
+// that are currently enabled in the runtime configuration.
+func (cfg *RuntimeConfig) EnabledSensitiveEndpoints() []string {
+ if cfg == nil {
+ return nil
+ }
+
+ enabled := make([]string, 0, 5)
+ if cfg.AllowEvaluate {
+ enabled = append(enabled, "evaluate")
+ }
+ if cfg.AllowMacro {
+ enabled = append(enabled, "macro")
+ }
+ if cfg.AllowScreencast {
+ enabled = append(enabled, "screencast")
+ }
+ if cfg.AllowDownload {
+ enabled = append(enabled, "download")
+ }
+ if cfg.AllowUpload {
+ enabled = append(enabled, "upload")
+ }
+ return enabled
+}
+
// SchedulerConfig holds task scheduler settings.
type SchedulerConfig struct {
Enabled bool `json:"enabled,omitempty"`
@@ -709,6 +735,11 @@ func DefaultFileConfig() FileConfig {
start := 9868
end := 9968
maxTabs := 20
+ allowEvaluate := false
+ allowMacro := false
+ allowScreencast := false
+ allowDownload := false
+ allowUpload := false
return FileConfig{
Server: ServerConfig{
Port: "9867",
@@ -724,6 +755,13 @@ func DefaultFileConfig() FileConfig {
StealthLevel: "light",
TabEvictionPolicy: "reject",
},
+ Security: SecurityConfig{
+ AllowEvaluate: &allowEvaluate,
+ AllowMacro: &allowMacro,
+ AllowScreencast: &allowScreencast,
+ AllowDownload: &allowDownload,
+ AllowUpload: &allowUpload,
+ },
Profiles: ProfilesConfig{
BaseDir: filepath.Join(userConfigDir(), "profiles"),
DefaultProfile: "default",
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index 56d31854..cc2ad4f1 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -164,6 +164,21 @@ func TestDefaultFileConfig(t *testing.T) {
if len(fc.Attach.AllowSchemes) != 2 || fc.Attach.AllowSchemes[0] != "ws" || fc.Attach.AllowSchemes[1] != "wss" {
t.Errorf("DefaultFileConfig.Attach.AllowSchemes = %v, want [ws wss]", fc.Attach.AllowSchemes)
}
+ if fc.Security.AllowEvaluate == nil || *fc.Security.AllowEvaluate {
+ t.Errorf("DefaultFileConfig.Security.AllowEvaluate = %v, want explicit false", formatBoolPtr(fc.Security.AllowEvaluate))
+ }
+ if fc.Security.AllowMacro == nil || *fc.Security.AllowMacro {
+ t.Errorf("DefaultFileConfig.Security.AllowMacro = %v, want explicit false", formatBoolPtr(fc.Security.AllowMacro))
+ }
+ if fc.Security.AllowScreencast == nil || *fc.Security.AllowScreencast {
+ t.Errorf("DefaultFileConfig.Security.AllowScreencast = %v, want explicit false", formatBoolPtr(fc.Security.AllowScreencast))
+ }
+ if fc.Security.AllowDownload == nil || *fc.Security.AllowDownload {
+ t.Errorf("DefaultFileConfig.Security.AllowDownload = %v, want explicit false", formatBoolPtr(fc.Security.AllowDownload))
+ }
+ if fc.Security.AllowUpload == nil || *fc.Security.AllowUpload {
+ t.Errorf("DefaultFileConfig.Security.AllowUpload = %v, want explicit false", formatBoolPtr(fc.Security.AllowUpload))
+ }
}
// TestLoadNestedConfig tests loading the new nested config format.
@@ -469,6 +484,50 @@ func TestDefaultFileConfigJSON(t *testing.T) {
if parsed.InstanceDefaults.Mode != "headless" {
t.Errorf("round-trip InstanceDefaults.Mode = %v, want headless", parsed.InstanceDefaults.Mode)
}
+ if parsed.Security.AllowEvaluate == nil || *parsed.Security.AllowEvaluate {
+ t.Errorf("round-trip Security.AllowEvaluate = %v, want explicit false", formatBoolPtr(parsed.Security.AllowEvaluate))
+ }
+ if parsed.Security.AllowMacro == nil || *parsed.Security.AllowMacro {
+ t.Errorf("round-trip Security.AllowMacro = %v, want explicit false", formatBoolPtr(parsed.Security.AllowMacro))
+ }
+ if parsed.Security.AllowScreencast == nil || *parsed.Security.AllowScreencast {
+ t.Errorf("round-trip Security.AllowScreencast = %v, want explicit false", formatBoolPtr(parsed.Security.AllowScreencast))
+ }
+ if parsed.Security.AllowDownload == nil || *parsed.Security.AllowDownload {
+ t.Errorf("round-trip Security.AllowDownload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowDownload))
+ }
+ if parsed.Security.AllowUpload == nil || *parsed.Security.AllowUpload {
+ t.Errorf("round-trip Security.AllowUpload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowUpload))
+ }
+}
+
+func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T) {
+ cfg := &RuntimeConfig{
+ AllowEvaluate: true,
+ AllowMacro: true,
+ AllowScreencast: true,
+ AllowDownload: true,
+ AllowUpload: true,
+ }
+
+ fc := DefaultFileConfig()
+ ApplyFileConfigToRuntime(cfg, &fc)
+
+ if cfg.AllowEvaluate {
+ t.Errorf("ApplyFileConfigToRuntime AllowEvaluate = %v, want false", cfg.AllowEvaluate)
+ }
+ if cfg.AllowMacro {
+ t.Errorf("ApplyFileConfigToRuntime AllowMacro = %v, want false", cfg.AllowMacro)
+ }
+ if cfg.AllowScreencast {
+ t.Errorf("ApplyFileConfigToRuntime AllowScreencast = %v, want false", cfg.AllowScreencast)
+ }
+ if cfg.AllowDownload {
+ t.Errorf("ApplyFileConfigToRuntime AllowDownload = %v, want false", cfg.AllowDownload)
+ }
+ if cfg.AllowUpload {
+ t.Errorf("ApplyFileConfigToRuntime AllowUpload = %v, want false", cfg.AllowUpload)
+ }
}
// Helper functions
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index cbbf9089..39f4b7e9 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -484,7 +484,9 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowMacro {
- web.ErrorCode(w, 403, "macro_disabled", "macro endpoint is disabled; enable it in config to use this endpoint", false, nil)
+ web.ErrorCode(w, 403, "macro_disabled", web.DisabledEndpointMessage("macro", "security.allowMacro"), false, map[string]any{
+ "setting": "security.allowMacro",
+ })
return
}
var req struct {
diff --git a/internal/handlers/download.go b/internal/handlers/download.go
index 487027b2..024ccc7e 100644
--- a/internal/handlers/download.go
+++ b/internal/handlers/download.go
@@ -57,7 +57,9 @@ func validateDownloadURL(rawURL string) error {
// GET /download?url=<url>[&tabId=<id>][&output=file&path=/tmp/file][&raw=true]
func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowDownload {
- web.ErrorCode(w, 403, "download_disabled", "download endpoint is disabled; enable it in config to use this endpoint", false, nil)
+ web.ErrorCode(w, 403, "download_disabled", web.DisabledEndpointMessage("download", "security.allowDownload"), false, map[string]any{
+ "setting": "security.allowDownload",
+ })
return
}
dlURL := r.URL.Query().Get("url")
diff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.go
index 38c2d47e..3de88392 100644
--- a/internal/handlers/evaluate.go
+++ b/internal/handlers/evaluate.go
@@ -23,7 +23,9 @@ func (h *Handlers) evaluateEnabled() bool {
// @Endpoint POST /evaluate
func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
if !h.evaluateEnabled() {
- web.ErrorCode(w, 403, "evaluate_disabled", "evaluate endpoint is disabled; enable it in config to use this endpoint", false, nil)
+ web.ErrorCode(w, 403, "evaluate_disabled", web.DisabledEndpointMessage("evaluate", "security.allowEvaluate"), false, map[string]any{
+ "setting": "security.allowEvaluate",
+ })
return
}
@@ -70,7 +72,9 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
// @Endpoint POST /tabs/{id}/evaluate
func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {
if !h.evaluateEnabled() {
- web.ErrorCode(w, 403, "evaluate_disabled", "evaluate endpoint is disabled; enable it in config to use this endpoint", false, nil)
+ web.ErrorCode(w, 403, "evaluate_disabled", web.DisabledEndpointMessage("evaluate", "security.allowEvaluate"), false, map[string]any{
+ "setting": "security.allowEvaluate",
+ })
return
}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index bdeebc4c..ccbf5494 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -132,10 +132,8 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("POST /find", h.HandleFind)
mux.HandleFunc("GET /screencast", h.HandleScreencast)
mux.HandleFunc("GET /screencast/tabs", h.HandleScreencastAll)
- if h.Config != nil && h.Config.AllowEvaluate {
- mux.HandleFunc("POST /tabs/{id}/evaluate", h.HandleTabEvaluate)
- mux.HandleFunc("POST /evaluate", h.HandleEvaluate)
- }
+ mux.HandleFunc("POST /tabs/{id}/evaluate", h.HandleTabEvaluate)
+ mux.HandleFunc("POST /evaluate", h.HandleEvaluate)
mux.HandleFunc("GET /welcome", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(assets.WelcomeHTML))
diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.go
index 61086c62..574a3a22 100644
--- a/internal/handlers/handlers_test.go
+++ b/internal/handlers/handlers_test.go
@@ -3,6 +3,7 @@ package handlers
import (
"bytes"
"context"
+ "encoding/json"
"fmt"
"net/http"
"net/http/httptest"
@@ -119,6 +120,42 @@ func TestHandlers(t *testing.T) {
}
}
+func TestHelpIncludesSecurityStatus(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/help", nil)
+ w := httptest.NewRecorder()
+ h.HandleHelp(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200 from /help, got %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), "\"security\"") {
+ t.Fatalf("expected /help response to include security status")
+ }
+ if !strings.Contains(w.Body.String(), "security.allowEvaluate") {
+ t.Fatalf("expected /help response to include locked setting names")
+ }
+}
+
+func TestOpenAPIIncludesSensitiveEndpointStatus(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{AllowDownload: true}, nil, nil, nil)
+
+ req := httptest.NewRequest("GET", "/openapi.json", nil)
+ w := httptest.NewRecorder()
+ h.HandleOpenAPI(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200 from /openapi.json, got %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), "\"x-pinchtab-security\"") {
+ t.Fatalf("expected /openapi.json response to include security metadata")
+ }
+ if !strings.Contains(w.Body.String(), "\"x-pinchtab-enabled\":true") {
+ t.Fatalf("expected /openapi.json response to mark enabled sensitive endpoints")
+ }
+}
+
func TestHandleNavigate(t *testing.T) {
cfg := &config.RuntimeConfig{}
m := &mockBridge{}
@@ -212,7 +249,7 @@ func TestRoutesRegistration(t *testing.T) {
}
}
-func TestEvaluateRouteNotRegisteredByDefault(t *testing.T) {
+func TestEvaluateRouteLockedByDefault(t *testing.T) {
h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
mux := http.NewServeMux()
h.RegisterRoutes(mux, nil)
@@ -220,8 +257,11 @@ func TestEvaluateRouteNotRegisteredByDefault(t *testing.T) {
req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
- if w.Code != 404 {
- t.Fatalf("expected 404 when evaluate is disabled, got %d", w.Code)
+ if w.Code != 403 {
+ t.Fatalf("expected 403 when evaluate is disabled, got %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), "security.allowEvaluate") {
+ t.Fatalf("expected evaluate lock response to include the setting name, got %s", w.Body.String())
}
}
@@ -237,3 +277,25 @@ func TestEvaluateRouteRegisteredWhenEnabled(t *testing.T) {
t.Fatalf("expected evaluate route to be active, got %d", w.Code)
}
}
+
+func TestSensitiveTabRouteLockedByDefault(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ req := httptest.NewRequest("POST", "/tabs/tab1/evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 403 {
+ t.Fatalf("expected 403 when tab evaluate is disabled, got %d", w.Code)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
+ t.Fatalf("failed to parse response: %v", err)
+ }
+ if payload["code"] != "evaluate_disabled" {
+ t.Fatalf("expected evaluate_disabled code, got %v", payload["code"])
+ }
+}
diff --git a/internal/handlers/help.go b/internal/handlers/help.go
index 80ba7392..59bd8008 100644
--- a/internal/handlers/help.go
+++ b/internal/handlers/help.go
@@ -7,22 +7,32 @@ import (
)
func (h *Handlers) HandleHelp(wr http.ResponseWriter, _ *http.Request) {
+ security := h.endpointSecurityStates()
web.JSON(wr, 200, map[string]any{
"name": "pinchtab",
"endpoints": map[string]any{
- "GET /health": "health status",
- "GET /tabs": "list tabs",
- "GET /metrics": "runtime metrics",
- "GET /help": "this help payload",
- "GET /openapi.json": "lightweight machine-readable API schema",
- "GET /text": "extract page text (supports mode=raw,maxChars=<int>,format=text)",
- "POST|GET /navigate": "navigate tab (JSON body or query params)",
- "GET /nav": "alias for GET /navigate",
- "POST|GET /action": "run a single action (JSON body or query params)",
- "POST /actions": "run multiple actions",
- "POST /macro": "run macro steps with single request",
- "GET /snapshot": "accessibility snapshot",
+ "GET /health": "health status",
+ "GET /tabs": "list tabs",
+ "GET /metrics": "runtime metrics",
+ "GET /help": "this help payload",
+ "GET /openapi.json": "lightweight machine-readable API schema",
+ "GET /text": "extract page text (supports mode=raw,maxChars=<int>,format=text)",
+ "POST|GET /navigate": "navigate tab (JSON body or query params)",
+ "GET /nav": "alias for GET /navigate",
+ "POST|GET /action": "run a single action (JSON body or query params)",
+ "POST /actions": "run multiple actions",
+ "GET /snapshot": "accessibility snapshot",
+ "POST /evaluate": endpointStatusSummary(security["evaluate"], "run JavaScript in the current tab"),
+ "POST /tabs/{id}/evaluate": endpointStatusSummary(security["evaluate"], "run JavaScript in a specific tab"),
+ "POST /macro": endpointStatusSummary(security["macro"], "run macro steps with single request"),
+ "GET /download": endpointStatusSummary(security["download"], "download a URL using the browser session"),
+ "GET /tabs/{id}/download": endpointStatusSummary(security["download"], "download a URL with a specific tab context"),
+ "POST /upload": endpointStatusSummary(security["upload"], "set files on a file input"),
+ "POST /tabs/{id}/upload": endpointStatusSummary(security["upload"], "set files on a file input in a specific tab"),
+ "GET /screencast": endpointStatusSummary(security["screencast"], "stream live tab frames"),
+ "GET /screencast/tabs": endpointStatusSummary(security["screencast"], "list tabs available for live capture"),
},
+ "security": security,
"notes": []string{
"Use Authorization: Bearer <token> when auth is enabled.",
"Prefer /text with maxChars for token-efficient reads.",
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index e1e34986..8a93763c 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -7,12 +7,14 @@ import (
)
func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
+ security := h.endpointSecurityStates()
web.JSON(w, 200, map[string]any{
"openapi": "3.0.0",
"info": map[string]any{
"title": "Pinchtab API",
"version": "0.7.x-local",
},
+ "x-pinchtab-security": security,
"paths": map[string]any{
"/health": map[string]any{"get": map[string]any{"summary": "Health"}},
"/tabs": map[string]any{"get": map[string]any{"summary": "List tabs"}},
@@ -23,8 +25,52 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
"/nav": map[string]any{"get": map[string]any{"summary": "Navigate alias"}},
"/action": map[string]any{"post": map[string]any{"summary": "Single action"}, "get": map[string]any{"summary": "Single action (query params)"}},
"/actions": map[string]any{"post": map[string]any{"summary": "Batch actions"}},
- "/macro": map[string]any{"post": map[string]any{"summary": "Macro action pipeline"}},
"/snapshot": map[string]any{"get": map[string]any{"summary": "Accessibility snapshot"}},
+ "/evaluate": map[string]any{"post": map[string]any{
+ "summary": "Run JavaScript in the current tab",
+ "description": security["evaluate"].Message,
+ "x-pinchtab-enabled": security["evaluate"].Enabled,
+ }},
+ "/tabs/{id}/evaluate": map[string]any{"post": map[string]any{
+ "summary": "Run JavaScript in a specific tab",
+ "description": security["evaluate"].Message,
+ "x-pinchtab-enabled": security["evaluate"].Enabled,
+ }},
+ "/macro": map[string]any{"post": map[string]any{
+ "summary": "Macro action pipeline",
+ "description": security["macro"].Message,
+ "x-pinchtab-enabled": security["macro"].Enabled,
+ }},
+ "/download": map[string]any{"get": map[string]any{
+ "summary": "Download a URL using the browser session",
+ "description": security["download"].Message,
+ "x-pinchtab-enabled": security["download"].Enabled,
+ }},
+ "/tabs/{id}/download": map[string]any{"get": map[string]any{
+ "summary": "Download a URL with a specific tab context",
+ "description": security["download"].Message,
+ "x-pinchtab-enabled": security["download"].Enabled,
+ }},
+ "/upload": map[string]any{"post": map[string]any{
+ "summary": "Set files on a file input",
+ "description": security["upload"].Message,
+ "x-pinchtab-enabled": security["upload"].Enabled,
+ }},
+ "/tabs/{id}/upload": map[string]any{"post": map[string]any{
+ "summary": "Set files on a file input in a specific tab",
+ "description": security["upload"].Message,
+ "x-pinchtab-enabled": security["upload"].Enabled,
+ }},
+ "/screencast": map[string]any{"get": map[string]any{
+ "summary": "Stream live tab frames",
+ "description": security["screencast"].Message,
+ "x-pinchtab-enabled": security["screencast"].Enabled,
+ }},
+ "/screencast/tabs": map[string]any{"get": map[string]any{
+ "summary": "List tabs available for live capture",
+ "description": security["screencast"].Message,
+ "x-pinchtab-enabled": security["screencast"].Enabled,
+ }},
},
})
}
diff --git a/internal/handlers/screencast.go b/internal/handlers/screencast.go
index cfec5e76..c4081317 100644
--- a/internal/handlers/screencast.go
+++ b/internal/handlers/screencast.go
@@ -20,7 +20,9 @@ import (
// Query params: tabId (required), quality (1-100, default 40), maxWidth (default 800), fps (1-30, default 5)
func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowScreencast {
- web.ErrorCode(w, 403, "screencast_disabled", "screencast endpoint is disabled; enable it in config to use this endpoint", false, nil)
+ web.ErrorCode(w, 403, "screencast_disabled", web.DisabledEndpointMessage("screencast", "security.allowScreencast"), false, map[string]any{
+ "setting": "security.allowScreencast",
+ })
return
}
tabID := r.URL.Query().Get("tabId")
@@ -148,7 +150,9 @@ func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
// HandleScreencastAll returns info for building a multi-tab screencast view.
func (h *Handlers) HandleScreencastAll(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowScreencast {
- web.ErrorCode(w, 403, "screencast_disabled", "screencast endpoint is disabled; enable it in config to use this endpoint", false, nil)
+ web.ErrorCode(w, 403, "screencast_disabled", web.DisabledEndpointMessage("screencast", "security.allowScreencast"), false, map[string]any{
+ "setting": "security.allowScreencast",
+ })
return
}
type tabInfo struct {
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
new file mode 100644
index 00000000..8edee09c
--- /dev/null
+++ b/internal/handlers/security.go
@@ -0,0 +1,68 @@
+package handlers
+
+import "github.com/pinchtab/pinchtab/internal/web"
+
+type endpointSecurityState struct {
+ Enabled bool `json:"enabled"`
+ Setting string `json:"setting"`
+ Message string `json:"message"`
+ Paths []string `json:"paths"`
+}
+
+func (h *Handlers) macroEnabled() bool {
+ return h != nil && h.Config != nil && h.Config.AllowMacro
+}
+
+func (h *Handlers) screencastEnabled() bool {
+ return h != nil && h.Config != nil && h.Config.AllowScreencast
+}
+
+func (h *Handlers) downloadEnabled() bool {
+ return h != nil && h.Config != nil && h.Config.AllowDownload
+}
+
+func (h *Handlers) uploadEnabled() bool {
+ return h != nil && h.Config != nil && h.Config.AllowUpload
+}
+
+func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
+ return map[string]endpointSecurityState{
+ "evaluate": {
+ Enabled: h.evaluateEnabled(),
+ Setting: "security.allowEvaluate",
+ Message: web.DisabledEndpointMessage("evaluate", "security.allowEvaluate"),
+ Paths: []string{"POST /evaluate", "POST /tabs/{id}/evaluate"},
+ },
+ "macro": {
+ Enabled: h.macroEnabled(),
+ Setting: "security.allowMacro",
+ Message: web.DisabledEndpointMessage("macro", "security.allowMacro"),
+ Paths: []string{"POST /macro"},
+ },
+ "screencast": {
+ Enabled: h.screencastEnabled(),
+ Setting: "security.allowScreencast",
+ Message: web.DisabledEndpointMessage("screencast", "security.allowScreencast"),
+ Paths: []string{"GET /screencast", "GET /screencast/tabs", "GET /instances/{id}/screencast", "GET /instances/{id}/proxy/screencast"},
+ },
+ "download": {
+ Enabled: h.downloadEnabled(),
+ Setting: "security.allowDownload",
+ Message: web.DisabledEndpointMessage("download", "security.allowDownload"),
+ Paths: []string{"GET /download", "GET /tabs/{id}/download"},
+ },
+ "upload": {
+ Enabled: h.uploadEnabled(),
+ Setting: "security.allowUpload",
+ Message: web.DisabledEndpointMessage("upload", "security.allowUpload"),
+ Paths: []string{"POST /upload", "POST /tabs/{id}/upload"},
+ },
+ }
+}
+
+func endpointStatusSummary(state endpointSecurityState, summary string) string {
+ if state.Enabled {
+ return summary + " (enabled)"
+ }
+ return summary + " (locked by " + state.Setting + ")"
+}
diff --git a/internal/handlers/upload.go b/internal/handlers/upload.go
index 55a1f5e1..0dcdbcfc 100644
--- a/internal/handlers/upload.go
+++ b/internal/handlers/upload.go
@@ -37,7 +37,9 @@ type uploadRequest struct {
// Both can be combined. Files are written to a temp dir and passed to CDP.
func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {
if !h.Config.AllowUpload {
- web.ErrorCode(w, 403, "upload_disabled", "upload endpoint is disabled; enable it in config to use this endpoint", false, nil)
+ web.ErrorCode(w, 403, "upload_disabled", web.DisabledEndpointMessage("upload", "security.allowUpload"), false, map[string]any{
+ "setting": "security.allowUpload",
+ })
return
}
tabID := r.URL.Query().Get("tabId")
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
index b65b71e4..c7a0ce2a 100644
--- a/internal/orchestrator/handlers.go
+++ b/internal/orchestrator/handlers.go
@@ -6,6 +6,14 @@ import (
"github.com/pinchtab/pinchtab/internal/web"
)
+func registerCapabilityRoute(mux *http.ServeMux, route string, enabled bool, feature, setting, code string, next http.HandlerFunc) {
+ if enabled {
+ mux.HandleFunc(route, next)
+ return
+ }
+ mux.HandleFunc(route, web.DisabledEndpointHandler(feature, setting, code))
+}
+
func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
// Profile management
mux.HandleFunc("POST /profiles/{id}/start", o.handleStartByID)
@@ -24,16 +32,16 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("POST /instances/{id}/stop", o.handleStopByInstanceID)
mux.HandleFunc("GET /instances/{id}/logs", o.handleLogsByID)
mux.HandleFunc("GET /instances/{id}/tabs", o.handleInstanceTabs)
- mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)
mux.HandleFunc("POST /instances/{id}/tabs/open", o.handleInstanceTabOpen)
mux.HandleFunc("POST /instances/{id}/tab", o.proxyToInstance)
- mux.HandleFunc("GET /instances/{id}/screencast", o.proxyToInstance)
+ registerCapabilityRoute(mux, "GET /instances/{id}/proxy/screencast", o.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", o.handleProxyScreencast)
+ registerCapabilityRoute(mux, "GET /instances/{id}/screencast", o.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", o.proxyToInstance)
// Tab operations - custom handlers
mux.HandleFunc("POST /tabs/{id}/close", o.handleTabClose)
// Tab operations - generic proxy (all route to the appropriate instance)
- tabProxyRoutes := []string{
+ for _, route := range []string{
"POST /tabs/{id}/navigate",
"GET /tabs/{id}/snapshot",
"GET /tabs/{id}/screenshot",
@@ -42,21 +50,18 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
"GET /tabs/{id}/text",
"GET /tabs/{id}/pdf",
"POST /tabs/{id}/pdf",
- "GET /tabs/{id}/download",
- "POST /tabs/{id}/upload",
"POST /tabs/{id}/lock",
"POST /tabs/{id}/unlock",
"GET /tabs/{id}/cookies",
"POST /tabs/{id}/cookies",
"GET /tabs/{id}/metrics",
"POST /tabs/{id}/find",
- }
- if o.allowEvaluate {
- tabProxyRoutes = append(tabProxyRoutes, "POST /tabs/{id}/evaluate")
- }
- for _, route := range tabProxyRoutes {
+ } {
mux.HandleFunc(route, o.proxyTabRequest)
}
+ registerCapabilityRoute(mux, "POST /tabs/{id}/evaluate", o.AllowsEvaluate(), "evaluate", "security.allowEvaluate", "evaluate_disabled", o.proxyTabRequest)
+ registerCapabilityRoute(mux, "GET /tabs/{id}/download", o.AllowsDownload(), "download", "security.allowDownload", "download_disabled", o.proxyTabRequest)
+ registerCapabilityRoute(mux, "POST /tabs/{id}/upload", o.AllowsUpload(), "upload", "security.allowUpload", "upload_disabled", o.proxyTabRequest)
}
func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index c1d019df..cc4c0b79 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -203,6 +203,26 @@ func (o *Orchestrator) ApplyRuntimeConfig(cfg *config.RuntimeConfig) {
}
}
+func (o *Orchestrator) AllowsEvaluate() bool {
+ return o != nil && o.allowEvaluate
+}
+
+func (o *Orchestrator) AllowsMacro() bool {
+ return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowMacro
+}
+
+func (o *Orchestrator) AllowsScreencast() bool {
+ return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowScreencast
+}
+
+func (o *Orchestrator) AllowsDownload() bool {
+ return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowDownload
+}
+
+func (o *Orchestrator) AllowsUpload() bool {
+ return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowUpload
+}
+
func (o *Orchestrator) SetPortRange(start, end int) {
o.portAllocator = NewPortAllocator(start, end)
}
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index fdea2d59..8c4962d8 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -1,9 +1,14 @@
package orchestrator
import (
+ "bytes"
+ "net/http"
+ "net/http/httptest"
+ "strings"
"testing"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
)
func TestOrchestrator_Launch_Lifecycle(t *testing.T) {
@@ -228,3 +233,35 @@ func TestOrchestrator_Attach_DuplicateName(t *testing.T) {
t.Error("expected error when attaching duplicate name")
}
}
+
+func TestOrchestrator_RegisterHandlers_LocksSensitiveRoutes(t *testing.T) {
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{})
+
+ mux := http.NewServeMux()
+ o.RegisterHandlers(mux)
+
+ tests := []struct {
+ method string
+ path string
+ body string
+ setting string
+ }{
+ {method: "POST", path: "/tabs/tab1/evaluate", body: `{"expression":"1+1"}`, setting: "security.allowEvaluate"},
+ {method: "GET", path: "/tabs/tab1/download", setting: "security.allowDownload"},
+ {method: "POST", path: "/tabs/tab1/upload", body: `{}`, setting: "security.allowUpload"},
+ {method: "GET", path: "/instances/inst1/screencast", setting: "security.allowScreencast"},
+ }
+
+ for _, tt := range tests {
+ req := httptest.NewRequest(tt.method, tt.path, bytes.NewBufferString(tt.body))
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != 403 {
+ t.Fatalf("%s %s expected 403, got %d", tt.method, tt.path, w.Code)
+ }
+ if !strings.Contains(w.Body.String(), tt.setting) {
+ t.Fatalf("%s %s expected setting %s in response, got %s", tt.method, tt.path, tt.setting, w.Body.String())
+ }
+ }
+}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index f23fe293..4a058f93 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -147,17 +147,21 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
shorthandRoutes := []string{
"GET /snapshot", "GET /screenshot", "GET /text",
- "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
+ "POST /navigate", "POST /action", "POST /actions",
"POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /cookies", "POST /cookies",
- "GET /download", "POST /upload",
"GET /stealth/status", "POST /fingerprint/rotate",
- "GET /screencast", "GET /screencast/tabs",
- "POST /find", "POST /macro",
+ "POST /find",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToManaged)
}
+ strategy.RegisterCapabilityRoute(mux, "POST /evaluate", s.orch.AllowsEvaluate(), "evaluate", "security.allowEvaluate", "evaluate_disabled", s.proxyToManaged)
+ strategy.RegisterCapabilityRoute(mux, "GET /download", s.orch.AllowsDownload(), "download", "security.allowDownload", "download_disabled", s.proxyToManaged)
+ strategy.RegisterCapabilityRoute(mux, "POST /upload", s.orch.AllowsUpload(), "upload", "security.allowUpload", "upload_disabled", s.proxyToManaged)
+ strategy.RegisterCapabilityRoute(mux, "GET /screencast", s.orch.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", s.proxyToManaged)
+ strategy.RegisterCapabilityRoute(mux, "GET /screencast/tabs", s.orch.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", s.proxyToManaged)
+ strategy.RegisterCapabilityRoute(mux, "POST /macro", s.orch.AllowsMacro(), "macro", "security.allowMacro", "macro_disabled", s.proxyToManaged)
mux.HandleFunc("GET /tabs", s.handleTabs)
mux.HandleFunc("GET /autorestart/status", s.handleStatus)
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index f17e45cf..1f30cab3 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -43,17 +43,21 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
// Shorthand endpoints proxy to first running instance.
shorthandRoutes := []string{
"GET /snapshot", "GET /screenshot", "GET /text",
- "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
+ "POST /navigate", "POST /action", "POST /actions",
"POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /cookies", "POST /cookies",
- "GET /download", "POST /upload",
"GET /stealth/status", "POST /fingerprint/rotate",
- "GET /screencast", "GET /screencast/tabs",
- "POST /find", "POST /macro",
+ "POST /find",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)
}
+ strategy.RegisterCapabilityRoute(mux, "POST /evaluate", s.orch.AllowsEvaluate(), "evaluate", "security.allowEvaluate", "evaluate_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "GET /download", s.orch.AllowsDownload(), "download", "security.allowDownload", "download_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "POST /upload", s.orch.AllowsUpload(), "upload", "security.allowUpload", "upload_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "GET /screencast", s.orch.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "GET /screencast/tabs", s.orch.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "POST /macro", s.orch.AllowsMacro(), "macro", "security.allowMacro", "macro_disabled", s.proxyToFirst)
// /tabs returns empty list when no instances running.
mux.HandleFunc("GET /tabs", s.handleTabs)
diff --git a/internal/strategy/gating.go b/internal/strategy/gating.go
new file mode 100644
index 00000000..af165641
--- /dev/null
+++ b/internal/strategy/gating.go
@@ -0,0 +1,17 @@
+package strategy
+
+import (
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+// RegisterCapabilityRoute registers a route that either proxies to the active
+// handler or returns a feature-gated 403 when the capability is disabled.
+func RegisterCapabilityRoute(mux *http.ServeMux, route string, enabled bool, feature, setting, code string, handler http.HandlerFunc) {
+ if enabled {
+ mux.HandleFunc(route, handler)
+ return
+ }
+ mux.HandleFunc(route, web.DisabledEndpointHandler(feature, setting, code))
+}
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index 51e059a7..4973f05b 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -51,17 +51,21 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
// Shorthand endpoints — all proxy to first running instance.
shorthandRoutes := []string{
"GET /snapshot", "GET /screenshot", "GET /text",
- "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
+ "POST /navigate", "POST /action", "POST /actions",
"POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /cookies", "POST /cookies",
- "GET /download", "POST /upload",
"GET /stealth/status", "POST /fingerprint/rotate",
- "GET /screencast", "GET /screencast/tabs",
- "POST /find", "POST /macro",
+ "POST /find",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)
}
+ strategy.RegisterCapabilityRoute(mux, "POST /evaluate", s.orch.AllowsEvaluate(), "evaluate", "security.allowEvaluate", "evaluate_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "GET /download", s.orch.AllowsDownload(), "download", "security.allowDownload", "download_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "POST /upload", s.orch.AllowsUpload(), "upload", "security.allowUpload", "upload_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "GET /screencast", s.orch.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "GET /screencast/tabs", s.orch.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", s.proxyToFirst)
+ strategy.RegisterCapabilityRoute(mux, "POST /macro", s.orch.AllowsMacro(), "macro", "security.allowMacro", "macro_disabled", s.proxyToFirst)
mux.HandleFunc("GET /tabs", s.handleTabs)
}
diff --git a/internal/strategy/simple/simple_test.go b/internal/strategy/simple/simple_test.go
index 6a71a005..bc882204 100644
--- a/internal/strategy/simple/simple_test.go
+++ b/internal/strategy/simple/simple_test.go
@@ -1,14 +1,31 @@
package simple
import (
+ "context"
"encoding/json"
+ "io"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/proxy"
)
+type mockRunner struct {
+ portAvail bool
+}
+
+func (m *mockRunner) Run(context.Context, string, []string, []string, io.Writer, io.Writer) (orchestrator.Cmd, error) {
+ return nil, nil
+}
+
+func (m *mockRunner) IsPortAvailable(string) bool {
+ return m.portAvail
+}
+
// fakeBridge creates a test server that mimics a bridge instance.
func fakeBridge(t *testing.T) *httptest.Server {
t.Helper()
@@ -92,3 +109,23 @@ func TestStrategy_HandleTabs_NoInstances(t *testing.T) {
t.Errorf("expected 200, got %d", rec.Code)
}
}
+
+func TestStrategy_RegisterRoutes_LocksSensitiveShorthandRoutes(t *testing.T) {
+ orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ orch.ApplyRuntimeConfig(&config.RuntimeConfig{})
+
+ s := &Strategy{orch: orch}
+ mux := http.NewServeMux()
+ s.RegisterRoutes(mux)
+
+ req := httptest.NewRequest("POST", "/evaluate", strings.NewReader(`{"expression":"1+1"}`))
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, req)
+
+ if rec.Code != 403 {
+ t.Fatalf("expected 403, got %d: %s", rec.Code, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "security.allowEvaluate") {
+ t.Fatalf("expected lock response to mention security.allowEvaluate, got %s", rec.Body.String())
+ }
+}
diff --git a/internal/web/endpointlock.go b/internal/web/endpointlock.go
new file mode 100644
index 00000000..a9488a84
--- /dev/null
+++ b/internal/web/endpointlock.go
@@ -0,0 +1,20 @@
+package web
+
+import (
+ "fmt"
+ "net/http"
+)
+
+// DisabledEndpointMessage returns a consistent message for locked endpoint families.
+func DisabledEndpointMessage(feature, setting string) string {
+ return fmt.Sprintf("%s endpoint is disabled; enable %s in config to use this endpoint", feature, setting)
+}
+
+// DisabledEndpointHandler returns a handler that reports a feature gate lock.
+func DisabledEndpointHandler(feature, setting, code string) http.HandlerFunc {
+ return func(w http.ResponseWriter, _ *http.Request) {
+ ErrorCode(w, http.StatusForbidden, code, DisabledEndpointMessage(feature, setting), false, map[string]any{
+ "setting": setting,
+ })
+ }
+}