High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(cli): add security setup wizard with config versioning
Bosch2b378b1c77ef
diff --git a/cmd/pinchtab/cmd_daemon.go b/cmd/pinchtab/cmd_daemon.goindex c2092be3..a7fa19d1 100644--- a/cmd/pinchtab/cmd_daemon.go+++ b/cmd/pinchtab/cmd_daemon.go@@ -66,11 +66,16 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {switch subcommand {case "install":- configPath, _, _, err := ensureDaemonConfig(false)+ configPath, fileCfg, _, err := ensureDaemonConfig(false)if err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))os.Exit(1)}+ // Run wizard if needed (first install or version upgrade)+ if config.NeedsWizard(fileCfg) {+ isNew := config.IsFirstRun(fileCfg)+ runSecurityWizard(fileCfg, configPath, isNew)+ }if err := manager.Preflight(); err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install unavailable: %v", err)))os.Exit(1)@@ -201,7 +206,7 @@ func printDaemonManagerResult(message string, err error) {}}-func ensureDaemonConfig(force bool) (string, *config.RuntimeConfig, configBootstrapStatus, error) {+func ensureDaemonConfig(force bool) (string, *config.FileConfig, configBootstrapStatus, error) {_, configPath, err := config.LoadFileConfig()if err != nil {return "", nil, "", err@@ -222,20 +227,22 @@ func ensureDaemonConfig(force bool) (string, *config.RuntimeConfig, configBootstif exists {status = configRecovered}- return configPath, config.Load(), status, nil+ return configPath, &defaults, status, nil}// If file exists and not forced, check if it needs recovery to secure baseline_, changed, err := cli.RestoreSecurityDefaults()if err != nil {- return configPath, config.Load(), configVerified, err+ fileCfg, _, _ := config.LoadFileConfig()+ return configPath, fileCfg, configVerified, err}status := configVerifiedif changed {status = configRecovered}- return configPath, config.Load(), status, nil+ fileCfg, _, _ := config.LoadFileConfig()+ return configPath, fileCfg, status, nil}type configBootstrapStatus stringdiff --git a/cmd/pinchtab/cmd_daemon_test.go b/cmd/pinchtab/cmd_daemon_test.goindex b455e742..1d2e5fad 100644--- a/cmd/pinchtab/cmd_daemon_test.go+++ b/cmd/pinchtab/cmd_daemon_test.go@@ -39,10 +39,10 @@ func TestEnsureOnboardConfigCreatesDefaultConfig(t *testing.T) {if gotPath != configPath {t.Fatalf("config path = %q, want %q", gotPath, configPath)}- if cfg.Bind != "127.0.0.1" {- t.Fatalf("bind = %q, want 127.0.0.1", cfg.Bind)+ if cfg.Server.Bind != "127.0.0.1" {+ t.Fatalf("bind = %q, want 127.0.0.1", cfg.Server.Bind)}- if strings.TrimSpace(cfg.Token) == "" {+ if strings.TrimSpace(cfg.Server.Token) == "" {t.Fatal("expected generated token to be set")}data, err := os.ReadFile(configPath)@@ -89,19 +89,19 @@ func TestEnsureOnboardConfigRecoversExistingSecuritySettings(t *testing.T) {if status != configRecovered {t.Fatalf("status = %q, want %q", status, configRecovered)}- if cfg.Bind != "127.0.0.1" {- t.Fatalf("bind = %q, want 127.0.0.1", cfg.Bind)+ if cfg.Server.Bind != "127.0.0.1" {+ t.Fatalf("bind = %q, want 127.0.0.1", cfg.Server.Bind)}- if cfg.Port != "9999" {- t.Fatalf("port = %q, want 9999", cfg.Port)+ if cfg.Server.Port != "9999" {+ t.Fatalf("port = %q, want 9999", cfg.Server.Port)}- if cfg.ChromeBinary != "/custom/chrome" {- t.Fatalf("chrome binary = %q, want /custom/chrome", cfg.ChromeBinary)+ if cfg.Browser.ChromeBinary != "/custom/chrome" {+ t.Fatalf("chrome binary = %q, want /custom/chrome", cfg.Browser.ChromeBinary)}- if cfg.AllowEvaluate {+ if boolPtrValue(cfg.Security.AllowEvaluate) {t.Fatal("expected allowEvaluate to be reset to false")}- if strings.TrimSpace(cfg.Token) == "" {+ if strings.TrimSpace(cfg.Server.Token) == "" {t.Fatal("expected recovery to generate a token")}}diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.goindex 10a61506..8eaa028a 100644--- a/cmd/pinchtab/cmd_server.go+++ b/cmd/pinchtab/cmd_server.go@@ -10,6 +10,7 @@ var serverCmd = &cobra.Command{Use: "server",Short: "Start full server",Run: func(cmd *cobra.Command, args []string) {+ maybeRunWizard()cfg := config.Load()server.RunDashboard(cfg, version)},diff --git a/cmd/pinchtab/cmd_wizard.go b/cmd/pinchtab/cmd_wizard.gonew file mode 100644index 00000000..433d3dd5--- /dev/null+++ b/cmd/pinchtab/cmd_wizard.go@@ -0,0 +1,223 @@+package main++import (+ "fmt"+ "os"+ "strings"++ "github.com/pinchtab/pinchtab/internal/cli"+ "github.com/pinchtab/pinchtab/internal/config"+)++// runSecurityWizard runs the interactive security setup wizard.+// isNew indicates a fresh install (full wizard) vs upgrade (migration notice).+// Returns true if the user completed setup, false if they cancelled.+func runSecurityWizard(cfg *config.FileConfig, configPath string, isNew bool) bool {+ interactive := isInteractiveTerminal()++ if !interactive {+ return runNonInteractiveSetup(cfg, configPath, isNew)+ }++ if isNew {+ return runFullWizard(cfg, configPath)+ }+ return runUpgradeNotice(cfg, configPath)+}++// runNonInteractiveSetup prints a summary and applies defaults silently.+func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew bool) bool {+ if isNew {+ fmt.Println()+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "π Security defaults applied"))+ fmt.Printf(" Dashboard: http://%s:%s\n", orDefault(cfg.Server.Bind, "127.0.0.1"), orDefault(cfg.Server.Port, "9867"))+ if cfg.Server.Token != "" {+ fmt.Printf(" Token: %s\n", cfg.Server.Token[:12]+"...")+ fmt.Printf(" Dashboard: http://%s:%s?token=%s\n",+ orDefault(cfg.Server.Bind, "127.0.0.1"),+ orDefault(cfg.Server.Port, "9867"),+ cfg.Server.Token)+ }+ fmt.Println(" IDPI: enabled (localhost only)")+ fmt.Println()+ fmt.Println(" Run " + cli.StyleStdout(cli.CommandStyle, "pinchtab security") + " to review all settings.")+ fmt.Println()+ } else {+ fmt.Println()+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "π Config updated to v"+config.CurrentConfigVersion))+ fmt.Println(" Run " + cli.StyleStdout(cli.CommandStyle, "pinchtab security") + " to review changes.")+ fmt.Println()+ }++ cfg.ConfigVersion = config.CurrentConfigVersion+ _ = config.SaveFileConfig(cfg, configPath)+ return true+}++// runFullWizard runs the interactive first-run wizard.+func runFullWizard(cfg *config.FileConfig, configPath string) bool {+ fmt.Println()+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "π Security Setup"))+ fmt.Println()+ fmt.Println(" We care about your security β PinchTab ships with the strongest defaults.")+ fmt.Println()+ printSeparator()++ // Step 1: IDPI+ fmt.Println()+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, " 1. IDPI (Injection Detection)"))+ fmt.Println()+ domains := cfg.Security.IDPI.AllowedDomains+ if len(domains) == 0 {+ domains = []string{"127.0.0.1", "localhost", "::1"}+ }+ fmt.Printf(" Allowed domains: %s\n", cli.StyleStdout(cli.ValueStyle, strings.Join(domains, ", ")))+ fmt.Println(" Only locally-served sites can be automated without warnings.")+ fmt.Println()++ picked, err := promptSelect("IDPI allowed domains", []menuOption{+ {label: "Confirm defaults", value: "confirm"},+ {label: "Open in browser to edit", value: "browser"},+ })+ if err != nil {+ return false+ }+ if picked == "browser" {+ fmt.Println()+ fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, "Complete setup in your browser, then restart the server."))+ fmt.Printf(" %s\n", dashboardURL(cfg, "/setup"))+ fmt.Println()+ // Save what we have so far+ cfg.ConfigVersion = config.CurrentConfigVersion+ _ = config.SaveFileConfig(cfg, configPath)+ return true+ }++ // Step 2: Dashboard access+ printSeparator()+ fmt.Println()+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, " 2. Dashboard Access"))+ fmt.Println()+ if cfg.Server.Token != "" {+ fmt.Printf(" Token: %s\n", cli.StyleStdout(cli.ValueStyle, cfg.Server.Token))+ fmt.Println()+ url := dashboardURL(cfg, "")+ fmt.Printf(" Dashboard: %s\n", cli.StyleStdout(cli.CommandStyle, url))+ } else {+ fmt.Println(" " + cli.StyleStdout(cli.WarningStyle, "No token set β dashboard is unprotected!"))+ }+ fmt.Println()++ picked, err = promptSelect("Dashboard token", []menuOption{+ {label: "Keep token", value: "keep"},+ {label: "Copy to clipboard", value: "copy"},+ {label: "Generate new token", value: "new"},+ })+ if err != nil {+ return false+ }++ switch picked {+ case "copy":+ copyToClipboard(cfg.Server.Token)+ case "new":+ token, err := config.GenerateAuthToken()+ if err == nil {+ cfg.Server.Token = token+ fmt.Printf(" New token: %s\n", cli.StyleStdout(cli.ValueStyle, token))+ }+ }++ // Step 3: Security summary+ printSeparator()+ fmt.Println()+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, " 3. Security Settings"))+ fmt.Println()+ printSecuritySetting("evaluate", boolPtrValue(cfg.Security.AllowEvaluate))+ printSecuritySetting("download", boolPtrValue(cfg.Security.AllowDownload))+ printSecuritySetting("upload", boolPtrValue(cfg.Security.AllowUpload))+ printSecuritySetting("macros", boolPtrValue(cfg.Security.AllowMacro))+ printSecuritySetting("screencast", boolPtrValue(cfg.Security.AllowScreencast))+ fmt.Println()+ fmt.Println(" Review or change with " + cli.StyleStdout(cli.CommandStyle, "pinchtab security"))+ fmt.Println()++ printSeparator()+ fmt.Println()++ // Save+ cfg.ConfigVersion = config.CurrentConfigVersion+ if err := config.SaveFileConfig(cfg, configPath); err != nil {+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("failed to save config: %v", err)))+ return false+ }++ fmt.Println(cli.StyleStdout(cli.SuccessStyle, " β Setup complete!"))+ fmt.Println()+ return true+}++// runUpgradeNotice shows a brief notice for config upgrades.+func runUpgradeNotice(cfg *config.FileConfig, configPath string) bool {+ fmt.Println()+ fmt.Println(cli.StyleStdout(cli.HeadingStyle, "π Security update (v"+config.CurrentConfigVersion+")"))+ fmt.Println()++ oldVersion := cfg.ConfigVersion+ if oldVersion == "" {+ oldVersion = "pre-0.8.0"+ }+ fmt.Printf(" Config upgraded: %s β %s\n", oldVersion, config.CurrentConfigVersion)++ if cfg.Server.Token != "" {+ fmt.Printf(" Dashboard token: %s\n", cli.StyleStdout(cli.ValueStyle, cfg.Server.Token[:min(12, len(cfg.Server.Token))]+"..."))+ }++ fmt.Println()+ fmt.Println(" Run " + cli.StyleStdout(cli.CommandStyle, "pinchtab security") + " to review all settings.")+ fmt.Println()++ cfg.ConfigVersion = config.CurrentConfigVersion+ _ = config.SaveFileConfig(cfg, configPath)+ return true+}++// βββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββ++func printSeparator() {+ fmt.Println(" " + cli.StyleStdout(cli.MutedStyle, strings.Repeat("β", 50)))+}++func printSecuritySetting(name string, enabled bool) {+ status := cli.StyleStdout(cli.SuccessStyle, "disabled")+ if enabled {+ status = cli.StyleStdout(cli.WarningStyle, "enabled")+ }+ fmt.Printf(" β’ %-12s %s\n", name+":", status)+}++func boolPtrValue(p *bool) bool {+ if p == nil {+ return false+ }+ return *p+}++func dashboardURL(cfg *config.FileConfig, path string) string {+ host := orDefault(cfg.Server.Bind, "127.0.0.1")+ port := orDefault(cfg.Server.Port, "9867")+ url := fmt.Sprintf("http://%s:%s%s", host, port, path)+ if cfg.Server.Token != "" {+ url += "?token=" + cfg.Server.Token+ }+ return url+}++func orDefault(val, fallback string) string {+ if val == "" {+ return fallback+ }+ return val+}++// copyToClipboard is defined in cmd_config.godiff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.goindex 6b4842ec..ab306679 100644--- a/cmd/pinchtab/root.go+++ b/cmd/pinchtab/root.go@@ -22,6 +22,9 @@ browsers, manage tabs, and perform interactive tasks.`,Run: func(cmd *cobra.Command, args []string) {cfg := config.Load()+ // Check if security wizard needs to run+ maybeRunWizard()+if isInteractiveTerminal() {cli.PrintStartupBanner(cfg, cli.StartupBannerOptions{Mode: "menu",@@ -67,6 +70,21 @@ browsers, manage tabs, and perform interactive tasks.`,},}+// maybeRunWizard checks if the security wizard should run and triggers it.+func maybeRunWizard() {+ fileCfg, configPath, err := config.LoadFileConfig()+ if err != nil || configPath == "" {+ return // No config file context β skip wizard+ }++ if !config.NeedsWizard(fileCfg) {+ return+ }++ isNew := config.IsFirstRun(fileCfg)+ runSecurityWizard(fileCfg, configPath, isNew)+}+func menuListenStatus(cfg *config.RuntimeConfig) string {dashPort := cfg.Portif dashPort == "" {diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 8b6425c3..02d905ae 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -7,6 +7,9 @@ import ("time")+// CurrentConfigVersion is bumped when config schema changes require migration or wizard re-run.+const CurrentConfigVersion = "0.8.0"+// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).func DefaultFileConfig() FileConfig {start := 9868@@ -23,6 +26,7 @@ func DefaultFileConfig() FileConfig {allowUpload := falsemaxRedirects := -1return FileConfig{+ ConfigVersion: CurrentConfigVersion,Server: ServerConfig{Port: "9867",Bind: "127.0.0.1",diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex fd8e821a..984e6179 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -97,6 +97,7 @@ type SchedulerConfig struct {// FileConfig is the persistent configuration written to disk.type FileConfig struct {+ ConfigVersion string `json:"configVersion,omitempty"`Server ServerConfig `json:"server,omitempty"`Browser BrowserConfig `json:"browser,omitempty"`InstanceDefaults InstanceDefaultsConfig `json:"instanceDefaults,omitempty"`diff --git a/internal/config/config_utils.go b/internal/config/config_utils.goindex ec796ba1..5d1f9a84 100644--- a/internal/config/config_utils.go+++ b/internal/config/config_utils.go@@ -3,6 +3,7 @@ package configimport ("crypto/rand""encoding/hex"+ "strings""fmt""os""path/filepath"@@ -74,3 +75,50 @@ func MaskToken(t string) string {}return t[:4] + "..." + t[len(t)-4:]}++// NeedsWizard returns true if the config has no version or an older version than current.+func NeedsWizard(cfg *FileConfig) bool {+ if cfg.ConfigVersion == "" {+ return true+ }+ return CompareVersions(cfg.ConfigVersion, CurrentConfigVersion) < 0+}++// IsFirstRun returns true if the config has never been through the wizard.+func IsFirstRun(cfg *FileConfig) bool {+ return cfg.ConfigVersion == ""+}++// CompareVersions compares two semver-like version strings.+// Returns -1 if a < b, 0 if a == b, 1 if a > b.+func CompareVersions(a, b string) int {+ aParts := splitVersion(a)+ bParts := splitVersion(b)+ for i := 0; i < 3; i++ {+ if aParts[i] < bParts[i] {+ return -1+ }+ if aParts[i] > bParts[i] {+ return 1+ }+ }+ return 0+}++func splitVersion(v string) [3]int {+ parts := [3]int{}+ segs := strings.SplitN(v, ".", 3)+ for i, s := range segs {+ if i >= 3 {+ break+ }+ n := 0+ for _, c := range s {+ if c >= '0' && c <= '9' {+ n = n*10 + int(c-'0')+ }+ }+ parts[i] = n+ }+ return parts+}diff --git a/internal/config/config_utils_test.go b/internal/config/config_utils_test.goindex 55b4ff61..e352f302 100644--- a/internal/config/config_utils_test.go+++ b/internal/config/config_utils_test.go@@ -1,52 +1,56 @@package config-import (- "testing"-)+import "testing"-func TestMaskToken(t *testing.T) {+func TestCompareVersions(t *testing.T) {tests := []struct {- token string- want string+ a, b string+ want int}{- {"", "(none)"},- {"short", "***"},- {"very-long-token-secret", "very...cret"},+ {"0.8.0", "0.8.0", 0},+ {"0.7.0", "0.8.0", -1},+ {"0.8.0", "0.7.0", 1},+ {"1.0.0", "0.9.9", 1},+ {"0.8.1", "0.8.0", 1},+ {"0.8.0", "0.8.1", -1},+ {"1.0.0", "1.0.0", 0},}-for _, tt := range tests {- if got := MaskToken(tt.token); got != tt.want {- t.Errorf("MaskToken(%q) = %v, want %v", tt.token, got, tt.want)- }+ t.Run(tt.a+"_vs_"+tt.b, func(t *testing.T) {+ got := CompareVersions(tt.a, tt.b)+ if got != tt.want {+ t.Errorf("CompareVersions(%q, %q) = %d, want %d", tt.a, tt.b, got, tt.want)+ }+ })}}-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))+func TestNeedsWizard(t *testing.T) {+ tests := []struct {+ name string+ version string+ want bool+ }{+ {"empty version", "", true},+ {"old version", "0.7.0", true},+ {"current version", CurrentConfigVersion, false},+ {"future version", "1.0.0", false},}- 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)- }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ cfg := &FileConfig{ConfigVersion: tt.version}+ if got := NeedsWizard(cfg); got != tt.want {+ t.Errorf("NeedsWizard(%q) = %v, want %v", tt.version, got, tt.want)+ }+ })}}-func TestListenAddr(t *testing.T) {- cfg := &RuntimeConfig{Bind: "127.0.0.1", Port: "9867"}- if got := cfg.ListenAddr(); got != "127.0.0.1:9867" {- t.Errorf("expected 127.0.0.1:9867, got %s", got)+func TestIsFirstRun(t *testing.T) {+ if !IsFirstRun(&FileConfig{}) {+ t.Error("expected IsFirstRun for empty config")}-- cfg = &RuntimeConfig{Bind: "0.0.0.0", Port: "8080"}- if got := cfg.ListenAddr(); got != "0.0.0.0:8080" {- t.Errorf("expected 0.0.0.0:8080, got %s", got)+ if IsFirstRun(&FileConfig{ConfigVersion: "0.8.0"}) {+ t.Error("expected not IsFirstRun for versioned config")}}