Skip to content

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

feat: strick security defaults

Luigi Agostib023898d394f
diff --git a/README.md b/README.md
index bba03d35..40e3c3d8 100644
--- a/README.md
+++ b/README.md
@@ -166,37 +166,23 @@ Read more in the [Core Concepts](https://pinchtab.com/docs/core-concepts) guide.
---
-## Security — Prompt Injection Defense (IDPI)
-
-When an AI agent fetches arbitrary web pages, attackers can embed hidden instructions in the page content that attempt to override the agent's system prompt. PinchTab includes an optional, layered defense against this threat called **IDPI** (Indirect Prompt Injection defense).
-
-Enable it in your `config.json`:
-
-```json
-{
- "security": {
- "idpi": {
- "enabled": true,
- "allowedDomains": ["github.com", "*.github.com"],
- "strictMode": false,
- "scanContent": true,
- "wrapContent": false,
- "customPatterns": []
- }
- }
-}
-```
+## Security
+
+PinchTab defaults to a local-first posture:
+
+- `server.bind = 127.0.0.1`
+- sensitive endpoint families are off by default
+- attach is off by default
+- IDPI is enabled by default with a local-only website allowlist
+
+Two controls are independent and both matter:
+
+- the API token controls who can use the server
+- the security feature gates control what the server is allowed to do
-| Option | Default | Description |
-|--------|---------|-------------|
-| `enabled` | `false` | Master switch. No IDPI checks are performed when false |
-| `allowedDomains` | `[]` | Navigation whitelist. Patterns: `"example.com"`, `"*.example.com"`, `"*"` |
-| `strictMode` | `false` | `true` = HTTP 403 block; `false` = warn via `X-IDPI-Warning` header |
-| `scanContent` | `false` | Scan `/snapshot` and `/text` responses for injection phrases |
-| `wrapContent` | `false` | Wrap `/text` output in `<untrusted_web_content>` delimiters for downstream LLMs |
-| `customPatterns` | `[]` | Additional injection phrases to detect (case-insensitive) |
+IDPI adds a browser-content defense layer by restricting allowed domains and protecting extracted content from indirect prompt injection.
-All fields default to `false`/empty — existing behaviour is completely unchanged unless you opt in.
+See the full guide: [docs/guides/security.md](docs/guides/security.md)
---
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.go
index b7e2c04b..982b54e3 100644
--- a/cmd/pinchtab/cmd_bridge.go
+++ b/cmd/pinchtab/cmd_bridge.go
@@ -20,7 +20,11 @@ import (
// This is used for spawned instances by the orchestrator
func runBridgeServer(cfg *config.RuntimeConfig) {
listenAddr := cfg.ListenAddr()
- slog.Info("🦀 Pinchtab Bridge", "listen", listenAddr, "profile", cfg.ProfileDir)
+ printStartupBanner(cfg, startupBannerOptions{
+ Mode: "bridge",
+ ListenAddr: listenAddr,
+ ProfileDir: cfg.ProfileDir,
+ })
// Create a bridge instance with lazy initialization
// Chrome will be initialized on first request via ensureChrome()
@@ -51,7 +55,6 @@ func runBridgeServer(cfg *config.RuntimeConfig) {
}
go func() {
- slog.Info("bridge listening", "addr", listenAddr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("server error", "err", err)
os.Exit(1)
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index 9baa14d9..80074a85 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -24,6 +24,7 @@ MODES:
pinchtab server Start full server explicitly
pinchtab bridge Start single-instance bridge-only server
pinchtab connect <name> Get URL for a running profile
+ pinchtab security Review runtime security posture
QUICK START (requires running server):
pinchtab quick <url> Navigate + analyze page (beginner-friendly)
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index aba3e415..95183d27 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -37,8 +37,12 @@ func runDashboard(cfg *config.RuntimeConfig) {
dashPort = "9870"
}
startedAt := time.Now()
-
- slog.Info("🦀 PinchTab", "port", dashPort)
+ printStartupBanner(cfg, startupBannerOptions{
+ Mode: "server",
+ ListenAddr: cfg.Bind + ":" + dashPort,
+ PublicURL: fmt.Sprintf("http://localhost:%s", dashPort),
+ Strategy: cfg.Strategy,
+ })
profilesDir := cfg.ProfilesBaseDir
if err := os.MkdirAll(profilesDir, 0755); err != nil {
@@ -247,8 +251,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
// Periodic health check: log tabs and Chrome process info every 30 seconds
go periodicHealthCheck(orch)
- slog.Info("dashboard ready", "url", fmt.Sprintf("http://localhost:%s", dashPort))
-
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
slog.Error("server", "err", err)
os.Exit(1)
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
new file mode 100644
index 00000000..9bf53aa9
--- /dev/null
+++ b/cmd/pinchtab/cmd_security.go
@@ -0,0 +1,233 @@
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "reflect"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func handleSecurityCommand(cfg *config.RuntimeConfig) {
+ warnings := assessSecurityWarnings(cfg)
+ recommended := recommendedSecurityDefaultLines(cfg)
+
+ fmt.Println("Security posture:")
+ fmt.Println()
+ printSecuritySummary(os.Stdout, cfg, " ")
+
+ if len(warnings) == 0 {
+ fmt.Println("Warnings:")
+ fmt.Println()
+ fmt.Println(" none")
+ } else {
+ fmt.Println("Warnings:")
+ fmt.Println()
+ for _, warning := range warnings {
+ fmt.Printf(" - %s\n", warning.Message)
+ for i := 0; i+1 < len(warning.Attrs); i += 2 {
+ key, ok := warning.Attrs[i].(string)
+ if !ok || key == "hint" {
+ continue
+ }
+ fmt.Printf(" %s: %s\n", key, formatSecurityValue(warning.Attrs[i+1]))
+ }
+ for i := 0; i+1 < len(warning.Attrs); i += 2 {
+ key, ok := warning.Attrs[i].(string)
+ if ok && key == "hint" {
+ fmt.Printf(" hint: %s\n", formatSecurityValue(warning.Attrs[i+1]))
+ }
+ }
+ }
+ }
+
+ fmt.Println()
+ fmt.Println("Recommended security defaults:")
+ fmt.Println()
+ if len(recommended) == 0 {
+ fmt.Println(" none")
+ } else {
+ printRecommendedSecurityDefaults(recommended)
+ }
+ fmt.Println()
+
+ if !isInteractiveTerminal() {
+ fmt.Println("Interactive restore skipped because stdin/stdout is not a terminal.")
+ return
+ }
+
+ if !promptRestoreDefaults() {
+ fmt.Println("No changes made.")
+ return
+ }
+
+ configPath, changed, err := restoreSecurityDefaults()
+ if err != nil {
+ fmt.Printf("Error restoring defaults: %v\n", err)
+ os.Exit(1)
+ }
+ if !changed {
+ fmt.Printf("Security defaults already match %s\n", configPath)
+ return
+ }
+
+ fmt.Printf("Security defaults restored in %s\n", configPath)
+ fmt.Println("Restart PinchTab to apply file-based changes.")
+}
+
+func formatSecurityValue(value any) string {
+ switch v := value.(type) {
+ case []string:
+ return strings.Join(v, ", ")
+ default:
+ return fmt.Sprint(v)
+ }
+}
+
+func securityUsage() {
+ fmt.Println("Usage: pinchtab security")
+ fmt.Println()
+ fmt.Println("Shows runtime security posture and offers to restore recommended security defaults.")
+}
+
+func printRecommendedSecurityDefaults(lines []string) {
+ for _, line := range lines {
+ fmt.Printf(" - %s\n", line)
+ }
+}
+
+func recommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
+ posture := assessSecurityPosture(cfg)
+ ordered := []string{
+ "server.bind = 127.0.0.1",
+ "security.allowEvaluate = false",
+ "security.allowMacro = false",
+ "security.allowScreencast = false",
+ "security.allowDownload = false",
+ "security.allowUpload = false",
+ "security.attach.enabled = false",
+ "security.attach.allowHosts = 127.0.0.1,localhost,::1",
+ "security.attach.allowSchemes = ws,wss",
+ "security.idpi.enabled = true",
+ "security.idpi.allowedDomains = 127.0.0.1,localhost,::1",
+ "security.idpi.strictMode = true",
+ "security.idpi.scanContent = true",
+ "security.idpi.wrapContent = true",
+ }
+ needed := make(map[string]bool, len(ordered))
+
+ for _, check := range posture.Checks {
+ if check.Passed {
+ continue
+ }
+ switch check.ID {
+ case "bind_loopback":
+ needed["server.bind = 127.0.0.1"] = true
+ case "sensitive_endpoints_disabled":
+ needed["security.allowEvaluate = false"] = true
+ needed["security.allowMacro = false"] = true
+ needed["security.allowScreencast = false"] = true
+ needed["security.allowDownload = false"] = true
+ needed["security.allowUpload = false"] = true
+ case "attach_disabled":
+ needed["security.attach.enabled = false"] = true
+ needed["security.attach.allowHosts = 127.0.0.1,localhost,::1"] = true
+ needed["security.attach.allowSchemes = ws,wss"] = true
+ case "attach_local_only":
+ needed["security.attach.allowHosts = 127.0.0.1,localhost,::1"] = true
+ needed["security.attach.allowSchemes = ws,wss"] = true
+ case "idpi_whitelist_scoped", "idpi_strict_mode", "idpi_content_protection":
+ needed["security.idpi.enabled = true"] = true
+ needed["security.idpi.allowedDomains = 127.0.0.1,localhost,::1"] = true
+ needed["security.idpi.strictMode = true"] = true
+ needed["security.idpi.scanContent = true"] = true
+ needed["security.idpi.wrapContent = true"] = true
+ }
+ }
+
+ lines := make([]string, 0, len(needed))
+ for _, line := range ordered {
+ if needed[line] {
+ lines = append(lines, line)
+ }
+ }
+ return lines
+}
+
+func promptRestoreDefaults() bool {
+ fmt.Print("Restore recommended security defaults in config? (y/N): ")
+ reader := bufio.NewReader(os.Stdin)
+ response, err := reader.ReadString('\n')
+ if err != nil && strings.TrimSpace(response) == "" {
+ return false
+ }
+ switch strings.ToLower(strings.TrimSpace(response)) {
+ case "y", "yes":
+ return true
+ default:
+ return false
+ }
+}
+
+func isInteractiveTerminal() bool {
+ in, err := os.Stdin.Stat()
+ if err != nil || (in.Mode()&os.ModeCharDevice) == 0 {
+ return false
+ }
+ out, err := os.Stdout.Stat()
+ if err != nil || (out.Mode()&os.ModeCharDevice) == 0 {
+ return false
+ }
+ return true
+}
+
+func restoreSecurityDefaults() (string, bool, error) {
+ fc, configPath, err := config.LoadFileConfig()
+ if err != nil {
+ return "", false, err
+ }
+ before := securityDefaultsSnapshot(fc)
+ applyRecommendedSecurityDefaults(fc)
+ after := securityDefaultsSnapshot(fc)
+ if reflect.DeepEqual(before, after) {
+ return configPath, false, nil
+ }
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ return "", false, err
+ }
+ return configPath, true, nil
+}
+
+func applyRecommendedSecurityDefaults(fc *config.FileConfig) {
+ defaults := config.DefaultFileConfig()
+ if fc == nil {
+ return
+ }
+ fc.Server.Bind = defaults.Server.Bind
+ if strings.TrimSpace(fc.Server.Token) == "" {
+ token, err := config.GenerateAuthToken()
+ if err == nil {
+ fc.Server.Token = token
+ }
+ }
+ fc.Security = defaults.Security
+}
+
+type securityDefaultsState struct {
+ Bind string
+ Token string
+ Security config.SecurityConfig
+}
+
+func securityDefaultsSnapshot(fc *config.FileConfig) securityDefaultsState {
+ if fc == nil {
+ return securityDefaultsState{}
+ }
+ return securityDefaultsState{
+ Bind: fc.Server.Bind,
+ Token: fc.Server.Token,
+ Security: fc.Security,
+ }
+}
diff --git a/cmd/pinchtab/main.go b/cmd/pinchtab/main.go
index 02048c71..1c9ec45c 100644
--- a/cmd/pinchtab/main.go
+++ b/cmd/pinchtab/main.go
@@ -45,6 +45,15 @@ func main() {
os.Exit(0)
}
+ if len(os.Args) > 1 && os.Args[1] == "security" {
+ if len(os.Args) > 2 && (os.Args[2] == "help" || os.Args[2] == "--help" || os.Args[2] == "-h") {
+ securityUsage()
+ os.Exit(0)
+ }
+ handleSecurityCommand(cfg)
+ os.Exit(0)
+ }
+
// CLI commands
if len(os.Args) > 1 && isCLICommand(os.Args[1]) {
runCLI(cfg)
diff --git a/cmd/pinchtab/security_warnings.go b/cmd/pinchtab/security_warnings.go
index 584211c1..9e617bc5 100644
--- a/cmd/pinchtab/security_warnings.go
+++ b/cmd/pinchtab/security_warnings.go
@@ -2,25 +2,296 @@ package main
import (
"log/slog"
+ "strings"
"github.com/pinchtab/pinchtab/internal/config"
)
-func logSecurityWarnings(cfg *config.RuntimeConfig) {
+type securityWarning struct {
+ ID string
+ Message string
+ Attrs []any
+}
+
+type securityPostureCheck struct {
+ ID string
+ Label string
+ Passed bool
+ Detail string
+}
+
+type securityPosture struct {
+ Checks []securityPostureCheck
+ Passed int
+ Total int
+ Level string
+}
+
+func assessSecurityPosture(cfg *config.RuntimeConfig) securityPosture {
+ if cfg == nil {
+ return securityPosture{Level: "UNKNOWN"}
+ }
+
+ checks := []securityPostureCheck{
+ {
+ ID: "bind_loopback",
+ Label: "loopback bind",
+ Passed: isLoopbackBind(cfg.Bind),
+ Detail: cfg.Bind,
+ },
+ {
+ ID: "api_auth_enabled",
+ Label: "api auth",
+ Passed: strings.TrimSpace(cfg.Token) != "",
+ Detail: map[bool]string{true: "required", false: "disabled"}[strings.TrimSpace(cfg.Token) != ""],
+ },
+ {
+ ID: "sensitive_endpoints_disabled",
+ Label: "sensitive endpoints",
+ Passed: len(cfg.EnabledSensitiveEndpoints()) == 0,
+ Detail: formatEndpointStatus(cfg.EnabledSensitiveEndpoints()),
+ },
+ {
+ ID: "attach_disabled",
+ Label: "attach endpoint",
+ Passed: !cfg.AttachEnabled,
+ Detail: map[bool]string{true: "disabled", false: "enabled"}[!cfg.AttachEnabled],
+ },
+ {
+ ID: "attach_local_only",
+ Label: "attach host scope",
+ Passed: !attachAllowsNonLocalHosts(cfg.AttachAllowHosts),
+ Detail: formatHostScope(cfg.AttachAllowHosts),
+ },
+ {
+ ID: "idpi_whitelist_scoped",
+ Label: "website whitelist",
+ Passed: cfg.IDPI.Enabled && len(cfg.IDPI.AllowedDomains) > 0 && !allowsAllDomains(cfg.IDPI.AllowedDomains),
+ Detail: formatWhitelistStatus(cfg),
+ },
+ {
+ ID: "idpi_strict_mode",
+ Label: "IDPI strict mode",
+ Passed: cfg.IDPI.Enabled && cfg.IDPI.StrictMode,
+ Detail: formatStrictModeStatus(cfg),
+ },
+ {
+ ID: "idpi_content_protection",
+ Label: "IDPI content guard",
+ Passed: cfg.IDPI.Enabled && (cfg.IDPI.ScanContent || cfg.IDPI.WrapContent),
+ Detail: formatContentGuardStatus(cfg),
+ },
+ }
+
+ passed := 0
+ for _, check := range checks {
+ if check.Passed {
+ passed++
+ }
+ }
+
+ return securityPosture{
+ Checks: checks,
+ Passed: passed,
+ Total: len(checks),
+ Level: securityPostureLevel(passed, len(checks)),
+ }
+}
+
+func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
if cfg == nil {
- return
+ return nil
}
+ warnings := make([]securityWarning, 0, 8)
enabled := cfg.EnabledSensitiveEndpoints()
+
if len(enabled) > 0 {
- slog.Warn("sensitive endpoints enabled", "endpoints", enabled, "hint", "only enable them in trusted environments")
+ warnings = append(warnings, securityWarning{
+ ID: "sensitive_endpoints_enabled",
+ Message: "sensitive endpoints enabled",
+ Attrs: []any{"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")
+ warnings = append(warnings, securityWarning{
+ ID: "api_auth_disabled",
+ Message: "api authentication disabled",
+ Attrs: []any{"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")
+ warnings = append(warnings, securityWarning{
+ ID: "sensitive_endpoints_without_auth",
+ Message: "high-risk configuration: sensitive endpoints enabled without API authentication",
+ Attrs: []any{"endpoints", enabled, "hint", "set PINCHTAB_TOKEN or disable the sensitive endpoints"},
+ })
+ }
+
+ if !isLoopbackBind(cfg.Bind) {
+ warnings = append(warnings, securityWarning{
+ ID: "non_loopback_bind",
+ Message: "server exposed on a non-loopback bind address",
+ Attrs: []any{"bind", cfg.Bind, "hint", "prefer 127.0.0.1 or localhost unless remote access is intentional"},
+ })
+ }
+
+ if !cfg.IDPI.Enabled {
+ warnings = append(warnings, securityWarning{
+ ID: "idpi_disabled",
+ Message: "IDPI disabled; website whitelist inactive",
+ Attrs: []any{"setting", "security.idpi.enabled", "hint", "enable IDPI and keep security.idpi.allowedDomains scoped to approved websites"},
+ })
+ } else {
+ if len(cfg.IDPI.AllowedDomains) == 0 {
+ warnings = append(warnings, securityWarning{
+ ID: "idpi_whitelist_not_set",
+ Message: "website whitelist is not set for IDPI",
+ Attrs: []any{"setting", "security.idpi.allowedDomains", "hint", "configure allowedDomains to restrict which websites navigation may reach"},
+ })
+ } else if allowsAllDomains(cfg.IDPI.AllowedDomains) {
+ warnings = append(warnings, securityWarning{
+ ID: "idpi_whitelist_allows_all",
+ Message: "website whitelist allows all domains",
+ Attrs: []any{"setting", "security.idpi.allowedDomains", "hint", "remove '*' and list only approved domains"},
+ })
+ }
+
+ if !cfg.IDPI.StrictMode {
+ warnings = append(warnings, securityWarning{
+ ID: "idpi_warn_mode",
+ Message: "IDPI strict mode disabled",
+ Attrs: []any{"setting", "security.idpi.strictMode", "hint", "enable strict mode to block requests instead of only emitting warnings"},
+ })
+ }
+
+ if !cfg.IDPI.ScanContent && !cfg.IDPI.WrapContent {
+ warnings = append(warnings, securityWarning{
+ ID: "idpi_content_protection_disabled",
+ Message: "IDPI content protections are disabled",
+ Attrs: []any{"hint", "enable security.idpi.scanContent or security.idpi.wrapContent to protect text and snapshot responses"},
+ })
+ }
+ }
+
+ if cfg.AttachEnabled {
+ warnings = append(warnings, securityWarning{
+ ID: "attach_enabled",
+ Message: "attach endpoint enabled",
+ Attrs: []any{"hint", "only attach to Chrome instances you trust"},
+ })
+ if attachAllowsNonLocalHosts(cfg.AttachAllowHosts) {
+ warnings = append(warnings, securityWarning{
+ ID: "attach_external_hosts",
+ Message: "attach allowHosts includes non-local hosts",
+ Attrs: []any{"allowHosts", cfg.AttachAllowHosts, "hint", "keep security.attach.allowHosts limited to local addresses unless external Chrome instances are intentional"},
+ })
+ }
+ }
+
+ return warnings
+}
+
+func logSecurityWarnings(cfg *config.RuntimeConfig) {
+ for _, warning := range assessSecurityWarnings(cfg) {
+ attrs := append([]any{"category", "security", "warningId", warning.ID}, warning.Attrs...)
+ slog.Warn(warning.Message, attrs...)
+ }
+}
+
+func isLoopbackBind(bind string) bool {
+ switch strings.TrimSpace(strings.ToLower(bind)) {
+ case "127.0.0.1", "localhost", "::1", "":
+ return true
+ default:
+ return false
+ }
+}
+
+func allowsAllDomains(domains []string) bool {
+ for _, domain := range domains {
+ if strings.TrimSpace(domain) == "*" {
+ return true
+ }
+ }
+ return false
+}
+
+func attachAllowsNonLocalHosts(hosts []string) bool {
+ if len(hosts) == 0 {
+ return false
+ }
+ for _, host := range hosts {
+ switch strings.TrimSpace(strings.ToLower(host)) {
+ case "", "127.0.0.1", "localhost", "::1":
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+func securityPostureLevel(passed, total int) string {
+ if total == 0 {
+ return "UNKNOWN"
+ }
+ switch {
+ case passed == total:
+ return "LOCKED"
+ case passed >= total-2:
+ return "GUARDED"
+ case passed >= total/2:
+ return "ELEVATED"
+ default:
+ return "EXPOSED"
+ }
+}
+
+func formatEndpointStatus(enabled []string) string {
+ if len(enabled) == 0 {
+ return "disabled"
+ }
+ return strings.Join(enabled, ", ")
+}
+
+func formatHostScope(hosts []string) string {
+ if attachAllowsNonLocalHosts(hosts) {
+ return "external hosts allowed"
+ }
+ return "local-only"
+}
+
+func formatWhitelistStatus(cfg *config.RuntimeConfig) string {
+ if !cfg.IDPI.Enabled {
+ return "disabled"
+ }
+ if len(cfg.IDPI.AllowedDomains) == 0 {
+ return "not set"
+ }
+ if allowsAllDomains(cfg.IDPI.AllowedDomains) {
+ return "wildcard"
+ }
+ return strings.Join(cfg.IDPI.AllowedDomains, ", ")
+}
+
+func formatStrictModeStatus(cfg *config.RuntimeConfig) string {
+ if !cfg.IDPI.Enabled {
+ return "disabled"
+ }
+ if cfg.IDPI.StrictMode {
+ return "enforcing"
+ }
+ return "warn-only"
+}
+
+func formatContentGuardStatus(cfg *config.RuntimeConfig) string {
+ if !cfg.IDPI.Enabled {
+ return "disabled"
+ }
+ if cfg.IDPI.ScanContent || cfg.IDPI.WrapContent {
+ return "active"
}
+ return "disabled"
}
diff --git a/cmd/pinchtab/security_warnings_test.go b/cmd/pinchtab/security_warnings_test.go
new file mode 100644
index 00000000..14507a6d
--- /dev/null
+++ b/cmd/pinchtab/security_warnings_test.go
@@ -0,0 +1,296 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestAssessSecurityWarnings(t *testing.T) {
+ t.Run("safe local defaults stay quiet", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Bind: "127.0.0.1",
+ Token: "secret",
+ AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AttachAllowSchemes: []string{"ws", "wss"},
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"127.0.0.1", "localhost", "::1"},
+ StrictMode: true,
+ ScanContent: true,
+ WrapContent: true,
+ },
+ }
+
+ warnings := assessSecurityWarnings(cfg)
+ if len(warnings) != 0 {
+ t.Fatalf("expected no warnings, got %+v", warnings)
+ }
+ })
+
+ t.Run("website whitelist missing and other security gaps are flagged", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Bind: "0.0.0.0",
+ Token: "",
+ AllowEvaluate: true,
+ AllowDownload: true,
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"localhost", "chrome.internal"},
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ },
+ }
+
+ warnings := assessSecurityWarnings(cfg)
+ ids := make(map[string]bool, len(warnings))
+ for _, warning := range warnings {
+ ids[warning.ID] = true
+ }
+
+ for _, expected := range []string{
+ "sensitive_endpoints_enabled",
+ "api_auth_disabled",
+ "sensitive_endpoints_without_auth",
+ "non_loopback_bind",
+ "idpi_whitelist_not_set",
+ "idpi_warn_mode",
+ "idpi_content_protection_disabled",
+ "attach_enabled",
+ "attach_external_hosts",
+ } {
+ if !ids[expected] {
+ t.Fatalf("expected warning %q, got %+v", expected, warnings)
+ }
+ }
+ })
+
+ t.Run("wildcard whitelist is warned", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Bind: "127.0.0.1",
+ Token: "secret",
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"*"},
+ StrictMode: true,
+ ScanContent: true,
+ },
+ }
+
+ warnings := assessSecurityWarnings(cfg)
+ ids := make(map[string]bool, len(warnings))
+ for _, warning := range warnings {
+ ids[warning.ID] = true
+ }
+
+ if !ids["idpi_whitelist_allows_all"] {
+ t.Fatalf("expected wildcard whitelist warning, got %+v", warnings)
+ }
+ })
+
+ t.Run("disabled IDPI is warned", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Bind: "127.0.0.1",
+ Token: "secret",
+ AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AttachAllowSchemes: []string{"ws", "wss"},
+ }
+
+ warnings := assessSecurityWarnings(cfg)
+ ids := make(map[string]bool, len(warnings))
+ for _, warning := range warnings {
+ ids[warning.ID] = true
+ }
+
+ if !ids["idpi_disabled"] {
+ t.Fatalf("expected idpi_disabled warning, got %+v", warnings)
+ }
+ })
+}
+
+func TestAssessSecurityPosture(t *testing.T) {
+ t.Run("fully locked local config scores all defaults", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Bind: "127.0.0.1",
+ Token: "secret",
+ AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AttachAllowSchemes: []string{"ws", "wss"},
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ AllowedDomains: []string{"127.0.0.1", "localhost", "::1"},
+ StrictMode: true,
+ ScanContent: true,
+ WrapContent: true,
+ },
+ }
+
+ posture := assessSecurityPosture(cfg)
+ if posture.Passed != posture.Total {
+ t.Fatalf("expected all checks to pass, got %d/%d", posture.Passed, posture.Total)
+ }
+ if posture.Level != "LOCKED" {
+ t.Fatalf("expected LOCKED posture, got %q", posture.Level)
+ }
+ })
+
+ t.Run("exposed config drops posture score", func(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ Bind: "0.0.0.0",
+ AllowEvaluate: true,
+ AllowDownload: true,
+ AttachEnabled: true,
+ AttachAllowHosts: []string{"chrome.internal"},
+ IDPI: config.IDPIConfig{
+ Enabled: true,
+ },
+ }
+
+ posture := assessSecurityPosture(cfg)
+ if posture.Passed >= posture.Total/2 {
+ t.Fatalf("expected exposed posture below half-score, got %d/%d", posture.Passed, posture.Total)
+ }
+ if posture.Level != "EXPOSED" {
+ t.Fatalf("expected EXPOSED posture, got %q", posture.Level)
+ }
+ })
+}
+
+func TestApplyRecommendedSecurityDefaults(t *testing.T) {
+ allowEvaluate := true
+ attachEnabled := true
+ fc := &config.FileConfig{
+ Server: config.ServerConfig{
+ Port: "9999",
+ Bind: "0.0.0.0",
+ Token: "secret",
+ },
+ Security: config.SecurityConfig{
+ AllowEvaluate: &allowEvaluate,
+ Attach: config.AttachConfig{
+ Enabled: &attachEnabled,
+ AllowHosts: []string{"chrome.internal"},
+ },
+ IDPI: config.IDPIConfig{
+ Enabled: false,
+ },
+ },
+ }
+
+ applyRecommendedSecurityDefaults(fc)
+
+ if fc.Server.Port != "9999" {
+ t.Fatalf("expected port to be preserved, got %q", fc.Server.Port)
+ }
+ if fc.Server.Token != "secret" {
+ t.Fatalf("expected token to be preserved, got %q", fc.Server.Token)
+ }
+ if fc.Server.Bind != "127.0.0.1" {
+ t.Fatalf("expected bind to reset to loopback, got %q", fc.Server.Bind)
+ }
+ if fc.Security.AllowEvaluate == nil || *fc.Security.AllowEvaluate {
+ t.Fatalf("expected allowEvaluate to reset to false, got %+v", fc.Security.AllowEvaluate)
+ }
+ if !fc.Security.IDPI.Enabled {
+ t.Fatalf("expected idpi to be enabled")
+ }
+}
+
+func TestApplyRecommendedSecurityDefaults_GeneratesTokenWhenMissing(t *testing.T) {
+ fc := &config.FileConfig{}
+
+ applyRecommendedSecurityDefaults(fc)
+
+ if fc.Server.Token == "" {
+ t.Fatalf("expected generated token, got empty")
+ }
+}
+
+func TestRestoreSecurityDefaults(t *testing.T) {
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ allowEvaluate := true
+ attachEnabled := true
+ fc := &config.FileConfig{
+ Server: config.ServerConfig{
+ Port: "9999",
+ Bind: "0.0.0.0",
+ Token: "secret",
+ },
+ Security: config.SecurityConfig{
+ AllowEvaluate: &allowEvaluate,
+ Attach: config.AttachConfig{
+ Enabled: &attachEnabled,
+ AllowHosts: []string{"chrome.internal"},
+ },
+ IDPI: config.IDPIConfig{
+ Enabled: false,
+ },
+ },
+ }
+ if err := config.SaveFileConfig(fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ gotPath, changed, err := restoreSecurityDefaults()
+ if err != nil {
+ t.Fatalf("restoreSecurityDefaults() error = %v", err)
+ }
+ if gotPath != configPath {
+ t.Fatalf("restoreSecurityDefaults() path = %q, want %q", gotPath, configPath)
+ }
+ if !changed {
+ t.Fatalf("restoreSecurityDefaults() changed = false, want true")
+ }
+
+ saved, err := os.ReadFile(configPath)
+ if err != nil {
+ t.Fatalf("ReadFile() error = %v", err)
+ }
+ loaded := &config.FileConfig{}
+ if err := config.PatchConfigJSON(loaded, string(saved)); err != nil {
+ t.Fatalf("PatchConfigJSON() error = %v", err)
+ }
+ if loaded.Server.Port != "9999" {
+ t.Fatalf("expected port to be preserved, got %q", loaded.Server.Port)
+ }
+ if loaded.Server.Token != "secret" {
+ t.Fatalf("expected token to be preserved, got %q", loaded.Server.Token)
+ }
+ if loaded.Server.Bind != "127.0.0.1" {
+ t.Fatalf("expected bind to be restored, got %q", loaded.Server.Bind)
+ }
+ if !loaded.Security.IDPI.Enabled {
+ t.Fatalf("expected idpi to be enabled after restore")
+ }
+}
+
+func TestRestoreSecurityDefaults_TokenOnlyChangeIsSaved(t *testing.T) {
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+
+ fc := config.DefaultFileConfig()
+ fc.Server.Token = ""
+ if err := config.SaveFileConfig(&fc, configPath); err != nil {
+ t.Fatalf("SaveFileConfig() error = %v", err)
+ }
+
+ _, changed, err := restoreSecurityDefaults()
+ if err != nil {
+ t.Fatalf("restoreSecurityDefaults() error = %v", err)
+ }
+ if !changed {
+ t.Fatalf("restoreSecurityDefaults() changed = false, want true")
+ }
+
+ loaded, _, err := config.LoadFileConfig()
+ if err != nil {
+ t.Fatalf("LoadFileConfig() error = %v", err)
+ }
+ if loaded.Server.Token == "" {
+ t.Fatalf("expected generated token to be persisted")
+ }
+}
diff --git a/cmd/pinchtab/startup_output.go b/cmd/pinchtab/startup_output.go
new file mode 100644
index 00000000..ee2acc24
--- /dev/null
+++ b/cmd/pinchtab/startup_output.go
@@ -0,0 +1,179 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type startupBannerOptions struct {
+ Mode string
+ ListenAddr string
+ PublicURL string
+ Strategy string
+ ProfileDir string
+}
+
+func printStartupBanner(cfg *config.RuntimeConfig, opts startupBannerOptions) {
+ fmt.Fprintln(os.Stdout, renderStartupLogo(blankIfEmpty(opts.Mode, "server")))
+ fmt.Fprintf(os.Stdout, " %s %s\n", styleLabel("listen"), styleValue(blankIfEmpty(opts.ListenAddr, cfg.ListenAddr())))
+ if opts.PublicURL != "" {
+ fmt.Fprintf(os.Stdout, " %s %s\n", styleLabel("url"), styleValue(opts.PublicURL))
+ }
+ if opts.Strategy != "" {
+ fmt.Fprintf(os.Stdout, " %s %s\n", styleLabel("strategy"), styleValue(opts.Strategy))
+ }
+ if opts.ProfileDir != "" {
+ fmt.Fprintf(os.Stdout, " %s %s\n", styleLabel("profile"), styleValue(opts.ProfileDir))
+ }
+ printSecuritySummary(os.Stdout, cfg, " ")
+ fmt.Fprintln(os.Stdout)
+}
+
+func printSecuritySummary(w io.Writer, cfg *config.RuntimeConfig, prefix string) {
+ posture := assessSecurityPosture(cfg)
+
+ fmt.Fprintf(
+ w,
+ "%s%s %s %s\n",
+ prefix,
+ styleLabel("security"),
+ styleSecurityLevel(posture.Level),
+ styleSecurityBar(posture.Level, renderPostureBar(posture.Passed, posture.Total)),
+ )
+ for _, check := range posture.Checks {
+ fmt.Fprintf(
+ w,
+ "%s [%s] %s %s\n",
+ prefix,
+ styleMarker(check.Passed),
+ styleCheckLabel(check.Label),
+ styleCheckDetail(check.Passed, check.Detail),
+ )
+ }
+}
+
+func renderPostureBar(passed, total int) string {
+ if total <= 0 {
+ return "[--------]"
+ }
+ var b strings.Builder
+ b.WriteByte('[')
+ for i := 0; i < total; i++ {
+ if i < passed {
+ b.WriteByte('#')
+ } else {
+ b.WriteByte('-')
+ }
+ }
+ b.WriteByte(']')
+ return b.String()
+}
+
+func blankIfEmpty(value, fallback string) string {
+ if strings.TrimSpace(value) == "" {
+ return fallback
+ }
+ return value
+}
+
+func renderStartupLogo(mode string) string {
+ return styleLogo(startupLogo) + " " + styleMode(mode)
+}
+
+func styleLogo(text string) string {
+ return applyStyle(text, ansiBold, ansiCyan)
+}
+
+func styleMode(text string) string {
+ return applyStyle(text, ansiDim)
+}
+
+func styleLabel(text string) string {
+ return applyStyle(fmt.Sprintf("%-8s", text), ansiDim)
+}
+
+func styleValue(text string) string {
+ return applyStyle(text, ansiBold)
+}
+
+func styleCheckLabel(text string) string {
+ return applyStyle(fmt.Sprintf("%-20s", text), ansiDim)
+}
+
+func styleCheckDetail(passed bool, text string) string {
+ if passed {
+ return applyStyle(text, ansiGreen)
+ }
+ return applyStyle(text, ansiYellow)
+}
+
+func styleMarker(passed bool) string {
+ if passed {
+ return applyStyle("ok", ansiBold, ansiGreen)
+ }
+ return applyStyle("!!", ansiBold, ansiRed)
+}
+
+func styleSecurityLevel(level string) string {
+ return applyStyle(level, ansiBold, securityLevelColor(level))
+}
+
+func styleSecurityBar(level, bar string) string {
+ return applyStyle(bar, ansiBold, securityLevelColor(level))
+}
+
+func securityLevelColor(level string) string {
+ switch level {
+ case "LOCKED":
+ return ansiGreen
+ case "GUARDED":
+ return ansiYellow
+ case "ELEVATED":
+ return ansiRed
+ default:
+ return ansiRed
+ }
+}
+
+func applyStyle(text string, codes ...string) string {
+ if !shouldColorizeOutput() || len(codes) == 0 {
+ return text
+ }
+ return "\x1b[" + strings.Join(codes, ";") + "m" + text + "\x1b[0m"
+}
+
+func shouldColorizeOutput() bool {
+ if os.Getenv("NO_COLOR") != "" {
+ return false
+ }
+ if force := os.Getenv("CLICOLOR_FORCE"); force != "" && force != "0" {
+ return true
+ }
+ if strings.EqualFold(os.Getenv("TERM"), "dumb") {
+ return false
+ }
+ info, err := os.Stdout.Stat()
+ if err != nil {
+ return false
+ }
+ return (info.Mode() & os.ModeCharDevice) != 0
+}
+
+const (
+ ansiBold = "1"
+ ansiDim = "2"
+ ansiRed = "31"
+ ansiGreen = "32"
+ ansiYellow = "33"
+ ansiCyan = "36"
+)
+
+const startupLogo = ` ____ _ _ _____ _
+ | _ \(_)_ __ ___| |__ |_ _|_ _| |__
+ | |_) | | '_ \ / __| '_ \ | |/ _ | '_ \
+ | __/| | | | | (__| | | | | | (_| | |_) |
+ |_| |_|_| |_|\___|_| |_| |_|\__,_|_.__/`
diff --git a/cmd/pinchtab/startup_output_test.go b/cmd/pinchtab/startup_output_test.go
new file mode 100644
index 00000000..50a16c27
--- /dev/null
+++ b/cmd/pinchtab/startup_output_test.go
@@ -0,0 +1,22 @@
+package main
+
+import "testing"
+
+func TestSecurityLevelColor(t *testing.T) {
+ tests := []struct {
+ level string
+ want string
+ }{
+ {level: "LOCKED", want: ansiGreen},
+ {level: "GUARDED", want: ansiYellow},
+ {level: "ELEVATED", want: ansiRed},
+ {level: "EXPOSED", want: ansiRed},
+ {level: "UNKNOWN", want: ansiRed},
+ }
+
+ for _, tt := range tests {
+ if got := securityLevelColor(tt.level); got != tt.want {
+ t.Fatalf("securityLevelColor(%q) = %q, want %q", tt.level, got, tt.want)
+ }
+ }
+}
diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx
index 54b268ef..19ce5304 100644
--- a/dashboard/src/App.tsx
+++ b/dashboard/src/App.tsx
@@ -1,15 +1,21 @@
import { useEffect } from "react";
import {
- HashRouter,
+ BrowserRouter,
Routes,
Route,
Navigate,
useLocation,
+ useNavigate,
} from "react-router-dom";
import { useAppStore } from "./stores/useAppStore";
import { NavBar } from "./components/molecules";
-import { MonitoringPage, ProfilesPage, SettingsPage } from "./pages";
+import { LoginPage, MonitoringPage, ProfilesPage, SettingsPage } from "./pages";
import * as api from "./services/api";
+import {
+ AUTH_REQUIRED_EVENT,
+ clearStoredAuthToken,
+ getStoredAuthToken,
+} from "./services/auth";
function AppContent() {
const {
@@ -21,19 +27,42 @@ function AppContent() {
settings,
} = useAppStore();
const location = useLocation();
+ const navigate = useNavigate();
const memoryMetricsEnabled = settings.monitoring?.memoryMetrics ?? false;
+ const authToken = getStoredAuthToken();
+ const authenticated = authToken !== "";
useEffect(() => {
document.documentElement.setAttribute("data-site-mode", "agent");
}, []);
- // Log navigation for debugging
useEffect(() => {
- console.log("📍 Navigation:", location.pathname);
- }, [location]);
+ const handleAuthRequired = () => {
+ clearStoredAuthToken();
+ navigate("/login", {
+ replace: true,
+ state: { from: location.pathname },
+ });
+ };
+ window.addEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
+ return () =>
+ window.removeEventListener(AUTH_REQUIRED_EVENT, handleAuthRequired);
+ }, [location.pathname, navigate]);
+
+ useEffect(() => {
+ if (!authenticated && location.pathname !== "/login") {
+ navigate("/login", {
+ replace: true,
+ state: { from: location.pathname },
+ });
+ }
+ }, [authenticated, location.pathname, navigate]);
// Initial load
useEffect(() => {
+ if (!authenticated) {
+ return;
+ }
const load = async () => {
try {
const [instances, profiles, health] = await Promise.all([
@@ -49,10 +78,13 @@ function AppContent() {
}
};
load();
- }, [setInstances, setProfiles, setServerInfo]);
+ }, [authenticated, setInstances, setProfiles, setServerInfo]);
// Subscribe to SSE events
useEffect(() => {
+ if (!authenticated) {
+ return;
+ }
const unsubscribe = api.subscribeToEvents(
{
onInit: (agents) => {
@@ -75,6 +107,7 @@ function AppContent() {
return unsubscribe;
}, [
+ authenticated,
applyMonitoringSnapshot,
memoryMetricsEnabled,
setAgents,
@@ -82,19 +115,43 @@ function AppContent() {
setProfiles,
]);
+ if (!authenticated) {
+ return (
+ <Routes>
+ <Route path="/login" element={<LoginPage />} />
+ <Route path="*" element={<Navigate to="/login" replace />} />
+ </Routes>
+ );
+ }
+
return (
<div className="dashboard-shell flex h-screen flex-col bg-bg-app">
<NavBar />
<main className="dashboard-grid flex-1 overflow-hidden">
<Routes>
- <Route path="/" element={<Navigate to="/monitoring" replace />} />
- <Route path="/monitoring" element={<MonitoringPage />} />
- <Route path="/profiles" element={<ProfilesPage />} />
+ <Route path="/" element={<Navigate to="/dashboard/monitoring" replace />} />
+ <Route
+ path="/login"
+ element={<Navigate to="/dashboard/monitoring" replace />}
+ />
+ <Route
+ path="/dashboard"
+ element={<Navigate to="/dashboard/monitoring" replace />}
+ />
+ <Route
+ path="/dashboard/monitoring"
+ element={<MonitoringPage />}
+ />
+ <Route path="/dashboard/profiles" element={<ProfilesPage />} />
+ <Route
+ path="/dashboard/agents"
+ element={<Navigate to="/dashboard/monitoring" replace />}
+ />
+ <Route path="/dashboard/settings" element={<SettingsPage />} />
<Route
- path="/agents"
- element={<Navigate to="/monitoring" replace />}
+ path="*"
+ element={<Navigate to="/dashboard/monitoring" replace />}
/>
- <Route path="/settings" element={<SettingsPage />} />
</Routes>
</main>
</div>
@@ -103,8 +160,8 @@ function AppContent() {
export default function App() {
return (
- <HashRouter>
+ <BrowserRouter>
<AppContent />
- </HashRouter>
+ </BrowserRouter>
);
}
diff --git a/dashboard/src/components/molecules/NavBar.tsx b/dashboard/src/components/molecules/NavBar.tsx
index d3b9df01..244b8b54 100644
--- a/dashboard/src/components/molecules/NavBar.tsx
+++ b/dashboard/src/components/molecules/NavBar.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import { NavLink, useLocation } from "react-router-dom";
+import { NavLink, useLocation, useNavigate } from "react-router-dom";
import { useAppStore } from "../../stores/useAppStore";
import "./NavBar.css";
@@ -10,9 +10,9 @@ interface Tab {
}
const tabs: Tab[] = [
- { id: "monitoring", path: "/monitoring", label: "Monitoring" },
- { id: "profiles", path: "/profiles", label: "Profiles" },
- { id: "settings", path: "/settings", label: "Settings" },
+ { id: "monitoring", path: "/dashboard/monitoring", label: "Monitoring" },
+ { id: "profiles", path: "/dashboard/profiles", label: "Profiles" },
+ { id: "settings", path: "/dashboard/settings", label: "Settings" },
];
interface NavBarProps {
@@ -25,6 +25,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const tabsRef = useRef<HTMLElement>(null);
const location = useLocation();
+ const navigate = useNavigate();
// Close mobile menu on route change
useEffect(() => {
@@ -44,7 +45,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {
const num = parseInt(e.key);
if (num >= 1 && num <= tabs.length) {
e.preventDefault();
- window.location.hash = tabs[num - 1].path;
+ navigate(tabs[num - 1].path);
return;
}
if (e.key === "r" && onRefresh) {
@@ -54,7 +55,7 @@ export default function NavBar({ onRefresh }: NavBarProps) {
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
- }, [onRefresh, handleRefresh]);
+ }, [navigate, onRefresh, handleRefresh]);
return (
<header className="sticky top-0 z-50 border-b border-border-subtle bg-bg-app/95 backdrop-blur">
diff --git a/dashboard/src/components/molecules/ScreencastTile.tsx b/dashboard/src/components/molecules/ScreencastTile.tsx
index 4a5f5250..06632ec6 100644
--- a/dashboard/src/components/molecules/ScreencastTile.tsx
+++ b/dashboard/src/components/molecules/ScreencastTile.tsx
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react";
+import { getStoredAuthToken } from "../../services/auth";
interface Props {
instancePort: string;
@@ -38,7 +39,17 @@ export default function ScreencastTile({
// Use window.location.hostname so this works when the dashboard is served
// from a remote host (e.g. a headless Ubuntu server) instead of localhost.
const host = window.location.hostname;
- const wsUrl = `ws://${host}:${instancePort}/screencast?tabId=${encodeURIComponent(tabId)}&quality=${quality}&maxWidth=${maxWidth}&fps=${fps}`;
+ const token = getStoredAuthToken();
+ const params = new URLSearchParams({
+ tabId,
+ quality: String(quality),
+ maxWidth: String(maxWidth),
+ fps: String(fps),
+ });
+ if (token) {
+ params.set("token", token);
+ }
+ const wsUrl = `ws://${host}:${instancePort}/screencast?${params.toString()}`;
const socket = new WebSocket(wsUrl);
socket.binaryType = "arraybuffer";
diff --git a/dashboard/src/pages/LoginPage.tsx b/dashboard/src/pages/LoginPage.tsx
new file mode 100644
index 00000000..b789b6de
--- /dev/null
+++ b/dashboard/src/pages/LoginPage.tsx
@@ -0,0 +1,68 @@
+import { useState } from "react";
+import type { FormEvent } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+import { Button, Card } from "../components/atoms";
+import * as api from "../services/api";
+import { setStoredAuthToken } from "../services/auth";
+
+export default function LoginPage() {
+ const navigate = useNavigate();
+ const location = useLocation();
+ const [token, setToken] = useState("");
+ const [error, setError] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ const from =
+ (location.state as { from?: string } | null)?.from || "/dashboard/monitoring";
+
+ const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ setSubmitting(true);
+ setError("");
+ try {
+ await api.verifyBackendToken(token);
+ setStoredAuthToken(token);
+ navigate(from, { replace: true });
+ } catch (e) {
+ setError(e instanceof Error ? e.message : "Authentication failed");
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <div className="flex min-h-screen items-center justify-center bg-bg-app px-4">
+ <Card className="w-full max-w-md p-6">
+ <div className="mb-6">
+ <div className="dashboard-section-label mb-2">Authentication</div>
+ <h1 className="text-xl font-semibold text-text-primary">
+ Enter API token
+ </h1>
+ <p className="mt-2 text-sm leading-6 text-text-muted">
+ This PinchTab server requires a bearer token before the dashboard
+ can load protected routes and APIs.
+ </p>
+ </div>
+
+ <form className="space-y-4" onSubmit={handleSubmit}>
+ <input
+ type="password"
+ autoFocus
+ value={token}
+ onChange={(e) => setToken(e.target.value)}
+ className="w-full rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20"
+ placeholder="Paste bearer token"
+ />
+ {error && (
+ <div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs leading-5 text-destructive">
+ {error}
+ </div>
+ )}
+ <Button type="submit" disabled={submitting || token.trim() === ""}>
+ {submitting ? "Authorizing..." : "Continue"}
+ </Button>
+ </form>
+ </Card>
+ </div>
+ );
+}
diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsx
index 60b940a9..e379d515 100644
--- a/dashboard/src/pages/SettingsPage.tsx
+++ b/dashboard/src/pages/SettingsPage.tsx
@@ -5,6 +5,8 @@ import * as api from "../services/api";
import type {
BackendConfig,
BackendConfigState,
+ BackendIDPIConfig,
+ BackendSecurityConfig,
LocalDashboardSettings,
} from "../types";
@@ -13,6 +15,7 @@ type SectionId =
| "defaults"
| "orchestration"
| "security"
+ | "security-idpi"
| "profiles"
| "network"
| "browser"
@@ -43,6 +46,11 @@ const sections: Array<{
label: "Security",
description: "Sensitive endpoint gates and access controls.",
},
+ {
+ id: "security-idpi",
+ label: "Security IDPI",
+ description: "Indirect prompt injection website and content defenses.",
+ },
{
id: "profiles",
label: "Profiles",
@@ -71,6 +79,41 @@ const fieldClass =
const selectClass =
"rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-primary transition-all duration-150 focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20";
+type SecurityEndpointKey = Exclude<keyof BackendSecurityConfig, "attach">;
+type IDPIToggleKey = Exclude<
+ keyof BackendIDPIConfig,
+ "allowedDomains" | "customPatterns"
+>;
+
+const securityEndpointRows = [
+ ["allowEvaluate", "Allow evaluate"],
+ ["allowMacro", "Allow macro"],
+ ["allowScreencast", "Allow screencast"],
+ ["allowDownload", "Allow download"],
+ ["allowUpload", "Allow upload"],
+] as const satisfies ReadonlyArray<readonly [SecurityEndpointKey, string]>;
+
+const idpiToggleRows = [
+ ["enabled", "Enable IDPI", "Turn on indirect prompt injection defenses."],
+ [
+ "strictMode",
+ "Strict mode",
+ "Block disallowed domains and suspicious content instead of only warning.",
+ ],
+ [
+ "scanContent",
+ "Scan content",
+ "Inspect extracted text and snapshots for prompt-injection patterns.",
+ ],
+ [
+ "wrapContent",
+ "Wrap content",
+ "Mark returned page text as untrusted content for downstream consumers.",
+ ],
+] as const satisfies ReadonlyArray<
+ readonly [IDPIToggleKey, string, string]
+>;
+
function csvToList(value: string): string[] {
return value
.split(",")
@@ -138,6 +181,7 @@ export default function SettingsPage() {
);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
+ const [generatingToken, setGeneratingToken] = useState(false);
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
@@ -191,11 +235,23 @@ export default function SettingsPage() {
const restartReasons =
backendState?.restartReasons || serverInfo?.restartReasons || [];
const sensitiveEndpointsEnabled = backendConfig
- ? Object.values(backendConfig.security).some(Boolean)
+ ? [
+ backendConfig.security.allowEvaluate,
+ backendConfig.security.allowMacro,
+ backendConfig.security.allowScreencast,
+ backendConfig.security.allowDownload,
+ backendConfig.security.allowUpload,
+ ].some(Boolean)
: false;
const apiTokenMissing = backendConfig
? backendConfig.server.token.trim() === ""
: false;
+ const idpiEnabled = backendConfig ? backendConfig.security.idpi.enabled : false;
+ const idpiAllowedDomains = backendConfig
+ ? backendConfig.security.idpi.allowedDomains
+ : [];
+ const idpiWildcard = idpiAllowedDomains.includes("*");
+ const idpiDomainsConfigured = idpiAllowedDomains.length > 0 && !idpiWildcard;
const updateBackendSection = <K extends keyof BackendConfig>(
section: K,
@@ -220,6 +276,26 @@ export default function SettingsPage() {
setNotice("");
};
+ const handleGenerateToken = async () => {
+ if (!backendConfig) {
+ return;
+ }
+ setGeneratingToken(true);
+ setError("");
+ setNotice("");
+ try {
+ const token = await api.generateBackendToken();
+ updateBackendSection("server", { token });
+ setNotice("Generated a new API token. Save changes to persist it.");
+ } catch (e) {
+ const message =
+ e instanceof Error ? e.message : "Failed to generate API token";
+ setError(message);
+ } finally {
+ setGeneratingToken(false);
+ }
+ };
+
const handleSave = async () => {
if (!hasChanges || !backendConfig) return;
@@ -720,7 +796,7 @@ export default function SettingsPage() {
{activeSection === "security" && (
<SectionCard
title="Security"
- description="These feature gates affect what sensitive capabilities PinchTab exposes. They are applied to future launched instances and live middleware where supported."
+ description="These controls define what risky capabilities PinchTab exposes."
>
<div
className={`rounded-sm px-4 py-3 text-sm leading-6 ${
@@ -733,13 +809,7 @@ export default function SettingsPage() {
? "One or more sensitive endpoint families are enabled. Features like script execution, downloads, uploads, and live capture can expose high-risk capabilities. Only enable them in trusted environments. You are responsible for securing network access, authentication, and downstream use."
: "These endpoint families can expose high-risk capabilities when enabled. Only turn them on in trusted environments, and only when you accept responsibility for network access, authentication, and downstream use."}
</div>
- {[
- ["allowEvaluate", "Allow evaluate"],
- ["allowMacro", "Allow macro"],
- ["allowScreencast", "Allow screencast"],
- ["allowDownload", "Allow download"],
- ["allowUpload", "Allow upload"],
- ].map(([key, label]) => (
+ {securityEndpointRows.map(([key, label]) => (
<SettingRow
key={key}
label={label}
@@ -748,15 +818,56 @@ export default function SettingsPage() {
<label className="flex items-center justify-end gap-3 text-sm text-text-secondary">
<input
type="checkbox"
- checked={
- backendConfig.security[
- key as keyof BackendConfig["security"]
- ]
- }
+ checked={backendConfig.security[key]}
onChange={(e) =>
updateBackendSection("security", {
[key]: e.target.checked,
- } as Partial<BackendConfig["security"]>)
+ } as Partial<Pick<BackendSecurityConfig, SecurityEndpointKey>>)
+ }
+ className="h-4 w-4"
+ />
+ Enable
+ </label>
+ </SettingRow>
+ ))}
+ </SectionCard>
+ )}
+
+ {activeSection === "security-idpi" && (
+ <SectionCard
+ title="Security IDPI"
+ description="Indirect prompt injection controls restrict which websites are allowed and add protections around extracted content before it reaches downstream automation."
+ >
+ <div
+ className={`mb-4 rounded-sm px-4 py-3 text-sm leading-6 ${
+ !idpiEnabled || !idpiDomainsConfigured
+ ? "border border-destructive/35 bg-destructive/10 text-destructive"
+ : idpiWildcard
+ ? "border border-warning/25 bg-warning/10 text-warning"
+ : "border border-success/25 bg-success/10 text-success"
+ }`}
+ >
+ {!idpiEnabled
+ ? "IDPI is disabled. Browser content is not being filtered by website allowlist or content protections."
+ : !idpiDomainsConfigured
+ ? "The website whitelist is not set to a restricted domain list. This is the main IDPI defense and should be configured."
+ : idpiWildcard
+ ? "The website whitelist contains '*', which effectively disables domain restriction."
+ : "IDPI is enforcing a specific website whitelist and content protections."}
+ </div>
+ {idpiToggleRows.map(([key, label, description]) => (
+ <SettingRow key={key} label={label} description={description}>
+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">
+ <input
+ type="checkbox"
+ checked={backendConfig.security.idpi[key]}
+ onChange={(e) =>
+ updateBackendSection("security", {
+ idpi: {
+ ...backendConfig.security.idpi,
+ [key]: e.target.checked,
+ },
+ })
}
className="h-4 w-4"
/>
@@ -764,6 +875,48 @@ export default function SettingsPage() {
</label>
</SettingRow>
))}
+ <SettingRow
+ label="Allowed websites"
+ description="Comma-separated domain allowlist for web content. Use exact hosts or patterns like *.example.com."
+ >
+ <div className="space-y-2">
+ <input
+ value={listToCsv(backendConfig.security.idpi.allowedDomains)}
+ onChange={(e) =>
+ updateBackendSection("security", {
+ idpi: {
+ ...backendConfig.security.idpi,
+ allowedDomains: csvToList(e.target.value),
+ },
+ })
+ }
+ className={fieldClass}
+ placeholder="127.0.0.1, localhost, ::1"
+ />
+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs leading-5 text-warning">
+ Keep this list narrow. Empty or wildcard entries weaken
+ the main IDPI boundary.
+ </div>
+ </div>
+ </SettingRow>
+ <SettingRow
+ label="Custom patterns"
+ description="Optional comma-separated phrases to treat as suspicious prompt-injection content."
+ >
+ <input
+ value={listToCsv(backendConfig.security.idpi.customPatterns)}
+ onChange={(e) =>
+ updateBackendSection("security", {
+ idpi: {
+ ...backendConfig.security.idpi,
+ customPatterns: csvToList(e.target.value),
+ },
+ })
+ }
+ className={fieldClass}
+ placeholder="ignore previous instructions, exfiltrate data"
+ />
+ </SettingRow>
</SectionCard>
)}
@@ -837,15 +990,25 @@ export default function SettingsPage() {
description="Bearer token required by authenticated requests when set. Leaving this empty means reachable clients are unauthenticated."
>
<div className="space-y-2">
- <input
- value={backendConfig.server.token}
- onChange={(e) =>
- updateBackendSection("server", {
- token: e.target.value,
- })
- }
- className={fieldClass}
- />
+ <div className="flex gap-2">
+ <input
+ value={backendConfig.server.token}
+ onChange={(e) =>
+ updateBackendSection("server", {
+ token: e.target.value,
+ })
+ }
+ className={fieldClass}
+ />
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={handleGenerateToken}
+ disabled={generatingToken}
+ >
+ {generatingToken ? "Generating..." : "Generate"}
+ </Button>
+ </div>
{apiTokenMissing && (
<div className="rounded-sm border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs leading-5 text-destructive">
No API token is set. Anyone who can reach this server
@@ -877,10 +1040,13 @@ export default function SettingsPage() {
<label className="flex items-center justify-end gap-3 text-sm text-text-secondary">
<input
type="checkbox"
- checked={backendConfig.attach.enabled}
+ checked={backendConfig.security.attach.enabled}
onChange={(e) =>
- updateBackendSection("attach", {
- enabled: e.target.checked,
+ updateBackendSection("security", {
+ attach: {
+ ...backendConfig.security.attach,
+ enabled: e.target.checked,
+ },
})
}
className="h-4 w-4"
@@ -894,10 +1060,13 @@ export default function SettingsPage() {
>
<div className="space-y-2">
<input
- value={listToCsv(backendConfig.attach.allowHosts)}
+ value={listToCsv(backendConfig.security.attach.allowHosts)}
onChange={(e) =>
- updateBackendSection("attach", {
- allowHosts: csvToList(e.target.value),
+ updateBackendSection("security", {
+ attach: {
+ ...backendConfig.security.attach,
+ allowHosts: csvToList(e.target.value),
+ },
})
}
className={fieldClass}
@@ -914,10 +1083,13 @@ export default function SettingsPage() {
description="Comma-separated scheme allowlist, usually ws and wss."
>
<input
- value={listToCsv(backendConfig.attach.allowSchemes)}
+ value={listToCsv(backendConfig.security.attach.allowSchemes)}
onChange={(e) =>
- updateBackendSection("attach", {
- allowSchemes: csvToList(e.target.value),
+ updateBackendSection("security", {
+ attach: {
+ ...backendConfig.security.attach,
+ allowSchemes: csvToList(e.target.value),
+ },
})
}
className={fieldClass}
diff --git a/dashboard/src/pages/index.ts b/dashboard/src/pages/index.ts
index 26911708..b0578278 100644
--- a/dashboard/src/pages/index.ts
+++ b/dashboard/src/pages/index.ts
@@ -2,3 +2,4 @@ export { default as MonitoringPage } from "./MonitoringPage";
export { default as ProfilesPage } from "./ProfilesPage";
export { default as AgentsPage } from "./AgentsPage";
export { default as SettingsPage } from "./SettingsPage";
+export { default as LoginPage } from "./LoginPage";
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index fe752508..2e05b361 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -20,13 +20,44 @@ import {
normalizeDashboardServerInfo,
normalizeMonitoringSnapshot,
} from "../types";
+import {
+ addTokenToUrl,
+ dispatchAuthRequired,
+ getStoredAuthToken,
+} from "./auth";
const BASE = ""; // Uses proxy in dev
-async function request<T>(url: string, options?: RequestInit): Promise<T> {
- const res = await fetch(BASE + url, options);
+type RequestMeta = {
+ authToken?: string;
+ suppressAuthRedirect?: boolean;
+};
+
+async function request<T>(
+ url: string,
+ options?: RequestInit,
+ meta?: RequestMeta,
+): Promise<T> {
+ const headers = new Headers(options?.headers ?? {});
+ const token = meta?.authToken?.trim() || getStoredAuthToken();
+ if (token) {
+ headers.set("Authorization", `Bearer ${token}`);
+ }
+
+ const res = await fetch(BASE + url, {
+ ...options,
+ headers,
+ });
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
+ if (
+ res.status === 401 &&
+ !meta?.suppressAuthRedirect &&
+ typeof window !== "undefined"
+ ) {
+ window.localStorage.removeItem("pinchtab.auth.token");
+ dispatchAuthRequired(err.code || "unauthorized");
+ }
throw new Error(err.error || "Request failed");
}
return res.json();
@@ -121,6 +152,17 @@ export async function fetchHealth(): Promise<DashboardServerInfo> {
);
}
+export async function verifyBackendToken(
+ token: string,
+): Promise<DashboardServerInfo> {
+ return normalizeDashboardServerInfo(
+ await request<DashboardServerInfo>("/health", undefined, {
+ authToken: token,
+ suppressAuthRedirect: true,
+ }),
+ );
+}
+
export async function fetchBackendConfig(): Promise<BackendConfigState> {
return normalizeBackendConfigState(
await request<BackendConfigState>("/api/config"),
@@ -139,6 +181,13 @@ export async function saveBackendConfig(
);
}
+export async function generateBackendToken(): Promise<string> {
+ const res = await request<{ token: string }>("/api/config/generate-token", {
+ method: "POST",
+ });
+ return res.token;
+}
+
// SSE Events — endpoint is /api/events
export interface SystemEvent {
type: "instance.started" | "instance.stopped" | "instance.error";
@@ -163,7 +212,9 @@ export function subscribeToEvents(
handlers: EventHandler,
options?: { includeMemory?: boolean },
): () => void {
- const url = options?.includeMemory ? "/api/events?memory=1" : "/api/events";
+ const url = addTokenToUrl(
+ options?.includeMemory ? "/api/events?memory=1" : "/api/events",
+ );
const es = new EventSource(url);
es.addEventListener("init", (e) => {
@@ -206,7 +257,9 @@ export function subscribeToEvents(
// Suppress connection errors (expected on page reload/navigation)
es.onerror = () => {
- // SSE will auto-reconnect; silence console noise
+ if (!getStoredAuthToken()) {
+ dispatchAuthRequired("missing_token");
+ }
};
// Clean up on page unload to prevent ERR_INCOMPLETE_CHUNKED_ENCODING
diff --git a/dashboard/src/services/auth.ts b/dashboard/src/services/auth.ts
new file mode 100644
index 00000000..04ab3ddc
--- /dev/null
+++ b/dashboard/src/services/auth.ts
@@ -0,0 +1,35 @@
+const AUTH_TOKEN_KEY = "pinchtab.auth.token";
+const AUTH_REQUIRED_EVENT = "pinchtab-auth-required";
+
+export function getStoredAuthToken(): string {
+ return window.localStorage.getItem(AUTH_TOKEN_KEY)?.trim() ?? "";
+}
+
+export function setStoredAuthToken(token: string): void {
+ window.localStorage.setItem(AUTH_TOKEN_KEY, token.trim());
+}
+
+export function clearStoredAuthToken(): void {
+ window.localStorage.removeItem(AUTH_TOKEN_KEY);
+}
+
+export function dispatchAuthRequired(reason: string): void {
+ window.dispatchEvent(
+ new CustomEvent(AUTH_REQUIRED_EVENT, {
+ detail: { reason },
+ }),
+ );
+}
+
+export function addTokenToUrl(url: string, token?: string): string {
+ const authToken = (token ?? getStoredAuthToken()).trim();
+ if (!authToken) {
+ return url;
+ }
+
+ const absolute = new URL(url, window.location.origin);
+ absolute.searchParams.set("token", authToken);
+ return absolute.pathname + absolute.search;
+}
+
+export { AUTH_REQUIRED_EVENT };
diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.ts
index 6b85bd4e..4ccda04f 100644
--- a/dashboard/src/types/index.ts
+++ b/dashboard/src/types/index.ts
@@ -87,6 +87,8 @@ export interface BackendSecurityConfig {
allowScreencast: boolean;
allowDownload: boolean;
allowUpload: boolean;
+ attach: BackendAttachConfig;
+ idpi: BackendIDPIConfig;
}
export interface BackendProfilesConfig {
@@ -107,6 +109,15 @@ export interface BackendAttachConfig {
allowSchemes: string[];
}
+export interface BackendIDPIConfig {
+ enabled: boolean;
+ allowedDomains: string[];
+ strictMode: boolean;
+ scanContent: boolean;
+ wrapContent: boolean;
+ customPatterns: string[];
+}
+
export interface BackendTimeoutsConfig {
actionSec: number;
navigateSec: number;
@@ -121,7 +132,6 @@ export interface BackendConfig {
security: BackendSecurityConfig;
profiles: BackendProfilesConfig;
multiInstance: BackendMultiInstanceConfig;
- attach: BackendAttachConfig;
timeouts: BackendTimeoutsConfig;
}
@@ -165,6 +175,19 @@ export const defaultBackendConfig: BackendConfig = {
allowScreencast: false,
allowDownload: false,
allowUpload: false,
+ attach: {
+ enabled: false,
+ allowHosts: ["127.0.0.1", "localhost", "::1"],
+ allowSchemes: ["ws", "wss"],
+ },
+ idpi: {
+ enabled: true,
+ allowedDomains: ["127.0.0.1", "localhost", "::1"],
+ strictMode: true,
+ scanContent: true,
+ wrapContent: true,
+ customPatterns: [],
+ },
},
profiles: {
baseDir: "",
@@ -176,11 +199,6 @@ export const defaultBackendConfig: BackendConfig = {
instancePortStart: 9868,
instancePortEnd: 9968,
},
- attach: {
- enabled: false,
- allowHosts: ["127.0.0.1", "localhost", "::1"],
- allowSchemes: ["ws", "wss"],
- },
timeouts: {
actionSec: 30,
navigateSec: 60,
@@ -211,6 +229,26 @@ export function normalizeBackendConfig(
security: {
...defaultBackendConfig.security,
...(input?.security ?? {}),
+ attach: {
+ ...defaultBackendConfig.security.attach,
+ ...(input?.security?.attach ?? {}),
+ allowHosts:
+ input?.security?.attach?.allowHosts ??
+ defaultBackendConfig.security.attach.allowHosts,
+ allowSchemes:
+ input?.security?.attach?.allowSchemes ??
+ defaultBackendConfig.security.attach.allowSchemes,
+ },
+ idpi: {
+ ...defaultBackendConfig.security.idpi,
+ ...(input?.security?.idpi ?? {}),
+ allowedDomains:
+ input?.security?.idpi?.allowedDomains ??
+ defaultBackendConfig.security.idpi.allowedDomains,
+ customPatterns:
+ input?.security?.idpi?.customPatterns ??
+ defaultBackendConfig.security.idpi.customPatterns,
+ },
},
profiles: {
...defaultBackendConfig.profiles,
@@ -220,14 +258,6 @@ export function normalizeBackendConfig(
...defaultBackendConfig.multiInstance,
...(input?.multiInstance ?? {}),
},
- attach: {
- ...defaultBackendConfig.attach,
- ...(input?.attach ?? {}),
- allowHosts:
- input?.attach?.allowHosts ?? defaultBackendConfig.attach.allowHosts,
- allowSchemes:
- input?.attach?.allowSchemes ?? defaultBackendConfig.attach.allowSchemes,
- },
timeouts: {
...defaultBackendConfig.timeouts,
...(input?.timeouts ?? {}),
diff --git a/docs/architecture/index.md b/docs/architecture/index.md
index 5f4e6b99..e4750fef 100644
--- a/docs/architecture/index.md
+++ b/docs/architecture/index.md
@@ -18,7 +18,7 @@ Today, the main production shape is:
PinchTab also supports an advanced attach path:
- the server can register an externally managed Chrome instance through `POST /instances/attach`
-- attach is policy-gated by `attach.enabled`, `attach.allowHosts`, and `attach.allowSchemes`
+- attach is policy-gated by `security.attach.enabled`, `security.attach.allowHosts`, and `security.attach.allowSchemes`
The current managed implementation is bridge-backed. Any direct-CDP-only managed model is architectural discussion elsewhere, not the default runtime path in this codebase.
diff --git a/docs/architecture/orchestration.md b/docs/architecture/orchestration.md
index 0cb76165..9edd4c56 100644
--- a/docs/architecture/orchestration.md
+++ b/docs/architecture/orchestration.md
@@ -70,9 +70,9 @@ flowchart LR
Current attach behavior:
-- requires `attach.enabled`
-- validates the CDP URL against `attach.allowSchemes`
-- validates the host against `attach.allowHosts`
+- requires `security.attach.enabled`
+- validates the CDP URL against `security.attach.allowSchemes`
+- validates the host against `security.attach.allowHosts`
- registers the instance as `attached: true`
- does not start or stop an external Chrome process
diff --git a/docs/guides/attach-chrome.md b/docs/guides/attach-chrome.md
index 41c06101..3c2e9fae 100644
--- a/docs/guides/attach-chrome.md
+++ b/docs/guides/attach-chrome.md
@@ -37,7 +37,7 @@ With attach:
The current codebase implements:
- `POST /instances/attach`
-- attach policy in config under `attach`
+- attach policy in config under `security.attach`
- attached-instance metadata in `GET /instances`
The attach request body is:
@@ -61,10 +61,12 @@ Example:
```json
{
- "attach": {
- "enabled": true,
- "allowHosts": ["127.0.0.1", "localhost", "::1"],
- "allowSchemes": ["ws", "wss"]
+ "security": {
+ "attach": {
+ "enabled": true,
+ "allowHosts": ["127.0.0.1", "localhost", "::1"],
+ "allowSchemes": ["ws", "wss"]
+ }
}
}
```
@@ -138,7 +140,7 @@ curl -X POST http://localhost:9867/instances/attach \
Notes:
- `name` is optional; if omitted, the server generates one like `attached-...`
-- the server validates the URL against `attach.allowHosts` and `attach.allowSchemes`
+- the server validates the URL against `security.attach.allowHosts` and `security.attach.allowSchemes`
---
@@ -231,4 +233,4 @@ curl -X POST http://localhost:9867/instances/start \
-d '{"mode":"headless"}'
# CLI Alternative
pinchtab instance start
-```
\ No newline at end of file
+```
diff --git a/docs/guides/security.md b/docs/guides/security.md
new file mode 100644
index 00000000..1374263f
--- /dev/null
+++ b/docs/guides/security.md
@@ -0,0 +1,208 @@
+# Security
+
+PinchTab is designed to be usable by default on a local machine without exposing high-risk browser control features unless you explicitly turn them on.
+
+The default security posture is:
+
+- `server.bind = 127.0.0.1`
+- `server.token` is generated during default setup and should remain set
+- `security.allowEvaluate = false`
+- `security.allowMacro = false`
+- `security.allowScreencast = false`
+- `security.allowDownload = false`
+- `security.allowUpload = false`
+- `security.attach.enabled = false`
+- `security.attach.allowHosts = ["127.0.0.1", "localhost", "::1"]`
+- `security.attach.allowSchemes = ["ws", "wss"]`
+- `security.idpi.enabled = true`
+- `security.idpi.allowedDomains = ["127.0.0.1", "localhost", "::1"]`
+- `security.idpi.strictMode = true`
+- `security.idpi.scanContent = true`
+- `security.idpi.wrapContent = true`
+
+Use `pinchtab security` to review the current posture and restore the recommended defaults.
+
+## Security Philosophy
+
+PinchTab follows a few simple rules:
+
+- default to local-only access
+- default dangerous capabilities to off
+- separate transport access from feature exposure
+- fail closed when content or domain trust cannot be established
+
+This means there are two independent questions:
+
+1. who can reach the server
+2. what the server is allowed to do once reached
+
+Both matter.
+
+Binding to loopback reduces who can reach the API. Tokens reduce who can use it successfully. Sensitive endpoint gates reduce what a successful caller can do. IDPI reduces which websites and extracted content are trusted enough to pass deeper into an agent workflow.
+
+## API Token
+
+`server.token` is the bearer token expected by the server. When it is set, requests must send:
+
+```http
+Authorization: Bearer <token>
+```
+
+Why this matters:
+
+- without a token, any process that can reach the server can call the API
+- on `127.0.0.1`, that still includes local scripts, browser pages, other users on the same machine, and malware
+- on `0.0.0.0` or a LAN bind, a missing token is a much bigger risk
+
+Recommended practice:
+
+- keep `server.bind` on `127.0.0.1`
+- set a strong random `server.token`
+- only widen the bind when remote access is intentional
+
+`pinchtab config init` generates and stores a token as part of the default setup:
+
+```bash
+pinchtab config init
+```
+
+You can also generate one from the dashboard Settings page or let `pinchtab security` restore create one if `server.token` is empty.
+
+If you are calling the API manually:
+
+```bash
+curl -H "Authorization: Bearer <token>" http://127.0.0.1:9867/health
+```
+
+CLI commands use the configured local server settings by default, and `PINCHTAB_TOKEN` can override the token for a single shell session.
+
+## Sensitive Endpoints
+
+Some endpoint families expose much more power than normal navigation and inspection. PinchTab keeps them disabled by default:
+
+- `security.allowEvaluate`
+- `security.allowMacro`
+- `security.allowScreencast`
+- `security.allowDownload`
+- `security.allowUpload`
+
+Why they are considered dangerous:
+
+- `evaluate` can execute JavaScript in page context
+- `macro` can trigger higher-level automation flows
+- `screencast` can stream live page contents
+- `download` can fetch and persist remote content
+- `upload` can push local files into browser flows
+
+These are not the same as authentication.
+
+- auth decides who may call the API
+- sensitive endpoint gates decide which high-risk capabilities exist at all
+
+For example, a token-protected server with `security.allowEvaluate = true` is still intentionally exposing JavaScript execution to any caller that has the token.
+
+When disabled, these routes are locked and return a `403` explaining that the endpoint family is disabled in config.
+
+## Attach Policy
+
+Attach is an advanced feature for registering an externally managed Chrome instance through a CDP URL. It is disabled by default:
+
+```json
+{
+ "security": {
+ "attach": {
+ "enabled": false,
+ "allowHosts": ["127.0.0.1", "localhost", "::1"],
+ "allowSchemes": ["ws", "wss"]
+ }
+ }
+}
+```
+
+If you enable attach:
+
+- keep `allowHosts` narrowly scoped
+- prefer local-only hosts unless external Chrome targets are intentional
+- only attach to browsers and CDP endpoints you trust
+
+## IDPI
+
+IDPI stands for Indirect Prompt Injection defense.
+
+It exists to reduce the chance that untrusted website content influences downstream agents through hidden instructions, poisoned text, or unsafe navigation.
+
+PinchTab's IDPI layer currently does four things:
+
+- restricts navigation to an allowlist of approved domains
+- blocks or warns when a URL cannot be matched against that allowlist
+- scans extracted content for suspicious prompt-injection patterns
+- wraps text output so downstream systems can treat it as untrusted content
+
+The default local-only IDPI config is:
+
+```json
+{
+ "security": {
+ "idpi": {
+ "enabled": true,
+ "allowedDomains": ["127.0.0.1", "localhost", "::1"],
+ "strictMode": true,
+ "scanContent": true,
+ "wrapContent": true,
+ "customPatterns": []
+ }
+ }
+}
+```
+
+Important notes:
+
+- if `allowedDomains` is empty, the main domain restriction is not doing useful work
+- if `allowedDomains` contains `"*"`, the whitelist effectively allows everything
+- `strictMode = true` blocks disallowed domains and suspicious content
+- `strictMode = false` allows the request but emits warnings instead
+- `scanContent` protects `/text` and `/snapshot` style extraction paths
+- `wrapContent` adds explicit untrusted-content framing for downstream consumers
+
+Supported domain patterns are:
+
+- exact host: `example.com`
+- subdomain wildcard: `*.example.com`
+- full wildcard: `*`
+
+`*` is convenient, but it defeats the main allowlist defense and should be avoided unless you are deliberately disabling domain restriction.
+
+## Recommended Config
+
+For a secure local setup:
+
+```json
+{
+ "server": {
+ "bind": "127.0.0.1",
+ "token": "replace-with-a-generated-token"
+ },
+ "security": {
+ "allowEvaluate": false,
+ "allowMacro": false,
+ "allowScreencast": false,
+ "allowDownload": false,
+ "allowUpload": false,
+ "attach": {
+ "enabled": false,
+ "allowHosts": ["127.0.0.1", "localhost", "::1"],
+ "allowSchemes": ["ws", "wss"]
+ },
+ "idpi": {
+ "enabled": true,
+ "allowedDomains": ["127.0.0.1", "localhost", "::1"],
+ "strictMode": true,
+ "scanContent": true,
+ "wrapContent": true,
+ "customPatterns": []
+ }
+ }
+}
+```
+
+If you intentionally expose PinchTab beyond localhost, treat the token as mandatory and keep the sensitive endpoint families disabled unless you have a specific reason to enable them.
diff --git a/docs/index.json b/docs/index.json
index 9ffd4b25..4d4371dd 100644
--- a/docs/index.json
+++ b/docs/index.json
@@ -9,6 +9,7 @@
],
"guides": [
"guides/contributing.md",
+ "guides/security.md",
"guides/attach-chrome.md",
"guides/multi-instance.md",
"guides/identifying-instances.md",
diff --git a/docs/reference/config.md b/docs/reference/config.md
index c0338831..77c57ee9 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -4,6 +4,8 @@
Use this page as the command and schema reference. Broader deployment patterns can move to a separate guide later.
+For security posture, token usage, sensitive endpoint policy, and IDPI guidance, see [Security](../guides/security.md).
+
## Commands
### `pinchtab config init`
@@ -54,7 +56,7 @@ Reads a single dotted-path value from the config file.
```bash
pinchtab config get server.port
pinchtab config get instanceDefaults.mode
-pinchtab config get attach.allowHosts
+pinchtab config get security.attach.allowHosts
```
### `pinchtab config set`
@@ -147,7 +149,20 @@ Current nested config shape:
"allowMacro": false,
"allowScreencast": false,
"allowDownload": false,
- "allowUpload": false
+ "allowUpload": false,
+ "attach": {
+ "enabled": false,
+ "allowHosts": ["127.0.0.1", "localhost", "::1"],
+ "allowSchemes": ["ws", "wss"]
+ },
+ "idpi": {
+ "enabled": true,
+ "allowedDomains": ["127.0.0.1", "localhost", "::1"],
+ "strictMode": true,
+ "scanContent": true,
+ "wrapContent": true,
+ "customPatterns": []
+ }
},
"profiles": {
"baseDir": "/path/to/profiles",
@@ -159,11 +174,6 @@ Current nested config shape:
"instancePortStart": 9868,
"instancePortEnd": 9968
},
- "attach": {
- "enabled": false,
- "allowHosts": ["127.0.0.1", "localhost", "::1"],
- "allowSchemes": ["ws", "wss"]
- },
"timeouts": {
"actionSec": 30,
"navigateSec": 60,
@@ -180,10 +190,9 @@ Current nested config shape:
| `server` | HTTP server settings |
| `browser` | Chrome executable and launch wiring |
| `instanceDefaults` | Default behavior for managed instances |
-| `security` | Sensitive feature gates |
+| `security` | Sensitive feature gates, attach policy, and IDPI |
| `profiles` | Profile storage defaults |
| `multiInstance` | Strategy, allocation, and instance port range |
-| `attach` | Policy for attaching to external Chrome targets |
| `timeouts` | Runtime timeouts |
## Common Examples
@@ -233,10 +242,29 @@ PINCHTAB_BIND=0.0.0.0 PINCHTAB_TOKEN=secret pinchtab
```json
{
- "attach": {
- "enabled": true,
- "allowHosts": ["127.0.0.1", "localhost", "chrome.internal"],
- "allowSchemes": ["ws", "wss"]
+ "security": {
+ "attach": {
+ "enabled": true,
+ "allowHosts": ["127.0.0.1", "localhost", "chrome.internal"],
+ "allowSchemes": ["ws", "wss"]
+ }
+ }
+}
+```
+
+### IDPI Policy
+
+```json
+{
+ "security": {
+ "idpi": {
+ "enabled": true,
+ "allowedDomains": ["example.com", "*.example.com"],
+ "strictMode": true,
+ "scanContent": true,
+ "wrapContent": true,
+ "customPatterns": []
+ }
}
}
```
@@ -272,7 +300,7 @@ Use `pinchtab config init` to create a nested config file.
- `instanceDefaults.maxParallelTabs >= 0`
- valid `multiInstance.strategy`
- valid `multiInstance.allocationPolicy`
-- valid `attach.allowSchemes`
+- valid `security.attach.allowSchemes`
- `multiInstance.instancePortStart <= multiInstance.instancePortEnd`
- non-negative timeout values
@@ -285,10 +313,10 @@ Valid enum values:
| `instanceDefaults.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` |
| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart` |
| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |
-| `attach.allowSchemes` | `ws`, `wss` |
+| `security.attach.allowSchemes` | `ws`, `wss` |
## Notes
- `config show` reports effective runtime values, not just raw file contents.
- `config get`, `set`, and `patch` operate on the file config model, not on transient env overrides.
-- Most operational behavior now belongs in `config.json`, not in startup env vars.
\ No newline at end of file
+- Most operational behavior now belongs in `config.json`, not in startup env vars.
diff --git a/docs/reference/instances.md b/docs/reference/instances.md
index 8d3e07eb..565b2d9b 100644
--- a/docs/reference/instances.md
+++ b/docs/reference/instances.md
@@ -202,4 +202,4 @@ curl -X POST http://localhost:9867/instances/attach \
Notes:
- there is no CLI attach command
-- attach is allowed only when enabled in config under `attach`
+- attach is allowed only when enabled in config under `security.attach`
diff --git a/internal/config/config.go b/internal/config/config.go
index a9a73805..67d6a426 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -1,6 +1,8 @@
package config
import (
+ "crypto/rand"
+ "encoding/hex"
"encoding/json"
"fmt"
"log/slog"
@@ -121,7 +123,6 @@ type FileConfig struct {
Security SecurityConfig `json:"security,omitempty"`
Profiles ProfilesConfig `json:"profiles,omitempty"`
MultiInstance MultiInstanceConfig `json:"multiInstance,omitempty"`
- Attach AttachConfig `json:"attach,omitempty"`
Timeouts TimeoutsConfig `json:"timeouts,omitempty"`
Scheduler SchedulerFileConfig `json:"scheduler,omitempty"`
}
@@ -166,12 +167,13 @@ type ProfilesConfig struct {
// SecurityConfig holds security/permission settings.
type SecurityConfig struct {
- AllowEvaluate *bool `json:"allowEvaluate,omitempty"`
- AllowMacro *bool `json:"allowMacro,omitempty"`
- AllowScreencast *bool `json:"allowScreencast,omitempty"`
- AllowDownload *bool `json:"allowDownload,omitempty"`
- AllowUpload *bool `json:"allowUpload,omitempty"`
- IDPI IDPIConfig `json:"idpi,omitempty"`
+ AllowEvaluate *bool `json:"allowEvaluate,omitempty"`
+ AllowMacro *bool `json:"allowMacro,omitempty"`
+ AllowScreencast *bool `json:"allowScreencast,omitempty"`
+ AllowDownload *bool `json:"allowDownload,omitempty"`
+ AllowUpload *bool `json:"allowUpload,omitempty"`
+ Attach AttachConfig `json:"attach,omitempty"`
+ IDPI IDPIConfig `json:"idpi,omitempty"`
}
// IDPIConfig holds the configuration for the Indirect Prompt Injection (IDPI)
@@ -183,8 +185,8 @@ type IDPIConfig struct {
// AllowedDomains is a whitelist of permitted navigation targets.
// An empty list means all domains are allowed (no restriction).
- // Patterns support exact matches ("example.com") and single-level wildcard
- // prefixes ("*.example.com"). The special value "*" allows everything.
+ // Patterns support exact matches ("pinchtab.com") and single-level wildcard
+ // prefixes ("*.pinchtab.com"). The special value "*" allows everything.
AllowedDomains []string `json:"allowedDomains,omitempty"`
// StrictMode controls the response when a threat is detected.
@@ -207,6 +209,8 @@ type IDPIConfig struct {
CustomPatterns []string `json:"customPatterns,omitempty"`
}
+var defaultLocalAllowedDomains = []string{"127.0.0.1", "localhost", "::1"}
+
// MultiInstanceConfig holds multi-instance orchestration settings.
type MultiInstanceConfig struct {
Strategy string `json:"strategy,omitempty"`
@@ -456,6 +460,16 @@ func finalizeProfileConfig(cfg *RuntimeConfig) {
}
}
+// GenerateAuthToken returns a cryptographically random bearer token suitable
+// for server authentication.
+func GenerateAuthToken() (string, error) {
+ buf := make([]byte, 24)
+ if _, err := rand.Read(buf); err != nil {
+ return "", fmt.Errorf("generate auth token: %w", err)
+ }
+ return hex.EncodeToString(buf), nil
+}
+
// Load returns the RuntimeConfig with precedence: env vars > config file > defaults.
func Load() *RuntimeConfig {
cfg := &RuntimeConfig{
@@ -509,6 +523,15 @@ func Load() *RuntimeConfig {
AttachEnabled: false,
AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},
AttachAllowSchemes: []string{"ws", "wss"},
+
+ // IDPI defaults
+ IDPI: IDPIConfig{
+ Enabled: true,
+ AllowedDomains: append([]string(nil), defaultLocalAllowedDomains...),
+ StrictMode: true,
+ ScanContent: true,
+ WrapContent: true,
+ },
}
finalizeProfileConfig(cfg)
@@ -668,14 +691,14 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {
}
// Attach
- if fc.Attach.Enabled != nil {
- cfg.AttachEnabled = *fc.Attach.Enabled
+ if fc.Security.Attach.Enabled != nil {
+ cfg.AttachEnabled = *fc.Security.Attach.Enabled
}
- if len(fc.Attach.AllowHosts) > 0 {
- cfg.AttachAllowHosts = append([]string(nil), fc.Attach.AllowHosts...)
+ if len(fc.Security.Attach.AllowHosts) > 0 {
+ cfg.AttachAllowHosts = append([]string(nil), fc.Security.Attach.AllowHosts...)
}
- if len(fc.Attach.AllowSchemes) > 0 {
- cfg.AttachAllowSchemes = append([]string(nil), fc.Attach.AllowSchemes...)
+ if len(fc.Security.Attach.AllowSchemes) > 0 {
+ cfg.AttachAllowSchemes = append([]string(nil), fc.Security.Attach.AllowSchemes...)
}
// Timeouts
@@ -761,6 +784,17 @@ func DefaultFileConfig() FileConfig {
AllowScreencast: &allowScreencast,
AllowDownload: &allowDownload,
AllowUpload: &allowUpload,
+ Attach: AttachConfig{
+ AllowHosts: []string{"127.0.0.1", "localhost", "::1"},
+ AllowSchemes: []string{"ws", "wss"},
+ },
+ IDPI: IDPIConfig{
+ Enabled: true,
+ AllowedDomains: append([]string(nil), defaultLocalAllowedDomains...),
+ StrictMode: true,
+ ScanContent: true,
+ WrapContent: true,
+ },
},
Profiles: ProfilesConfig{
BaseDir: filepath.Join(userConfigDir(), "profiles"),
@@ -772,10 +806,6 @@ func DefaultFileConfig() FileConfig {
InstancePortStart: &start,
InstancePortEnd: &end,
},
- Attach: AttachConfig{
- AllowHosts: []string{"127.0.0.1", "localhost", "::1"},
- AllowSchemes: []string{"ws", "wss"},
- },
Timeouts: TimeoutsConfig{
ActionSec: 30,
NavigateSec: 60,
@@ -847,6 +877,11 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
AllowScreencast: &allowScreencast,
AllowDownload: &allowDownload,
AllowUpload: &allowUpload,
+ Attach: AttachConfig{
+ Enabled: &attachEnabled,
+ AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
+ AllowSchemes: append([]string(nil), cfg.AttachAllowSchemes...),
+ },
},
Profiles: ProfilesConfig{
BaseDir: cfg.ProfilesBaseDir,
@@ -858,11 +893,6 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
InstancePortStart: &start,
InstancePortEnd: &end,
},
- Attach: AttachConfig{
- Enabled: &attachEnabled,
- AllowHosts: append([]string(nil), cfg.AttachAllowHosts...),
- AllowSchemes: append([]string(nil), cfg.AttachAllowSchemes...),
- },
Timeouts: TimeoutsConfig{
ActionSec: int(cfg.ActionTimeout / time.Second),
NavigateSec: int(cfg.NavigateTimeout / time.Second),
@@ -923,9 +953,9 @@ func handleConfigGet() {
fmt.Println("Examples:")
fmt.Println(" pinchtab config get server.port")
fmt.Println(" pinchtab config get instanceDefaults.mode")
- fmt.Println(" pinchtab config get attach.allowHosts")
+ fmt.Println(" pinchtab config get security.attach.allowHosts")
fmt.Println()
- fmt.Println("Sections: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts")
+ fmt.Println("Sections: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts")
os.Exit(1)
}
@@ -965,6 +995,12 @@ func handleConfigInit() {
}
fc := DefaultFileConfig()
+ token, err := GenerateAuthToken()
+ if err != nil {
+ fmt.Printf("Error generating auth token: %v\n", err)
+ os.Exit(1)
+ }
+ fc.Server.Token = token
data, _ := json.MarshalIndent(fc, "", " ")
if err := os.WriteFile(configPath, data, 0644); err != nil {
fmt.Printf("Error writing config: %v\n", err)
@@ -1045,8 +1081,9 @@ func handleConfigSet() {
fmt.Println(" pinchtab config set server.port 8080")
fmt.Println(" pinchtab config set instanceDefaults.mode headed")
fmt.Println(" pinchtab config set multiInstance.strategy explicit")
+ fmt.Println(" pinchtab config set security.attach.enabled true")
fmt.Println()
- fmt.Println("Sections: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts")
+ fmt.Println("Sections: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts")
os.Exit(1)
}
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index cc2ad4f1..53ac6974 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -62,6 +62,24 @@ func TestMaskToken(t *testing.T) {
}
}
+func TestGenerateAuthToken(t *testing.T) {
+ token, err := GenerateAuthToken()
+ if err != nil {
+ t.Fatalf("GenerateAuthToken() error = %v", err)
+ }
+ if len(token) != 48 {
+ t.Fatalf("GenerateAuthToken() len = %d, want 48", len(token))
+ }
+ for _, r := range token {
+ switch {
+ case r >= '0' && r <= '9':
+ case r >= 'a' && r <= 'f':
+ default:
+ t.Fatalf("GenerateAuthToken() produced non-hex rune %q", r)
+ }
+ }
+}
+
func TestLoadConfigDefaults(t *testing.T) {
clearConfigEnvVars(t)
// Point to non-existent config to test pure defaults
@@ -93,6 +111,21 @@ func TestLoadConfigDefaults(t *testing.T) {
if len(cfg.AttachAllowSchemes) != 2 || cfg.AttachAllowSchemes[0] != "ws" || cfg.AttachAllowSchemes[1] != "wss" {
t.Errorf("default AttachAllowSchemes = %v, want [ws wss]", cfg.AttachAllowSchemes)
}
+ if !cfg.IDPI.Enabled {
+ t.Errorf("default IDPI.Enabled = %v, want true", cfg.IDPI.Enabled)
+ }
+ if len(cfg.IDPI.AllowedDomains) != 3 || cfg.IDPI.AllowedDomains[0] != "127.0.0.1" {
+ t.Errorf("default IDPI.AllowedDomains = %v, want local-only allowlist", cfg.IDPI.AllowedDomains)
+ }
+ if !cfg.IDPI.StrictMode {
+ t.Errorf("default IDPI.StrictMode = %v, want true", cfg.IDPI.StrictMode)
+ }
+ if !cfg.IDPI.ScanContent {
+ t.Errorf("default IDPI.ScanContent = %v, want true", cfg.IDPI.ScanContent)
+ }
+ if !cfg.IDPI.WrapContent {
+ t.Errorf("default IDPI.WrapContent = %v, want true", cfg.IDPI.WrapContent)
+ }
}
func TestLoadConfigEnvOverrides(t *testing.T) {
@@ -161,8 +194,8 @@ func TestDefaultFileConfig(t *testing.T) {
if fc.MultiInstance.Strategy != "simple" {
t.Errorf("DefaultFileConfig.MultiInstance.Strategy = %v, want simple", fc.MultiInstance.Strategy)
}
- 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 len(fc.Security.Attach.AllowSchemes) != 2 || fc.Security.Attach.AllowSchemes[0] != "ws" || fc.Security.Attach.AllowSchemes[1] != "wss" {
+ t.Errorf("DefaultFileConfig.Security.Attach.AllowSchemes = %v, want [ws wss]", fc.Security.Attach.AllowSchemes)
}
if fc.Security.AllowEvaluate == nil || *fc.Security.AllowEvaluate {
t.Errorf("DefaultFileConfig.Security.AllowEvaluate = %v, want explicit false", formatBoolPtr(fc.Security.AllowEvaluate))
@@ -179,6 +212,21 @@ func TestDefaultFileConfig(t *testing.T) {
if fc.Security.AllowUpload == nil || *fc.Security.AllowUpload {
t.Errorf("DefaultFileConfig.Security.AllowUpload = %v, want explicit false", formatBoolPtr(fc.Security.AllowUpload))
}
+ if !fc.Security.IDPI.Enabled {
+ t.Errorf("DefaultFileConfig.Security.IDPI.Enabled = %v, want true", fc.Security.IDPI.Enabled)
+ }
+ if len(fc.Security.IDPI.AllowedDomains) != 3 || fc.Security.IDPI.AllowedDomains[0] != "127.0.0.1" {
+ t.Errorf("DefaultFileConfig.Security.IDPI.AllowedDomains = %v, want local-only allowlist", fc.Security.IDPI.AllowedDomains)
+ }
+ if !fc.Security.IDPI.StrictMode {
+ t.Errorf("DefaultFileConfig.Security.IDPI.StrictMode = %v, want true", fc.Security.IDPI.StrictMode)
+ }
+ if !fc.Security.IDPI.ScanContent {
+ t.Errorf("DefaultFileConfig.Security.IDPI.ScanContent = %v, want true", fc.Security.IDPI.ScanContent)
+ }
+ if !fc.Security.IDPI.WrapContent {
+ t.Errorf("DefaultFileConfig.Security.IDPI.WrapContent = %v, want true", fc.Security.IDPI.WrapContent)
+ }
}
// TestLoadNestedConfig tests loading the new nested config format.
@@ -204,17 +252,17 @@ func TestLoadNestedConfig(t *testing.T) {
"tabEvictionPolicy": "close_oldest"
},
"security": {
- "allowEvaluate": true
+ "allowEvaluate": true,
+ "attach": {
+ "enabled": true,
+ "allowHosts": ["localhost", "chrome.internal"],
+ "allowSchemes": ["wss"]
+ }
},
"multiInstance": {
"strategy": "explicit",
"allocationPolicy": "round_robin"
},
- "attach": {
- "enabled": true,
- "allowHosts": ["localhost", "chrome.internal"],
- "allowSchemes": ["wss"]
- },
"timeouts": {
"actionSec": 60,
"navigateSec": 120
@@ -393,8 +441,8 @@ func TestIsLegacyConfig(t *testing.T) {
isLegacy: false,
},
{
- name: "nested format with attach",
- json: `{"attach": {"enabled": true}}`,
+ name: "nested format with security.attach",
+ json: `{"security": {"attach": {"enabled": true}}}`,
isLegacy: false,
},
{
@@ -499,6 +547,21 @@ func TestDefaultFileConfigJSON(t *testing.T) {
if parsed.Security.AllowUpload == nil || *parsed.Security.AllowUpload {
t.Errorf("round-trip Security.AllowUpload = %v, want explicit false", formatBoolPtr(parsed.Security.AllowUpload))
}
+ if !parsed.Security.IDPI.Enabled {
+ t.Errorf("round-trip Security.IDPI.Enabled = %v, want true", parsed.Security.IDPI.Enabled)
+ }
+ if len(parsed.Security.IDPI.AllowedDomains) != 3 || parsed.Security.IDPI.AllowedDomains[0] != "127.0.0.1" {
+ t.Errorf("round-trip Security.IDPI.AllowedDomains = %v, want local-only allowlist", parsed.Security.IDPI.AllowedDomains)
+ }
+ if !parsed.Security.IDPI.StrictMode {
+ t.Errorf("round-trip Security.IDPI.StrictMode = %v, want true", parsed.Security.IDPI.StrictMode)
+ }
+ if !parsed.Security.IDPI.ScanContent {
+ t.Errorf("round-trip Security.IDPI.ScanContent = %v, want true", parsed.Security.IDPI.ScanContent)
+ }
+ if !parsed.Security.IDPI.WrapContent {
+ t.Errorf("round-trip Security.IDPI.WrapContent = %v, want true", parsed.Security.IDPI.WrapContent)
+ }
}
func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T) {
@@ -508,6 +571,9 @@ func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T)
AllowScreencast: true,
AllowDownload: true,
AllowUpload: true,
+ IDPI: IDPIConfig{
+ Enabled: false,
+ },
}
fc := DefaultFileConfig()
@@ -528,6 +594,15 @@ func TestApplyFileConfigToRuntimeResetsSecurityFlagsToSafeDefaults(t *testing.T)
if cfg.AllowUpload {
t.Errorf("ApplyFileConfigToRuntime AllowUpload = %v, want false", cfg.AllowUpload)
}
+ if !cfg.IDPI.Enabled {
+ t.Errorf("ApplyFileConfigToRuntime IDPI.Enabled = %v, want true", cfg.IDPI.Enabled)
+ }
+ if len(cfg.IDPI.AllowedDomains) != 3 || cfg.IDPI.AllowedDomains[0] != "127.0.0.1" {
+ t.Errorf("ApplyFileConfigToRuntime IDPI.AllowedDomains = %v, want local-only allowlist", cfg.IDPI.AllowedDomains)
+ }
+ if !cfg.IDPI.StrictMode || !cfg.IDPI.ScanContent || !cfg.IDPI.WrapContent {
+ t.Errorf("ApplyFileConfigToRuntime IDPI = %+v, want strict+scan+wrap enabled", cfg.IDPI)
+ }
}
// Helper functions
diff --git a/internal/config/editor.go b/internal/config/editor.go
index 9de727f6..c507cead 100644
--- a/internal/config/editor.go
+++ b/internal/config/editor.go
@@ -32,12 +32,10 @@ func SetConfigValue(fc *FileConfig, path string, value string) error {
return setProfilesField(&fc.Profiles, field, value)
case "multiInstance":
return setMultiInstanceField(&fc.MultiInstance, field, value)
- case "attach":
- return setAttachField(&fc.Attach, field, value)
case "timeouts":
return setTimeoutsField(&fc.Timeouts, field, value)
default:
- return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts)", section)
+ return fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)
}
}
@@ -132,6 +130,13 @@ func setInstanceDefaultsField(c *InstanceDefaultsConfig, field, value string) er
}
func setSecurityField(s *SecurityConfig, field, value string) error {
+ if strings.HasPrefix(field, "attach.") {
+ return setAttachField(&s.Attach, strings.TrimPrefix(field, "attach."), value)
+ }
+ if strings.HasPrefix(field, "idpi.") {
+ return setIDPIField(&s.IDPI, strings.TrimPrefix(field, "idpi."), value)
+ }
+
b, err := parseBool(value)
if err != nil {
return fmt.Errorf("security.%s: %w", field, err)
@@ -216,7 +221,7 @@ func setAttachField(a *AttachConfig, field, value string) error {
case "enabled":
b, err := parseBool(value)
if err != nil {
- return fmt.Errorf("attach.enabled: %w", err)
+ return fmt.Errorf("security.attach.enabled: %w", err)
}
a.Enabled = &b
case "allowHosts":
@@ -224,13 +229,13 @@ func setAttachField(a *AttachConfig, field, value string) error {
case "allowSchemes":
a.AllowSchemes = parseCSVList(value)
default:
- return fmt.Errorf("unknown field attach.%s", field)
+ return fmt.Errorf("unknown field security.attach.%s", field)
}
return nil
}
// GetConfigValue reads a dotted-path field from FileConfig and returns its string representation.
-// The path format matches SetConfigValue (e.g., "server.port", "attach.allowHosts").
+// The path format matches SetConfigValue (e.g., "server.port", "security.attach.allowHosts").
// Pointer fields that are unset return an empty string.
// Slice fields are returned as comma-separated values.
func GetConfigValue(fc *FileConfig, path string) (string, error) {
@@ -254,12 +259,10 @@ func GetConfigValue(fc *FileConfig, path string) (string, error) {
return getProfilesField(&fc.Profiles, field)
case "multiInstance":
return getMultiInstanceField(&fc.MultiInstance, field)
- case "attach":
- return getAttachField(&fc.Attach, field)
case "timeouts":
return getTimeoutsField(&fc.Timeouts, field)
default:
- return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, attach, timeouts)", section)
+ return "", fmt.Errorf("unknown section %q (valid: server, browser, instanceDefaults, security, profiles, multiInstance, timeouts)", section)
}
}
@@ -323,6 +326,13 @@ func getInstanceDefaultsField(c *InstanceDefaultsConfig, field string) (string,
}
func getSecurityField(s *SecurityConfig, field string) (string, error) {
+ if strings.HasPrefix(field, "attach.") {
+ return getAttachField(&s.Attach, strings.TrimPrefix(field, "attach."))
+ }
+ if strings.HasPrefix(field, "idpi.") {
+ return getIDPIField(&s.IDPI, strings.TrimPrefix(field, "idpi."))
+ }
+
switch field {
case "allowEvaluate":
return formatBoolPtr(s.AllowEvaluate), nil
@@ -374,7 +384,62 @@ func getAttachField(a *AttachConfig, field string) (string, error) {
case "allowSchemes":
return strings.Join(a.AllowSchemes, ","), nil
default:
- return "", fmt.Errorf("unknown field attach.%s", field)
+ return "", fmt.Errorf("unknown field security.attach.%s", field)
+ }
+}
+
+func setIDPIField(i *IDPIConfig, field, value string) error {
+ switch field {
+ case "enabled":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.enabled: %w", err)
+ }
+ i.Enabled = b
+ case "allowedDomains":
+ i.AllowedDomains = parseCSVList(value)
+ case "strictMode":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.strictMode: %w", err)
+ }
+ i.StrictMode = b
+ case "scanContent":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.scanContent: %w", err)
+ }
+ i.ScanContent = b
+ case "wrapContent":
+ b, err := parseBool(value)
+ if err != nil {
+ return fmt.Errorf("security.idpi.wrapContent: %w", err)
+ }
+ i.WrapContent = b
+ case "customPatterns":
+ i.CustomPatterns = parseCSVList(value)
+ default:
+ return fmt.Errorf("unknown field security.idpi.%s", field)
+ }
+ return nil
+}
+
+func getIDPIField(i *IDPIConfig, field string) (string, error) {
+ switch field {
+ case "enabled":
+ return strconv.FormatBool(i.Enabled), nil
+ case "allowedDomains":
+ return strings.Join(i.AllowedDomains, ","), nil
+ case "strictMode":
+ return strconv.FormatBool(i.StrictMode), nil
+ case "scanContent":
+ return strconv.FormatBool(i.ScanContent), nil
+ case "wrapContent":
+ return strconv.FormatBool(i.WrapContent), nil
+ case "customPatterns":
+ return strings.Join(i.CustomPatterns, ","), nil
+ default:
+ return "", fmt.Errorf("unknown field security.idpi.%s", field)
}
}
diff --git a/internal/config/editor_test.go b/internal/config/editor_test.go
index d80da570..60c84093 100644
--- a/internal/config/editor_test.go
+++ b/internal/config/editor_test.go
@@ -136,15 +136,51 @@ func TestSetConfigValue_AttachFields(t *testing.T) {
check func(*FileConfig) bool
wantErr bool
}{
- {"attach.enabled", "true", func(fc *FileConfig) bool { return fc.Attach.Enabled != nil && *fc.Attach.Enabled }, false},
- {"attach.allowHosts", "localhost, chrome.internal", func(fc *FileConfig) bool {
- return len(fc.Attach.AllowHosts) == 2 && fc.Attach.AllowHosts[1] == "chrome.internal"
+ {"security.attach.enabled", "true", func(fc *FileConfig) bool { return fc.Security.Attach.Enabled != nil && *fc.Security.Attach.Enabled }, false},
+ {"security.attach.allowHosts", "localhost, chrome.internal", func(fc *FileConfig) bool {
+ return len(fc.Security.Attach.AllowHosts) == 2 && fc.Security.Attach.AllowHosts[1] == "chrome.internal"
}, false},
- {"attach.allowSchemes", "ws,wss", func(fc *FileConfig) bool {
- return len(fc.Attach.AllowSchemes) == 2 && fc.Attach.AllowSchemes[0] == "ws"
+ {"security.attach.allowSchemes", "ws,wss", func(fc *FileConfig) bool {
+ return len(fc.Security.Attach.AllowSchemes) == 2 && fc.Security.Attach.AllowSchemes[0] == "ws"
}, false},
- {"attach.enabled", "maybe", nil, true},
- {"attach.unknown", "value", nil, true},
+ {"security.attach.enabled", "maybe", nil, true},
+ {"security.attach.unknown", "value", nil, true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.path+"="+tt.value, func(t *testing.T) {
+ fc := &FileConfig{}
+ err := SetConfigValue(fc, tt.path, tt.value)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("SetConfigValue() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if !tt.wantErr && !tt.check(fc) {
+ t.Errorf("SetConfigValue() did not set value correctly")
+ }
+ })
+ }
+}
+
+func TestSetConfigValue_IDPIFields(t *testing.T) {
+ tests := []struct {
+ path string
+ value string
+ check func(*FileConfig) bool
+ wantErr bool
+ }{
+ {"security.idpi.enabled", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.Enabled }, false},
+ {"security.idpi.allowedDomains", "localhost, example.com", func(fc *FileConfig) bool {
+ return len(fc.Security.IDPI.AllowedDomains) == 2 && fc.Security.IDPI.AllowedDomains[1] == "example.com"
+ }, false},
+ {"security.idpi.strictMode", "false", func(fc *FileConfig) bool { return !fc.Security.IDPI.StrictMode }, false},
+ {"security.idpi.scanContent", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.ScanContent }, false},
+ {"security.idpi.wrapContent", "true", func(fc *FileConfig) bool { return fc.Security.IDPI.WrapContent }, false},
+ {"security.idpi.customPatterns", "ignore previous instructions, exfiltrate data", func(fc *FileConfig) bool {
+ return len(fc.Security.IDPI.CustomPatterns) == 2 && fc.Security.IDPI.CustomPatterns[0] == "ignore previous instructions"
+ }, false},
+ {"security.idpi.enabled", "maybe", nil, true},
+ {"security.idpi.unknown", "value", nil, true},
}
for _, tt := range tests {
@@ -386,7 +422,13 @@ func TestGetConfigValue_RoundTrip(t *testing.T) {
{"multiInstance.allocationPolicy", "round_robin", "round_robin"},
{"multiInstance.instancePortStart", "9900", "9900"},
{"multiInstance.instancePortEnd", "9950", "9950"},
- {"attach.enabled", "true", "true"},
+ {"security.attach.enabled", "true", "true"},
+ {"security.idpi.enabled", "true", "true"},
+ {"security.idpi.allowedDomains", "localhost,example.com", "localhost,example.com"},
+ {"security.idpi.strictMode", "false", "false"},
+ {"security.idpi.scanContent", "true", "true"},
+ {"security.idpi.wrapContent", "true", "true"},
+ {"security.idpi.customPatterns", "ignore previous instructions,exfiltrate", "ignore previous instructions,exfiltrate"},
{"timeouts.actionSec", "60", "60"},
{"timeouts.navigateSec", "90", "90"},
{"timeouts.shutdownSec", "15", "15"},
@@ -428,7 +470,7 @@ func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {
"security.allowUpload",
"multiInstance.instancePortStart",
"multiInstance.instancePortEnd",
- "attach.enabled",
+ "security.attach.enabled",
}
for _, path := range ptrs {
t.Run(path, func(t *testing.T) {
@@ -445,20 +487,20 @@ func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {
func TestGetConfigValue_AttachSlices(t *testing.T) {
fc := &FileConfig{}
- fc.Attach.AllowHosts = []string{"127.0.0.1", "localhost"}
- fc.Attach.AllowSchemes = []string{"ws", "wss"}
+ fc.Security.Attach.AllowHosts = []string{"127.0.0.1", "localhost"}
+ fc.Security.Attach.AllowSchemes = []string{"ws", "wss"}
- hosts, err := GetConfigValue(fc, "attach.allowHosts")
+ hosts, err := GetConfigValue(fc, "security.attach.allowHosts")
if err != nil {
- t.Fatalf("GetConfigValue(attach.allowHosts) error = %v", err)
+ t.Fatalf("GetConfigValue(security.attach.allowHosts) error = %v", err)
}
if hosts != "127.0.0.1,localhost" {
t.Errorf("allowHosts = %q, want %q", hosts, "127.0.0.1,localhost")
}
- schemes, err := GetConfigValue(fc, "attach.allowSchemes")
+ schemes, err := GetConfigValue(fc, "security.attach.allowSchemes")
if err != nil {
- t.Fatalf("GetConfigValue(attach.allowSchemes) error = %v", err)
+ t.Fatalf("GetConfigValue(security.attach.allowSchemes) error = %v", err)
}
if schemes != "ws,wss" {
t.Errorf("allowSchemes = %q, want %q", schemes, "ws,wss")
@@ -468,11 +510,12 @@ func TestGetConfigValue_AttachSlices(t *testing.T) {
func TestGetConfigValue_UnknownPaths(t *testing.T) {
fc := &FileConfig{}
errorCases := []string{
- "port", // missing section
- "", // empty
- "unknown.field", // unknown section
- "server.ghost", // unknown field in known section
- "attach.badfield", // unknown attach field
+ "port", // missing section
+ "", // empty
+ "unknown.field", // unknown section
+ "server.ghost", // unknown field in known section
+ "security.attach.badfield", // unknown attach field
+ "security.idpi.badfield", // unknown idpi field
}
for _, path := range errorCases {
t.Run(path, func(t *testing.T) {
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 42899631..3a5a4cd9 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -94,10 +94,10 @@ func ValidateFileConfig(fc *FileConfig) []error {
}
// Attach validation
- for _, scheme := range fc.Attach.AllowSchemes {
+ for _, scheme := range fc.Security.Attach.AllowSchemes {
if !isValidAttachScheme(scheme) {
errs = append(errs, ValidationError{
- Field: "attach.allowSchemes",
+ Field: "security.attach.allowSchemes",
Message: fmt.Sprintf("invalid value %q (must be ws or wss)", scheme),
})
}
diff --git a/internal/config/validate_test.go b/internal/config/validate_test.go
index 541ba252..ba42eb60 100644
--- a/internal/config/validate_test.go
+++ b/internal/config/validate_test.go
@@ -176,7 +176,9 @@ func TestValidateFileConfig_InvalidAttachScheme(t *testing.T) {
for _, tt := range tests {
fc := &FileConfig{
- Attach: AttachConfig{AllowSchemes: tt.schemes},
+ Security: SecurityConfig{
+ Attach: AttachConfig{AllowSchemes: tt.schemes},
+ },
}
errs := ValidateFileConfig(fc)
hasErr := len(errs) > 0
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index 8a04ed38..4ec147ff 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -38,6 +38,10 @@ type configEnvelope struct {
RestartReasons []string `json:"restartReasons,omitempty"`
}
+type tokenEnvelope struct {
+ Token string `json:"token"`
+}
+
type healthEnvelope struct {
Status string `json:"status"`
Mode string `json:"mode"`
@@ -76,6 +80,7 @@ func NewConfigAPI(
func (c *ConfigAPI) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("GET /api/config", c.HandleGetConfig)
mux.HandleFunc("PUT /api/config", c.HandlePutConfig)
+ mux.HandleFunc("POST /api/config/generate-token", c.HandleGenerateToken)
}
func (c *ConfigAPI) HandleHealth(w http.ResponseWriter, r *http.Request) {
@@ -152,6 +157,15 @@ func (c *ConfigAPI) HandlePutConfig(w http.ResponseWriter, r *http.Request) {
})
}
+func (c *ConfigAPI) HandleGenerateToken(w http.ResponseWriter, r *http.Request) {
+ token, err := config.GenerateAuthToken()
+ if err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, tokenEnvelope{Token: token})
+}
+
func (c *ConfigAPI) healthInfo() (healthEnvelope, error) {
_, _, restartReasons, err := c.currentConfig()
if err != nil {
diff --git a/internal/dashboard/dashboard.go b/internal/dashboard/dashboard.go
index 7fdc7bac..26078ce2 100644
--- a/internal/dashboard/dashboard.go
+++ b/internal/dashboard/dashboard.go
@@ -136,10 +136,11 @@ func (d *Dashboard) RegisterHandlers(mux *http.ServeMux) {
mux.Handle("GET /dashboard/assets/", http.StripPrefix("/dashboard", d.withLongCache(fileServer)))
mux.Handle("GET /dashboard/favicon.png", http.StripPrefix("/dashboard", d.withLongCache(fileServer)))
- // SPA: serve dashboard.html for / and /dashboard
+ // SPA: serve dashboard.html for /, /login, and /dashboard/*
mux.Handle("GET /{$}", d.withNoCache(http.HandlerFunc(d.handleDashboardUI)))
+ mux.Handle("GET /login", d.withNoCache(http.HandlerFunc(d.handleDashboardUI)))
mux.Handle("GET /dashboard", d.withNoCache(http.HandlerFunc(d.handleDashboardUI)))
- mux.Handle("GET /dashboard/", d.withNoCache(http.HandlerFunc(d.handleDashboardUI)))
+ mux.Handle("GET /dashboard/{path...}", d.withNoCache(http.HandlerFunc(d.handleDashboardUI)))
}
func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
index 088fe5f4..8c272236 100644
--- a/internal/handlers/middleware.go
+++ b/internal/handlers/middleware.go
@@ -55,6 +55,10 @@ func LoggingMiddleware(next http.Handler) http.Handler {
func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if isPublicDashboardPath(r.URL.Path) {
+ next.ServeHTTP(w, r)
+ return
+ }
if cfg.Token != "" {
auth := r.Header.Get("Authorization")
qToken := r.URL.Query().Get("token")
@@ -84,6 +88,14 @@ func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {
})
}
+func isPublicDashboardPath(path string) bool {
+ switch path {
+ case "/", "/login", "/dashboard", "/dashboard/":
+ return true
+ }
+ return strings.HasPrefix(path, "/dashboard/") || path == "/dashboard/favicon.png"
+}
+
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.go
index 4659aefe..76b9265c 100644
--- a/internal/handlers/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -90,6 +90,61 @@ func TestAuthMiddleware_MissingTokenHeader(t *testing.T) {
}
}
+func TestAuthMiddleware_PublicDashboardPathBypassesAuth(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ called := false
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("GET", "/login", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should have been called for public dashboard path")
+ }
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_PublicDashboardSubpathBypassesAuth(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ called := false
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("GET", "/dashboard/monitoring", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if !called {
+ t.Fatal("handler should have been called for public dashboard subpath")
+ }
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+}
+
+func TestAuthMiddleware_ProtectedAPIStillRequiresAuth(t *testing.T) {
+ cfg := &config.RuntimeConfig{Token: "secret123"}
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ }))
+
+ req := httptest.NewRequest("GET", "/api/config", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != 401 {
+ t.Fatalf("expected 401, got %d", w.Code)
+ }
+}
+
func TestAuthMiddleware_TableDriven(t *testing.T) {
tests := []struct {
name string
diff --git a/tests/integration/config_cli_test.go b/tests/integration/config_cli_test.go
index 9ab12353..1143ba59 100644
--- a/tests/integration/config_cli_test.go
+++ b/tests/integration/config_cli_test.go
@@ -340,7 +340,7 @@ func TestConfigCLI_Get_UnknownPath(t *testing.T) {
}
}
-// TestConfigCLI_Get_SliceField tests that slice fields (e.g., attach.allowHosts)
+// TestConfigCLI_Get_SliceField tests that slice fields (e.g., security.attach.allowHosts)
// are returned as comma-separated values.
func TestConfigCLI_Get_SliceField(t *testing.T) {
tmpDir := t.TempDir()
@@ -352,22 +352,22 @@ func TestConfigCLI_Get_SliceField(t *testing.T) {
t.Fatalf("config init failed: %v\nOutput: %s", err, out)
}
- setCmd := exec.Command(server.BinaryPath, "config", "set", "attach.allowHosts", "127.0.0.1,localhost")
+ setCmd := exec.Command(server.BinaryPath, "config", "set", "security.attach.allowHosts", "127.0.0.1,localhost")
setCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)
if out, err := setCmd.CombinedOutput(); err != nil {
t.Fatalf("config set failed: %v\nOutput: %s", err, out)
}
- getCmd := exec.Command(server.BinaryPath, "config", "get", "attach.allowHosts")
+ getCmd := exec.Command(server.BinaryPath, "config", "get", "security.attach.allowHosts")
getCmd.Env = append(filterTestEnv(), "PINCHTAB_CONFIG="+configPath)
out, err := getCmd.CombinedOutput()
if err != nil {
- t.Fatalf("config get attach.allowHosts failed: %v\nOutput: %s", err, out)
+ t.Fatalf("config get security.attach.allowHosts failed: %v\nOutput: %s", err, out)
}
got := strings.TrimSpace(string(out))
if got != "127.0.0.1,localhost" {
- t.Errorf("config get attach.allowHosts = %q, want %q", got, "127.0.0.1,localhost")
+ t.Errorf("config get security.attach.allowHosts = %q, want %q", got, "127.0.0.1,localhost")
}
}